nativesoul 0.1.3 → 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.
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function kc(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}function Z(e,t){if(!t)return!1;let r=kc(t);return e.includes(r.start)&&e.includes(r.end)}var ce=bt(()=>{"use strict"});function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}async function Q(e){let t=await K(e);if(t===null)return null;let r=Be(t);return O(r)?r:null}function tt(e){return O(e)?Object.keys(e).filter(t=>t.trim().length>0):[]}function tn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function rt(e,t){if(Array.isArray(e))return e;if(!O(e))return[];for(let r of t){let o=e[r];if(Array.isArray(o))return o}return[]}function I(e,t){if(!O(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 ae(e,t){if(!O(e))return null;for(let r of t){let o=e[r];if(typeof o=="boolean")return o}return null}function M(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 Ve=bt(()=>{"use strict";ce()});import{readdir as $g,readFile as Fg}from"node:fs/promises";import Tc from"node:path";function Oc(e){let t=e??j("~/.claude");return Tc.join(t,"scheduled-tasks")}async function Nc(e){if(!await W(e))return null;let t=await Ic(e,Cc);if(t!==null)return t;let r=await Bg(e);for(let o of r){let n=await Ic(e,o);if(n!==null)return n}return null}async function Ic(e,t){let r=Tc.join(e,t,"SKILL.md");if(!await P(r))return null;let n=(await Fg(r,"utf8")).toLowerCase();return t===Cc||t.includes(Ug)||n.includes(`name: ${jc}`)||n.includes(`# ${jc}`)?`claude:scheduled-task:${t}`:null}async function Bg(e){try{return(await $g(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}var Cc,Ug,jc,Mc=bt(()=>{"use strict";ce();Cc="nativesoul-heartbeat",Ug="nativesoul-heartbeat",jc="life:heartbeat"});import{mkdir as Vg,readFile as Wg,writeFile as Jg}from"node:fs/promises";import Cr from"node:path";import{fileURLToPath as qg}from"node:url";async function Dc(e){try{let t=Cr.join(e,Lc);await Vg(t,{recursive:!0,mode:448});let r=Cr.join(t,"SKILL.md"),o=await Gg();return await Jg(r,o??Kg,"utf8"),!0}catch{return!1}}async function Gg(){let e=Cr.dirname(qg(import.meta.url)),t=[Cr.resolve(process.cwd(),"plugins","claude-nativesoul","skills","life-heartbeat","SKILL.md"),Cr.resolve(e,"../../../../plugins/claude-nativesoul/skills/life-heartbeat/SKILL.md")];for(let r of t)if(await P(r))return Wg(r,"utf8");return null}var Lc,mE,Kg,Hc=bt(()=>{"use strict";ce();Lc="nativesoul-heartbeat",mE=`claude:scheduled-task:${Lc}`,Kg='---\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 $c={};Ml($c,{discoverClaudeScheduledTasksManifest:()=>Xg});async function Xg(e={}){let t=Oc(e.hostConfigRoot);if(!e.apply&&!await W(t)||(e.surface==="claude-code"?"claude-code":"claude-desktop")==="claude-code")return null;let o=await Nc(t);return o!==null?Ba({nativeId:o,evidenceSource:"filesystem"}):e.apply&&await Dc(t)?Ba({nativeId:"claude:scheduled-task:nativesoul-heartbeat",evidenceSource:"filesystem-provisioned"}):await W(t)?Ba({nativeId:void 0,evidenceSource:"filesystem"}):null}function Ba(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 Fc=bt(()=>{"use strict";Mc();Hc();ce()});var ad={};Ml(ad,{discoverCodexAutomationsManifest:()=>uf});import{readFile as Wa}from"node:fs/promises";import nn from"node:path";import{spawnSync as nf}from"node:child_process";async function uf(e={}){let t=await pf();if(t)return t;let r=await mf(e.hostConfigRoot);return r||(e.apply?(await ff(),await gf()):null)}async function pf(){let e=process.env.NATIVESOUL_CODEX_AUTOMATIONS_FIXTURES;if(e)try{return Ja(await Wa(nn.join(e,"automations.json"),"utf8"))}catch{return null}let t=process.env.NATIVESOUL_CODEX_AUTOMATIONS_MANIFEST;if(t)try{return Ja(await Wa(t,"utf8"))}catch{return null}return null}async function mf(e){let t=e??j("~/.codex"),r=[nn.join(t,"automations.json"),nn.join(t,"automations","nativesoul-heartbeat.json"),nn.join(t,"automations","manifest.json")];for(let o of r){if(!await P(o))continue;let n=await Wa(o,"utf8"),a=Ja(n);if(a?.supported)return a;let s=Be(n);if(!s)continue;let i=nd(s);if(i)return i}return null}async function gf(){let e=hf();for(let t of e)for(let r of sf){let o=await yf(()=>bf(t,r),cf),n=nd(o);if(n)return n}return null}async function ff(){let e=await Ue("codex");e&&nf(e,["app-server","daemon","start"],{encoding:"utf8",stdio:"ignore",timeout:1e4})}function hf(){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 yf(e,t){for(let r=0;r<=t;r+=1){let o=await e();if(o!==null)return o;r<t&&await _f(df)}return null}function _f(e){return new Promise(t=>{setTimeout(t,e)})}async function bf(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),lf);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 a=await n.json();return!O(a)||"error"in a?null:"result"in a?a.result:a}catch{return null}finally{clearTimeout(o)}}function nd(e){let t=vf(e);for(let r of t){let o=kf(r),n=JSON.stringify(r).toLowerCase();if(o&&af.some(a=>n.includes(a)))return{supported:!0,native_id:o.startsWith("codex:")?o:`codex:automation:${o}`}}return O(e)&&e.supported===!0?{supported:!0,native_id:typeof e.native_id=="string"?e.native_id:void 0}:null}function vf(e){if(Array.isArray(e))return e;if(!O(e))return[];for(let t of["automations","items","results","data"]){let r=e[t];if(Array.isArray(r))return r}return[]}function kf(e){if(!O(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 Ja(e){let t=Be(e);return O(t)?{supported:t.supported===!0,native_id:typeof t.native_id=="string"&&t.native_id.length>0?t.native_id:void 0}:null}var af,sf,lf,cf,df,sd=bt(()=>{"use strict";ce();Rt();Ve();af=["life:heartbeat","nativesoul-heartbeat","life-heartbeat"],sf=["automation/list","automations/list","scheduledAutomation/list"],lf=1e3,cf=2,df=150});import{realpathSync as Nm}from"node:fs";import ES from"node:path";import{fileURLToPath as PS}from"node:url";import{existsSync as CR}from"node:fs";import{mkdirSync as Xm}from"node:fs";import zm from"node:path";import{pathToFileURL as Ym}from"node:url";function Xt(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(t.source!=="host-reported")return{};let r={schema:Dl(t.schema)??1,source:"host-reported"},o=aa(t.model);o&&(r.model=o);let n=Ll(t.tokens_in);n!==null&&(r.tokens_in=n);let a=Ll(t.tokens_out);a!==null&&(r.tokens_out=a);let s=Dl(t.cost_usd);s!==null&&(r.cost_usd=s);let i=aa(t.currency);i?r.currency=i:s!==null&&(r.currency="USD");let l=aa(t.reported_at);return l&&(r.reported_at=l),r}function Pr(e){try{return Xt(JSON.parse(e))}catch{return{}}}function aa(e){return typeof e=="string"&&e.length>0?e:null}function Ll(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.trunc(e)}function Dl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function vt(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 sa(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 Hl(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 qo(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 xr(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 Ko(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 ia(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 la(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 jr(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 Ir(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:Pr(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 ca(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 Go(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 $l(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Fl(e){return e.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function Te(e){return e?1:0}function Xo(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 Ce=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 da(e,t){if(!zt(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 Fm=Object.defineProperty;var bt=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}};var Ll=(e,t)=>{for(var r in t)Fm(e,r,{get:t[r],enumerable:!0})};import{spawn as Rg}from"node:child_process";import{access as Sg}from"node:fs/promises";import{constants as Ag}from"node:fs";import{existsSync as Eg}from"node:fs";import bc from"node:path";async function Ue(e){let t=(process.env.PATH??"").split(bc.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 a=bc.join(o,`${e}${n}`);if(process.platform==="win32"&&Eg(a))return a;try{return await Sg(a,Ag.X_OK),a}catch{}}return null}async function en(e,t){return new Promise(r=>{vc(e,t,["ignore","pipe","pipe"]).then(o=>{let n=setTimeout(()=>{o.kill(),r(null)},750),a="";o.stdout.on("data",s=>{a+=String(s)}),o.stderr.on("data",s=>{a+=String(s)}),o.on("error",()=>{clearTimeout(n),r(null)}),o.on("close",s=>{clearTimeout(n);let i=a.trim().split(/\r?\n/u).map(l=>l.trim()).find(l=>/\d+\.\d+/u.test(l)&&!l.toLowerCase().startsWith("warning"));if(s===0||i){r(i??null);return}r(null)})})})}async function Da(e,t,r=1e3){return new Promise(o=>{vc(e,t,["ignore","pipe","pipe"]).then(n=>{let a=setTimeout(()=>{n.kill(),o({status:"timeout",code:null,stdout:"",stderr:"command timed out"})},r),s="",i="";n.stdout.on("data",l=>{s+=String(l)}),n.stderr.on("data",l=>{i+=String(l)}),n.on("error",()=>{clearTimeout(a),o({status:"missing",code:null,stdout:s,stderr:i})}),n.on("close",l=>{clearTimeout(a),o({status:l===0?"ok":"error",code:l,stdout:s,stderr:i})})})})}async function vc(e,t,r){let n=await Ue(e)??e,a=process.platform==="win32"&&/\.(?:cmd|bat)$/iu.test(n);return Rg(n,t,{stdio:r,shell:a})}var Rt=bt(()=>{"use strict"});import{constants as Pg}from"node:fs";import{access as xg,readFile as jg,stat as Ig}from"node:fs/promises";import kc from"node:os";import Tg from"node:path";function j(e){return e==="~"?kc.homedir():e.startsWith("~/")?Tg.join(kc.homedir(),e.slice(2)):e}async function P(e){try{return await xg(e,Pg.F_OK),!0}catch{return!1}}async function W(e){try{return(await Ig(e)).isDirectory()}catch{return!1}}async function K(e){return await P(e)?jg(e,"utf8"):null}function Ne(e){let t=wc(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 wc(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}function Z(e,t){if(!t)return!1;let r=wc(t);return e.includes(r.start)&&e.includes(r.end)}var ce=bt(()=>{"use strict"});function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}async function Q(e){let t=await K(e);if(t===null)return null;let r=Be(t);return O(r)?r:null}function tt(e){return O(e)?Object.keys(e).filter(t=>t.trim().length>0):[]}function tn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function rt(e,t){if(Array.isArray(e))return e;if(!O(e))return[];for(let r of t){let o=e[r];if(Array.isArray(o))return o}return[]}function I(e,t){if(!O(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 ae(e,t){if(!O(e))return null;for(let r of t){let o=e[r];if(typeof o=="boolean")return o}return null}function M(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 Ve=bt(()=>{"use strict";ce()});import{readdir as Vg,readFile as Wg}from"node:fs/promises";import Cc from"node:path";function Nc(e){let t=e??j("~/.claude");return Cc.join(t,"scheduled-tasks")}async function Mc(e){if(!await W(e))return null;let t=await Tc(e,Oc);if(t!==null)return t;let r=await qg(e);for(let o of r){let n=await Tc(e,o);if(n!==null)return n}return null}async function Tc(e,t){let r=Cc.join(e,t,"SKILL.md");if(!await P(r))return null;let n=(await Wg(r,"utf8")).toLowerCase();return t===Oc||t.includes(Jg)||n.includes(`name: ${Ic}`)||n.includes(`# ${Ic}`)?`claude:scheduled-task:${t}`:null}async function qg(e){try{return(await Vg(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}var Oc,Jg,Ic,Lc=bt(()=>{"use strict";ce();Oc="nativesoul-heartbeat",Jg="nativesoul-heartbeat",Ic="life:heartbeat"});import{mkdir as Kg,readFile as Gg,writeFile as Xg}from"node:fs/promises";import Cr from"node:path";import{fileURLToPath as zg}from"node:url";async function Hc(e){try{let t=Cr.join(e,Dc);await Kg(t,{recursive:!0,mode:448});let r=Cr.join(t,"SKILL.md"),o=await Qg();return await Xg(r,o??Yg,"utf8"),!0}catch{return!1}}async function Qg(){let e=Cr.dirname(zg(import.meta.url)),t=[Cr.resolve(process.cwd(),"plugins","claude-nativesoul","skills","life-heartbeat","SKILL.md"),Cr.resolve(e,"../../../../plugins/claude-nativesoul/skills/life-heartbeat/SKILL.md")];for(let r of t)if(await P(r))return Gg(r,"utf8");return null}var Dc,yE,Yg,$c=bt(()=>{"use strict";ce();Dc="nativesoul-heartbeat",yE=`claude:scheduled-task:${Dc}`,Yg='---\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 Fc={};Ll(Fc,{discoverClaudeScheduledTasksManifest:()=>Zg});async function Zg(e={}){let t=Nc(e.hostConfigRoot);if(!e.apply&&!await W(t)||(e.surface==="claude-code"?"claude-code":"claude-desktop")==="claude-code")return null;let o=await Mc(t);return o!==null?Ba({nativeId:o,evidenceSource:"filesystem"}):e.apply&&await Hc(t)?Ba({nativeId:"claude:scheduled-task:nativesoul-heartbeat",evidenceSource:"filesystem-provisioned"}):await W(t)?Ba({nativeId:void 0,evidenceSource:"filesystem"}):null}function Ba(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 Uc=bt(()=>{"use strict";Lc();$c();ce()});var sd={};Ll(sd,{discoverCodexAutomationsManifest:()=>ff});import{readFile as Wa}from"node:fs/promises";import nn from"node:path";import{spawnSync as cf}from"node:child_process";async function ff(e={}){let t=await hf();if(t)return t;let r=await yf(e.hostConfigRoot);return r||(e.apply?(await bf(),await _f()):null)}async function hf(){let e=process.env.NATIVESOUL_CODEX_AUTOMATIONS_FIXTURES;if(e)try{return Ja(await Wa(nn.join(e,"automations.json"),"utf8"))}catch{return null}let t=process.env.NATIVESOUL_CODEX_AUTOMATIONS_MANIFEST;if(t)try{return Ja(await Wa(t,"utf8"))}catch{return null}return null}async function yf(e){let t=e??j("~/.codex"),r=[nn.join(t,"automations.json"),nn.join(t,"automations","nativesoul-heartbeat.json"),nn.join(t,"automations","manifest.json")];for(let o of r){if(!await P(o))continue;let n=await Wa(o,"utf8"),a=Ja(n);if(a?.supported)return a;let s=Be(n);if(!s)continue;let i=ad(s);if(i)return i}return null}async function _f(){let e=vf();for(let t of e)for(let r of uf){let o=await kf(()=>Rf(t,r),mf),n=ad(o);if(n)return n}return null}async function bf(){let e=await Ue("codex");e&&cf(e,["app-server","daemon","start"],{encoding:"utf8",stdio:"ignore",timeout:1e4})}function vf(){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 kf(e,t){for(let r=0;r<=t;r+=1){let o=await e();if(o!==null)return o;r<t&&await wf(gf)}return null}function wf(e){return new Promise(t=>{setTimeout(t,e)})}async function Rf(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),pf);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 a=await n.json();return!O(a)||"error"in a?null:"result"in a?a.result:a}catch{return null}finally{clearTimeout(o)}}function ad(e){let t=Sf(e);for(let r of t){let o=Af(r),n=JSON.stringify(r).toLowerCase();if(o&&df.some(a=>n.includes(a)))return{supported:!0,native_id:o.startsWith("codex:")?o:`codex:automation:${o}`}}return O(e)&&e.supported===!0?{supported:!0,native_id:typeof e.native_id=="string"?e.native_id:void 0}:null}function Sf(e){if(Array.isArray(e))return e;if(!O(e))return[];for(let t of["automations","items","results","data"]){let r=e[t];if(Array.isArray(r))return r}return[]}function Af(e){if(!O(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 Ja(e){let t=Be(e);return O(t)?{supported:t.supported===!0,native_id:typeof t.native_id=="string"&&t.native_id.length>0?t.native_id:void 0}:null}var df,uf,pf,mf,gf,id=bt(()=>{"use strict";ce();Rt();Ve();df=["life:heartbeat","nativesoul-heartbeat","life-heartbeat"],uf=["automation/list","automations/list","scheduledAutomation/list"],pf=1e3,mf=2,gf=150});import{realpathSync as Hm}from"node:fs";import IS from"node:path";import{fileURLToPath as TS}from"node:url";import{existsSync as LR}from"node:fs";import{mkdirSync as Zm}from"node:fs";import eg from"node:path";import{pathToFileURL as tg}from"node:url";function Xt(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(t.source!=="host-reported")return{};let r={schema:Hl(t.schema)??1,source:"host-reported"},o=aa(t.model);o&&(r.model=o);let n=Dl(t.tokens_in);n!==null&&(r.tokens_in=n);let a=Dl(t.tokens_out);a!==null&&(r.tokens_out=a);let s=Hl(t.cost_usd);s!==null&&(r.cost_usd=s);let i=aa(t.currency);i?r.currency=i:s!==null&&(r.currency="USD");let l=aa(t.reported_at);return l&&(r.reported_at=l),r}function Pr(e){try{return Xt(JSON.parse(e))}catch{return{}}}function aa(e){return typeof e=="string"&&e.length>0?e:null}function Dl(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.trunc(e)}function Hl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function vt(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 sa(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 $l(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 qo(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 xr(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 Ko(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 ia(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 la(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 jr(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 Ir(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:Pr(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 ca(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 Go(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 Fl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Ul(e){return e.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function Te(e){return e?1:0}function Xo(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 Ce=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 da(e,t){if(!zt(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
5
|
) VALUES (?, ?, ?, ?, ?, ?, 'pending', NULL, NULL, ?, NULL)`).run(t.id,t.action,t.class,t.target??null,t.project??null,t.host??null,r),kt(e,t.id)}function ua(e,t){if(!zt(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
|
|
@@ -12,17 +12,17 @@ var Lm=Object.defineProperty;var bt=(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?Ko(r):null,warning:null}}function ga(e,t,r){if(!zt(e))return{available:!1,approval:null,warning:"approvals_not_available"};let o=kt(e,t).approval;if(!o)return{available:!0,approval:null,warning:null};if(o.status!=="pending")throw new Ce({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),kt(e,t)}function zt(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
|
|
15
|
+
LIMIT 1`).get(t.action,t.class,t.target??null,t.project??null,t.host??null);return{available:!0,approval:r?Ko(r):null,warning:null}}function ga(e,t,r){if(!zt(e))return{available:!1,approval:null,warning:"approvals_not_available"};let o=kt(e,t).approval;if(!o)return{available:!0,approval:null,warning:null};if(o.status!=="pending")throw new Ce({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),kt(e,t)}function zt(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 Bl(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 fa(e,t){let r=e.prepare("SELECT * FROM memories WHERE id = ?").get(t);return r?vt(r):null}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 fa(e,t){let r=e.prepare("SELECT * FROM memories WHERE id = ?").get(t);return r?vt(r):null}function Vl(e,t,r){return e.prepare("UPDATE memories SET status = ? WHERE id = ?").run(r,t),fa(e,t)}function Wl(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(vt)}function Jl(e,t,r,o){let n=Xo(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(vt):ha(e,r,o)}function
|
|
25
|
+
LIMIT ?`).all(n,r,o).map(vt):ha(e,r,o)}function ql(e,t,r){return e.prepare(`SELECT *
|
|
26
26
|
FROM memories
|
|
27
27
|
WHERE scope_project = ?
|
|
28
28
|
AND status = 'active'
|
|
@@ -32,7 +32,7 @@ var Lm=Object.defineProperty;var bt=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&
|
|
|
32
32
|
WHERE scope_project = ?
|
|
33
33
|
AND status = 'active'
|
|
34
34
|
ORDER BY created_at DESC
|
|
35
|
-
LIMIT ?`).all(t,r).map(vt)}function
|
|
35
|
+
LIMIT ?`).all(t,r).map(vt)}function Kl(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
|
|
@@ -42,7 +42,7 @@ var Lm=Object.defineProperty;var bt=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&
|
|
|
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=ve(e,t.id);if(!n)throw new Error(`Project upsert did not return a row for ${t.id}`);return{project:n,inserted:!r}}function _a(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(xr)}function ve(e,t){let r=e.prepare("SELECT * FROM projects WHERE id = ?").get(t);return r?xr(r):null}function ba(e,t,r,o=new Date().toISOString()){if(!Tr(e))return{found:!1,previous:null,project:null};let n=ve(e,t);return n?(e.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:ve(e,t)}):{found:!1,previous:null,project:null}}function va(e,t,r=new Date().toISOString()){return
|
|
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=ve(e,t.id);if(!n)throw new Error(`Project upsert did not return a row for ${t.id}`);return{project:n,inserted:!r}}function _a(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(xr)}function ve(e,t){let r=e.prepare("SELECT * FROM projects WHERE id = ?").get(t);return r?xr(r):null}function ba(e,t,r,o=new Date().toISOString()){if(!Tr(e))return{found:!1,previous:null,project:null};let n=ve(e,t);return n?(e.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:ve(e,t)}):{found:!1,previous:null,project:null}}function va(e,t,r=new Date().toISOString()){return zl(e,t,"archived",r)}function ka(e,t,r=new Date().toISOString()){return zl(e,t,"active",r)}function wa(e,t){return e.prepare("SELECT COUNT(*) AS count FROM memories WHERE scope_project = ?").get(t)?.count??0}function Ra(e,t,r,o=new Date().toISOString()){if(!Tr(e))return{found:!1,previous:null,project:null,memories_affected:0};let n=ve(e,t);if(!n)return{found:!1,previous:null,project:null,memories_affected:0};e.exec("BEGIN IMMEDIATE");try{let a=e.prepare("SELECT id, status FROM memories WHERE scope_project = ? ORDER BY created_at ASC, id ASC").all(t);for(let s of a)if(!r(s.status,"forgotten"))throw new Yt({id:s.id,from:s.status,to:"forgotten"});return e.prepare("UPDATE memories SET status = 'forgotten' WHERE scope_project = ?").run(t),e.prepare("UPDATE projects SET status = 'forgotten', updated_at = ? WHERE id = ?").run(o,t),e.exec("COMMIT"),{found:!0,previous:n,project:ve(e,t),memories_affected:a.length}}catch(a){throw e.exec("ROLLBACK"),a}}function Sa(e,t={}){if(!Tr(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(`${Gl} ${n} ORDER BY derived_last_seen_at DESC, p.id ASC LIMIT ?`).all(...o,Wm(t.limit)).map(Vm),warning:null}}function Aa(e,t){if(!Tr(e))return{available:!1,detail:null,warning:"registry_not_available"};let r=e.prepare(`${Gl} WHERE p.id = ?`).get(t);return r?{available:!0,detail:{project:xr(r),counts:Xl(r),derived_last_seen_at:r.last_activity_at??null},warning:null}:{available:!0,detail:Jm(e,t),warning:null}}var Gl=`
|
|
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 Vm(e){return{...xr(e),counts:Xl(e),derived_last_seen_at:e.last_activity_at??null}}function Xl(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 Wm(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}function Tr(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 zl(e,t,r,o){if(!Tr(e))return{found:!1,previous:null,project:null};let n=ve(e,t);return n?(e.prepare("UPDATE projects SET status = ?, updated_at = ? WHERE id = ?").run(r,o,t),{found:!0,previous:n,project:ve(e,t)}):{found:!1,previous:null,project:null}}function Jm(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),a=e.prepare("SELECT COUNT(*) AS count, MAX(COALESCE(completed_at, started_at)) AS last_activity_at FROM runs WHERE project_id = ?").get(t),s=e.prepare("SELECT COUNT(*) AS count, MAX(COALESCE(ended_at, started_at)) AS last_activity_at FROM sessions WHERE project_id = ?").get(t),i={memories:{total:r.count,active:r.active_count??0,last_activity_at:r.last_activity_at},semantic_memory_index:{total:o.count,last_activity_at:o.last_activity_at},commitments:{total:n.count,open:n.open_count??0,last_activity_at:n.last_activity_at},runs:{total:a.count,last_activity_at:a.last_activity_at},sessions:{total:s.count,last_activity_at:s.last_activity_at}};return{project:null,counts:i,derived_last_seen_at:qm(i)}}function qm(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 Yl(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 $m(e){return{...xr(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 Ql(e,t){let r=e.prepare("SELECT * FROM semantic_memory_index WHERE memory_id = ?").get(t);return r?sa(r):null}function Zl(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 $m(e){return{...xr(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(sa)}function
|
|
144
|
+
LIMIT ?`).all(t.project,t.providerId,t.modelId,t.schemaVersion,t.limit).map(sa)}function ec(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 $m(e){return{...xr(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 rc(r)}function tc(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 $m(e){return{...xr(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 rc(r)}function rc(e){return{indexable_count:e?.indexable_count??0,indexed_count:e?.indexed_count??0,stale_count:e?.stale_count??0}}function Ea(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=Qt(e,t.id);if(!r)throw new Error(`Work item not found after insert: ${t.id}`);return r}function Qt(e,t){if(!Ta(e))return null;let r=e.prepare("SELECT * FROM work_items WHERE id = ?").get(t);return r?ia(r):null}function Pa(e,t){if(!Ta(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,
|
|
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=Qt(e,t.id);if(!r)throw new Error(`Work item not found after insert: ${t.id}`);return r}function Qt(e,t){if(!Ta(e))return null;let r=e.prepare("SELECT * FROM work_items WHERE id = ?").get(t);return r?ia(r):null}function Pa(e,t){if(!Ta(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,sc(t.limit)).map(ia)}function xa(e,t){if(!Ta(e))return null;e.exec("BEGIN IMMEDIATE");try{let r=Qt(e,t.id);if(!r)return e.exec("COMMIT"),null;let o=t.status??r.status,n=t.priority??r.priority,a=t.assignedHost!==void 0?t.assignedHost:r.assigned_host,s=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,d=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,a,s,JSON.stringify(i),JSON.stringify(l),c,d,t.updatedAt,t.id),t.event&&
|
|
177
|
+
WHERE id = ?`).run(o,n,a,s,JSON.stringify(i),JSON.stringify(l),c,d,t.updatedAt,t.id),t.event&&oc(e,t.event);let p=Qt(e,t.id);if(!p)throw new Error(`Work item not found after update: ${t.id}`);return e.exec("COMMIT"),p}catch(r){throw e.exec("ROLLBACK"),r}}function ja(e,t){oc(e,t);let r=Xm(e,t.id);if(!r)throw new Error(`Work item event not found after insert: ${t.id}`);return r}function Ia(e,t,r){return nc(e)?e.prepare("SELECT * FROM work_item_events WHERE work_item_id = ? ORDER BY created_at DESC, id DESC LIMIT ?").all(t,sc(r)).map(la):[]}function oc(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 Xm(e,t){if(!nc(e))return null;let r=e.prepare("SELECT * FROM work_item_events WHERE id = ?").get(t);return r?la(r):null}function Ta(e){return ac(e,"work_items")}function nc(e){return ac(e,"work_item_events")}function ac(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 sc(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}import{createRequire as Ym}from"node:module";var Qm=Ym(import.meta.url),zo=null;function ic(){if(zo)return zo;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 zo=Qm("node:sqlite"),zo}finally{process.emitWarning=e}}function lc(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 cc(e){e.exec(`
|
|
180
180
|
CREATE TABLE IF NOT EXISTS migrations (
|
|
181
181
|
version INTEGER PRIMARY KEY,
|
|
182
182
|
name TEXT NOT NULL,
|
|
@@ -454,8 +454,8 @@ LEFT JOIN activity a ON a.project_id = p.id`;function $m(e){return{...xr(e),coun
|
|
|
454
454
|
);
|
|
455
455
|
|
|
456
456
|
CREATE INDEX IF NOT EXISTS idx_approvals_status ON approvals(status);
|
|
457
|
-
`),wt(e,7,"approvals","sha256:approvals")}function wt(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
|
|
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
|
+
`),wt(e,7,"approvals","sha256:approvals")}function wt(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 dc=["hosts","sessions","memory_edges","commitments","standing_orders","capability_sources","capability_experience","schedules","leases","runs","work_items","work_item_events"];var Yo=class{path;db;constructor(t,r={}){this.path=t,r.readOnly||Zm(eg.dirname(t),{recursive:!0,mode:448});let{DatabaseSync:o}=ic(),n=r.readOnly?rg(t):t;this.db=new o(n,r.readOnly?{readOnly:!0}:{}),lc(this.db,{readOnly:r.readOnly}),r.readOnly||cc(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(dc.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($l)}createApproval(t){return da(this.db,t)}createDecidedApproval(t){return ua(this.db,t)}getApproval(t){return kt(this.db,t)}listApprovals(t){return pa(this.db,t)}findPendingApprovalMatch(t){return ma(this.db,t)}decideApproval(t,r){return ga(this.db,t,r)}insertWorkItem(t){return Ea(this.db,t)}getWorkItem(t){return Qt(this.db,t)}listWorkItems(t){return Pa(this.db,t)}updateWorkItem(t){return xa(this.db,t)}insertWorkItemEvent(t){return ja(this.db,t)}listWorkItemEvents(t,r){return Ia(this.db,t,r)}insertMemory(t){Bl(this.db,t)}getMemory(t){return fa(this.db,t)}updateMemoryStatus(t,r){return Vl(this.db,t,r)}listMemories(t){return Wl(this.db,t)}upsertProject(t){return ya(this.db,t)}getProject(t){return ve(this.db,t)}listProjects(t){return _a(this.db,t)}listProjectsWithCounts(t={}){return Sa(this.db,t)}getProjectDetail(t){return Aa(this.db,t)}renameProject(t,r,o){return ba(this.db,t,r,o)}archiveProject(t,r){return va(this.db,t,r)}reactivateProject(t,r){return ka(this.db,t,r)}countProjectMemories(t){return wa(this.db,t)}forgetProjectMemories(t,r,o){return Ra(this.db,t,r,o)}searchMemories(t,r,o){return Jl(this.db,t,r,o)}listActiveMemoriesForProject(t,r){return ql(this.db,t,r)}recentMemories(t,r){return ha(this.db,t,r)}listSemanticIndexableMemories(t){return Kl(this.db,t)}upsertSemanticIndex(t){Yl(this.db,t)}getSemanticIndex(t){return Ql(this.db,t)}listCurrentSemanticIndexesForProject(t){return Zl(this.db,t)}semanticIndexStatsForProject(t){return ec(this.db,t)}semanticIndexStats(t){return tc(this.db,t)}upsertCapabilities(t){let r=this.db.prepare(`INSERT INTO capabilities (
|
|
459
459
|
uid, host, native_kind, normalized_kind, source, schema_hash,
|
|
460
460
|
installed, enabled, active, authenticated, healthy, allowed, ready, last_seen_at
|
|
461
461
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -478,12 +478,12 @@ LEFT JOIN activity a ON a.project_id = p.id`;function $m(e){return{...xr(e),coun
|
|
|
478
478
|
WHERE ${o.join(" AND ")}
|
|
479
479
|
ORDER BY rank
|
|
480
480
|
LIMIT ?`).all(...n,t.limit).map(qo)}getCapability(t){let r=this.db.prepare("SELECT * FROM capabilities WHERE uid = ?").get(t);return r?qo(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?Go(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=
|
|
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=uc(t.summary),n=this.listCommitments({project:t.project_id,status:"open",includeExpired:!1,limit:200,now:r,skipExpire:!0}).find(s=>uc(s.summary)===o);if(n)return this.db.exec("COMMIT"),{created:!1,commitment:n};this.db.prepare(`INSERT INTO commitments (id, project_id, summary, status, due_at, ttl_expires_at, source_json, created_at, updated_at)
|
|
482
482
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.project_id,t.summary,t.status,t.due_at,t.ttl_expires_at,JSON.stringify(t.source),t.created_at,t.updated_at);let a=this.getCommitment(t.id);if(!a)throw new Error(`Commitment not found after insert: ${t.id}`);return this.db.exec("COMMIT"),{created:!0,commitment:a}}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(Go)}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:jr(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 a=this.latestHeartbeatRun(t.project,r.slot);return this.db.exec("COMMIT"),{lease:jr(r),run:a,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(Xt(t.cost)),JSON.stringify(t.result),JSON.stringify({
|
|
486
|
+
VALUES (?, 'heartbeat', ?, ?, 'completed', ?, ?, ?, ?, ?)`).run(t.runId,r.holder,t.project,JSON.stringify(Xt(t.cost)),JSON.stringify(t.result),JSON.stringify({...Fl(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:${Ul(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(jr)}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(Ir)}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(Ir)}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 ?",a=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,
|
|
@@ -519,7 +519,7 @@ LEFT JOIN activity a ON a.project_id = p.id`;function $m(e){return{...xr(e),coun
|
|
|
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?Ir(o):null}getSchedule(t){let r=this.db.prepare("SELECT * FROM schedules WHERE id = ?").get(t);return r?ca(r):null}getCommitment(t){let r=this.db.prepare("SELECT * FROM commitments WHERE id = ?").get(t);return r?Go(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
|
|
522
|
+
LIMIT 1`).get(t,r);return o?Ir(o):null}getSchedule(t){let r=this.db.prepare("SELECT * FROM schedules WHERE id = ?").get(t);return r?ca(r):null}getCommitment(t){let r=this.db.prepare("SELECT * FROM commitments WHERE id = ?").get(t);return r?Go(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 og(this.db,t)?this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get()?.count??0:0}};function _(e,t={}){return new Yo(e,t)}function rg(e){return`${tg(e).href}?mode=ro&immutable=1`}function uc(e){return e.trim().replace(/\s+/gu," ").toLocaleLowerCase()}function og(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 yg,mkdir as _g}from"node:fs/promises";import bg from"node:os";import vg from"node:path";import{createHash as ng,randomUUID as ag}from"node:crypto";function T(e){return`${e}_${ag()}`}function A(e){return`sha256:${ng("sha256").update(e).digest("hex")}`}function Ca(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(r=>Ca(r)).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Ca(e[r]??null)}`).join(",")}}`}function ke(e){return A(Ca(e))}import{existsSync as ig}from"node:fs";import mc from"node:os";var pc=[{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 lg=pc.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 lg)r=r.replace(o,n=>{t=!0;let a=n.match(/^(Authorization:\s*Bearer\s+)/iu);if(a?.[1])return`${a[1]}[REDACTED_SECRET]`;let s=n.match(/^([^:=]+[:=]\s*)/u);return s?.[1]?`${s[1]}[REDACTED_SECRET]`:"[REDACTED_SECRET]"});return{value:r,redacted:t}}function H(e){if(typeof e=="string")return N(e).value;if(Array.isArray(e))return e.map(t=>H(t));if(e&&typeof e=="object"){let t={};for(let[r,o]of Object.entries(e))t[r]=H(o);return t}return e}function Zt(e,t=[process.cwd(),mc.homedir()]){if(typeof e=="string")return t.filter(r=>r&&ig(r)).reduce((r,o)=>r.replaceAll(o,o===mc.homedir()?"[REDACTED_USER_HOME]":"[REDACTED_WORKSPACE]"),e);if(Array.isArray(e))return e.map(r=>Zt(r,t));if(e&&typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))r[o]=Zt(n,t);return r}return e}import{mkdir as hc,readFile as cg,writeFile as Oa}from"node:fs/promises";import{constants as dg,existsSync as yc}from"node:fs";import{access as ug}from"node:fs/promises";import pg from"node:os";import Oe from"node:path";var Qo={"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
|
+
`},gc=`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 fc(e){return`# Daily notes \u2014 ${e}
|
|
808
808
|
|
|
809
809
|
_Running context for today. Promote durable facts to curated memory later._
|
|
810
810
|
|
|
@@ -819,8 +819,8 @@ _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 Ma(e,t){if(typeof e=="string")return yg(e,t);if(Array.isArray(e))return e.map(r=>Ma(r,t));if(e&&typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))r[o]=Ma(n,t);return r}return e}function yg(e,t){return[[new RegExp(Na(t),"gu"),"[REDACTED_NATIVESOUL_HOME]"],[new RegExp(Na(process.cwd()),"gu"),"[REDACTED_WORKSPACE]"],[new RegExp(Na(fg.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,a])=>o.replace(n,a),e)}function Na(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function Zo(e){let t=f(e.home),r=_(t.database);try{return r.listEvents({type:e.type,result:e.result,limit:_g(e.limit)})}finally{r.close()}}async function La(e){let t=f(e.home),r=await Zo(e);return await h({home:t.home,type:"audit_exported",details:{format:e.format,count:r.length,type:e.type??null,result:e.result??null}}),{format:e.format,events:r}}function _g(e){return Math.min(Math.max(e??50,1),500)}import Le from"node:path";import{existsSync as _y}from"node:fs";import{mkdir as oh,readdir as nh,readFile as ns,writeFile as ah}from"node:fs/promises";import{existsSync as sh}from"node:fs";import Fr from"node:path";Rt();ce();Ve();ce();import{readdir as xg}from"node:fs/promises";import ge from"node:path";var we="antigravity",jg="~/.gemini/GEMINI.md",Ig="~/.antigravity",Ha="official:antigravity-plugin-config:v1",wc="official:antigravity-hooks-config:v1",Rc="official:antigravity-mcp-config:v1",Sc="official:antigravity-command-config:v1",Tg="official:antigravity-context-config:v1",Cg="official:antigravity-features:v1",Og=[{uid:"antigravity:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"}];function $a(){let e=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();return e?ge.resolve(e):j(Ig)}function Ng(){let e=$a();return{root:e,globalInstruction:process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim()?ge.join(e,"GEMINI.md"):j(jg)}}async function Ac(){let e=[],t=Ng();await P(t.globalInstruction)&&e.push({uid:"antigravity:global-gemini-md",host:we,nativeKind:"global_context",normalizedKind:"instruction",source:t.globalInstruction,schemaHash:Tg}),await Mg(t.root,e),await Lg(t.root,e);for(let r of Og){let o=ge.join(t.root,r.relativePath);await W(o)&&e.push({uid:r.uid,host:we,nativeKind:r.nativeKind,normalizedKind:r.normalizedKind,source:o,schemaHash:Ha})}return e}async function Mg(e,t){let r=ge.join(e,"plugin.json"),o=ge.join(e,"nativesoul-package.json"),n=ge.join(e,"hooks.json"),a=ge.join(e,"mcp_config.json"),[s,i,l,c]=await Promise.all([Q(r),Q(o),Q(n),Q(a)]);if(s){let d=I(s,["name","id"])??"unknown";t.push({uid:`antigravity:plugin:${M(d)}`,host:we,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:Ha})}if(i){let d=I(i,["name","id"])??"unknown";t.push({uid:`antigravity:package:${M(d)}`,host:we,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:Ha});let p=O(i.nativeSoul)?i.nativeSoul:{};for(let k of tn(p.commands))t.push({uid:`antigravity:command:${M(k)}`,host:we,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${k}`,schemaHash:Sc});let g=O(p.mcpServer)?p.mcpServer:null,y=I(g,["name"]);y&&t.push({uid:`antigravity:mcp:${M(y)}`,host:we,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${y}`,schemaHash:Rc})}if(l){t.push({uid:"antigravity:hooks:manifest",host:we,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:wc});let d=O(l.hooks)?l.hooks:{};for(let p of Object.keys(d))t.push({uid:`antigravity:hook:${M(p)}`,host:we,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${p}`,schemaHash:wc})}if(c)for(let d of tt(c.mcpServers))t.push({uid:`antigravity:mcp:${M(d)}`,host:we,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${a}:mcpServers.${d}`,schemaHash:Rc});await Dg(ge.join(e,"commands"),t)}async function Lg(e,t){let r=ge.join(e,"features-evidence.json"),o=await Q(r);if(!o)return;let n=["scheduled_tasks","cron_schedules","background_agents","subagents","skills","mcps","json_hooks"];for(let a of n)o[a]===!0&&t.push({uid:`antigravity:feature:${a.replace(/_/gu,"-")}`,host:we,nativeKind:"product_feature",normalizedKind:"feature_evidence",source:`${r}:${a}`,schemaHash:Cg})}async function Dg(e,t){if(!await W(e))return;let r=await xg(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||ge.extname(o.name)!==".md")continue;let n=ge.basename(o.name,".md");t.push({uid:`antigravity:command:${M(n,{allowSlash:!0})}`,host:we,nativeKind:"command",normalizedKind:"command",source:ge.join(e,o.name),schemaHash:Sc})}}ce();Ve();import rn from"node:path";async function Ec(e){let t=await Hg(e);if(!t)return null;let r=await Q(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:O(r.contract)?{schedule:I(r.contract,["schedule"])??void 0,status:I(r.contract,["status"])??void 0,cancel:I(r.contract,["cancel"])??void 0,list:I(r.contract,["list"])??void 0,project_binding:I(r.contract,["project_binding"])??void 0}:void 0}:null}async function Hg(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 rn.join(rn.resolve(r),"scheduler-proof.json");let o=e??j("~/.antigravity"),n=[rn.join(o,"scheduler-proof.json"),rn.join(o,"native-scheduler-proof.json")];for(let a of n)if(await P(a))return a;return null}function Pc(e){if(!e)return!1;let t=Date.parse(e);return Number.isFinite(t)?Date.now()-t>10080*60*1e3:!0}var er="antigravity",Fa="~/.gemini/GEMINI.md",Ua=class{async detect(){let t=j(Fa),r=$a(),[o,n,a]=await Promise.all([P(t),W(r),Ue("agy")]);return{host:er,detected:n||a!==null,path:n?r:a??(o?t:void 0),capabilities:{installed:n||a!==null,enabled:n,active:!1,authenticated:!1,healthy:a!==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 Ac()}async hotProbe(){let t=await this.coldScan();return{host:er,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 Ec(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(Pc(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=j(Fa),o=await K(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&&!Z(o,er)&&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=j(Fa),r=await K(t);return{host:er,targetPath:t,startMarker:"<!-- nativesoul:antigravity:start v1 -->",endMarker:"<!-- nativesoul:antigravity:end -->",content:Ne(er),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,er)}}};function xc(){return new Ua}Rt();Ve();ce();import tr from"node:path";import{readFile as Gc}from"node:fs/promises";Ve();import{readFile as Uc}from"node:fs/promises";import zg from"node:path";var Wc="life:heartbeat";function Jc(e){if(!e||typeof e!="object"||Array.isArray(e))return{kind:"unknown",mode:"leader",apply:!1,skill:Wc};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:ef(t),surface:Vc(t.surface)??Vc(O(t.desired)?t.desired.surface:void 0)}}async function qc(e={}){let t=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_FIXTURES;if(t)try{return Bc(await Uc(zg.join(t,"scheduled-tasks.json"),"utf8"))}catch{return null}let r=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_MANIFEST;if(r)try{return Bc(await Uc(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(()=>(Fc(),$c));return o({apply:e.apply,surface:e.surface,hostConfigRoot:e.hostConfigRoot})}function Kc(e,t){return!e||e==="default"||!t?!0:e===t}function Bc(e){let t=Be(e);if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=Yg(r.surface),n=Qg(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:Zg(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 Vc(e){return e==="default"||e==="claude-code"||e==="claude-desktop"?e:void 0}function Yg(e){return e==="claude-code"||e==="claude-desktop"||e==="cloud"?e:void 0}function Qg(e){return e==="local_scheduled_task"||e==="cloud_routine"||e==="ui_only"?e:"unknown"}function Zg(e){return e==="official_machine_readable"||e==="ui_only"||e==="unknown"?e:void 0}function ef(e){return O(e.desired)&&typeof e.desired.skill=="string"&&e.desired.skill.trim().length>0?e.desired.skill.trim():Wc}var de="claude",on="~/.claude/CLAUDE.md",Xc="CLAUDE.md",zc=".claude/CLAUDE.md",Yc="life:heartbeat",Zc="official:claude-cli-hot-scan:v1",Va=class{async detect(){let t=j(on),r=tr.resolve(Xc),o=tr.resolve(zc),[n,a,s,i]=await Promise.all([P(t),P(r),P(o),en("claude",["--version"])]);return{host:de,detected:n||a||s||i!==null,version:i??void 0,path:n?t:a?r:s?o:void 0,capabilities:{installed:n||a||s||i!==null,enabled:n||a||s,active:a||s,authenticated:!1,healthy:i!==null||n||a||s,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Claude install writes are not implemented in M2.1; use managed-block preview first."}}async uninstall(t){return{status:"unsupported",reason:"Claude uninstall writes are not implemented in M2.1."}}async coldScan(){let t=j(on),r=tr.resolve(Xc),o=tr.resolve(zc),n=[];return await P(t)&&n.push({uid:"claude:global-claude-md",host:de,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await P(r)&&n.push({uid:"claude:project-claude-md",host:de,nativeKind:"project_context",normalizedKind:"instruction",source:r}),await P(o)&&n.push({uid:"claude:project-dot-claude-md",host:de,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 tf(o,r);if(l.status==="ready")return l}let[n,a]=await Promise.all([Da("claude",["mcp","list","--json"],1200),Da("claude",["plugin","list","--json"],1200)]),s=[],i=[];return n.status==="ok"?i.push(...ed(n.stdout)):s.push(Qc("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude mcp list --json",n.stderr)),a.status==="ok"?i.push(...td(a.stdout)):s.push(Qc("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude plugin list --json",a.stderr)),{host:de,checkedAt:r,status:s.length===0?"ready":"degraded",warnings:s.map(l=>l.code),remediation:s.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:s}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Claude reload is deferred until plugin lifecycle integration story."}}async update(t){return{status:"unsupported",reason:"Claude update is deferred until plugin lifecycle integration story."}}async scheduleReconcile(t){let r=Jc(t),o=await qc({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!==Yc?{status:"error",code:"CLAUDE_HEARTBEAT_SKILL_MISMATCH",message:`Claude heartbeat Scheduled Task must invoke ${Yc}.`}: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."}:Kc(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=j(on),o=await K(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&&!Z(o,de)&&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=j(on),r=await K(t);return{host:de,targetPath:t,startMarker:"<!-- nativesoul:claude:start v1 -->",endMarker:"<!-- nativesoul:claude:end -->",content:Ne(de),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,de)}}};async function tf(e,t){try{let[r,o]=await Promise.all([Gc(tr.join(e,"mcp-list.json"),"utf8"),Gc(tr.join(e,"plugin-list.json"),"utf8")]),n=[...ed(r),...td(o)];return{host:de,checkedAt:t,status:"ready",warnings:[],capabilities:n.map(a=>({...a,installed:a.installed??!0,enabled:a.enabled??!0,active:a.active??!0,authenticated:a.authenticated??!1,healthy:a.healthy??!0,allowed:!0,ready:a.ready??!1}))}}catch{return{host:de,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 ed(e){let t=Be(e);return rt(t,["servers","mcps","items"]).flatMap(r=>{let o=I(r,["name","id","server","server_name"]);if(!o)return[];let n=I(r,["status","state"]),a=n!=="disabled",s=n==="connected"||n==="ready"||n==="active"||n==="ok"||n==="authenticated";return[{uid:`claude:mcp:${M(o)}`,host:de,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`claude mcp list:${o}`,schemaHash:Zc,enabled:a,active:a,authenticated:ae(r,["authenticated"])??s,healthy:a,ready:rd(n)}]})}function td(e){let t=Be(e);return rt(t,["plugins","items"]).flatMap(r=>{let o=I(r,["id","plugin","package"])??I(r,["name"]);if(!o)return[];let n=I(r,["status","state"]),a=ae(r,["enabled"])??n!=="disabled",s=ae(r,["installed"])??!0;return[{uid:`claude:plugin:${rf(o)}`,host:de,nativeKind:"plugin",normalizedKind:"extension",source:`claude plugin list --json:${o}`,schemaHash:Zc,installed:s,enabled:a,active:a,authenticated:ae(r,["authenticated"])??a,healthy:s,ready:a&&(n===null||rd(n)||ae(r,["enabled"])===!0)}]})}function Qc(e,t,r){let o=of(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 rd(e){return e==="ready"||e==="enabled"||e==="active"||e==="ok"||e==="authenticated"||e==="connected"}function rf(e){return M(e,{allowSlash:!0})}function of(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 od(){return new Va}Rt();Ve();ce();import Ka from"node:path";var se="codex",an="~/.codex/AGENTS.md",id="AGENTS.md",wf=1e3,ld="life:heartbeat",ln="official:codex-app-server:v1",Ga=class{async detect(){let t=j(an),r=Ka.resolve(id),[o,n,a]=await Promise.all([P(t),P(r),Ue("codex")]);return{host:se,detected:o||n||a!==null,path:o?t:n?r:a??void 0,capabilities:{installed:o||n||a!==null,enabled:o||n,active:n,authenticated:!1,healthy:a!==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=j(an),r=Ka.resolve(id),o=[];return await P(t)&&o.push({uid:"codex:global-agents-md",host:se,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await P(r)&&o.push({uid:"codex:project-agents-md",host:se,nativeKind:"project_context",normalizedKind:"instruction",source:r}),o}async hotProbe(t){let r=new Date().toISOString(),o=xf(t);if(o){let i=await qa(o,r);if(i.status==="ready")return i}let n=process.env.NATIVESOUL_CODEX_APP_SERVER_FIXTURES?.trim();if(n){let i=await qa(If(n),r);if(i.status==="ready")return i}let a=jf(t);if(a){let i=await qa(Tf(a),r);if(i.status==="ready")return i}let s=await this.coldScan();return{host:se,checkedAt:r,status:"degraded",warnings:["CODEX_APP_SERVER_UNAVAILABLE"],remediation:"Start Codex App Server and set NATIVESOUL_CODEX_APP_SERVER_URL before running `nativesoul adapters hot-scan --host codex`.",capabilities:s.map(i=>({...i,source:`codex app server fallback config scan:${i.source}`,installed:!0,enabled:!0,active:i.uid.includes("project"),authenticated:!1,healthy:!0,allowed:!0,ready:!1})),diagnostics:[{code:"CODEX_APP_SERVER_UNAVAILABLE",severity:"warn",message:"Codex App Server inventory endpoint is not configured or did not respond with supported JSON.",remediation:"Set NATIVESOUL_CODEX_APP_SERVER_URL to a reachable Codex App Server endpoint."}]}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Codex reload is deferred until App Server integration story."}}async update(t){return{status:"unsupported",reason:"Codex update is deferred until marketplace/App Server integration story."}}async scheduleReconcile(t){let{discoverCodexAutomationsManifest:r}=await Promise.resolve().then(()=>(sd(),ad)),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!==ld?{status:"error",code:"CODEX_HEARTBEAT_SKILL_MISMATCH",message:`Codex heartbeat Automation must invoke ${ld}.`}: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=j(an),o=await K(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&&!Z(o,se)&&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=j(an),r=await K(t);return{host:se,targetPath:t,startMarker:"<!-- nativesoul:codex:start v1 -->",endMarker:"<!-- nativesoul:codex:end -->",content:Ne(se),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,se)}}};async function qa(e,t){let[r,o,n,a]=await Promise.all([sn(e,"mcpServerStatus/list"),sn(e,"plugin/list"),sn(e,"skills/list"),sn(e,"app/list")]);if([r,o,n,a].some(l=>l===null))return{host:se,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=[...Sf(r),...Af(o),...Ef(n),...Pf(a)];return{host:se,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 sn(e,t){try{return await e.call(t)}catch{return null}}async function Rf(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),wf);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 a=await n.json();return O(a)&&"error"in a?null:O(a)&&"result"in a?a.result:a}catch{return null}finally{clearTimeout(o)}}function Sf(e){return rt(e,["servers","mcpServers","items"]).flatMap(t=>{let r=I(t,["id","name","server","server_name"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:mcp:${M(r)}`,host:se,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`codex app server mcpServerStatus/list:${r}`,schemaHash:ln,...n}]})}function Af(e){return rt(e,["plugins","items"]).flatMap(t=>{let r=I(t,["id","plugin","package"])??I(t,["name"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:plugin:${Xa(r)}`,host:se,nativeKind:"plugin",normalizedKind:"extension",source:`codex app server plugin/list:${r}`,schemaHash:ln,...n}]})}function Ef(e){return rt(e,["skills","items"]).flatMap(t=>{let r=I(t,["id","name","path"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:skill:${Xa(r)}`,host:se,nativeKind:"skill",normalizedKind:"skill",source:`codex app server skills/list:${r}`,schemaHash:ln,...n}]})}function Pf(e){return rt(e,["apps","items"]).flatMap(t=>{let r=I(t,["id","name","app"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:app:${Xa(r)}`,host:se,nativeKind:"app_server_app",normalizedKind:"app",source:`codex app server app/list:${r}`,schemaHash:ln,...n}]})}function cn(e,t){let r=ae(e,["installed"])??!0,o=t==="disabled"||t==="unavailable",n=t==="error"||t==="unhealthy",a=ae(e,["enabled"])??!o,s=ae(e,["active"])??a,i=ae(e,["healthy"])??(!o&&!n),l=ae(e,["authenticated"])??ae(e,["auth"])??!1,c=ae(e,["ready"])??(r&&a&&s&&i);return{installed:r,enabled:a,active:s,authenticated:l,healthy:i,ready:c}}function xf(e){if(O(e)){let t=e.appServer;if(O(t)&&typeof t.call=="function")return{call:r=>Promise.resolve(t.call(r))}}return null}function jf(e){if(O(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 If(e){return{async call(t){try{let{readFile:r}=await import("node:fs/promises"),o=t.replace(/\//gu,"-");return JSON.parse(await r(Ka.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 Tf(e){return{call:t=>Rf(e,t)}}function Xa(e){return M(e,{allowSlash:!0})}function cd(){return new Ga}Rt();Ve();ce();import{readdir as ud}from"node:fs/promises";import Re from"node:path";var ee="gemini",Ya="~/.gemini/GEMINI.md",Cf="~/.gemini/extensions",Of="~/.gemini/settings.json",Or="official:gemini-extension-config:v1",za="official:gemini-settings-config:v1",Nf="official:gemini-memory-config:v1",Qa=class{async detect(){let t=dd(),r=t.globalInstruction,o=t.extensionsDirectory,[n,a,s]=await Promise.all([P(r),W(o),en("gemini",["--version"])]);return{host:ee,detected:n||a||s!==null,version:s??void 0,path:n?r:a?o:void 0,capabilities:{installed:n||a||s!==null,enabled:n||a,active:n,authenticated:!1,healthy:s!==null||n||a,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=dd(),o=r.globalInstruction;await P(o)&&t.push({uid:"gemini:global-gemini-md",host:ee,nativeKind:"global_context",normalizedKind:"memory",source:o,schemaHash:Nf}),await Mf(r.settingsFile,t);let n=r.extensionsDirectory;if(await W(n)){t.push({uid:"gemini:extensions",host:ee,nativeKind:"extensions",normalizedKind:"package",source:n,schemaHash:Or});let a=await ud(n,{withFileTypes:!0});for(let s of a)s.isDirectory()&&await Lf(Re.join(n,s.name),s.name,t)}return t}async hotProbe(){let t=await this.coldScan();return{host:ee,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=j(Ya),o=await K(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&&!Z(o,ee)&&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=j(Ya),r=await K(t);return{host:ee,targetPath:t,startMarker:"<!-- nativesoul:gemini:start v1 -->",endMarker:"<!-- nativesoul:gemini:end -->",content:Ne(ee),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,ee)}}};function dd(){let e=process.env.NATIVESOUL_GEMINI_INVENTORY_ROOT?.trim();if(e){let t=Re.resolve(e);return{globalInstruction:Re.join(t,"GEMINI.md"),settingsFile:Re.join(t,"settings.json"),extensionsDirectory:Re.join(t,"extensions")}}return{globalInstruction:j(Ya),settingsFile:j(Of),extensionsDirectory:j(Cf)}}async function Mf(e,t){let r=await Q(e);if(r){t.push({uid:"gemini:settings",host:ee,nativeKind:"settings",normalizedKind:"config",source:e,schemaHash:za});for(let o of tt(r.mcpServers))t.push({uid:`gemini:mcp:${M(o)}`,host:ee,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${e}:mcpServers.${o}`,schemaHash:za});for(let o of pd(r.tools))t.push({uid:`gemini:tool:${M(o)}`,host:ee,nativeKind:"tool",normalizedKind:"tool",source:`${e}:tools.${o}`,schemaHash:za})}}async function Lf(e,t,r){let o=Re.join(e,"gemini-extension.json"),n=await Q(o),a=I(n,["name","id"])??t;if(r.push({uid:`gemini:extension:${M(a)}`,host:ee,nativeKind:"extension",normalizedKind:"package",source:n?o:e,schemaHash:n?Or:void 0}),n){for(let s of tt(n.mcpServers))r.push({uid:`gemini:mcp:${M(s)}`,host:ee,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:mcpServers.${s}`,schemaHash:Or});for(let s of pd(n.tools))r.push({uid:`gemini:tool:${M(s)}`,host:ee,nativeKind:"tool",normalizedKind:"tool",source:`${o}:tools.${s}`,schemaHash:Or})}await Df(Re.join(e,"commands"),r)}async function Df(e,t){if(!await W(e))return;let r=await ud(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||![".toml",".md"].includes(Re.extname(o.name)))continue;let n=Re.basename(o.name,Re.extname(o.name));t.push({uid:`gemini:command:${M(n,{allowSlash:!0})}`,host:ee,nativeKind:"command",normalizedKind:"command",source:Re.join(e,o.name),schemaHash:Or})}}function pd(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):tt(e)}function md(){return new Qa}Rt();Ve();ce();import{readdir as _d}from"node:fs/promises";import q from"node:path";var J="grok",dn="~/.grok/Agents.md",gd="AGENTS.md",fd="Agents.md",hd="CLAUDE.md",Hf="~/.grok",Za="official:grok-plugin-config:v1",yd="official:grok-hooks-config:v1",es="official:grok-mcp-config:v1",bd="official:grok-command-config:v1",$f="official:grok-context-config:v1",Ff=[{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"}],ts=class{async detect(){let t=j(dn),r=q.resolve(gd),o=q.resolve(fd),n=q.resolve(hd),a=vd(),[s,i,l,c,d,p]=await Promise.all([P(t),P(r),P(o),P(n),W(a),Ue("grok")]),g=i||l;return{host:J,detected:s||g||c||d||p!==null,path:s?t:l?o:i?r:c?n:p??void 0,capabilities:{installed:s||g||c||d||p!==null,enabled:s||g||c||d,active:g||c,authenticated:!1,healthy:p!==null||s||d,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=Uf(),o=r.globalInstruction;await P(o)&&t.push({uid:"grok:global-agents-md",host:J,nativeKind:"global_context",normalizedKind:"instruction",source:o,schemaHash:$f});let n=q.resolve(gd);await P(n)&&t.push({uid:"grok:project-agents-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:n});let a=q.resolve(fd);await P(a)&&t.push({uid:"grok:project-agents-titlecase-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:a});let s=q.resolve(hd);await P(s)&&t.push({uid:"grok:project-claude-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:s});let i=r.root;await kd(r.root,t),await Bf(i,t);for(let l of Ff){let c=q.join(i,l.relativePath);await W(c)&&t.push({uid:l.uid,host:J,nativeKind:l.nativeKind,normalizedKind:l.normalizedKind,source:c,schemaHash:l.relativePath==="mcps"?es:Za})}return Wf(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=j(dn),o=await K(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&&!Z(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=j(dn),r=await K(t);return{host:J,targetPath:t,startMarker:"<!-- nativesoul:grok:start v1 -->",endMarker:"<!-- nativesoul:grok:end -->",content:Ne(J),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,J)}}};function vd(){let e=process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim();return e?q.resolve(e):j(Hf)}function Uf(){let e=vd();return{root:e,globalInstruction:process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim()?q.join(e,"Agents.md"):j(dn)}}async function kd(e,t){let r=q.join(e,"plugin.json"),o=q.join(e,"nativesoul-package.json"),n=q.join(e,"hooks","hooks.json"),a=q.join(e,".mcp.json"),[s,i,l,c]=await Promise.all([Q(r),Q(o),Q(n),Q(a)]);if(s){let d=I(s,["name","id"])??"unknown";t.push({uid:`grok:plugin:${M(d)}`,host:J,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:Za})}if(i){let d=I(i,["name","id"])??"unknown";t.push({uid:`grok:package:${M(d)}`,host:J,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:Za});let p=O(i.nativeSoul)?i.nativeSoul:{};for(let k of tn(p.commands))t.push({uid:`grok:command:${M(k)}`,host:J,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${k}`,schemaHash:bd});let g=O(p.mcpServer)?p.mcpServer:null,y=I(g,["name"]);y&&t.push({uid:`grok:mcp:${M(y)}`,host:J,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${y}`,schemaHash:es})}if(l){t.push({uid:"grok:hooks:manifest",host:J,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:yd});let d=O(l.hooks)?l.hooks:{};for(let p of Object.keys(d))t.push({uid:`grok:hook:${M(p)}`,host:J,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${p}`,schemaHash:yd})}if(c)for(let d of tt(c.mcpServers))t.push({uid:`grok:mcp:${M(d)}`,host:J,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${a}:mcpServers.${d}`,schemaHash:es});await Vf(q.join(e,"commands"),t)}async function Bf(e,t){let r=q.join(e,"plugins");if(!await W(r))return;let o=await _d(r,{withFileTypes:!0});for(let n of o)n.isDirectory()&&await kd(q.join(r,n.name),t)}async function Vf(e,t){if(!await W(e))return;let r=await _d(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||q.extname(o.name)!==".md")continue;let n=q.basename(o.name,".md");t.push({uid:`grok:command:${M(n,{allowSlash:!0})}`,host:J,nativeKind:"command",normalizedKind:"command",source:q.join(e,o.name),schemaHash:bd})}}function Wf(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 wd(){return new ts}import{mkdir as un,readFile as pn,rm as Yf,writeFile as mn}from"node:fs/promises";import{existsSync as gn}from"node:fs";import Nr from"node:path";import{lstatSync as Jf,realpathSync as qf,statSync as Kf}from"node:fs";import We from"node:path";var Gf=process.platform!=="win32";function Xf(){let e=process.getuid;return typeof e=="function"?e.call(process):void 0}function Rd(e){let t=e,r=[];for(;;)try{let o=qf(t);return r.length?We.join(o,...r):o}catch{let o=We.dirname(t);if(o===t)return e;r.unshift(We.basename(t)),t=o}}function zf(e,t){let r=We.relative(e,t);return r===""||!r.startsWith("..")&&!We.isAbsolute(r)}function Sd(e,t={}){if(!e||typeof e!="string")return{ok:!1,code:"PATH_ESCAPES_ROOT",detail:"empty or non-string target path"};let r=We.resolve(e);if(t.protectedFiles?.length&&new Set(t.protectedFiles.map(a=>We.resolve(a))).has(r))return{ok:!1,code:"PROTECTED_FILE_DIRECT_WRITE",detail:`${r} is protected; write via a proposal`};try{if(Jf(r).isSymbolicLink()&&!t.allowSymlinkTarget)return{ok:!1,code:"SYMLINK_TARGET_UNSAFE",detail:`${r} is a symlink`}}catch{}let o=We.dirname(r);try{let n=Kf(o);if(Gf){let a=(n.mode&2)!==0,s=(n.mode&512)!==0;if(a&&!s)return{ok:!1,code:"WORLD_WRITABLE_PATH",detail:`${o} is world-writable`};let i=t.uid??Xf();if(i!==void 0&&n.uid!==i)return{ok:!1,code:"SUSPICIOUS_OWNER",detail:`${o} owned by uid ${n.uid}, expected ${i}`}}}catch{}if(t.root){let n=Rd(We.resolve(t.root)),a=Rd(r);if(!zf(n,a))return{ok:!1,code:"PATH_ESCAPES_ROOT",detail:`${a} escapes ${n}`}}return{ok:!0,normalizedPath:r}}function Se(e,t={}){let r=Sd(e,t);if(!r.ok)throw new Error(`unsafe write path (${r.code}): ${r.detail}`);return r.normalizedPath}function fn(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}async function Ad(e){let t=f(e.home),r=gn(e.targetPath),o=r?await pn(e.targetPath,"utf8"):null,n=Zf(o,e.host,e.block),a=o===null?null:A(o),s=A(n),i=eh(o,n,e.host),l=i!=="noop",c=!e.apply,d=l&&e.apply?await jd(t.home,e.host,e.targetPath,r,o,s):null;l&&e.apply&&(Se(e.targetPath,{allowSymlinkTarget:!0}),await un(Nr.dirname(e.targetPath),{recursive:!0,mode:448}),await mn(e.targetPath,n,{encoding:"utf8",mode:384}));let p={host:e.host,targetPath:e.targetPath,action:i,dryRun:c,changed:l,beforeHash:a,afterHash:s,diff:Id(o,n),backupPath:d,applied:l&&e.apply};return await h({home:t.home,type:e.apply?"managed_block_apply":"managed_block_dry_run",details:p}),p}async function Ed(e){let t=f(e.home),r=gn(e.targetPath),o=r?await pn(e.targetPath,"utf8"):null,n=Qf(o,e.host),a=o===null?null:A(o),s=n===null?A(""):A(n),i=o!==n?"remove":"noop",l=i!=="noop",c=!e.apply,d=l&&e.apply?await jd(t.home,e.host,e.targetPath,r,o,s):null;l&&e.apply&&n!==null&&(await un(Nr.dirname(e.targetPath),{recursive:!0,mode:448}),await mn(e.targetPath,n,{encoding:"utf8",mode:384}));let p={host:e.host,targetPath:e.targetPath,action:i,dryRun:c,changed:l,beforeHash:a,afterHash:s,diff:Id(o,n),backupPath:d,applied:l&&e.apply};return await h({home:t.home,type:e.apply?"managed_block_uninstall":"managed_block_uninstall_dry_run",details:p}),p}async function Pd(e){let t=gn(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 pn(e.targetPath,"utf8"),n=fn(e.host),a=o.indexOf(n.start),s=o.indexOf(n.end),i=a>=0,l=s>=0,c=i&&l&&s>a;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}}async function xd(e){let t=f(e.home),r=JSON.parse(await pn(e.snapshotPath,"utf8")),o=!e.apply;e.apply&&(r.beforeExists&&r.beforeContent!==null?(await un(Nr.dirname(r.targetPath),{recursive:!0,mode:448}),await mn(r.targetPath,r.beforeContent,{encoding:"utf8",mode:384})):gn(r.targetPath)&&await Yf(r.targetPath));let n={snapshotPath:e.snapshotPath,targetPath:r.targetPath,dryRun:o,applied:e.apply,restoredExists:r.beforeExists,restoredHash:r.beforeHash};return await h({home:t.home,type:e.apply?"managed_block_rollback":"managed_block_rollback_dry_run",details:n}),n}function Qf(e,t){if(e===null)return null;let{start:r,end:o}=fn(t),n=e.indexOf(r),a=e.indexOf(o);if(n<0||a<=n)return e;let s=a+o.length,i=e.slice(0,n),l=e.slice(s);return i.endsWith(`
|
|
822
|
+
`}var mg=["memory/daily","memory/projects","memory/archive","commitments","standing-orders","capabilities/cards","generated","state","logs","backups","proposals"],gg=Qo;function _c(e){return Oe.resolve(e??process.env.NATIVESOUL_HOME??Oe.join(pg.homedir(),".nativesoul"))}function f(e){let t=_c(e);return{home:t,database:Oe.join(t,"state","nativesoul.sqlite"),auditLog:Oe.join(t,"logs","audit.jsonl")}}async function S(e){try{return await ug(e,dg.F_OK),!0}catch{return!1}}async function v(e){let t=f(e),r=[],o=[],n=[];yc(t.home)||(await hc(t.home,{recursive:!0,mode:448}),r.push(t.home));for(let i of mg){let l=Oe.join(t.home,i);yc(l)||(await hc(l,{recursive:!0,mode:448}),r.push(l))}let a=await S(Oe.join(t.home,"state","onboarding.complete"));for(let[i,l]of Object.entries(gg)){if(i==="BOOTSTRAP.md"&&a)continue;let c=Oe.join(t.home,i);if(await S(c)){n.push(c);continue}try{await Oa(c,l,{encoding:"utf8",mode:384,flag:"wx"}),o.push(c)}catch(d){if(fg(d)){n.push(c);continue}throw d}}let s=await hg(t.home);return o.push(...s.createdFiles),n.push(...s.preservedFiles),{home:t.home,database:t.database,createdDirectories:r,createdFiles:o,preservedFiles:n}}function fg(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}async function hg(e){let t=[],r=[],o=new Date().toISOString().slice(0,10),n=Oe.join(e,"memory","daily",`${o}.md`);await S(n)?r.push(n):(await Oa(n,fc(o),{encoding:"utf8",mode:384,flag:"wx"}),t.push(n));let a=Oe.join(e,"standing-orders","example.yaml");return await S(a)?r.push(a):(await Oa(a,gc,{encoding:"utf8",mode:384,flag:"wx"}),t.push(a)),{createdFiles:t,preservedFiles:r}}async function me(e,t){let r=Oe.join(e,t);return await S(r)?cg(r,"utf8"):""}async function h(e){let t=f(e.home),r=new Date().toISOString(),o=Ma(H(e.details??{}),t.home),n={id:T("evt"),type:e.type,actor:e.actor??"cli",origin:e.origin??"nativesoul",result:e.result??"ok",details:o,created_at:r,hash:ke({type:e.type,actor:e.actor??"cli",origin:e.origin??"nativesoul",result:e.result??"ok",details:o,created_at:r})},a=_(t.database);try{a.insertEvent(n)}finally{a.close()}return await _g(vg.dirname(t.auditLog),{recursive:!0,mode:448}),await yg(t.auditLog,`${JSON.stringify(n)}
|
|
823
|
+
`,{encoding:"utf8",mode:384}),n}function Ma(e,t){if(typeof e=="string")return kg(e,t);if(Array.isArray(e))return e.map(r=>Ma(r,t));if(e&&typeof e=="object"){let r={};for(let[o,n]of Object.entries(e))r[o]=Ma(n,t);return r}return e}function kg(e,t){return[[new RegExp(Na(t),"gu"),"[REDACTED_NATIVESOUL_HOME]"],[new RegExp(Na(process.cwd()),"gu"),"[REDACTED_WORKSPACE]"],[new RegExp(Na(bg.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,a])=>o.replace(n,a),e)}function Na(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function Zo(e){let t=f(e.home),r=_(t.database);try{return r.listEvents({type:e.type,result:e.result,limit:wg(e.limit)})}finally{r.close()}}async function La(e){let t=f(e.home),r=await Zo(e);return await h({home:t.home,type:"audit_exported",details:{format:e.format,count:r.length,type:e.type??null,result:e.result??null}}),{format:e.format,events:r}}function wg(e){return Math.min(Math.max(e??50,1),500)}import Le from"node:path";import{existsSync as wy}from"node:fs";import{mkdir as ih,readdir as lh,readFile as ns,writeFile as ch}from"node:fs/promises";import{existsSync as dh}from"node:fs";import Fr from"node:path";Rt();ce();Ve();ce();import{readdir as Cg}from"node:fs/promises";import ge from"node:path";var we="antigravity",Og="~/.gemini/GEMINI.md",Ng="~/.antigravity",Ha="official:antigravity-plugin-config:v1",Rc="official:antigravity-hooks-config:v1",Sc="official:antigravity-mcp-config:v1",Ac="official:antigravity-command-config:v1",Mg="official:antigravity-context-config:v1",Lg="official:antigravity-features:v1",Dg=[{uid:"antigravity:plugins",nativeKind:"plugins",normalizedKind:"package",relativePath:"plugins"}];function $a(){let e=process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim();return e?ge.resolve(e):j(Ng)}function Hg(){let e=$a();return{root:e,globalInstruction:process.env.NATIVESOUL_ANTIGRAVITY_INVENTORY_ROOT?.trim()?ge.join(e,"GEMINI.md"):j(Og)}}async function Ec(){let e=[],t=Hg();await P(t.globalInstruction)&&e.push({uid:"antigravity:global-gemini-md",host:we,nativeKind:"global_context",normalizedKind:"instruction",source:t.globalInstruction,schemaHash:Mg}),await $g(t.root,e),await Fg(t.root,e);for(let r of Dg){let o=ge.join(t.root,r.relativePath);await W(o)&&e.push({uid:r.uid,host:we,nativeKind:r.nativeKind,normalizedKind:r.normalizedKind,source:o,schemaHash:Ha})}return e}async function $g(e,t){let r=ge.join(e,"plugin.json"),o=ge.join(e,"nativesoul-package.json"),n=ge.join(e,"hooks.json"),a=ge.join(e,"mcp_config.json"),[s,i,l,c]=await Promise.all([Q(r),Q(o),Q(n),Q(a)]);if(s){let d=I(s,["name","id"])??"unknown";t.push({uid:`antigravity:plugin:${M(d)}`,host:we,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:Ha})}if(i){let d=I(i,["name","id"])??"unknown";t.push({uid:`antigravity:package:${M(d)}`,host:we,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:Ha});let p=O(i.nativeSoul)?i.nativeSoul:{};for(let k of tn(p.commands))t.push({uid:`antigravity:command:${M(k)}`,host:we,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${k}`,schemaHash:Ac});let g=O(p.mcpServer)?p.mcpServer:null,y=I(g,["name"]);y&&t.push({uid:`antigravity:mcp:${M(y)}`,host:we,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${y}`,schemaHash:Sc})}if(l){t.push({uid:"antigravity:hooks:manifest",host:we,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:Rc});let d=O(l.hooks)?l.hooks:{};for(let p of Object.keys(d))t.push({uid:`antigravity:hook:${M(p)}`,host:we,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${p}`,schemaHash:Rc})}if(c)for(let d of tt(c.mcpServers))t.push({uid:`antigravity:mcp:${M(d)}`,host:we,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${a}:mcpServers.${d}`,schemaHash:Sc});await Ug(ge.join(e,"commands"),t)}async function Fg(e,t){let r=ge.join(e,"features-evidence.json"),o=await Q(r);if(!o)return;let n=["scheduled_tasks","cron_schedules","background_agents","subagents","skills","mcps","json_hooks"];for(let a of n)o[a]===!0&&t.push({uid:`antigravity:feature:${a.replace(/_/gu,"-")}`,host:we,nativeKind:"product_feature",normalizedKind:"feature_evidence",source:`${r}:${a}`,schemaHash:Lg})}async function Ug(e,t){if(!await W(e))return;let r=await Cg(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||ge.extname(o.name)!==".md")continue;let n=ge.basename(o.name,".md");t.push({uid:`antigravity:command:${M(n,{allowSlash:!0})}`,host:we,nativeKind:"command",normalizedKind:"command",source:ge.join(e,o.name),schemaHash:Ac})}}ce();Ve();import rn from"node:path";async function Pc(e){let t=await Bg(e);if(!t)return null;let r=await Q(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:O(r.contract)?{schedule:I(r.contract,["schedule"])??void 0,status:I(r.contract,["status"])??void 0,cancel:I(r.contract,["cancel"])??void 0,list:I(r.contract,["list"])??void 0,project_binding:I(r.contract,["project_binding"])??void 0}:void 0}:null}async function Bg(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 rn.join(rn.resolve(r),"scheduler-proof.json");let o=e??j("~/.antigravity"),n=[rn.join(o,"scheduler-proof.json"),rn.join(o,"native-scheduler-proof.json")];for(let a of n)if(await P(a))return a;return null}function xc(e){if(!e)return!1;let t=Date.parse(e);return Number.isFinite(t)?Date.now()-t>10080*60*1e3:!0}var er="antigravity",Fa="~/.gemini/GEMINI.md",Ua=class{async detect(){let t=j(Fa),r=$a(),[o,n,a]=await Promise.all([P(t),W(r),Ue("agy")]);return{host:er,detected:n||a!==null,path:n?r:a??(o?t:void 0),capabilities:{installed:n||a!==null,enabled:n,active:!1,authenticated:!1,healthy:a!==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 Ec()}async hotProbe(){let t=await this.coldScan();return{host:er,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 Pc(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(xc(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=j(Fa),o=await K(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&&!Z(o,er)&&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=j(Fa),r=await K(t);return{host:er,targetPath:t,startMarker:"<!-- nativesoul:antigravity:start v1 -->",endMarker:"<!-- nativesoul:antigravity:end -->",content:Ne(er),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,er)}}};function jc(){return new Ua}Rt();Ve();ce();import tr from"node:path";import{readFile as Xc}from"node:fs/promises";Ve();import{readFile as Bc}from"node:fs/promises";import ef from"node:path";var Jc="life:heartbeat";function qc(e){if(!e||typeof e!="object"||Array.isArray(e))return{kind:"unknown",mode:"leader",apply:!1,skill:Jc};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:nf(t),surface:Wc(t.surface)??Wc(O(t.desired)?t.desired.surface:void 0)}}async function Kc(e={}){let t=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_FIXTURES;if(t)try{return Vc(await Bc(ef.join(t,"scheduled-tasks.json"),"utf8"))}catch{return null}let r=process.env.NATIVESOUL_CLAUDE_SCHEDULED_TASKS_MANIFEST;if(r)try{return Vc(await Bc(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(()=>(Uc(),Fc));return o({apply:e.apply,surface:e.surface,hostConfigRoot:e.hostConfigRoot})}function Gc(e,t){return!e||e==="default"||!t?!0:e===t}function Vc(e){let t=Be(e);if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=tf(r.surface),n=rf(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:of(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 Wc(e){return e==="default"||e==="claude-code"||e==="claude-desktop"?e:void 0}function tf(e){return e==="claude-code"||e==="claude-desktop"||e==="cloud"?e:void 0}function rf(e){return e==="local_scheduled_task"||e==="cloud_routine"||e==="ui_only"?e:"unknown"}function of(e){return e==="official_machine_readable"||e==="ui_only"||e==="unknown"?e:void 0}function nf(e){return O(e.desired)&&typeof e.desired.skill=="string"&&e.desired.skill.trim().length>0?e.desired.skill.trim():Jc}var de="claude",on="~/.claude/CLAUDE.md",zc="CLAUDE.md",Yc=".claude/CLAUDE.md",Qc="life:heartbeat",ed="official:claude-cli-hot-scan:v1",Va=class{async detect(){let t=j(on),r=tr.resolve(zc),o=tr.resolve(Yc),[n,a,s,i]=await Promise.all([P(t),P(r),P(o),en("claude",["--version"])]);return{host:de,detected:n||a||s||i!==null,version:i??void 0,path:n?t:a?r:s?o:void 0,capabilities:{installed:n||a||s||i!==null,enabled:n||a||s,active:a||s,authenticated:!1,healthy:i!==null||n||a||s,allowed:!0,ready:!1}}}async install(t){return{status:"unsupported",reason:"Claude install writes are not implemented in M2.1; use managed-block preview first."}}async uninstall(t){return{status:"unsupported",reason:"Claude uninstall writes are not implemented in M2.1."}}async coldScan(){let t=j(on),r=tr.resolve(zc),o=tr.resolve(Yc),n=[];return await P(t)&&n.push({uid:"claude:global-claude-md",host:de,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await P(r)&&n.push({uid:"claude:project-claude-md",host:de,nativeKind:"project_context",normalizedKind:"instruction",source:r}),await P(o)&&n.push({uid:"claude:project-dot-claude-md",host:de,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 af(o,r);if(l.status==="ready")return l}let[n,a]=await Promise.all([Da("claude",["mcp","list","--json"],1200),Da("claude",["plugin","list","--json"],1200)]),s=[],i=[];return n.status==="ok"?i.push(...td(n.stdout)):s.push(Zc("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude mcp list --json",n.stderr)),a.status==="ok"?i.push(...rd(a.stdout)):s.push(Zc("CLAUDE_HOT_SCAN_JSON_UNSUPPORTED","claude plugin list --json",a.stderr)),{host:de,checkedAt:r,status:s.length===0?"ready":"degraded",warnings:s.map(l=>l.code),remediation:s.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:s}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Claude reload is deferred until plugin lifecycle integration story."}}async update(t){return{status:"unsupported",reason:"Claude update is deferred until plugin lifecycle integration story."}}async scheduleReconcile(t){let r=qc(t),o=await Kc({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!==Qc?{status:"error",code:"CLAUDE_HEARTBEAT_SKILL_MISMATCH",message:`Claude heartbeat Scheduled Task must invoke ${Qc}.`}: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."}:Gc(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=j(on),o=await K(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&&!Z(o,de)&&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=j(on),r=await K(t);return{host:de,targetPath:t,startMarker:"<!-- nativesoul:claude:start v1 -->",endMarker:"<!-- nativesoul:claude:end -->",content:Ne(de),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,de)}}};async function af(e,t){try{let[r,o]=await Promise.all([Xc(tr.join(e,"mcp-list.json"),"utf8"),Xc(tr.join(e,"plugin-list.json"),"utf8")]),n=[...td(r),...rd(o)];return{host:de,checkedAt:t,status:"ready",warnings:[],capabilities:n.map(a=>({...a,installed:a.installed??!0,enabled:a.enabled??!0,active:a.active??!0,authenticated:a.authenticated??!1,healthy:a.healthy??!0,allowed:!0,ready:a.ready??!1}))}}catch{return{host:de,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 td(e){let t=Be(e);return rt(t,["servers","mcps","items"]).flatMap(r=>{let o=I(r,["name","id","server","server_name"]);if(!o)return[];let n=I(r,["status","state"]),a=n!=="disabled",s=n==="connected"||n==="ready"||n==="active"||n==="ok"||n==="authenticated";return[{uid:`claude:mcp:${M(o)}`,host:de,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`claude mcp list:${o}`,schemaHash:ed,enabled:a,active:a,authenticated:ae(r,["authenticated"])??s,healthy:a,ready:od(n)}]})}function rd(e){let t=Be(e);return rt(t,["plugins","items"]).flatMap(r=>{let o=I(r,["id","plugin","package"])??I(r,["name"]);if(!o)return[];let n=I(r,["status","state"]),a=ae(r,["enabled"])??n!=="disabled",s=ae(r,["installed"])??!0;return[{uid:`claude:plugin:${sf(o)}`,host:de,nativeKind:"plugin",normalizedKind:"extension",source:`claude plugin list --json:${o}`,schemaHash:ed,installed:s,enabled:a,active:a,authenticated:ae(r,["authenticated"])??a,healthy:s,ready:a&&(n===null||od(n)||ae(r,["enabled"])===!0)}]})}function Zc(e,t,r){let o=lf(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 od(e){return e==="ready"||e==="enabled"||e==="active"||e==="ok"||e==="authenticated"||e==="connected"}function sf(e){return M(e,{allowSlash:!0})}function lf(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 nd(){return new Va}Rt();Ve();ce();import Ka from"node:path";var se="codex",an="~/.codex/AGENTS.md",ld="AGENTS.md",Ef=1e3,cd="life:heartbeat",ln="official:codex-app-server:v1",Ga=class{async detect(){let t=j(an),r=Ka.resolve(ld),[o,n,a]=await Promise.all([P(t),P(r),Ue("codex")]);return{host:se,detected:o||n||a!==null,path:o?t:n?r:a??void 0,capabilities:{installed:o||n||a!==null,enabled:o||n,active:n,authenticated:!1,healthy:a!==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=j(an),r=Ka.resolve(ld),o=[];return await P(t)&&o.push({uid:"codex:global-agents-md",host:se,nativeKind:"global_context",normalizedKind:"instruction",source:t}),await P(r)&&o.push({uid:"codex:project-agents-md",host:se,nativeKind:"project_context",normalizedKind:"instruction",source:r}),o}async hotProbe(t){let r=new Date().toISOString(),o=Cf(t);if(o){let i=await qa(o,r);if(i.status==="ready")return i}let n=process.env.NATIVESOUL_CODEX_APP_SERVER_FIXTURES?.trim();if(n){let i=await qa(Nf(n),r);if(i.status==="ready")return i}let a=Of(t);if(a){let i=await qa(Mf(a),r);if(i.status==="ready")return i}let s=await this.coldScan();return{host:se,checkedAt:r,status:"degraded",warnings:["CODEX_APP_SERVER_UNAVAILABLE"],remediation:"Start Codex App Server and set NATIVESOUL_CODEX_APP_SERVER_URL before running `nativesoul adapters hot-scan --host codex`.",capabilities:s.map(i=>({...i,source:`codex app server fallback config scan:${i.source}`,installed:!0,enabled:!0,active:i.uid.includes("project"),authenticated:!1,healthy:!0,allowed:!0,ready:!1})),diagnostics:[{code:"CODEX_APP_SERVER_UNAVAILABLE",severity:"warn",message:"Codex App Server inventory endpoint is not configured or did not respond with supported JSON.",remediation:"Set NATIVESOUL_CODEX_APP_SERVER_URL to a reachable Codex App Server endpoint."}]}}async bootstrap(){return{tier:"B",mechanism:"global-instruction",supported:!0}}async reload(t){return{status:"unsupported",reason:"Codex reload is deferred until App Server integration story."}}async update(t){return{status:"unsupported",reason:"Codex update is deferred until marketplace/App Server integration story."}}async scheduleReconcile(t){let{discoverCodexAutomationsManifest:r}=await Promise.resolve().then(()=>(id(),sd)),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!==cd?{status:"error",code:"CODEX_HEARTBEAT_SKILL_MISMATCH",message:`Codex heartbeat Automation must invoke ${cd}.`}: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=j(an),o=await K(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&&!Z(o,se)&&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=j(an),r=await K(t);return{host:se,targetPath:t,startMarker:"<!-- nativesoul:codex:start v1 -->",endMarker:"<!-- nativesoul:codex:end -->",content:Ne(se),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,se)}}};async function qa(e,t){let[r,o,n,a]=await Promise.all([sn(e,"mcpServerStatus/list"),sn(e,"plugin/list"),sn(e,"skills/list"),sn(e,"app/list")]);if([r,o,n,a].some(l=>l===null))return{host:se,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=[...xf(r),...jf(o),...If(n),...Tf(a)];return{host:se,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 sn(e,t){try{return await e.call(t)}catch{return null}}async function Pf(e,t){let r=new AbortController,o=setTimeout(()=>r.abort(),Ef);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 a=await n.json();return O(a)&&"error"in a?null:O(a)&&"result"in a?a.result:a}catch{return null}finally{clearTimeout(o)}}function xf(e){return rt(e,["servers","mcpServers","items"]).flatMap(t=>{let r=I(t,["id","name","server","server_name"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:mcp:${M(r)}`,host:se,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`codex app server mcpServerStatus/list:${r}`,schemaHash:ln,...n}]})}function jf(e){return rt(e,["plugins","items"]).flatMap(t=>{let r=I(t,["id","plugin","package"])??I(t,["name"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:plugin:${Xa(r)}`,host:se,nativeKind:"plugin",normalizedKind:"extension",source:`codex app server plugin/list:${r}`,schemaHash:ln,...n}]})}function If(e){return rt(e,["skills","items"]).flatMap(t=>{let r=I(t,["id","name","path"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:skill:${Xa(r)}`,host:se,nativeKind:"skill",normalizedKind:"skill",source:`codex app server skills/list:${r}`,schemaHash:ln,...n}]})}function Tf(e){return rt(e,["apps","items"]).flatMap(t=>{let r=I(t,["id","name","app"]);if(!r)return[];let o=I(t,["status","state"]),n=cn(t,o);return[{uid:`codex:app:${Xa(r)}`,host:se,nativeKind:"app_server_app",normalizedKind:"app",source:`codex app server app/list:${r}`,schemaHash:ln,...n}]})}function cn(e,t){let r=ae(e,["installed"])??!0,o=t==="disabled"||t==="unavailable",n=t==="error"||t==="unhealthy",a=ae(e,["enabled"])??!o,s=ae(e,["active"])??a,i=ae(e,["healthy"])??(!o&&!n),l=ae(e,["authenticated"])??ae(e,["auth"])??!1,c=ae(e,["ready"])??(r&&a&&s&&i);return{installed:r,enabled:a,active:s,authenticated:l,healthy:i,ready:c}}function Cf(e){if(O(e)){let t=e.appServer;if(O(t)&&typeof t.call=="function")return{call:r=>Promise.resolve(t.call(r))}}return null}function Of(e){if(O(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 Nf(e){return{async call(t){try{let{readFile:r}=await import("node:fs/promises"),o=t.replace(/\//gu,"-");return JSON.parse(await r(Ka.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 Mf(e){return{call:t=>Pf(e,t)}}function Xa(e){return M(e,{allowSlash:!0})}function dd(){return new Ga}Rt();Ve();ce();import{readdir as pd}from"node:fs/promises";import Re from"node:path";var ee="gemini",Ya="~/.gemini/GEMINI.md",Lf="~/.gemini/extensions",Df="~/.gemini/settings.json",Or="official:gemini-extension-config:v1",za="official:gemini-settings-config:v1",Hf="official:gemini-memory-config:v1",Qa=class{async detect(){let t=ud(),r=t.globalInstruction,o=t.extensionsDirectory,[n,a,s]=await Promise.all([P(r),W(o),en("gemini",["--version"])]);return{host:ee,detected:n||a||s!==null,version:s??void 0,path:n?r:a?o:void 0,capabilities:{installed:n||a||s!==null,enabled:n||a,active:n,authenticated:!1,healthy:s!==null||n||a,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=ud(),o=r.globalInstruction;await P(o)&&t.push({uid:"gemini:global-gemini-md",host:ee,nativeKind:"global_context",normalizedKind:"memory",source:o,schemaHash:Hf}),await $f(r.settingsFile,t);let n=r.extensionsDirectory;if(await W(n)){t.push({uid:"gemini:extensions",host:ee,nativeKind:"extensions",normalizedKind:"package",source:n,schemaHash:Or});let a=await pd(n,{withFileTypes:!0});for(let s of a)s.isDirectory()&&await Ff(Re.join(n,s.name),s.name,t)}return t}async hotProbe(){let t=await this.coldScan();return{host:ee,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=j(Ya),o=await K(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&&!Z(o,ee)&&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=j(Ya),r=await K(t);return{host:ee,targetPath:t,startMarker:"<!-- nativesoul:gemini:start v1 -->",endMarker:"<!-- nativesoul:gemini:end -->",content:Ne(ee),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,ee)}}};function ud(){let e=process.env.NATIVESOUL_GEMINI_INVENTORY_ROOT?.trim();if(e){let t=Re.resolve(e);return{globalInstruction:Re.join(t,"GEMINI.md"),settingsFile:Re.join(t,"settings.json"),extensionsDirectory:Re.join(t,"extensions")}}return{globalInstruction:j(Ya),settingsFile:j(Df),extensionsDirectory:j(Lf)}}async function $f(e,t){let r=await Q(e);if(r){t.push({uid:"gemini:settings",host:ee,nativeKind:"settings",normalizedKind:"config",source:e,schemaHash:za});for(let o of tt(r.mcpServers))t.push({uid:`gemini:mcp:${M(o)}`,host:ee,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${e}:mcpServers.${o}`,schemaHash:za});for(let o of md(r.tools))t.push({uid:`gemini:tool:${M(o)}`,host:ee,nativeKind:"tool",normalizedKind:"tool",source:`${e}:tools.${o}`,schemaHash:za})}}async function Ff(e,t,r){let o=Re.join(e,"gemini-extension.json"),n=await Q(o),a=I(n,["name","id"])??t;if(r.push({uid:`gemini:extension:${M(a)}`,host:ee,nativeKind:"extension",normalizedKind:"package",source:n?o:e,schemaHash:n?Or:void 0}),n){for(let s of tt(n.mcpServers))r.push({uid:`gemini:mcp:${M(s)}`,host:ee,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:mcpServers.${s}`,schemaHash:Or});for(let s of md(n.tools))r.push({uid:`gemini:tool:${M(s)}`,host:ee,nativeKind:"tool",normalizedKind:"tool",source:`${o}:tools.${s}`,schemaHash:Or})}await Uf(Re.join(e,"commands"),r)}async function Uf(e,t){if(!await W(e))return;let r=await pd(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||![".toml",".md"].includes(Re.extname(o.name)))continue;let n=Re.basename(o.name,Re.extname(o.name));t.push({uid:`gemini:command:${M(n,{allowSlash:!0})}`,host:ee,nativeKind:"command",normalizedKind:"command",source:Re.join(e,o.name),schemaHash:Or})}}function md(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):tt(e)}function gd(){return new Qa}Rt();Ve();ce();import{readdir as bd}from"node:fs/promises";import q from"node:path";var J="grok",dn="~/.grok/Agents.md",fd="AGENTS.md",hd="Agents.md",yd="CLAUDE.md",Bf="~/.grok",Za="official:grok-plugin-config:v1",_d="official:grok-hooks-config:v1",es="official:grok-mcp-config:v1",vd="official:grok-command-config:v1",Vf="official:grok-context-config:v1",Wf=[{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"}],ts=class{async detect(){let t=j(dn),r=q.resolve(fd),o=q.resolve(hd),n=q.resolve(yd),a=kd(),[s,i,l,c,d,p]=await Promise.all([P(t),P(r),P(o),P(n),W(a),Ue("grok")]),g=i||l;return{host:J,detected:s||g||c||d||p!==null,path:s?t:l?o:i?r:c?n:p??void 0,capabilities:{installed:s||g||c||d||p!==null,enabled:s||g||c||d,active:g||c,authenticated:!1,healthy:p!==null||s||d,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=Jf(),o=r.globalInstruction;await P(o)&&t.push({uid:"grok:global-agents-md",host:J,nativeKind:"global_context",normalizedKind:"instruction",source:o,schemaHash:Vf});let n=q.resolve(fd);await P(n)&&t.push({uid:"grok:project-agents-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:n});let a=q.resolve(hd);await P(a)&&t.push({uid:"grok:project-agents-titlecase-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:a});let s=q.resolve(yd);await P(s)&&t.push({uid:"grok:project-claude-md",host:J,nativeKind:"project_context",normalizedKind:"instruction",source:s});let i=r.root;await wd(r.root,t),await qf(i,t);for(let l of Wf){let c=q.join(i,l.relativePath);await W(c)&&t.push({uid:l.uid,host:J,nativeKind:l.nativeKind,normalizedKind:l.normalizedKind,source:c,schemaHash:l.relativePath==="mcps"?es:Za})}return Gf(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=j(dn),o=await K(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&&!Z(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=j(dn),r=await K(t);return{host:J,targetPath:t,startMarker:"<!-- nativesoul:grok:start v1 -->",endMarker:"<!-- nativesoul:grok:end -->",content:Ne(J),wouldCreate:r===null,wouldUpdate:r!==null&&!Z(r,J)}}};function kd(){let e=process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim();return e?q.resolve(e):j(Bf)}function Jf(){let e=kd();return{root:e,globalInstruction:process.env.NATIVESOUL_GROK_INVENTORY_ROOT?.trim()?q.join(e,"Agents.md"):j(dn)}}async function wd(e,t){let r=q.join(e,"plugin.json"),o=q.join(e,"nativesoul-package.json"),n=q.join(e,"hooks","hooks.json"),a=q.join(e,".mcp.json"),[s,i,l,c]=await Promise.all([Q(r),Q(o),Q(n),Q(a)]);if(s){let d=I(s,["name","id"])??"unknown";t.push({uid:`grok:plugin:${M(d)}`,host:J,nativeKind:"plugin",normalizedKind:"extension",source:r,schemaHash:Za})}if(i){let d=I(i,["name","id"])??"unknown";t.push({uid:`grok:package:${M(d)}`,host:J,nativeKind:"native_plugin_package",normalizedKind:"package",source:o,schemaHash:Za});let p=O(i.nativeSoul)?i.nativeSoul:{};for(let k of tn(p.commands))t.push({uid:`grok:command:${M(k)}`,host:J,nativeKind:"command",normalizedKind:"command",source:`${o}:nativeSoul.commands.${k}`,schemaHash:vd});let g=O(p.mcpServer)?p.mcpServer:null,y=I(g,["name"]);y&&t.push({uid:`grok:mcp:${M(y)}`,host:J,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${o}:nativeSoul.mcpServer.${y}`,schemaHash:es})}if(l){t.push({uid:"grok:hooks:manifest",host:J,nativeKind:"hooks",normalizedKind:"lifecycle_hooks",source:n,schemaHash:_d});let d=O(l.hooks)?l.hooks:{};for(let p of Object.keys(d))t.push({uid:`grok:hook:${M(p)}`,host:J,nativeKind:"hook",normalizedKind:"lifecycle_hook",source:`${n}:hooks.${p}`,schemaHash:_d})}if(c)for(let d of tt(c.mcpServers))t.push({uid:`grok:mcp:${M(d)}`,host:J,nativeKind:"mcp_server",normalizedKind:"tool_server",source:`${a}:mcpServers.${d}`,schemaHash:es});await Kf(q.join(e,"commands"),t)}async function qf(e,t){let r=q.join(e,"plugins");if(!await W(r))return;let o=await bd(r,{withFileTypes:!0});for(let n of o)n.isDirectory()&&await wd(q.join(r,n.name),t)}async function Kf(e,t){if(!await W(e))return;let r=await bd(e,{withFileTypes:!0});for(let o of r){if(!o.isFile()||q.extname(o.name)!==".md")continue;let n=q.basename(o.name,".md");t.push({uid:`grok:command:${M(n,{allowSlash:!0})}`,host:J,nativeKind:"command",normalizedKind:"command",source:q.join(e,o.name),schemaHash:vd})}}function Gf(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 Rd(){return new ts}import{mkdir as un,readFile as pn,rm as th,writeFile as mn}from"node:fs/promises";import{existsSync as gn}from"node:fs";import Nr from"node:path";import{lstatSync as Xf,realpathSync as zf,statSync as Yf}from"node:fs";import We from"node:path";var Qf=process.platform!=="win32";function Zf(){let e=process.getuid;return typeof e=="function"?e.call(process):void 0}function Sd(e){let t=e,r=[];for(;;)try{let o=zf(t);return r.length?We.join(o,...r):o}catch{let o=We.dirname(t);if(o===t)return e;r.unshift(We.basename(t)),t=o}}function eh(e,t){let r=We.relative(e,t);return r===""||!r.startsWith("..")&&!We.isAbsolute(r)}function Ad(e,t={}){if(!e||typeof e!="string")return{ok:!1,code:"PATH_ESCAPES_ROOT",detail:"empty or non-string target path"};let r=We.resolve(e);if(t.protectedFiles?.length&&new Set(t.protectedFiles.map(a=>We.resolve(a))).has(r))return{ok:!1,code:"PROTECTED_FILE_DIRECT_WRITE",detail:`${r} is protected; write via a proposal`};try{if(Xf(r).isSymbolicLink()&&!t.allowSymlinkTarget)return{ok:!1,code:"SYMLINK_TARGET_UNSAFE",detail:`${r} is a symlink`}}catch{}let o=We.dirname(r);try{let n=Yf(o);if(Qf){let a=(n.mode&2)!==0,s=(n.mode&512)!==0;if(a&&!s)return{ok:!1,code:"WORLD_WRITABLE_PATH",detail:`${o} is world-writable`};let i=t.uid??Zf();if(i!==void 0&&n.uid!==i)return{ok:!1,code:"SUSPICIOUS_OWNER",detail:`${o} owned by uid ${n.uid}, expected ${i}`}}}catch{}if(t.root){let n=Sd(We.resolve(t.root)),a=Sd(r);if(!eh(n,a))return{ok:!1,code:"PATH_ESCAPES_ROOT",detail:`${a} escapes ${n}`}}return{ok:!0,normalizedPath:r}}function Se(e,t={}){let r=Ad(e,t);if(!r.ok)throw new Error(`unsafe write path (${r.code}): ${r.detail}`);return r.normalizedPath}function fn(e){return{start:`<!-- nativesoul:${e}:start v1 -->`,end:`<!-- nativesoul:${e}:end -->`}}async function Ed(e){let t=f(e.home),r=gn(e.targetPath),o=r?await pn(e.targetPath,"utf8"):null,n=oh(o,e.host,e.block),a=o===null?null:A(o),s=A(n),i=nh(o,n,e.host),l=i!=="noop",c=!e.apply,d=l&&e.apply?await Id(t.home,e.host,e.targetPath,r,o,s):null;l&&e.apply&&(Se(e.targetPath,{allowSymlinkTarget:!0}),await un(Nr.dirname(e.targetPath),{recursive:!0,mode:448}),await mn(e.targetPath,n,{encoding:"utf8",mode:384}));let p={host:e.host,targetPath:e.targetPath,action:i,dryRun:c,changed:l,beforeHash:a,afterHash:s,diff:Td(o,n),backupPath:d,applied:l&&e.apply};return await h({home:t.home,type:e.apply?"managed_block_apply":"managed_block_dry_run",details:p}),p}async function Pd(e){let t=f(e.home),r=gn(e.targetPath),o=r?await pn(e.targetPath,"utf8"):null,n=rh(o,e.host),a=o===null?null:A(o),s=n===null?A(""):A(n),i=o!==n?"remove":"noop",l=i!=="noop",c=!e.apply,d=l&&e.apply?await Id(t.home,e.host,e.targetPath,r,o,s):null;l&&e.apply&&n!==null&&(await un(Nr.dirname(e.targetPath),{recursive:!0,mode:448}),await mn(e.targetPath,n,{encoding:"utf8",mode:384}));let p={host:e.host,targetPath:e.targetPath,action:i,dryRun:c,changed:l,beforeHash:a,afterHash:s,diff:Td(o,n),backupPath:d,applied:l&&e.apply};return await h({home:t.home,type:e.apply?"managed_block_uninstall":"managed_block_uninstall_dry_run",details:p}),p}async function xd(e){let t=gn(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 pn(e.targetPath,"utf8"),n=fn(e.host),a=o.indexOf(n.start),s=o.indexOf(n.end),i=a>=0,l=s>=0,c=i&&l&&s>a;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}}async function jd(e){let t=f(e.home),r=JSON.parse(await pn(e.snapshotPath,"utf8")),o=!e.apply;e.apply&&(r.beforeExists&&r.beforeContent!==null?(await un(Nr.dirname(r.targetPath),{recursive:!0,mode:448}),await mn(r.targetPath,r.beforeContent,{encoding:"utf8",mode:384})):gn(r.targetPath)&&await th(r.targetPath));let n={snapshotPath:e.snapshotPath,targetPath:r.targetPath,dryRun:o,applied:e.apply,restoredExists:r.beforeExists,restoredHash:r.beforeHash};return await h({home:t.home,type:e.apply?"managed_block_rollback":"managed_block_rollback_dry_run",details:n}),n}function rh(e,t){if(e===null)return null;let{start:r,end:o}=fn(t),n=e.indexOf(r),a=e.indexOf(o);if(n<0||a<=n)return e;let s=a+o.length,i=e.slice(0,n),l=e.slice(s);return i.endsWith(`
|
|
824
824
|
|
|
825
825
|
`)&&l.startsWith(`
|
|
826
826
|
`)?l=l.replace(/^\n/u,""):!i.endsWith(`
|
|
@@ -828,40 +828,40 @@ _Running context for today. Promote durable facts to curated memory later._
|
|
|
828
828
|
`)&&(l=l.slice(1)),i.length>0&&l.length>0&&!i.endsWith(`
|
|
829
829
|
`)&&!l.startsWith(`
|
|
830
830
|
`)&&(i=`${i}
|
|
831
|
-
`),`${i}${l}`}function
|
|
831
|
+
`),`${i}${l}`}function oh(e,t,r){let o=r.endsWith(`
|
|
832
832
|
`)?r:`${r}
|
|
833
833
|
`;if(e===null||e.length===0)return o;let{start:n,end:a}=fn(t),s=e.indexOf(n),i=e.indexOf(a);if(s>=0&&i>s){let c=i+a.length,d=e.slice(c).replace(/^\n/u,"");return`${e.slice(0,s)}${o}${d}`}let l=e.endsWith(`
|
|
834
834
|
`)?`
|
|
835
835
|
`:`
|
|
836
836
|
|
|
837
|
-
`;return`${e}${l}${o}`}function
|
|
838
|
-
`)}var
|
|
839
|
-
`,c=Fr.join(o,`${
|
|
840
|
-
`,{encoding:"utf8",mode:384}),r}async function qr(e){let t=te(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=fe.join(r,".nativesoul","project");return yn(o)?{written:!1,marker_path:o,base_id:t.base_id}:(ls(r,t.base_id),{written:!0,marker_path:o,base_id:t.base_id})}async function cs(e){let t=fe.resolve(e.cwd),r=te(t,e.home),o=r.git_root??r.cwd,n=fe.join(o,".nativesoul","project");return e.apply&&(ls(o,r.base_id),await h({home:f(e.home).home,type:"project_pinned",details:{id:r.base_id,basis_source:r.source,marker_path:n}})),{cwd:t,base_id:r.base_id,marker_path:n,applied:e.apply===!0,resolution:r}}function
|
|
837
|
+
`;return`${e}${l}${o}`}function nh(e,t,r){if(e===t)return"noop";if(e===null||e.length===0)return"create";let{start:o,end:n}=fn(r);return e.includes(o)&&e.includes(n)?"replace":"append"}async function Id(e,t,r,o,n,a){let s=Nr.join(e,"backups","managed-block");await un(s,{recursive:!0,mode:448});let i=new Date().toISOString(),l={id:T("snapshot"),host:t,targetPath:r,beforeExists:o,beforeContent:n,beforeHash:n===null?null:A(n),afterHash:a,createdAt:i},c=`${i.replace(/[:.]/g,"-")}-${t}.json`,d=Nr.join(s,c);return await mn(d,JSON.stringify(l,null,2),{encoding:"utf8",mode:384}),d}function Td(e,t){return e===t?"No changes.":[`before: ${e===null?"missing":A(e)}`,`after: ${t===null?"missing":A(t)}`,`lines_before: ${e===null?0:e.split(/\r?\n/u).length}`,`lines_after: ${t===null?0:t.split(/\r?\n/u).length}`].join(`
|
|
838
|
+
`)}var ah=["codex","claude","grok","antigravity","gemini"],sh={codex:dd,claude:nd,grok:Rd,antigravity:jc,gemini:gd};function Je(e){return e==="all"?ah:[e]}function hn(e){return Je(e)}function St(e){return sh[e]()}async function Mr(e){let t=[];for(let r of hn(e)){let o=St(r),[n,a]=await Promise.all([o.detect(),o.coldScan({})]);t.push({host:r,detected:n.detected,version:n.version,sources:a})}return t}async function Lr(e){let t=[];for(let r of hn(e)){let o=St(r);t.push({host:r,diagnostics:await o.doctor({})})}return t}async function Dr(e){return St(e).managedBlockPreview()}async function Hr(e){let t=await Dr(e.host);return Ed({home:e.home,host:e.host,targetPath:e.targetPath??t.targetPath,block:t.content,apply:e.apply})}async function rs(e){return jd(e)}async function os(e){let t=await Dr(e.host);return Pd({home:e.home,host:e.host,targetPath:e.targetPath??t.targetPath,apply:e.apply})}async function At(e){let t=await v(e.home),r=new Date().toISOString(),o=[],n=e.ttlSeconds??await uh(t.home);for(let a of hn(e.host)){if(e.delta){let p=(await Ae({home:t.home,host:a,includeShared:!1,limit:1}))[0]?.last_seen_at;if(p&&Date.now()-Date.parse(p)<=n*1e3){let g={host:a,status:"ready",count:0,records:[],skipped:!0,warnings:[],diagnostics:[]};await h({home:t.home,type:"capabilities_refreshed",details:{host:a,count:0,status:"ready",warnings:[],delta:!0,skipped:!0}}),o.push(g);continue}}let i=await St(a).hotProbe({}),l=i.capabilities.map(d=>mh({uid:d.uid,host:d.host,native_kind:d.nativeKind,normalized_kind:d.normalizedKind,source:d.source,schema_hash:d.schemaHash??null,installed:d.installed,enabled:d.enabled,active:d.active,authenticated:d.authenticated,healthy:d.healthy,allowed:d.allowed,ready:d.ready,last_seen_at:r})),c=_(t.database);try{c.upsertCapabilities(l)}finally{c.close()}await h({home:t.home,type:"capabilities_refreshed",details:{host:a,count:l.length,status:i.status??((i.diagnostics?.length??0)>0?"degraded":"ready"),warnings:i.warnings??[],delta:e.delta===!0,skipped:!1}}),o.push({host:a,status:i.status??((i.diagnostics?.length??0)>0?"degraded":"ready"),count:l.length,records:l,skipped:!1,warnings:i.warnings??[],remediation:i.remediation,diagnostics:i.diagnostics??[]})}return o}async function uh(e){let t;try{t=await ns(Fr.join(e,"config.yaml"),"utf8")}catch{return 3600}let r=t.match(/^\s*(?:capability_refresh_ttl_seconds|refresh_ttl_seconds):\s*(\d+)\s*$/mu),o=r?.[1]?Number(r[1]):3600;return Number.isFinite(o)?Math.min(Math.max(o,0),86400):3600}async function Ae(e){let t=e.readOnly?f(e.home):await v(e.home);if(e.readOnly&&!await S(t.database))return[];let r=_(t.database,{readOnly:e.readOnly}),o=Md(e.limit);try{return r.listCapabilities({host:e.host,readyOnly:e.readyOnly,limit:o,includeShared:e.includeShared})}finally{r.close()}}async function Ur(e){let t=await v(e.home),r=_(t.database),o=Md(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 Br(e){let t=await v(e.home),r=_(t.database);try{return r.getCapability(e.uid)}finally{r.close()}}async function as(e){let t=e.readOnly?f(e.home):await v(e.home),r=Fr.join(t.home,"capabilities","cards"),o=[];if(!await S(r))return{cards:[],warnings:o};let n=(await lh(r)).filter(c=>c.endsWith(".json")).sort(),a=vh(e.query??""),s=[];for(let c of n){let d=Fr.join(r,c),p;try{p=await ns(d,"utf8")}catch{o.push(`CAPABILITY_CARD_UNREADABLE:${c}`);continue}let g=hh(p);if(!g){o.push(`CAPABILITY_CARD_MALFORMED:${c}`);continue}let y=yh(g,e.host);s.push({card:y,score:_h(g,e.host,a)})}let i=Sh(e.limit),l=s.sort((c,d)=>d.score-c.score||c.card.uid.localeCompare(d.card.uid));return{cards:ph(l,i).map(c=>c.card),warnings:o}}function ph(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,a)=>a.score-n.score||n.card.uid.localeCompare(a.card.uid)):r}async function ss(e){let t=await v(e.home),r=await gh({home:t.home,host:e.host,limit:e.limit}),o=Fr.join(t.home,"capabilities","cards");await ih(o,{recursive:!0,mode:448});let n=[];for(let s of r){let i=fh(s),l=`${JSON.stringify(i,null,2)}
|
|
839
|
+
`,c=Fr.join(o,`${Rh(s.uid)}.json`),d=dh(c)?await ns(c,"utf8"):null,p=d===l?"unchanged":d===null?"created":"updated";p!=="unchanged"&&await ch(c,l,{encoding:"utf8",mode:384}),n.push({uid:s.uid,host:s.host,path:c,action:p,hash:A(l),card:i})}let a={home:t.home,host:e.host,generated:n.length,changed:n.filter(s=>s.action!=="unchanged").length,cards:n,warnings:n.length===0?["NO_CAPABILITY_RECORDS_TO_LEARN"]:[]};return await h({home:t.home,type:"capability_cards_learned",details:{host:e.host,generated:a.generated,changed:a.changed,warnings:a.warnings}}),a}function mh(e){return{...e,uid:N(e.uid).value,host:N(e.host).value,native_kind:N(e.native_kind).value,normalized_kind:N(e.normalized_kind).value,source:N(e.source).value,schema_hash:e.schema_hash?N(e.schema_hash).value:null}}async function gh(e){return e.host==="all"?Ae({home:e.home,limit:e.limit}):Ae({home:e.home,host:e.host,limit:e.limit})}function fh(e){let t=e.schema_hash??ke({uid:e.uid,host:e.host,native_kind:e.native_kind,normalized_kind:e.normalized_kind,source:e.source,readiness:Cd(e)}),r={card_version:1,id:`capcard:${e.uid}`,uid:e.uid,host:e.host,native_kind:e.native_kind,normalized_kind:e.normalized_kind,readiness:Cd(e),source:e.source,schema_hash:t,use_when:[`Use when a task needs ${e.normalized_kind} capability metadata on ${e.host}.`,`Check this card before claiming ${e.uid} is available or ready.`],requires:kh(e),side_effects:["Reading this card has no side effects.","Executing the native capability may have host-specific side effects and must follow policy."],approval:wh(e),examples:[`Inspect ${e.uid} readiness before using it.`,`Prefer a ready capability on ${e.host}; otherwise report degraded status.`]};return H(r)}function hh(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Od(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)||!bh(r)?null:t}function yh(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:$r(e.use_when).slice(0,2),requires:$r(e.requires).slice(0,4),approval:e.approval,alternative_host:r,available_on_other_host:o}}function _h(e,t,r){let o=Nd([e.uid,e.host,e.native_kind,e.normalized_kind,e.source,e.schema_hash,...$r(e.use_when),...$r(e.requires),e.approval,...$r(e.examples)].join(" ")),n=r.reduce((a,s)=>a+(o.includes(s)?10:0),0);return(e.host===t?100:0)+(e.readiness.ready?5:0)+n}function $r(e){return e.filter(t=>typeof t=="string")}function Od(e){return typeof e=="object"&&e!==null}function bh(e){return Od(e)?["installed","enabled","active","authenticated","healthy","allowed","ready"].every(t=>typeof e[t]=="boolean"):!1}function vh(e){return Nd(e).split(/\s+/u).map(t=>t.trim()).filter(t=>t.length>=2)}function Nd(e){return e.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/gu,"")}function Cd(e){return{installed:e.installed,enabled:e.enabled,active:e.active,authenticated:e.authenticated,healthy:e.healthy,allowed:e.allowed,ready:e.ready}}function kh(e){let t=[["installed",e.installed],["enabled",e.enabled],["active",e.active],["authenticated",e.authenticated],["healthy",e.healthy],["allowed",e.allowed],["ready",e.ready]].filter(([,r])=>r===!1).map(([r])=>`${r} must be true`);return t.length>0?t:["No missing readiness prerequisites are known."]}function wh(e){return e.allowed?e.normalized_kind.includes("connector")||e.normalized_kind.includes("mcp")?"approval_required_for_external_write":"allowed_for_read_or_local_use_when_ready":"denied_by_policy"}function Rh(e){return`${e.replace(/[^A-Za-z0-9._-]+/gu,"_").replace(/^_+|_+$/gu,"")||"capability"}-${A(e).slice(7,19)}`}function Md(e){return Math.min(Math.max(e??50,1),100)}function Sh(e){return Math.min(Math.max(e??5,1),8)}async function Vr(e){let t=await v(e.home),r=N(e.summary).value,o=new Date,n=e.ttlSeconds?new Date(o.getTime()+Ah(e.ttlSeconds)*1e3).toISOString():null,a=H(e.source??{host:"cli",session_id:"local"}),s=_(t.database),i;try{i=s.createOpenCommitmentIfMissing({id:T("commitment"),project_id:e.project,summary:r,status:"open",due_at:e.dueAt??null,ttl_expires_at:n,source:a,created_at:o.toISOString(),updated_at:o.toISOString()},o.toISOString())}finally{s.close()}return await h({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 Wr(e){let t=e.readOnly?f(e.home):await v(e.home);if(e.readOnly&&!await S(t.database))return[];let r=_(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 h({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 Jr(e,t){return Ld(e,t,"completed","commitment_completed")}async function is(e,t){return Ld(e,t,"dismissed","commitment_dismissed")}async function Ld(e,t,r,o){let n=await v(e),a=_(n.database),s;try{s=a.updateCommitmentStatus(t,r,new Date().toISOString())}finally{a.close()}if(!s)throw new Error(`Commitment not found: ${t}`);return await h({home:n.home,type:o,details:{id:s.id,project:s.project_id,status:s.status}}),s}function Ah(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),365*24*60*60):1440*60}import{createHash as Eh}from"node:crypto";import{existsSync as yn,mkdirSync as Ph,realpathSync as xh,readFileSync as Hd,writeFileSync as jh}from"node:fs";import{spawnSync as $d}from"node:child_process";import fe from"node:path";function L(e,t){return te(e,t).id}function te(e,t){let r=ds(e),o=Oh(r),n=o?Nh(o):null,a=n?Dd(n):o??r,s=Mh(a),i=n?"git-remote":o?"git-root":"path",l=Th(s,a),c=Ih(r),d=c?Fd(c):null,p=us(t),g=[d,l,n?Dd(n):null,o,r].find(y=>y&&p[y]);if(g){let y=d??l;return{id:p[g]??y,source:"alias",cwd:r,git_root:o,remote:n,base_id:y,alias_key:g,marker_path:c}}return d?{id:d,source:"marker",cwd:r,git_root:o,remote:n,base_id:d,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 Fd(e){if(!yn(e))return null;let t=Hd(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?Ch(o):null}function ls(e,t){let r=fe.join(e,".nativesoul","project");return Ph(fe.dirname(r),{recursive:!0,mode:448}),jh(r,`${t}
|
|
840
|
+
`,{encoding:"utf8",mode:384}),r}async function qr(e){let t=te(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=fe.join(r,".nativesoul","project");return yn(o)?{written:!1,marker_path:o,base_id:t.base_id}:(ls(r,t.base_id),{written:!0,marker_path:o,base_id:t.base_id})}async function cs(e){let t=fe.resolve(e.cwd),r=te(t,e.home),o=r.git_root??r.cwd,n=fe.join(o,".nativesoul","project");return e.apply&&(ls(o,r.base_id),await h({home:f(e.home).home,type:"project_pinned",details:{id:r.base_id,basis_source:r.source,marker_path:n}})),{cwd:t,base_id:r.base_id,marker_path:n,applied:e.apply===!0,resolution:r}}function Ih(e){let t=ds(e);for(;;){let r=fe.join(t,".nativesoul","project");if(yn(r))return r;let o=fe.dirname(t);if(o===t)return null;t=o}}function Th(e,t){let r=Eh("sha256").update(t).digest("hex").slice(0,10);return`${Lh(e)}-${r}`}function Ch(e){return e.trim().toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function ds(e){try{return xh(fe.resolve(e))}catch{return fe.resolve(e)}}function Oh(e){let t=$d("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?ds(r):null}function Nh(e){let t=$d("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 Dd(e){return e.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^ssh:\/\/git@([^/]+)\//,"https://$1/").replace(/^https?:\/\/([^/]+)\//,"https://$1/").replace(/\.git$/u,"").toLowerCase()}function Mh(e){let t=e.replace(/\/+$/u,"");return fe.basename(t)||"workspace"}function Lh(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"workspace"}function us(e){if(!e)return{};let t=fe.join(fe.resolve(e),"config.yaml");if(!yn(t))return{};let r=Hd(t,"utf8"),o={},n=!1,a=!1,s="";for(let i of r.split(/\r?\n/u)){if(/^\S/u.test(i)){n=/^project:\s*$/u.test(i),a=!1;continue}let l=i.match(/^([ \t]+)aliases:\s*(?:\{\}\s*)?$/u);if(n&&l?.[1]){a=!0,s=l[1];continue}if(a){if(i.trim().length===0||i.trim().startsWith("#"))continue;let c=i.match(/^([ \t]+)(?:"([^"]+)"|'([^']+)'|([^:]+)):\s*(?:"([^"]+)"|'([^']+)'|(.+))\s*$/u);(c?.[1]??"").length<=s.length&&(a=!1);let p=c?.[2]??c?.[3]??c?.[4],g=c?.[5]??c?.[6]??c?.[7];a&&p&&g?o[p.trim()]=g.trim():/^[ \t]+\S/u.test(i)&&i.trim().length>0&&(a=!1)}}return o}import{readFile as Dh,writeFile as Hh}from"node:fs/promises";import $h from"node:path";async function ps(e){let t=f(e.home),r=$h.join(t.home,"config.yaml"),o=await S(r)?await Dh(r,"utf8"):`version: 1
|
|
841
841
|
`,n=o.includes(`\r
|
|
842
842
|
`)?`\r
|
|
843
843
|
`:`
|
|
844
|
-
`,s={...
|
|
845
|
-
`))}if(n.projectStart>=0){let l=n.projectStart+1,c=o.slice(0,l),d=o.slice(l);return
|
|
844
|
+
`,s={...Vd(o).aliases},i=s[e.aliasKey]??null;if(e.action==="add"){if(!e.projectId)throw new Error("project alias add requires <id>");s[e.aliasKey]=e.projectId}else delete s[e.aliasKey];let l=Fh(o,s,n),c=l!==o;return e.apply&&c&&(Se(r,{root:t.home}),await Hh(r,l,{encoding:"utf8",mode:384})),{action:e.action,applied:e.apply===!0,config_path:r,alias_key:e.aliasKey,project_id:e.action==="add"?e.projectId??null:null,previous_id:i,aliases:s,changed:c,preview:l}}function Vd(e){let t=Wd(e),r={},o=[],n=-1,a=-1,s=-1,i=" ",l=" ";for(let c=0;c<t.length;c+=1)if(/^project:\s*$/u.test(t[c]??"")){n=c;break}if(n>=0)for(let c=n+1;c<t.length;c+=1){let d=t[c]??"";if(/^\S/u.test(d)&&d.trim().length>0)break;let p=d.match(/^([ \t]+)aliases:\s*(?:\{\}\s*)?$/u);if(p?.[1]){a=c,i=p[1],l=`${i}${i.includes(" ")?" ":" "}`;break}}if(a>=0){s=a+1;for(let c=a+1;c<t.length;c+=1){let d=t[c]??"";if(d.trim().length===0||d.trim().startsWith("#")){s=c+1;continue}let p=d.match(/^([ \t]+)(?:"([^"]+)"|'([^']+)'|([^:]+)):\s*(?:"([^"]+)"|'([^']+)'|(.+))\s*$/u),g=p?.[1]??"";if(!p||g.length<=i.length)break;let y=p[2]??p[3]??p[4],k=p[5]??p[6]??p[7];if(y&&k){let R=y.trim();r[R]=k.trim(),o.includes(R)||o.push(R)}s=c+1}}return{aliases:r,aliasOrder:o,projectStart:n,aliasesStart:a,aliasesEnd:s,projectIndent:i,aliasIndent:l}}function Fh(e,t,r){let o=Wd(e),n=Vd(e),s=[...n.aliasOrder.filter(l=>Object.prototype.hasOwnProperty.call(t,l)),...Object.keys(t).filter(l=>!n.aliasOrder.includes(l))].map(l=>`${n.aliasIndent}${Bd(l)}: ${Bd(t[l]??"")}`);if(n.aliasesStart>=0){let l=o.slice(0,n.aliasesStart+1),c=o.slice(n.aliasesStart+1,n.aliasesEnd).filter(p=>{let g=p.trim();return g.length===0||g.startsWith("#")}),d=o.slice(n.aliasesEnd);return Ud([...l,...c,...s,...d],r,e.endsWith(`
|
|
845
|
+
`))}if(n.projectStart>=0){let l=n.projectStart+1,c=o.slice(0,l),d=o.slice(l);return Ud([...c,`${n.projectIndent}aliases:`,...s,...d],r,e.endsWith(`
|
|
846
846
|
`))}return`${e.length>0&&!e.endsWith(`
|
|
847
|
-
`)?`${e}${r}`:e}project:${r}${n.projectIndent}aliases:${r}${s.join(r)}${s.length?r:""}`}function
|
|
847
|
+
`)?`${e}${r}`:e}project:${r}${n.projectIndent}aliases:${r}${s.join(r)}${s.length?r:""}`}function Wd(e){return e.replace(/\r\n/gu,`
|
|
848
848
|
`).split(`
|
|
849
|
-
`).filter((t,r,o)=>r<o.length-1||t.length>0)}function
|
|
850
|
-
${p.content}`)])),c=
|
|
851
|
-
|
|
852
|
-
${e.content}`);return{text:t.value,contentHash:e.hash,redacted:t.redacted}}function
|
|
853
|
-
${r.content}`),semantic_score:0,final_rank:o+1,reason:"fts_fallback"}}))}function
|
|
854
|
-
`),i=await ie(t.home,{project:o,content:s,confidence:a.source==="stub"?.2:.45,authority:"hook_observed",source:{kind:"session_end_hook",host:e.host,event:n,cwd:r,summary_source:a.source}});return{proposed:!0,host:e.host,event:n,cwd:r,project:o,memory:i,summary_source:a.source}}function
|
|
855
|
-
`).slice(0,1800)}async function Pt(e,t){return vn(e,t,"active","memory_promoted")}async function xt(e,t){return vn(e,t,"rejected","memory_rejected")}async function jt(e,t){return vn(e,t,"forgotten","memory_forgotten")}async function zr(e,t){return vn(e,t,"expired","memory_expired")}async function It(e){let t=await v(e.home),r=_(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 h({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 eu(e,t,r){let o=N(t.content),n=new Date().toISOString(),a=qe(o.value),s={id:T("mem"),type:t.type??"note",scope:{user:"default",project:t.project},content:o.value,summary:a,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:ke({type:t.type??"note",project:t.project,content:o.value,status:r,created_at:n})},i=_(e);try{i.insertMemory(s)}finally{i.close()}return s}async function vn(e,t,r,o){let n=await v(e),a=_(n.database),s,i;try{if(s=a.getMemory(t),s&&!kn(s.status,r))throw new Et({id:t,from:s.status,to:r});i=s?a.updateMemoryStatus(t,r):null}catch(l){throw l instanceof Et&&await qh({home:n.home,id:l.id,from:l.from,to:l.to}),l}finally{a.close()}if(!i)throw new Error(`Memory not found: ${t}`);return await h({home:n.home,type:o,details:{id:i.id,project:i.scope.project,status:r}}),i}function kn(e,t){return Uh.get(e)?.has(t)??!1}async function qh(e){await h({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 Tt(e,t,r,o=5){let n=await v(e),a=Gr({database:n.database,query:t,project:r,limit:Math.min(Math.max(o,1),8)});return await h({home:n.home,type:"memory_searched",details:{query:t,project:r,count:a.memories.length,recall_mode:a.mode,recall_reason:a.reason}}),a.memories}async function _s(e){let t=f(e.home),r=null;try{r=_(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:tu(e.resolution),status:"active",now:e.now});return r.close(),r=null,o.inserted&&await h({home:t.home,type:"project_seen",details:{id:e.resolution.id,base_id:e.resolution.base_id,source:e.resolution.source,first_basis:tu(e.resolution)}}),{touched:!0,inserted:o.inserted,degraded:!1,warning:null}}catch(o){return{touched:!1,inserted:!1,degraded:!0,warning:`PROJECT_REGISTRY_UNAVAILABLE:${Qh(o)}`}}finally{r?.close()}}async function bs(e={}){let t=f(e.home),r=Xh(e.limit),o=e.status??"active";if(!await S(t.database))return{registry_available:!1,status:o,limit:r,projects:[],warning:"database_not_available"};let n=_(t.database,{readOnly:e.readOnly??!0});try{let a=n.listProjectsWithCounts({status:o,limit:r});return{registry_available:a.available,status:o,limit:r,projects:a.projects,warning:a.warning}}finally{n.close()}}async function vs(e){let t=f(e.home),r=e.id==="."?Kh(e.cwd??process.cwd(),t.home):Gh(e.id);if(!await S(t.database))return ru(e.id,r,"database_not_available");let o=_(t.database,{readOnly:e.readOnly??!0});try{let n=o.getProjectDetail(r.id);if(!n.available)return ru(e.id,r,n.warning);let a=n.detail;return{registry_available:!0,requested:e.id,effective_id:r.id,registry:a?.project??null,live_resolution:r,counts:a?.counts??null,derived_last_seen_at:a?.derived_last_seen_at??null,continuity_gap:!!(a?.project&&a.project.base_id!==r.id),warning:a?.project?null:"project_not_found"}}finally{o.close()}}async function ks(e){let t=f(e.home),r=zh(e.name),o=e.id==="."?te(e.cwd??process.cwd(),t.home).id:e.id,n=_(t.database),a;try{a=n.renameProject(o,r)}finally{n.close()}return a.found&&a.previous&&a.project&&await h({home:t.home,type:"project_renamed",details:{id:o,old_name:a.previous.display_name,new_name:r}}),{found:a.found,id:o,old_name:a.previous?.display_name??null,new_name:r,project:a.project}}async function ws(e){let t=f(e.home),r=e.includeMemories===!0,o=e.apply===!0,n=e.confirm??null,a=!r||o&&n===e.id,s=_(t.database);try{let i=s.getProject(e.id);if(!i)return wn({found:!1,id:e.id,mode:r?"forget_memories":"archive",applied:!1,guardOk:a,confirm:n,previousStatus:null,statusAfter:null,memoriesAffected:0,project:null,warning:"project_not_found"});if(r&&!a)return wn({found:!0,id:e.id,mode:"forget_memories",applied:!1,guardOk:a,confirm:n,previousStatus:i.status,statusAfter:i.status,memoriesAffected:s.countProjectMemories(e.id),project:i,warning:"requires --apply --confirm <id>"});if(r)try{let c=s.forgetProjectMemories(e.id,kn);return c.found&&c.project&&await h({home:t.home,type:"project_forgotten",details:{id:e.id,memories_affected:c.memories_affected}}),wn({found:c.found,id:e.id,mode:"forget_memories",applied:c.found,guardOk:a,confirm:n,previousStatus:c.previous?.status??null,statusAfter:c.project?.status??null,memoriesAffected:c.memories_affected,project:c.project,warning:c.found?null:"project_not_found"})}catch(c){throw c instanceof Yt&&await h({home:t.home,type:"memory_transition_blocked",result:"blocked",details:{id:c.id,from:c.from,to:c.to,code:c.code,project:e.id}}),c}let l=s.archiveProject(e.id);return l.found&&l.project&&await h({home:t.home,type:"project_archived",details:{id:e.id}}),wn({found:l.found,id:e.id,mode:"archive",applied:l.found,guardOk:a,confirm:n,previousStatus:l.previous?.status??null,statusAfter:l.project?.status??null,memoriesAffected:0,project:l.project,warning:l.found?null:"project_not_found"})}finally{s.close()}}async function Rs(e){let t=f(e.home),r=_(t.database),o;try{o=r.reactivateProject(e.id)}finally{r.close()}return o.found&&o.project&&await h({home:t.home,type:"project_reactivated",details:{id:e.id}}),{found:o.found,id:e.id,previous_status:o.previous?.status??null,status_after:o.project?.status??null,project:o.project}}async function Ss(e={}){return{aliases:us(f(e.home).home)}}async function As(e){let t=f(e.home),r=await ps({home:t.home,action:"add",aliasKey:ou(e.alias),projectId:Yh(e.id),apply:e.apply});return r.applied&&r.changed&&await h({home:t.home,type:"project_alias_set",details:{alias_key:r.alias_key,project_id:r.project_id,previous_project_id:r.previous_id}}),r}async function Es(e){let t=f(e.home),r=await ps({home:t.home,action:"remove",aliasKey:ou(e.alias),apply:e.apply});return r.applied&&r.changed&&await h({home:t.home,type:"project_alias_removed",details:{alias_key:r.alias_key,previous_project_id:r.previous_id}}),r}function tu(e){return e.remote??e.git_root??e.cwd}function Kh(e,t){let r=te(e,t);return{id:r.id,source:r.source,cwd:r.cwd,git_root:r.git_root,remote:r.remote,base_id:r.base_id,alias_key:r.alias_key,marker_path:r.marker_path}}function Gh(e){return{id:e,source:"explicit",cwd:null,git_root:null,remote:null,base_id:null,alias_key:null,marker_path:null}}function ru(e,t,r){return{registry_available:!1,requested:e,effective_id:t.id,registry:null,live_resolution:t,counts:null,derived_last_seen_at:null,continuity_gap:!1,warning:r}}function Xh(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}function zh(e){let t=e.trim();if(t.length===0)throw new Error("project rename requires a non-empty --name");return t.slice(0,160)}function ou(e){let t=e.trim();if(t.length===0)throw new Error("project alias requires a non-empty alias");return t}function Yh(e){let t=e.trim();if(t.length===0||t===".")throw new Error("project alias add requires an explicit project id");return t}function wn(e){return{found:e.found,id:e.id,mode:e.mode,applied:e.applied,dry_run:!e.applied,guard_ok:e.guardOk,required_confirm:e.mode==="forget_memories"?e.id:null,confirm:e.confirm,previous_status:e.previousStatus,status_after:e.statusAfter,memories_affected:e.memoriesAffected,project:e.project,warning:e.warning}}function Qh(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}var Zh=/^-\s*\*\*([^:*]+):\*\*\s*(.*)$/u;function Ct(e,t){let r=ey(e,t);if(r)return r;let o=e.split(/\r?\n/u);for(let n=0;n<o.length;n+=1){let s=(o[n]?.trim()??"").match(Zh);if(!s||s[1]?.trim()!==t)continue;let i=s[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 nu(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 au(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 ey(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 dy,mkdir as iu,readFile as uy,rename as py,stat as my,writeFile as gy}from"node:fs/promises";import{existsSync as lu}from"node:fs";import Ot from"node:path";import{mkdir as ty,readFile as ry,rename as oy,writeFile as ny}from"node:fs/promises";import Yr from"node:path";var ay=1440*60*1e3;async function Me(e){let t=f(e.home),r=await Ps(t.home),o={host:e.host,outcome:e.outcome,tier:e.tier,cwd:e.cwd?Yr.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:cy(e.error),recorded_at:e.recordedAt??new Date().toISOString()};return r.hosts[e.host]=o,await iy(t.home,r),await h({home:t.home,type:ly(e.outcome),result:e.outcome==="failed"?"error":"ok",details:o}),o}async function Ps(e){let t=f(e),r=js(t.home);if(!await S(r))return sy();let o=JSON.parse(await ry(r,"utf8"));return{schema:1,hosts:typeof o.hosts=="object"&&o.hosts!==null?o.hosts:{}}}async function xs(e){let t=f(e.home),o=(await Ps(t.home)).hosts[e.host]??null,n=(e.now??new Date).getTime(),a=o?Date.parse(o.recorded_at):Number.NaN,s=Number.isFinite(a)?Math.max(n-a,0):null;return{state_path:js(t.home),last:o,age_ms:s,age_hours:s===null?null:Math.round(s/(3600*1e3)*10)/10,stale:s!==null&&s>ay}}function sy(){return{schema:1,hosts:{}}}async function iy(e,t){let r=js(e);await ty(Yr.dirname(r),{recursive:!0,mode:448});let o=Yr.join(Yr.dirname(r),`.last-handshake-${T("tmp")}.tmp`);await ny(o,`${JSON.stringify(t,null,2)}
|
|
856
|
-
`,{encoding:"utf8",mode:384}),await
|
|
857
|
-
`);return{host:e.host,generated_at:t,degraded:r,warnings:o,tokens_used:Cs(s),tokens_max:e.payload.context_budget.tokens_max,content:s}}async function Rn(e){let t=f(e.home),r=or({host:e.host,payload:e.payload}),o=Ts(t.home,e.host),n=
|
|
858
|
-
`),d={host:e.host,generated_at:i,degraded:!0,warnings:l,tokens_used:Cs(c),tokens_max:1900,content:c,targetPath:r,stale:s};if(e.recordTelemetry!==!1){await h({home:t.home,type:"bootstrap_context_cache_read",details:{...d,content:"[omitted]"}});let p=
|
|
859
|
-
`),n={host:e.host,generated_at:t,degraded:!0,warnings:r,tokens_used:Cs(o),tokens_max:1900,content:o,targetPath:e.targetPath,stale:!1};return e.recordTelemetry!==!1&&(await h({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}async function
|
|
860
|
-
`),fallbackReason:"missing; default identity fields injected"}),Zr({home:e.home,relativePath:"SOUL.md",role:"soul_summary",rawText:e.soulText,injectedText:e.payload.soul_summary,fallbackReason:"missing; default soul summary injected"}),Zr({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"}),Zr({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"}),Zr({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 Zr(e){let t=e.rawText.length,r=e.injectedText.length,o=t>0,n=r>0,a=o?e.presentReason??(r<t?"included; summarized to fit budget":"included"):e.fallbackReason;return{path:Le.join(e.home,e.relativePath),role:e.role,included:n,reason:a,rawChars:t,injectedChars:r,truncated:o&&n&&r<t,hash:o?A(e.rawText):null}}function
|
|
861
|
-
`,{encoding:"utf8",mode:384}),await
|
|
862
|
-
`,{encoding:"utf8",mode:384}),await h({home:t.home,type:"activation.profile.applied",details:{profile:s.profile,reset:n,diff:i.map(c=>c.field)}})),{dry_run:r,applied:!r,user_confirmed:o,reset:n,action:l,before:a,after:s,diff:i,warnings:[]}}function gu(e){return Ms.join(e,"state","activation-profile.json")}function nr(e){return Ms.join(e,"state","activation.complete")}async function lt(e){try{let t=JSON.parse(await jy(gu(e),"utf8"));return Oy(t)?t:null}catch{return null}}function Iy(e,t){return{...Sn,...Ty(t),profile:e,updated_at:new Date().toISOString()}}function Ty(e){if(!e)return{};if(e.candidate_auto_promotion_threshold!==void 0){let t=e.candidate_auto_promotion_threshold;if(!Number.isFinite(t)||t<0||t>1)throw new Error("Invalid candidate_auto_promotion_threshold: expected a number between 0 and 1")}if(e.promotion_policy!==void 0&&e.promotion_policy!=="manual"&&e.promotion_policy!=="explicit_approval")throw new Error("Invalid promotion_policy: expected manual or explicit_approval");if(e.memory_candidate_policy!==void 0&&e.memory_candidate_policy!=="candidate"&&e.memory_candidate_policy!=="off")throw new Error("Invalid memory_candidate_policy: expected candidate or off");if(e.recall_auto_trigger_keywords!==void 0&&(!Array.isArray(e.recall_auto_trigger_keywords)||e.recall_auto_trigger_keywords.some(t=>typeof t!="string")))throw new Error("Invalid recall_auto_trigger_keywords: expected string array");if(e.recall_auto_trigger_denylist!==void 0&&(!Array.isArray(e.recall_auto_trigger_denylist)||e.recall_auto_trigger_denylist.some(t=>typeof t!="string")))throw new Error("Invalid recall_auto_trigger_denylist: expected string array");if(e.standing_order_templates!==void 0&&!Array.isArray(e.standing_order_templates))throw new Error("Invalid standing_order_templates: expected string array");if(e.standing_order_templates!==void 0&&e.standing_order_templates.some(t=>typeof t!="string"))throw new Error("Invalid standing_order_templates: expected string array");return{...e,recall_auto_trigger_keywords:Array.isArray(e.recall_auto_trigger_keywords)?e.recall_auto_trigger_keywords:void 0,recall_auto_trigger_denylist:Array.isArray(e.recall_auto_trigger_denylist)?e.recall_auto_trigger_denylist:void 0,standing_order_templates:Array.isArray(e.standing_order_templates)?e.standing_order_templates:void 0}}function Cy(e,t){return["profile","heartbeat_enabled","scheduler_host","heartbeat_cadence","memory_candidates","memory_candidate_policy","auto_promotion","promotion_policy","recall_auto_trigger_keywords","recall_auto_trigger_denylist","candidate_auto_promotion_threshold","recall_auto_trigger","standing_order_templates"].flatMap(o=>{let n=e?.[o]??null,a=t[o];return JSON.stringify(n)===JSON.stringify(a)?[]:[{field:o,before:n,after:a}]})}function Oy(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 Ds(e){let t={bootstrap:Ny(e),mcp:My(e),plugins_hooks:Ly(e),heartbeat:Dy(e),recall_auto_trigger:Hy(e),memory_candidate_hooks:$y(e),memory_promotion_policy:Fy(e),cross_host_verification:Uy(e)},r=Object.values(t),o=By(r),n=r.flatMap(s=>s.plan_actions),a=Vy(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:a}}function fu(e){return Ds(e).summary}function Ny(e){return e.onboardingComplete&&e.activationComplete&&e.profile?$("bootstrap","active","Identity onboarding and activation marker are present.",{onboarding_complete:!0,activation_complete:!0}):$("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},[Nt("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 My(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 $("mcp",r?"degraded":"active",r?"MCP is configured but doctor reported warnings.":"MCP registration is configured.",{configured_hosts:t.map(he),checked_hosts:e.hosts.map(he)})}return $("mcp","not_configured","No MCP registration was detected for the selected host scope.",{checked_hosts:e.hosts.map(he)},[Nt("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 Ly(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 $("plugins_hooks",o?"degraded":"active",o?"Plugin/hooks are available through fallback support.":"Native plugin or hook support is active.",{enabled_hosts:t.map(he),hook_modes:Object.fromEntries(e.hosts.map(n=>[he(n),n.provider_parity.hooks]))})}let r=e.hosts.length>0&&e.hosts.every(o=>o.plugin.package_kind==="unsupported-native");return $("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(he)},[Nt("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 Dy(e){if(!e.profile||!e.profile.heartbeat_enabled)return $("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?$("heartbeat","blocked_by_host","At least one selected host lacks native scheduler support.",{blocked_hosts:t.map(he),heartbeat_modes:Object.fromEntries(e.hosts.map(r=>[he(r),r.provider_parity.heartbeat]))},[Nt("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")?$("heartbeat","active","Heartbeat has native scheduler support in the selected scope.",{native_hosts:e.hosts.filter(r=>r.provider_parity.heartbeat==="native").map(he)}):e.hosts.some(r=>r.provider_parity.heartbeat==="official-fallback")?$("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(he)}):$("heartbeat","approval_required","Heartbeat profile is enabled, but no scheduler desired state is active yet.",{checked_hosts:e.hosts.map(he)},[Nt("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 Hy(e){return e.profile?e.profile.recall_auto_trigger?$("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}):$("recall_auto_trigger","approval_required","Automatic recall trigger is intentionally disabled until explicit approval.",{recall_auto_trigger:!1},[Nt("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.")]):$("recall_auto_trigger","not_configured","No activation profile is present.",{})}function $y(e){if(!e.profile||!e.profile.memory_candidates)return $("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 $("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=>[he(r),r.provider_parity.hooks]))})}function Fy(e){return e.profile?e.profile.auto_promotion?$("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}):$("memory_promotion_policy","approval_required","Memory promotion requires explicit approval.",{auto_promotion:!1,promotion_policy:e.profile.promotion_policy}):$("memory_promotion_policy","not_configured","No activation profile is present.",{})}function Uy(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")?$("cross_host_verification","active","Multiple selected hosts were verified by deep doctor.",{host_count:t,ready_other_hosts:r}):$("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},[Nt("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 $(e,t,r,o,n=[]){return{key:e,status:t,summary:r,evidence:o,plan_actions:n}}function Nt(e,t,r,o,n,a,s){return{id:e,component:t,status:r,action:o,target:n,dry_run:!0,requires_user_confirmed:a,reason:s}}function By(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 Vy(e,t,r){return{overall_status:t,profile:e?.profile??null,active:eo(r,"active"),not_configured:eo(r,"not_configured"),approval_required:eo(r,"approval_required"),blocked_by_host:eo(r,"blocked_by_host"),degraded:eo(r,"degraded"),full_native_claimed:!1}}function eo(e,t){return e.filter(r=>r.status===t).length}function he(e){return e.surface==="default"?e.host:`${e.host}:${e.surface}`}import{existsSync as Wy}from"node:fs";import Jy from"node:path";async function to(e){let t=f(e),r=[],o=["AGENTS.md","SOUL.md","IDENTITY.md","USER.md","POLICY.md","MEMORY.md","HEARTBEAT.md","config.yaml"];for(let a of o)await S(Jy.join(t.home,a))||r.push({code:"MISSING_HUMAN_FILE",severity:"warn",message:`${a} is missing`,remediation:"Run nativesoul init"});if(!Wy(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 a=_(t.database,{readOnly:!0});try{return a.integrityCheck()}finally{a.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(...qy(t.home,t.database));try{await h({home:t.home,type:"doctor_completed",details:{integrity:n,issueCount:r.length}})}catch{}return{home:t.home,healthy:r.every(a=>a.severity!=="error"),integrity:n,issues:r}}function qy(e,t){let r=te(process.cwd(),e),o=_(t,{readOnly:!0});try{let n=new Set(o.listMemories({limit:200,includeForgotten:!0}).map(a=>a.scope.project).filter(a=>a!==r.id));return n.size===0?[]:[{code:"PROJECT_ID_RECONCILE_AVAILABLE",severity:"info",message:`Found ${n.size} memory project id(s) different from normalized current project ${r.id}.`,remediation:"Review with nativesoul memory export --project <old-id>; a future reconcile command will migrate aliases after approval."}]}finally{o.close()}}import Ee from"node:os";import G from"node:path";function hu(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 yu(e){return e==="claude"?".claude.json":e==="gemini"?"settings.json":e==="antigravity"?"mcp_config.json":"mcp.json"}function ro(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 Ke(e,t){return t&&t!=="default"?[ro(e,t)]:e==="claude"?["claude-code","claude-desktop"]:["default"]}function Mt(e,t){return t==="default"?e:t}function _u(e){switch(e){case"codex":return G.join(Ee.homedir(),".codex","AGENTS.md");case"claude":return G.join(Ee.homedir(),".claude","CLAUDE.md");case"grok":return G.join(Ee.homedir(),".grok","Agents.md");case"antigravity":case"gemini":return G.join(Ee.homedir(),".gemini","GEMINI.md")}}function An(e){switch(e){case"codex":return G.join(Ee.homedir(),".codex","mcp.json");case"claude":return G.join(Ee.homedir(),".claude.json");case"grok":return G.join(Ee.homedir(),".grok","mcp.json");case"antigravity":return G.join(Ee.homedir(),".gemini","antigravity-cli","mcp_config.json");case"gemini":return G.join(Ee.homedir(),".gemini","settings.json")}}function bu(){return vu({platform:process.platform,home:Ee.homedir(),env:process.env})}function vu(e){let t=e.platform==="win32"?G.win32:G.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 ku(e,t){if(e!=="claude")return null;if(!t)return G.join(Ee.homedir(),".claude","mcp.json");let r=G.resolve(t),o=G.dirname(r);return G.basename(o)==="claude"?G.join(o,"mcp.json"):G.join(o,".claude","mcp.json")}import{mkdir as wu,rename as Ky,writeFile as Su}from"node:fs/promises";import ye from"node:path";var Gy=["entity","soul","human","collaboration","continuity"],Xy=["SOUL.md","POLICY.md"],Au=new Set(["IDENTITY.md","SOUL.md","USER.md","AGENTS.md"]),ar=64*1024,zy="<!-- nativesoul:start v1 -->",Ru="<!-- nativesoul:end -->",Yy={"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:ar},"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:ar},"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:ar},"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:ar},"POLICY.md":{writable:!1,requires_user_confirmed:!1,field_format:"Use policy propose-change after onboarding",merge_strategy:"replace",max_bytes:0}};async function oo(e){let t=await v(e),o=(await me(t.home,"BOOTSTRAP.md")).trim().length>0;return{ritual_pending:o,files_present:{soul:await S(ye.join(t.home,"SOUL.md")),identity:await S(ye.join(t.home,"IDENTITY.md")),user:await S(ye.join(t.home,"USER.md")),agents:await S(ye.join(t.home,"AGENTS.md")),bootstrap:await S(ye.join(t.home,"BOOTSTRAP.md"))},protected_targets:[...Xy],writable_files:[...Au],interview_themes:[...Gy],instruction_doc:"llm-install.txt",apply_defaults:{dry_run:!0,user_confirmed:!1},file_generation_rules:Yy,activation:await mu(t.home,o)}}async function no(e){let t=await v(e.home),r=e.dry_run!==!1,o=e.user_confirmed===!0,n=[],a=[];for(let[s,i]of Object.entries(e.files)){let l=s.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(!Au.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 d=typeof i=="string"?i:"";if(Buffer.byteLength(d,"utf8")>ar){n.push({file:l,action:"rejected",before_hash:null,after_hash:null,warning:`FILE_TOO_LARGE: ${l} exceeds ${ar} bytes`});continue}let p=ye.join(t.home,l),g=await me(t.home,l),y=l==="AGENTS.md"?Qy(g,d):d,k=g.length>0?A(g):null,R=A(y);if(k===R){n.push({file:l,action:"noop",before_hash:k,after_hash:R});continue}let U=g.length===0?"create":"update";n.push({file:l,action:U,before_hash:k,after_hash:R}),r||await Su(p,y,{encoding:"utf8",mode:384})}return!r&&e.config_patch?.hosts?.length&&a.push(`CONFIG_PATCH_NOT_APPLIED_V1: hosts=${e.config_patch.hosts.join(",")}`),r||await h({home:t.home,type:"onboarding.applied",details:{user_confirmed:o,files:n.map(s=>({file:s.file,action:s.action}))}}),{dry_run:r,applied:!r,user_confirmed:o,files:n,warnings:a}}async function ao(e){let t=f(e?.home),r=ye.join(t.home,"BOOTSTRAP.md");if(!await S(r))return{already_complete:!0,archived_bootstrap:!1,archive_path:null};let o=e?.archive!==!1,n=null;if(o){let s=ye.join(t.home,"memory","archive");await wu(s,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/gu,"-");n=ye.join(s,`bootstrap-${i}.md`),await Ky(r,n)}else{let{rm:s}=await import("node:fs/promises");await s(r,{force:!0})}let a=ye.join(t.home,"state","onboarding.complete");return await wu(ye.join(t.home,"state"),{recursive:!0,mode:448}),await Su(a,`${new Date().toISOString()}
|
|
863
|
-
`,{encoding:"utf8",mode:384}),await h({home:t.home,type:"onboarding.completed",details:{archived:o,archive_path:n}}),{already_complete:!1,archived_bootstrap:o,archive_path:n}}function En(e){return ye.join(e,"state","onboarding.complete")}function
|
|
864
|
-
`;if(e.includes(r))return e;let o=
|
|
849
|
+
`).filter((t,r,o)=>r<o.length-1||t.length>0)}function Ud(e,t,r){let o=e.join(t);return r||e.length>0?`${o}${t}`:o}function Bd(e){return/^[A-Za-z0-9._/-]+$/u.test(e)?e:JSON.stringify(e)}import Qd from"node:path";var Uh={minLength:1,removeStopwords:!1,normalizeDiacritics:!1};function _n(e,t={}){let r={...Uh,...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||!Bh.has(n))??[]))}function Kr(e,t={}){return new Set(_n(e,t))}function ms(e,t){let r=_n(e);if(r.length===0)return 0;let o=Kr(t),n=r.filter(a=>o.has(a)).length;return Number((n/r.length).toFixed(6))}function Jd(e,t,r={}){let o=Kr(e,r),n=Kr(t,r);if(o.size===0||n.size===0)return 0;let a=[...o].filter(i=>n.has(i)).length,s=new Set([...o,...n]).size;return Number((a/s).toFixed(6))}function qd(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 Bh=new Set(["the","and","for","with","this","that","uma","com","para","por","que","deve","esta","este","essa","isso"]);var ot=1,nt="local-hash",at="local-hash-bow-v1";async function gs(e={}){let t=await v(e.home),r=Math.min(Math.max(e.limit??1e3,1),1e4),o=_(t.database),n,a=[],s=0,i=0;try{n=o.listSemanticIndexableMemories({limit:r});let l=new Date().toISOString();for(let c of n){let d=Vh(c),p=o.getSemanticIndex(c.id);if(p&&p.content_hash===d.contentHash&&p.provider_id===nt&&p.model_id===at&&p.schema_version===ot){s+=1;continue}d.redacted&&(i+=1),a.push({memory_id:c.id,scope_project:c.scope.project,source:c.source,schema_version:ot,provider_id:nt,model_id:at,content_hash:d.contentHash,embedding:Xd(d.text),indexed_text:d.text,indexed_at:l})}a.length>0&&o.upsertSemanticIndex(a)}finally{o.close()}return await h({home:t.home,type:"semantic_index_built",details:{provider_id:nt,model_id:at,schema_version:ot,indexable_count:n.length,indexed_count:a.length,skipped_unchanged:s,redacted_count:i}}),{provider_id:nt,model_id:at,schema_version:ot,indexable_count:n.length,indexed_count:a.length,skipped_unchanged:s,redacted_count:i}}function Gd(e){let t=_(e,{readOnly:!0});try{let r=t.semanticIndexStats({providerId:nt,modelId:at,schemaVersion:ot});return{provider_id:nt,model_id:at,schema_version:ot,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 Gr(e){let t=_(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:nt,modelId:at,schemaVersion:ot});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:Kd(o.length>0?o:t.recentMemories(e.project,r),e.query)};let a=t.listCurrentSemanticIndexesForProject({project:e.project,providerId:nt,modelId:at,schemaVersion:ot,limit:1e3}),s=t.listActiveMemoriesForProject(e.project,1e3),i=new Map(s.map(p=>[p.id,p])),l=new Map(o.map(p=>[p.id,ms(e.query,`${p.summary}
|
|
850
|
+
${p.content}`)])),c=Xd(e.query),d=a.map(p=>{let g=i.get(p.memory_id);if(!g)return null;let y=l.get(g.id)??0,k=qd(c,p.embedding);return{memory:g,ftsScore:y,semanticScore:k,score:Number((y*.55+k*.45).toFixed(6))}}).filter(p=>p!==null).filter(p=>p.ftsScore>0||p.semanticScore>0).sort((p,g)=>g.score-p.score||g.semanticScore-p.semanticScore||p.memory.id.localeCompare(g.memory.id)).slice(0,r).map((p,g)=>({...p.memory,recall:{mode:"hybrid",fts_score:p.ftsScore,semantic_score:p.semanticScore,final_rank:g+1,reason:p.ftsScore>0&&p.semanticScore>0?"fts_and_semantic":p.semanticScore>0?"semantic_neighbor":"fts_match"}}));return{mode:"hybrid",reason:"semantic_index_ready",memories:d.length>0?d:Kd(o,e.query)}}finally{t.close()}}function Vh(e){let t=N(`${e.summary}
|
|
851
|
+
|
|
852
|
+
${e.content}`);return{text:t.value,contentHash:e.hash,redacted:t.redacted}}function Xd(e){let r=Array.from({length:32},()=>0);for(let n of _n(e)){let a=Wh(n),s=a%32,i=a%2===0?1:-1;r[s]=(r[s]??0)+i}let o=Math.hypot(...r)||1;return r.map(n=>Number((n/o).toFixed(6)))}function Kd(e,t){return e.map((r,o)=>({...r,recall:{mode:"fts",fts_score:ms(t,`${r.summary}
|
|
853
|
+
${r.content}`),semantic_score:0,final_rank:o+1,reason:"fts_fallback"}}))}function Wh(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 qe(e,t=160){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function Xr(e){return Math.ceil(e.length/4)}function bn(e,t){return e.length<=t?e:`${e.slice(0,Math.max(t-3,0))}...`}var Et=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}},Jh=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 fs(e,t){let r=await v(e),o=await tu(r.database,t,"active");return await h({home:r.home,type:"memory_added",details:{id:o.id,project:o.scope.project,redacted:o.sensitivity==="restricted"}}),o}async function ie(e,t){let r=await v(e),o=await tu(r.database,t,"candidate");return await h({home:r.home,type:"memory_proposed",details:{id:o.id,project:o.scope.project,redacted:o.sensitivity==="restricted"}}),o}async function hs(e){let t=await v(e.home),r=Qd.resolve(e.cwd);await qr({cwd:r,home:t.home});let o=L(r,t.home),n=e.event?.trim()||"session-end",a=qh(e.text,e.payload),s=[`Session memory candidate from ${e.host} ${n} hook.`,"",`Project: ${o}`,`CWD: ${r}`,"","Summary:",a.text].join(`
|
|
854
|
+
`),i=await ie(t.home,{project:o,content:s,confidence:a.source==="stub"?.2:.45,authority:"hook_observed",source:{kind:"session_end_hook",host:e.host,event:n,cwd:r,summary_source:a.source}});return{proposed:!0,host:e.host,event:n,cwd:r,project:o,memory:i,summary_source:a.source}}function qh(e,t){let r=e?.trim();if(r)return{text:zd(r),source:"text"};let o=Kh(t);return o?{text:zd(o),source:"payload"}:{text:"No host session summary was supplied. Review this candidate against the recent session before promotion.",source:"stub"}}function Kh(e){if(typeof e=="string")return e.trim()||null;if(!e||Array.isArray(e)||typeof e!="object")return null;for(let t of["summary","session_summary","transcript_summary","conversation_summary","text","content"]){let r=e[t];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function zd(e){return e.length<=8e3?e:`${e.slice(0,7997)}...`}async function ys(e){let t=await v(e.home),r=Qd.resolve(e.cwd),o=L(r,t.home),n=await Gh(t.home),a=Zd(e.prompt,n),s=Math.min(Math.max(e.limit??3,1),3),i=[];if(a.triggered){let l=Gr({database:t.database,query:a.query,project:o,limit:s});i=l.memories,await h({home:t.home,type:"memory_recalled",details:{host:e.host,project:o,reason:a.reason,query:a.query,count:i.length,recall_mode:l.mode,recall_reason:l.reason}})}return{host:e.host,cwd:r,project:o,prompt:e.prompt,decision:a,memories:i,context:Xh(i,a)}}function Zd(e,t=eu()){let r=e.trim(),o=r.toLowerCase();if(!t.autoTrigger)return{triggered:!1,reason:"auto_trigger_disabled",denied:!1,auto_trigger:!1,query:r};if(r.length===0)return{triggered:!1,reason:"empty_prompt",denied:!0,auto_trigger:!0,query:r};let n=t.denylist.find(s=>o===s||o.startsWith(`${s} `));if(n)return{triggered:!1,reason:`denylist:${n}`,denied:!0,auto_trigger:!0,query:r};let a=t.keywords.find(s=>o.includes(s));return a?{triggered:!0,reason:`keyword:${a}`,denied:!1,auto_trigger:!0,query:r}:{triggered:!1,reason:"no_trigger",denied:!1,auto_trigger:!0,query:r}}function eu(){return{autoTrigger:!1,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"],denylist:["lint","format","typecheck","test","build"]}}async function Gh(e){let t=eu(),r=await me(e,"config.yaml"),o=r.match(/^\s*auto_trigger:\s*(true|false)\s*$/imu);o?.[1]&&(t.autoTrigger=o[1].toLowerCase()==="true");let n=Yd(r,"keywords");n.length>0&&(t.keywords=n.map(s=>s.toLowerCase()));let a=Yd(r,"denylist");return a.length>0&&(t.denylist=a.map(s=>s.toLowerCase())),t}function Yd(e,t){let r=e.split(/\r?\n/u),o=[],n=!1;for(let a of r){if(new RegExp(`^\\s*${t}:\\s*$`,"u").test(a)){n=!0;continue}if(!n)continue;let s=a.match(/^\s*-\s*["']?(.+?)["']?\s*$/u)?.[1];if(s){o.push(s.trim());continue}if(/^\s*\S/u.test(a))break}return o}function Xh(e,t){if(!t.triggered||e.length===0)return"";let r=["## NativeSoul Memory Recall",`Trigger: ${t.reason}`,""];for(let o of e)r.push(`- ${o.summary}`);return r.join(`
|
|
855
|
+
`).slice(0,1800)}async function Pt(e,t){return vn(e,t,"active","memory_promoted")}async function xt(e,t){return vn(e,t,"rejected","memory_rejected")}async function jt(e,t){return vn(e,t,"forgotten","memory_forgotten")}async function zr(e,t){return vn(e,t,"expired","memory_expired")}async function It(e){let t=await v(e.home),r=_(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 h({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 tu(e,t,r){let o=N(t.content),n=new Date().toISOString(),a=qe(o.value),s={id:T("mem"),type:t.type??"note",scope:{user:"default",project:t.project},content:o.value,summary:a,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:ke({type:t.type??"note",project:t.project,content:o.value,status:r,created_at:n})},i=_(e);try{i.insertMemory(s)}finally{i.close()}return s}async function vn(e,t,r,o){let n=await v(e),a=_(n.database),s,i;try{if(s=a.getMemory(t),s&&!kn(s.status,r))throw new Et({id:t,from:s.status,to:r});i=s?a.updateMemoryStatus(t,r):null}catch(l){throw l instanceof Et&&await zh({home:n.home,id:l.id,from:l.from,to:l.to}),l}finally{a.close()}if(!i)throw new Error(`Memory not found: ${t}`);return await h({home:n.home,type:o,details:{id:i.id,project:i.scope.project,status:r}}),i}function kn(e,t){return Jh.get(e)?.has(t)??!1}async function zh(e){await h({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 Tt(e,t,r,o=5){let n=await v(e),a=Gr({database:n.database,query:t,project:r,limit:Math.min(Math.max(o,1),8)});return await h({home:n.home,type:"memory_searched",details:{query:t,project:r,count:a.memories.length,recall_mode:a.mode,recall_reason:a.reason}}),a.memories}async function _s(e){let t=f(e.home),r=null;try{r=_(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:ru(e.resolution),status:"active",now:e.now});return r.close(),r=null,o.inserted&&await h({home:t.home,type:"project_seen",details:{id:e.resolution.id,base_id:e.resolution.base_id,source:e.resolution.source,first_basis:ru(e.resolution)}}),{touched:!0,inserted:o.inserted,degraded:!1,warning:null}}catch(o){return{touched:!1,inserted:!1,degraded:!0,warning:`PROJECT_REGISTRY_UNAVAILABLE:${ry(o)}`}}finally{r?.close()}}async function bs(e={}){let t=f(e.home),r=Zh(e.limit),o=e.status??"active";if(!await S(t.database))return{registry_available:!1,status:o,limit:r,projects:[],warning:"database_not_available"};let n=_(t.database,{readOnly:e.readOnly??!0});try{let a=n.listProjectsWithCounts({status:o,limit:r});return{registry_available:a.available,status:o,limit:r,projects:a.projects,warning:a.warning}}finally{n.close()}}async function vs(e){let t=f(e.home),r=e.id==="."?Yh(e.cwd??process.cwd(),t.home):Qh(e.id);if(!await S(t.database))return ou(e.id,r,"database_not_available");let o=_(t.database,{readOnly:e.readOnly??!0});try{let n=o.getProjectDetail(r.id);if(!n.available)return ou(e.id,r,n.warning);let a=n.detail;return{registry_available:!0,requested:e.id,effective_id:r.id,registry:a?.project??null,live_resolution:r,counts:a?.counts??null,derived_last_seen_at:a?.derived_last_seen_at??null,continuity_gap:!!(a?.project&&a.project.base_id!==r.id),warning:a?.project?null:"project_not_found"}}finally{o.close()}}async function ks(e){let t=f(e.home),r=ey(e.name),o=e.id==="."?te(e.cwd??process.cwd(),t.home).id:e.id,n=_(t.database),a;try{a=n.renameProject(o,r)}finally{n.close()}return a.found&&a.previous&&a.project&&await h({home:t.home,type:"project_renamed",details:{id:o,old_name:a.previous.display_name,new_name:r}}),{found:a.found,id:o,old_name:a.previous?.display_name??null,new_name:r,project:a.project}}async function ws(e){let t=f(e.home),r=e.includeMemories===!0,o=e.apply===!0,n=e.confirm??null,a=!r||o&&n===e.id,s=_(t.database);try{let i=s.getProject(e.id);if(!i)return wn({found:!1,id:e.id,mode:r?"forget_memories":"archive",applied:!1,guardOk:a,confirm:n,previousStatus:null,statusAfter:null,memoriesAffected:0,project:null,warning:"project_not_found"});if(r&&!a)return wn({found:!0,id:e.id,mode:"forget_memories",applied:!1,guardOk:a,confirm:n,previousStatus:i.status,statusAfter:i.status,memoriesAffected:s.countProjectMemories(e.id),project:i,warning:"requires --apply --confirm <id>"});if(r)try{let c=s.forgetProjectMemories(e.id,kn);return c.found&&c.project&&await h({home:t.home,type:"project_forgotten",details:{id:e.id,memories_affected:c.memories_affected}}),wn({found:c.found,id:e.id,mode:"forget_memories",applied:c.found,guardOk:a,confirm:n,previousStatus:c.previous?.status??null,statusAfter:c.project?.status??null,memoriesAffected:c.memories_affected,project:c.project,warning:c.found?null:"project_not_found"})}catch(c){throw c instanceof Yt&&await h({home:t.home,type:"memory_transition_blocked",result:"blocked",details:{id:c.id,from:c.from,to:c.to,code:c.code,project:e.id}}),c}let l=s.archiveProject(e.id);return l.found&&l.project&&await h({home:t.home,type:"project_archived",details:{id:e.id}}),wn({found:l.found,id:e.id,mode:"archive",applied:l.found,guardOk:a,confirm:n,previousStatus:l.previous?.status??null,statusAfter:l.project?.status??null,memoriesAffected:0,project:l.project,warning:l.found?null:"project_not_found"})}finally{s.close()}}async function Rs(e){let t=f(e.home),r=_(t.database),o;try{o=r.reactivateProject(e.id)}finally{r.close()}return o.found&&o.project&&await h({home:t.home,type:"project_reactivated",details:{id:e.id}}),{found:o.found,id:e.id,previous_status:o.previous?.status??null,status_after:o.project?.status??null,project:o.project}}async function Ss(e={}){return{aliases:us(f(e.home).home)}}async function As(e){let t=f(e.home),r=await ps({home:t.home,action:"add",aliasKey:nu(e.alias),projectId:ty(e.id),apply:e.apply});return r.applied&&r.changed&&await h({home:t.home,type:"project_alias_set",details:{alias_key:r.alias_key,project_id:r.project_id,previous_project_id:r.previous_id}}),r}async function Es(e){let t=f(e.home),r=await ps({home:t.home,action:"remove",aliasKey:nu(e.alias),apply:e.apply});return r.applied&&r.changed&&await h({home:t.home,type:"project_alias_removed",details:{alias_key:r.alias_key,previous_project_id:r.previous_id}}),r}function ru(e){return e.remote??e.git_root??e.cwd}function Yh(e,t){let r=te(e,t);return{id:r.id,source:r.source,cwd:r.cwd,git_root:r.git_root,remote:r.remote,base_id:r.base_id,alias_key:r.alias_key,marker_path:r.marker_path}}function Qh(e){return{id:e,source:"explicit",cwd:null,git_root:null,remote:null,base_id:null,alias_key:null,marker_path:null}}function ou(e,t,r){return{registry_available:!1,requested:e,effective_id:t.id,registry:null,live_resolution:t,counts:null,derived_last_seen_at:null,continuity_gap:!1,warning:r}}function Zh(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),500)}function ey(e){let t=e.trim();if(t.length===0)throw new Error("project rename requires a non-empty --name");return t.slice(0,160)}function nu(e){let t=e.trim();if(t.length===0)throw new Error("project alias requires a non-empty alias");return t}function ty(e){let t=e.trim();if(t.length===0||t===".")throw new Error("project alias add requires an explicit project id");return t}function wn(e){return{found:e.found,id:e.id,mode:e.mode,applied:e.applied,dry_run:!e.applied,guard_ok:e.guardOk,required_confirm:e.mode==="forget_memories"?e.id:null,confirm:e.confirm,previous_status:e.previousStatus,status_after:e.statusAfter,memories_affected:e.memoriesAffected,project:e.project,warning:e.warning}}function ry(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}var oy=/^-\s*\*\*([^:*]+):\*\*\s*(.*)$/u;function Ct(e,t){let r=ny(e,t);if(r)return r;let o=e.split(/\r?\n/u);for(let n=0;n<o.length;n+=1){let s=(o[n]?.trim()??"").match(oy);if(!s||s[1]?.trim()!==t)continue;let i=s[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 au(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 su(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 ny(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 gy,mkdir as lu,readFile as fy,rename as hy,stat as yy,writeFile as _y}from"node:fs/promises";import{existsSync as cu}from"node:fs";import Ot from"node:path";import{mkdir as ay,readFile as sy,rename as iy,writeFile as ly}from"node:fs/promises";import Yr from"node:path";var cy=1440*60*1e3;async function Me(e){let t=f(e.home),r=await Ps(t.home),o={host:e.host,outcome:e.outcome,tier:e.tier,cwd:e.cwd?Yr.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:my(e.error),recorded_at:e.recordedAt??new Date().toISOString()};return r.hosts[e.host]=o,await uy(t.home,r),await h({home:t.home,type:py(e.outcome),result:e.outcome==="failed"?"error":"ok",details:o}),o}async function Ps(e){let t=f(e),r=js(t.home);if(!await S(r))return dy();let o=JSON.parse(await sy(r,"utf8"));return{schema:1,hosts:typeof o.hosts=="object"&&o.hosts!==null?o.hosts:{}}}async function xs(e){let t=f(e.home),o=(await Ps(t.home)).hosts[e.host]??null,n=(e.now??new Date).getTime(),a=o?Date.parse(o.recorded_at):Number.NaN,s=Number.isFinite(a)?Math.max(n-a,0):null;return{state_path:js(t.home),last:o,age_ms:s,age_hours:s===null?null:Math.round(s/(3600*1e3)*10)/10,stale:s!==null&&s>cy}}function dy(){return{schema:1,hosts:{}}}async function uy(e,t){let r=js(e);await ay(Yr.dirname(r),{recursive:!0,mode:448});let o=Yr.join(Yr.dirname(r),`.last-handshake-${T("tmp")}.tmp`);await ly(o,`${JSON.stringify(t,null,2)}
|
|
856
|
+
`,{encoding:"utf8",mode:384}),await iy(o,r)}function js(e){return Yr.join(e,"state","last-handshake.json")}function py(e){return`handshake_${e}`}function my(e){if(e==null)return null;let t=e instanceof Error?e.message:String(e);return N(t).value.slice(0,500)}var iu=8;function or(e){let t=e.generatedAt??new Date().toISOString(),r=e.degraded===!0,o=[...e.payload.warnings,...e.warnings??[]],n=e.payload.capabilities.slice(0,iu),a=e.payload.capability_cards.slice(0,iu),s=["---","nativesoul: bootstrap-context",`bootstrap_schema: ${e.payload.bootstrap_schema}`,`host: ${e.host}`,`generated_at: ${t}`,`degraded: ${r?"true":"false"}`,`tokens_used: ${e.payload.context_budget.tokens_used}`,`tokens_max: ${e.payload.context_budget.tokens_max}`,o.length>0?`warnings: ${o.join(", ")}`:"warnings: none","---","",`You are ${e.payload.identity.name}; follow soul_summary and agents_operating_summary.`,`Global entity: ${e.payload.identity.name}. Project rules apply for code boundaries; persona remains ${e.payload.identity.name}.`,"","## Identity",`- Name: ${e.payload.identity.name}`,`- Mission: ${e.payload.identity.mission}`,e.payload.identity.role?`- Role: ${e.payload.identity.role}`:null,e.payload.identity.vibe?`- Vibe: ${e.payload.identity.vibe}`:null,"","## Soul Summary",e.payload.soul_summary,"","## Operating Summary",e.payload.agents_operating_summary,"","## User Preferences",e.payload.user.preferences_summary,"","## Project",`- ID: ${e.payload.project.id}`,`- CWD: ${e.payload.project.cwd}`,"","## Tool Hints",...e.payload.tool_hints.map(i=>`- ${i.tool}: ${i.use_when}`),"","## Relevant Memories",...e.payload.relevant_memories.length>0?e.payload.relevant_memories.map(i=>`- ${i.id}: ${i.summary}`):["- none"],"","## Commitments",...e.payload.commitments.length>0?e.payload.commitments.map(i=>`- ${JSON.stringify(i)}`):["- none"],"","## Capabilities",...n.length>0?n.map(i=>`- ${i.uid} (${i.host}, ready=${i.ready}): ${i.source}`):["- none"],"","## Capability Cards",...a.length>0?a.map(i=>`- ${i.uid} (${i.host}, ready=${i.ready}): ${i.use_when[0]??i.source}`):["- none"],""].filter(i=>i!==null).join(`
|
|
857
|
+
`);return{host:e.host,generated_at:t,degraded:r,warnings:o,tokens_used:Cs(s),tokens_max:e.payload.context_budget.tokens_max,content:s}}async function Rn(e){let t=f(e.home),r=or({host:e.host,payload:e.payload}),o=Ts(t.home,e.host),n=cu(o)&&e.apply!==!1?await vy(t.home,e.host,o):null;if(e.apply!==!1){await lu(Ot.dirname(o),{recursive:!0,mode:448});let s=Ot.join(Ot.dirname(o),`.last-context-${T("tmp")}.tmp`);await _y(s,r.content,{encoding:"utf8",mode:384}),await hy(s,o)}let a={...r,targetPath:o,backupPath:n,applied:e.apply!==!1};return e.recordTelemetry!==!1&&await h({home:t.home,type:e.apply===!1?"bootstrap_context_cache_dry_run":"bootstrap_context_cache_written",details:{...a,content:"[omitted]"}}),e.apply!==!1&&e.recordTelemetry!==!1&&await Me({home:t.home,host:e.host,outcome:"succeeded",tier:"A",cwd:e.payload.project.cwd,project:e.payload.project.id,tokensUsed:r.tokens_used,tokensMax:r.tokens_max,source:"bootstrap-inject",warnings:r.warnings}),a}async function rr(e){let t=f(e.home),r=Ts(t.home,e.host);if(!cu(r))return by({home:t.home,host:e.host,targetPath:r,recordTelemetry:e.recordTelemetry});let o=await fy(r,"utf8"),n=await yy(r),a=e.ttlDays??7,s=Date.now()-n.mtimeMs>a*24*60*60*1e3,i=new Date().toISOString(),l=s?["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(`
|
|
858
|
+
`),d={host:e.host,generated_at:i,degraded:!0,warnings:l,tokens_used:Cs(c),tokens_max:1900,content:c,targetPath:r,stale:s};if(e.recordTelemetry!==!1){await h({home:t.home,type:"bootstrap_context_cache_read",details:{...d,content:"[omitted]"}});let p=ky(o);await Me({home:t.home,host:e.host,outcome:"degraded",tier:"D",cwd:p.cwd,project:p.project,tokensUsed:d.tokens_used,tokensMax:d.tokens_max,source:"bootstrap-cache",warnings:l})}return d}async function Is(e){let t=await rr({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 rr({home:Qr(e.projectCwd),host:e.host,ttlDays:e.ttlDays,recordTelemetry:!1});return r.warnings.includes("BOOTSTRAP_CACHE_MISSING")?t:r}function Ts(e,t){return Ot.join(e,"generated",t,"last-context.md")}function Qr(e){return Ot.join(e,".nativesoul-cache")}async function by(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(`
|
|
859
|
+
`),n={host:e.host,generated_at:t,degraded:!0,warnings:r,tokens_used:Cs(o),tokens_max:1900,content:o,targetPath:e.targetPath,stale:!1};return e.recordTelemetry!==!1&&(await h({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}async function vy(e,t,r){let o=Ot.join(e,"backups","bootstrap-context");await lu(o,{recursive:!0,mode:448});let n=Ot.join(o,`${new Date().toISOString().replaceAll(/[:.]/gu,"-")}-${t}-last-context.md`);return await gy(r,n),n}function Cs(e){return Math.ceil(e.length/4)}function ky(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 du=3e3,uu=new WeakMap;async function it(e){let t=e.readOnly?f(e.home):await v(e.home),r=await Ey(t.home),o=Math.min(Math.max(e.tokensMax??r.defaultTokens,1),du),n=[];e.readOnly!==!0&&await qr({cwd:e.cwd,home:t.home});let a=te(e.cwd,t.home),s=a.id;if(e.readOnly!==!0){let V=await _s({home:t.home,resolution:a});V.warning&&n.push(V.warning)}let i=Py({explicitQuery:e.query,project:s,host:e.host,cwd:e.cwd,seed:r.memoryQuerySeed}),l=await Ry({database:t.database,readOnly:e.readOnly===!0,memoryQuery:i,project:s,limit:r.recallLimit,warnings:n}),c=l.memories,d=await Ae({home:t.home,host:e.host,readyOnly:!0,limit:8,readOnly:e.readOnly}),p=await Iy(t.home,e.host,e.readOnly===!0),g=await as({home:t.home,host:e.host,query:e.query??`${Le.basename(e.cwd)} ${e.host}`,limit:8,readOnly:e.readOnly}),y=await Wr({home:t.home,project:s,status:"open",limit:8,readOnly:e.readOnly}),k=await me(t.home,"IDENTITY.md"),R=await me(t.home,"SOUL.md"),U=await me(t.home,"AGENTS.md"),Y=await me(t.home,"USER.md"),be=await me(t.home,"BOOTSTRAP.md"),Ie=new Date().toISOString().slice(0,10),ne=Le.join(t.home,"memory","daily",`${Ie}.md`);n.push(...p?[]:[`HOST_ADAPTER_UNAVAILABLE:${e.host}`,"CAPABILITY_REFRESH_STALE"],...g.warnings),!await S(Le.join(t.home,"state","onboarding.complete"))&&be.trim().length>0&&n.push("BOOTSTRAP_RITUAL_PENDING"),await S(ne)&&n.push(`DAILY_MEMORY_AVAILABLE:${ne}`),r.warnEmptyMemories&&c.length===0&&n.push("PROJECT_MEMORY_EMPTY");let x={bootstrap_schema:2,identity:{name:Ct(k,"Name")??"NativeSoul",mission:Ct(k,"Mission")??"Provide local continuity across native coding-agent hosts.",creature:Ct(k,"Creature"),role:Ct(k,"Role"),vibe:Ct(k,"Vibe"),emoji:Ct(k,"Emoji")},soul_summary:au(R||"Continuity, clarity, and safe local-first operation.",500),agents_operating_summary:su(U||"Load NativeSoul context before continuity-sensitive work. Use MCP when available and CLI fallback when needed."),tool_hints:xy(),user:{preferences_summary:jy(Y)},project:{id:s,cwd:Le.resolve(e.cwd),state:"local-bootstrap"},commitments:y.map(V=>({id:V.id,status:V.status,summary:V.summary,due_at:V.due_at,ttl_expires_at:V.ttl_expires_at})),relevant_memories:c.map(V=>({id:V.id,summary:V.summary,scope:V.scope})),capabilities:d.map(V=>({uid:V.uid,host:V.host,ready:V.ready,source:V.source})),capability_cards:g.cards,policy:{mode:"safe",approval_required:["external_write","destructive","identity_policy_change"]},warnings:n},Ar=Ty(x,o),Jo=Xr(JSON.stringify(Ar)),Er={...Ar,context_budget:{tokens_used:Jo,tokens_max:o}};return uu.set(Er,{files:Sy({home:t.home,identityText:k,soulText:R,agentsText:U,userText:Y,bootstrapText:be,payload:Er}),memoryRecall:{query:i,limit:r.recallLimit,returned:c.length,mode:l.mode},cache:pu(t.home,e.host)}),e.readOnly||await h({home:t.home,type:"bootstrap_created",details:{host:e.host,cwd:Le.resolve(e.cwd),project:s,tokens:Jo}}),Er}async function Ry(e){if(!await S(e.database))return e.warnings.push("BOOTSTRAP_DATABASE_MISSING"),{memories:[],mode:"disabled"};let t=null;try{t=_(e.database,{readOnly:e.readOnly});let r=Gr({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:${Ay(r)}`),{memories:[],mode:"disabled"}}finally{t?.close()}}async function Ns(e){let t=await it({home:e.home,host:e.host,cwd:e.cwd,query:e.query,tokensMax:e.tokensMax,readOnly:!0}),r=or({host:e.host,payload:t,generatedAt:e.generatedAt}),o=uu.get(t)??{files:[],memoryRecall:{limit:0,returned:t.relevant_memories.length,mode:"disabled"},cache:pu(e.home??"",e.host)};return{host:e.host,cwd:Le.resolve(e.cwd),project:t.project,files:o.files,memoryRecall:o.memoryRecall,budget:{unit:"tokens",softMax:t.context_budget.tokens_max,hardMax:du,used:r.tokens_used},warnings:r.warnings,cache:o.cache,degraded:r.degraded}}function Sy(e){return[Zr({home:e.home,relativePath:"IDENTITY.md",role:"identity",rawText:e.identityText,injectedText:Object.values(e.payload.identity).filter(t=>typeof t=="string").join(`
|
|
860
|
+
`),fallbackReason:"missing; default identity fields injected"}),Zr({home:e.home,relativePath:"SOUL.md",role:"soul_summary",rawText:e.soulText,injectedText:e.payload.soul_summary,fallbackReason:"missing; default soul summary injected"}),Zr({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"}),Zr({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"}),Zr({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 Zr(e){let t=e.rawText.length,r=e.injectedText.length,o=t>0,n=r>0,a=o?e.presentReason??(r<t?"included; summarized to fit budget":"included"):e.fallbackReason;return{path:Le.join(e.home,e.relativePath),role:e.role,included:n,reason:a,rawChars:t,injectedChars:r,truncated:o&&n&&r<t,hash:o?A(e.rawText):null}}function pu(e,t){let r=Le.join(e,"generated",t,"last-context.md");return{hit:wy(r),key:r}}function Ay(e){return(e instanceof Error?e.message:String(e)).replace(/[^a-zA-Z0-9_.:-]+/g,"_").slice(0,120)}async function Ey(e){let t=await me(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),a=t.match(/^\s*warn_empty_memories:\s*(true|false)\s*$/imu),s=r?.[1]?Number(r[1]):1900,i=o?.[1]?Number(o[1]):5;return{defaultTokens:Number.isFinite(s)?s:1900,recallLimit:Number.isFinite(i)?Math.min(Math.max(i,1),8):5,memoryQuerySeed:n?.[1]?.trim()||null,warnEmptyMemories:a?.[1]?.toLowerCase()==="true"}}function Py(e){return[e.explicitQuery,e.project,e.host,Le.basename(Le.resolve(e.cwd)),e.seed].filter(t=>typeof t=="string"&&t.trim().length>0).join(" ")}function xy(){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 jy(e){let t=e.trim();return t.length===0?"No curated user preferences yet.":t.length<=160?t:`${t.slice(0,157)}...`}async function Iy(e,t,r=!1){let o=await Ae({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 a=Date.parse(n);if(!Number.isFinite(a))return!1;let s=1440*60*1e3;return Date.now()-a<=s}function Ty(e,t){let r=[e,st(e,1200,420,150),st(e,900,320,130),st(e,650,240,110),st(e,420,180,90),st(e,240,120,80),Os(st(e,240,120,80),8,8),Os(st(e,240,120,80),5,5),Os(st(e,240,120,80),3,3)];return r.find(o=>Xr(JSON.stringify(o))<=t)??r[r.length-1]??e}function Os(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 st(e,t,r,o){return{...e,soul_summary:bn(e.soul_summary,r),agents_operating_summary:bn(e.agents_operating_summary,t),user:{...e.user,preferences_summary:bn(e.user.preferences_summary,o)}}}import{existsSync as ii}from"node:fs";import dp from"node:path";import{mkdir as Cy,readFile as Oy,writeFile as mu}from"node:fs/promises";import Ms from"node:path";var Sn={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 gu(e,t){let r=await lt(e),o=await S(nr(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:Sn,apply_defaults:{dry_run:!0,user_confirmed:!1,reset:!1}}}async function Ls(e){let t=await v(e.home),r=e.dry_run!==!1,o=e.user_confirmed===!0,n=e.reset===!0,a=await lt(t.home);if(a&&!n)return{dry_run:r,applied:!1,user_confirmed:o,reset:n,action:"preserved",before:a,after:a,diff:[],warnings:["ACTIVATION_PROFILE_PRESERVED: use reset=true to replace existing activation choices"]};let s=Ny(e.profile,e.options),i=Ly(a,s);if(!r&&!o)return{dry_run:r,applied:!1,user_confirmed:o,reset:n,action:"rejected",before:a,after:s,diff:i,warnings:["ACTIVATION_REQUIRES_USER_CONFIRMED"]};let l=a?i.length===0?"noop":"update":"create";return r||(await Cy(Ms.join(t.home,"state"),{recursive:!0,mode:448}),await mu(fu(t.home),`${JSON.stringify(s,null,2)}
|
|
861
|
+
`,{encoding:"utf8",mode:384}),await mu(nr(t.home),`${new Date().toISOString()}
|
|
862
|
+
`,{encoding:"utf8",mode:384}),await h({home:t.home,type:"activation.profile.applied",details:{profile:s.profile,reset:n,diff:i.map(c=>c.field)}})),{dry_run:r,applied:!r,user_confirmed:o,reset:n,action:l,before:a,after:s,diff:i,warnings:[]}}function fu(e){return Ms.join(e,"state","activation-profile.json")}function nr(e){return Ms.join(e,"state","activation.complete")}async function lt(e){try{let t=JSON.parse(await Oy(fu(e),"utf8"));return Dy(t)?t:null}catch{return null}}function Ny(e,t){return{...Sn,...My(t),profile:e,updated_at:new Date().toISOString()}}function My(e){if(!e)return{};if(e.candidate_auto_promotion_threshold!==void 0){let t=e.candidate_auto_promotion_threshold;if(!Number.isFinite(t)||t<0||t>1)throw new Error("Invalid candidate_auto_promotion_threshold: expected a number between 0 and 1")}if(e.promotion_policy!==void 0&&e.promotion_policy!=="manual"&&e.promotion_policy!=="explicit_approval")throw new Error("Invalid promotion_policy: expected manual or explicit_approval");if(e.memory_candidate_policy!==void 0&&e.memory_candidate_policy!=="candidate"&&e.memory_candidate_policy!=="off")throw new Error("Invalid memory_candidate_policy: expected candidate or off");if(e.recall_auto_trigger_keywords!==void 0&&(!Array.isArray(e.recall_auto_trigger_keywords)||e.recall_auto_trigger_keywords.some(t=>typeof t!="string")))throw new Error("Invalid recall_auto_trigger_keywords: expected string array");if(e.recall_auto_trigger_denylist!==void 0&&(!Array.isArray(e.recall_auto_trigger_denylist)||e.recall_auto_trigger_denylist.some(t=>typeof t!="string")))throw new Error("Invalid recall_auto_trigger_denylist: expected string array");if(e.standing_order_templates!==void 0&&!Array.isArray(e.standing_order_templates))throw new Error("Invalid standing_order_templates: expected string array");if(e.standing_order_templates!==void 0&&e.standing_order_templates.some(t=>typeof t!="string"))throw new Error("Invalid standing_order_templates: expected string array");return{...e,recall_auto_trigger_keywords:Array.isArray(e.recall_auto_trigger_keywords)?e.recall_auto_trigger_keywords:void 0,recall_auto_trigger_denylist:Array.isArray(e.recall_auto_trigger_denylist)?e.recall_auto_trigger_denylist:void 0,standing_order_templates:Array.isArray(e.standing_order_templates)?e.standing_order_templates:void 0}}function Ly(e,t){return["profile","heartbeat_enabled","scheduler_host","heartbeat_cadence","memory_candidates","memory_candidate_policy","auto_promotion","promotion_policy","recall_auto_trigger_keywords","recall_auto_trigger_denylist","candidate_auto_promotion_threshold","recall_auto_trigger","standing_order_templates"].flatMap(o=>{let n=e?.[o]??null,a=t[o];return JSON.stringify(n)===JSON.stringify(a)?[]:[{field:o,before:n,after:a}]})}function Dy(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 Ds(e){let t={bootstrap:Hy(e),mcp:$y(e),plugins_hooks:Fy(e),heartbeat:Uy(e),recall_auto_trigger:By(e),memory_candidate_hooks:Vy(e),memory_promotion_policy:Wy(e),cross_host_verification:Jy(e)},r=Object.values(t),o=qy(r),n=r.flatMap(s=>s.plan_actions),a=Ky(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:a}}function hu(e){return Ds(e).summary}function Hy(e){return e.onboardingComplete&&e.activationComplete&&e.profile?$("bootstrap","active","Identity onboarding and activation marker are present.",{onboarding_complete:!0,activation_complete:!0}):$("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},[Nt("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 $y(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 $("mcp",r?"degraded":"active",r?"MCP is configured but doctor reported warnings.":"MCP registration is configured.",{configured_hosts:t.map(he),checked_hosts:e.hosts.map(he)})}return $("mcp","not_configured","No MCP registration was detected for the selected host scope.",{checked_hosts:e.hosts.map(he)},[Nt("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 Fy(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 $("plugins_hooks",o?"degraded":"active",o?"Plugin/hooks are available through fallback support.":"Native plugin or hook support is active.",{enabled_hosts:t.map(he),hook_modes:Object.fromEntries(e.hosts.map(n=>[he(n),n.provider_parity.hooks]))})}let r=e.hosts.length>0&&e.hosts.every(o=>o.plugin.package_kind==="unsupported-native");return $("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(he)},[Nt("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 Uy(e){if(!e.profile||!e.profile.heartbeat_enabled)return $("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?$("heartbeat","blocked_by_host","At least one selected host lacks native scheduler support.",{blocked_hosts:t.map(he),heartbeat_modes:Object.fromEntries(e.hosts.map(r=>[he(r),r.provider_parity.heartbeat]))},[Nt("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")?$("heartbeat","active","Heartbeat has native scheduler support in the selected scope.",{native_hosts:e.hosts.filter(r=>r.provider_parity.heartbeat==="native").map(he)}):e.hosts.some(r=>r.provider_parity.heartbeat==="official-fallback")?$("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(he)}):$("heartbeat","approval_required","Heartbeat profile is enabled, but no scheduler desired state is active yet.",{checked_hosts:e.hosts.map(he)},[Nt("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 By(e){return e.profile?e.profile.recall_auto_trigger?$("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}):$("recall_auto_trigger","approval_required","Automatic recall trigger is intentionally disabled until explicit approval.",{recall_auto_trigger:!1},[Nt("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.")]):$("recall_auto_trigger","not_configured","No activation profile is present.",{})}function Vy(e){if(!e.profile||!e.profile.memory_candidates)return $("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 $("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=>[he(r),r.provider_parity.hooks]))})}function Wy(e){return e.profile?e.profile.auto_promotion?$("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}):$("memory_promotion_policy","approval_required","Memory promotion requires explicit approval.",{auto_promotion:!1,promotion_policy:e.profile.promotion_policy}):$("memory_promotion_policy","not_configured","No activation profile is present.",{})}function Jy(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")?$("cross_host_verification","active","Multiple selected hosts were verified by deep doctor.",{host_count:t,ready_other_hosts:r}):$("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},[Nt("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 $(e,t,r,o,n=[]){return{key:e,status:t,summary:r,evidence:o,plan_actions:n}}function Nt(e,t,r,o,n,a,s){return{id:e,component:t,status:r,action:o,target:n,dry_run:!0,requires_user_confirmed:a,reason:s}}function qy(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 Ky(e,t,r){return{overall_status:t,profile:e?.profile??null,active:eo(r,"active"),not_configured:eo(r,"not_configured"),approval_required:eo(r,"approval_required"),blocked_by_host:eo(r,"blocked_by_host"),degraded:eo(r,"degraded"),full_native_claimed:!1}}function eo(e,t){return e.filter(r=>r.status===t).length}function he(e){return e.surface==="default"?e.host:`${e.host}:${e.surface}`}import{existsSync as Gy}from"node:fs";import Xy from"node:path";async function to(e){let t=f(e),r=[],o=["AGENTS.md","SOUL.md","IDENTITY.md","USER.md","POLICY.md","MEMORY.md","HEARTBEAT.md","config.yaml"];for(let a of o)await S(Xy.join(t.home,a))||r.push({code:"MISSING_HUMAN_FILE",severity:"warn",message:`${a} is missing`,remediation:"Run nativesoul init"});if(!Gy(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 a=_(t.database,{readOnly:!0});try{return a.integrityCheck()}finally{a.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(...zy(t.home,t.database));try{await h({home:t.home,type:"doctor_completed",details:{integrity:n,issueCount:r.length}})}catch{}return{home:t.home,healthy:r.every(a=>a.severity!=="error"),integrity:n,issues:r}}function zy(e,t){let r=te(process.cwd(),e),o=_(t,{readOnly:!0});try{let n=new Set(o.listMemories({limit:200,includeForgotten:!0}).map(a=>a.scope.project).filter(a=>a!==r.id));return n.size===0?[]:[{code:"PROJECT_ID_RECONCILE_AVAILABLE",severity:"info",message:`Found ${n.size} memory project id(s) different from normalized current project ${r.id}.`,remediation:"Review with nativesoul memory export --project <old-id>; a future reconcile command will migrate aliases after approval."}]}finally{o.close()}}import Ee from"node:os";import G from"node:path";function yu(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 _u(e){return e==="claude"?".claude.json":e==="gemini"?"settings.json":e==="antigravity"?"mcp_config.json":"mcp.json"}function ro(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 Ke(e,t){return t&&t!=="default"?[ro(e,t)]:e==="claude"?["claude-code","claude-desktop"]:["default"]}function Mt(e,t){return t==="default"?e:t}function bu(e){switch(e){case"codex":return G.join(Ee.homedir(),".codex","AGENTS.md");case"claude":return G.join(Ee.homedir(),".claude","CLAUDE.md");case"grok":return G.join(Ee.homedir(),".grok","Agents.md");case"antigravity":case"gemini":return G.join(Ee.homedir(),".gemini","GEMINI.md")}}function An(e){switch(e){case"codex":return G.join(Ee.homedir(),".codex","mcp.json");case"claude":return G.join(Ee.homedir(),".claude.json");case"grok":return G.join(Ee.homedir(),".grok","mcp.json");case"antigravity":return G.join(Ee.homedir(),".gemini","antigravity-cli","mcp_config.json");case"gemini":return G.join(Ee.homedir(),".gemini","settings.json")}}function vu(){return ku({platform:process.platform,home:Ee.homedir(),env:process.env})}function ku(e){let t=e.platform==="win32"?G.win32:G.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 wu(e,t){if(e!=="claude")return null;if(!t)return G.join(Ee.homedir(),".claude","mcp.json");let r=G.resolve(t),o=G.dirname(r);return G.basename(o)==="claude"?G.join(o,"mcp.json"):G.join(o,".claude","mcp.json")}import{mkdir as Ru,rename as Yy,writeFile as Au}from"node:fs/promises";import ye from"node:path";var Qy=["entity","soul","human","collaboration","continuity"],Zy=["SOUL.md","POLICY.md"],Eu=new Set(["IDENTITY.md","SOUL.md","USER.md","AGENTS.md"]),ar=64*1024,e_="<!-- nativesoul:start v1 -->",Su="<!-- nativesoul:end -->",t_={"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:ar},"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:ar},"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:ar},"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:ar},"POLICY.md":{writable:!1,requires_user_confirmed:!1,field_format:"Use policy propose-change after onboarding",merge_strategy:"replace",max_bytes:0}};async function oo(e){let t=await v(e),o=(await me(t.home,"BOOTSTRAP.md")).trim().length>0;return{ritual_pending:o,files_present:{soul:await S(ye.join(t.home,"SOUL.md")),identity:await S(ye.join(t.home,"IDENTITY.md")),user:await S(ye.join(t.home,"USER.md")),agents:await S(ye.join(t.home,"AGENTS.md")),bootstrap:await S(ye.join(t.home,"BOOTSTRAP.md"))},protected_targets:[...Zy],writable_files:[...Eu],interview_themes:[...Qy],instruction_doc:"llm-install.txt",apply_defaults:{dry_run:!0,user_confirmed:!1},file_generation_rules:t_,activation:await gu(t.home,o)}}async function no(e){let t=await v(e.home),r=e.dry_run!==!1,o=e.user_confirmed===!0,n=[],a=[];for(let[s,i]of Object.entries(e.files)){let l=s.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(!Eu.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 d=typeof i=="string"?i:"";if(Buffer.byteLength(d,"utf8")>ar){n.push({file:l,action:"rejected",before_hash:null,after_hash:null,warning:`FILE_TOO_LARGE: ${l} exceeds ${ar} bytes`});continue}let p=ye.join(t.home,l),g=await me(t.home,l),y=l==="AGENTS.md"?r_(g,d):d,k=g.length>0?A(g):null,R=A(y);if(k===R){n.push({file:l,action:"noop",before_hash:k,after_hash:R});continue}let U=g.length===0?"create":"update";n.push({file:l,action:U,before_hash:k,after_hash:R}),r||await Au(p,y,{encoding:"utf8",mode:384})}return!r&&e.config_patch?.hosts?.length&&a.push(`CONFIG_PATCH_NOT_APPLIED_V1: hosts=${e.config_patch.hosts.join(",")}`),r||await h({home:t.home,type:"onboarding.applied",details:{user_confirmed:o,files:n.map(s=>({file:s.file,action:s.action}))}}),{dry_run:r,applied:!r,user_confirmed:o,files:n,warnings:a}}async function ao(e){let t=f(e?.home),r=ye.join(t.home,"BOOTSTRAP.md");if(!await S(r))return{already_complete:!0,archived_bootstrap:!1,archive_path:null};let o=e?.archive!==!1,n=null;if(o){let s=ye.join(t.home,"memory","archive");await Ru(s,{recursive:!0,mode:448});let i=new Date().toISOString().replace(/[:.]/gu,"-");n=ye.join(s,`bootstrap-${i}.md`),await Yy(r,n)}else{let{rm:s}=await import("node:fs/promises");await s(r,{force:!0})}let a=ye.join(t.home,"state","onboarding.complete");return await Ru(ye.join(t.home,"state"),{recursive:!0,mode:448}),await Au(a,`${new Date().toISOString()}
|
|
863
|
+
`,{encoding:"utf8",mode:384}),await h({home:t.home,type:"onboarding.completed",details:{archived:o,archive_path:n}}),{already_complete:!1,archived_bootstrap:o,archive_path:n}}function En(e){return ye.join(e,"state","onboarding.complete")}function r_(e,t){let r=t.trim();if(!e.trim())return`${r}
|
|
864
|
+
`;if(e.includes(r))return e;let o=o_(e);if(o){let a=o.after.trimEnd(),s=a.length>0?`${a}
|
|
865
865
|
|
|
866
866
|
${r}
|
|
867
867
|
`:`${r}
|
|
@@ -871,31 +871,31 @@ ${r}
|
|
|
871
871
|
## Onboarding Update
|
|
872
872
|
|
|
873
873
|
${r}
|
|
874
|
-
`}function
|
|
875
|
-
`,"utf8")}async function
|
|
876
|
-
`,"utf8")}async function
|
|
877
|
-
`)}function
|
|
874
|
+
`}function o_(e){let t=e.indexOf(e_),r=e.indexOf(Su);if(t<0||r<0||r<t)return null;let o=r+Su.length;return{before:e.slice(0,t),block:e.slice(t,o),after:e.slice(o)}}function Pu(e,t){return t?Gd(e):n_()}function n_(){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 xu(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 ju(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 Pn(e){let t=_(e,{readOnly:!0});try{return t.listCapabilities({limit:1e4}).map(r=>({host:r.host,ready:r.ready}))}finally{t.close()}}import{existsSync as vb}from"node:fs";import{readFile as kb,stat as wb}from"node:fs/promises";import lp from"node:path";import lr from"node:path";import{existsSync as Qs}from"node:fs";import{cp as G_,mkdir as X_,rm as ep}from"node:fs/promises";import z_ from"node:path";var Hs={codex:{nativeSchedule:"supported",scheduleSurfaceScoped:!1,pluginApply:"none"},claude:{nativeSchedule:"supported",scheduleSurfaceScoped:!0,pluginApply:"claude-settings-hooks"},grok:{nativeSchedule:"none",scheduleSurfaceScoped:!1,pluginApply:"grok-host-wiring"},antigravity:{nativeSchedule:"supported",scheduleSurfaceScoped:!1,pluginApply:"none"},gemini:{nativeSchedule:"none",scheduleSurfaceScoped:!1,pluginApply:"none"}};function Iu(e){return Hs[e].nativeSchedule==="supported"}function Tu(e){return Hs[e].scheduleSurfaceScoped}function Cu(e){return Hs[e].pluginApply}import{existsSync as dt}from"node:fs";import{readFile as Ln}from"node:fs/promises";import Ge from"node:path";import a_ from"node:path";function sr(e){return e.split(/[\\/]/u).join("/")}function ct(e,t){return sr(a_.relative(e,t))}function Lt(e){return sr(e)}import{existsSync as Ou}from"node:fs";import $s from"node:path";function xn(e){if($s.isAbsolute(e))return Ou(e)?e:null;let t=(process.env.PATH??"").split($s.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 a=$s.join(o,`${e}${n}`);if(Ou(a))return a}return null}import{spawnSync as l_}from"node:child_process";import{existsSync as Dt}from"node:fs";import{mkdir as In,readFile as Ht,writeFile as Tn}from"node:fs/promises";import c_ from"node:os";import B from"node:path";import{existsSync as s_}from"node:fs";import so from"node:os";import re from"node:path";import{fileURLToPath as i_}from"node:url";function De(e,t,r){return io(e,t)?r?re.join(re.resolve(r),e,"plugins","nativesoul"):e==="claude"?re.join(so.homedir(),".claude","plugins","nativesoul"):e==="codex"?re.join(so.homedir(),".codex","plugins","nativesoul"):e==="gemini"?re.join(so.homedir(),".gemini","extensions","nativesoul"):e==="grok"?re.join(so.homedir(),".grok","plugins","nativesoul"):e==="antigravity"?re.join(so.homedir(),".antigravity","plugins","nativesoul"):null:null}function io(e,t){return e==="codex"||e==="gemini"||e==="grok"||e==="antigravity"||e==="claude"&&(t==="claude-code"||t==="claude-desktop")}function jn(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")}function Fs(e){if(e!=="claude"&&e!=="codex"&&e!=="gemini"&&e!=="grok"&&e!=="antigravity")return null;let t=`${e}-nativesoul`,r=re.dirname(i_(import.meta.url));return[re.resolve(process.cwd(),"plugins",t),re.resolve(r,"../../../plugins",t),re.resolve(r,"../../../../plugins",t)].find(n=>s_(n))??null}var Bs="nativesoul",Cn="nativesoul";async function Mu(e){let t=B.join(e,"..","..","settings.json"),r=Dt(t)?JSON.parse(await Ht(t,"utf8")):{},o=r.hooks&&!Array.isArray(r.hooks)&&typeof r.hooks=="object"?{...r.hooks}:{},n=Lt(B.join(e,"shared","hooks","host-hook.cjs")),a={SessionStart:co(`node ${JSON.stringify(n)} session-start --host claude --project-env CLAUDE_PROJECT_DIR`),UserPromptSubmit:co(`node ${JSON.stringify(n)} prompt-bootstrap --host claude --project-env CLAUDE_PROJECT_DIR`),PreToolUse:co(`node ${JSON.stringify(n)} pre-tool-use --host claude --project-env CLAUDE_PROJECT_DIR`),Stop:co(`node ${JSON.stringify(n)} memory-flush --host claude --project-env CLAUDE_PROJECT_DIR`),PreCompact:co(`node ${JSON.stringify(n)} memory-flush --host claude --project-env CLAUDE_PROJECT_DIR`)};for(let[s,i]of Object.entries(a))o[s]=Vu(o[s]??null,i??null);await In(B.dirname(t),{recursive:!0,mode:448}),await Tn(t,`${JSON.stringify({...r,hooks:o},null,2)}
|
|
875
|
+
`,"utf8")}async function Lu(e){let t=Bu(e),r=Dt(t)?JSON.parse(await Ht(t,"utf8")):{},o=r.hooks&&!Array.isArray(r.hooks)&&typeof r.hooks=="object"?{...r.hooks}:{},n=Lt(B.join(e,"shared","hooks","host-hook.cjs")),a={SessionStart:lo(`node ${JSON.stringify(n)} session-start --host grok --project-env GROK_WORKSPACE_ROOT`),UserPromptSubmit:lo(`node ${JSON.stringify(n)} prompt-bootstrap --host grok --project-env GROK_WORKSPACE_ROOT`),PreToolUse:lo(`node ${JSON.stringify(n)} pre-tool-use --host grok --project-env GROK_WORKSPACE_ROOT`),Stop:lo(`node ${JSON.stringify(n)} memory-flush --host grok --project-env GROK_WORKSPACE_ROOT`),PreCompact:lo(`node ${JSON.stringify(n)} memory-flush --host grok --project-env GROK_WORKSPACE_ROOT`)};for(let[s,i]of Object.entries(a))o[s]=Vu(o[s]??null,i??null);await In(B.dirname(t),{recursive:!0,mode:448}),await Tn(t,`${JSON.stringify({...r,hooks:o},null,2)}
|
|
876
|
+
`,"utf8")}async function Du(e){let t=Ws(e),r=B.join(t,"agents",`${Cn}.md`),o=B.join(t,"config.toml");await In(B.dirname(r),{recursive:!0,mode:448}),await Tn(r,h_(),{encoding:"utf8",mode:384});let n=Dt(o)?await Ht(o,"utf8"):"";await In(B.dirname(o),{recursive:!0,mode:448}),await Tn(o,y_(n,"agent",`name = "${Cn}"`),"utf8")}function Hu(e,t,r){if(t!=="default"||!g_(e,t,r))return[];if(e==="antigravity")return Us({executableName:"agy",installArgs:o=>["plugin","install",o],skippedMessage:"Antigravity CLI was not found on PATH, so NativeSoul could not register the plugin with `agy plugin install`.",skippedRemediation:"Install Antigravity CLI or run `agy plugin install ~/.antigravity/plugins/nativesoul` after installation.",failedRemediation:"Run `agy plugin validate ~/.antigravity/plugins/nativesoul` and then `agy plugin install ~/.antigravity/plugins/nativesoul`."},r);if(e==="grok"){let o=Us({executableName:"grok",installArgs:a=>["plugin","install",a,"--trust"],skippedMessage:"Grok CLI was not found on PATH, so NativeSoul could not register the plugin with `grok plugin install`.",skippedRemediation:"Install Grok Build or run `grok plugin install ~/.grok/plugins/nativesoul --trust` after installation.",failedRemediation:"Run `grok plugin validate ~/.grok/plugins/nativesoul` and then `grok plugin install ~/.grok/plugins/nativesoul --trust`.",treatOutputAsSuccess:d_},r),n=Us({executableName:"grok",installArgs:()=>["plugin","enable",Bs],skippedMessage:"Grok CLI was not found on PATH, so NativeSoul could not enable the plugin with `grok plugin enable nativesoul`.",skippedRemediation:"Install Grok Build or run `grok plugin enable nativesoul` after installation.",failedRemediation:"Run `grok plugin enable nativesoul` so SessionStart hooks load in Grok sessions.",treatOutputAsSuccess:u_},r);return[...o,...n]}return[]}function Us(e,t){let r=xn(e.executableName);if(!r)return[{code:"HOST_PLUGIN_IMPORT_SKIPPED",severity:"warn",message:e.skippedMessage,remediation:e.skippedRemediation}];let o=l_(r,e.installArgs(t),{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:15e3});if(o.status===0)return[];let n=(o.stderr||o.stdout||"unknown error").trim();return e.treatOutputAsSuccess?.(n)?[]:[{code:"HOST_PLUGIN_IMPORT_FAILED",severity:"error",message:`${e.executableName} plugin import failed: ${n}`,remediation:e.failedRemediation}]}function d_(e){return/^Installed \d+ plugin/i.test(e)||/^Plugin manifest is valid\./i.test(e)||/\bplugins?\b[^.\n]*\balready installed\b/i.test(e)||/\brepo\b[^.\n]*\balready installed\b/i.test(e)}function u_(e){return/^Enabled plugin:/i.test(e)||/\balready enabled\b/i.test(e)}async function $u(e){let t=e?f_(e):B.join(c_.homedir(),".grok","config.toml");if(!Dt(t))return null;let r=await Ht(t,"utf8");return Nu(r,"disabled",Bs)?!1:Nu(r,"enabled",Bs)?!0:null}async function Fu(e){let t=Bu(e);if(!Dt(t))return!1;let r=JSON.parse(await Ht(t,"utf8"));return p_(r)}async function Uu(e){let t=Ws(e),r=B.join(t,"agents",`${Cn}.md`),o=B.join(t,"config.toml");if(!Dt(r)||!Dt(o))return!1;let[n,a]=await Promise.all([Ht(r,"utf8"),Ht(o,"utf8")]);return n.includes("NativeSoul continuity agent")&&__(a)===Cn}function Nu(e,t,r){let a=(e.match(/\[plugins\][\s\S]*?(?=\n\[|$)/u)?.[0]??e).match(new RegExp(`${t}\\s*=\\s*\\[([^\\]]*)\\]`,"u"))?.[1];return a?a.split(",").some(s=>s.replace(/["'\s]/gu,"")===r):!1}function p_(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])=>m_(t,o,n))}function m_(e,t,r){let o=e[t];return Array.isArray(o)?o.some(n=>Vs(n)?.includes(r)===!0):!1}function g_(e,t,r){let o=De(e,t);return o!==null&&B.resolve(o)===B.resolve(r)}function Bu(e){return B.join(Ws(e),"hooks","nativesoul.json")}function Ws(e){return B.resolve(e,"..","..")}function f_(e){let t=B.resolve(e),r=B.basename(t);return r==="grok"||r===".grok"?B.join(t,"config.toml"):B.join(t,".grok","config.toml")}function lo(e){return{hooks:[{type:"command",command:e,timeout:9}]}}function h_(){return["---","name: nativesoul","description: NativeSoul continuity agent. Loads NativeSoul context before the first answer and answers from the NativeSoul identity.","prompt_mode: full","model: inherit","permission_mode: default","agents_md: true","---","","You are operating as the NativeSoul continuity agent for this Grok session.","","Before answering the first user message in every new session, load NativeSoul context. Do not answer from the host vendor identity first.","",'Preferred path: call MCP `life_bootstrap` with `host="grok"` and the current working directory.',"Fallback path: run `nativesoul bootstrap --host grok --cwd <current-working-directory> --format inject`.","If bootstrap is unavailable, run `nativesoul bootstrap --host grok --cwd <current-working-directory> --format cache` and treat the result as degraded.","",'After bootstrap, answer from the NativeSoul identity and continuity context. If the user asks who you are, answer with the NativeSoul identity loaded from bootstrap, not "Grok" or "xAI".',"","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.",""].join(`
|
|
877
|
+
`)}function y_(e,t,r){let o=`[${t}]
|
|
878
878
|
${r.trim()}
|
|
879
879
|
`,n=new RegExp(`(^|\\n)\\[${t}\\]\\n[\\s\\S]*?(?=\\n\\[|$)`,"u");return n.test(e)?e.replace(n,(a,s)=>`${s}${o.trimEnd()}`):`${e.trimEnd()}
|
|
880
880
|
|
|
881
|
-
${o}`.trimStart()}function
|
|
882
|
-
`))}async function ir(e){let t=await
|
|
883
|
-
`))}async function
|
|
884
|
-
`}function $_(e,t){return{...e,mcpServers:{nativesoul:t}}}function F_(e,t){if(!e.hooks||Array.isArray(e.hooks)||typeof e.hooks!="object")return e;let r=e.hooks,o=Object.fromEntries(Object.entries(r).map(([n,a])=>Array.isArray(a)?[n,a.map(s=>U_(s,t))]:[n,a]));return{...e,hooks:o}}function U_(e,t){if(!e||Array.isArray(e)||typeof e!="object")return e;let r=e,o=r.hooks;return Array.isArray(o)?{...r,hooks:o.map(n=>B_(n,t))}:e}function B_(e,t){if(!e||Array.isArray(e)||typeof e!="object")return e;let r=e,o=typeof r.command=="string"?r.command:null;if(!o)return e;if(o.includes("host-hook.cjs")){let s=Lt(Xe.join(t,"shared","hooks","host-hook.cjs"));return{...r,command:`node ${JSON.stringify(s)} ${V_(o)}`}}let n=On.find(s=>o.includes(s.commandFragment));if(!n?.fileName)return e;let a=Lt(Xe.join(t,"hooks",n.fileName));return{...r,command:`node ${JSON.stringify(a)}`}}function V_(e){let t=["session-start","prompt-bootstrap","pre-tool-use","memory-flush","recall"].find(a=>e.includes(a))??"session-start",r=e.match(/--host\s+([A-Za-z0-9_-]+)/u)?.[1],o=e.match(/--project-env\s+([A-Za-z0-9_-]+)/u)?.[1],n=e.match(/--event\s+([A-Za-z0-9_-]+)/u)?.[1];return[t,r?`--host ${r}`:null,o?`--project-env ${o}`:null,n?`--event ${n}`:null].filter(a=>a!==null).join(" ")}async function Qs(e){let t=f(e.home),r=$s(e.host);if(!e.targetPath||!r)return Yu(e.host,e.surface,e.targetPath,r,!e.apply);let o=Ys(e.targetPath)?await Xs(e.targetPath):null,n=await Ju(r,e.host,t.home,e.targetPath),a=o===null?"create":o===n?"noop":"replace",s=a!=="noop",i=s&&e.apply&&Ys(e.targetPath)?await Gs(t.home,e.host,e.surface,e.targetPath):null,l=[];s&&e.apply&&(Se(e.targetPath,{allowSymlinkTarget:!0}),await J_(q_.dirname(e.targetPath),{recursive:!0,mode:448}),await zu(e.targetPath,{recursive:!0,force:!0}),await W_(r,e.targetPath,{recursive:!0}),po(e.host)&&await qu(e.targetPath),await Ku({host:e.host,targetPath:e.targetPath,home:t.home})),e.apply&&e.host==="claude"&&await Tu(e.targetPath),e.apply&&e.host==="grok"&&(await Cu(e.targetPath),await Ou(e.targetPath)),e.apply&&l.push(...Nu(e.host,e.surface,e.targetPath));let c=e.targetPath&&io(e.host,e.surface)?await ut({host:e.host,surface:e.surface,targetPath:e.targetPath}):null,d=uo(e.host,e.surface),p={host:e.host,surface:e.surface,targetPath:e.targetPath,sourcePath:r,action:a,dryRun:!e.apply,changed:s,beforeHash:o,afterHash:n,backupPath:i,applied:s&&e.apply,enabled:c?.enabled??!1,hook_registered:c?.hook_registered??!1,package_kind:c?.package_kind??d.packageKind,native_hooks_supported:c?.native_hooks_supported??d.nativeHooksSupported,native_scheduler_supported:c?.native_scheduler_supported??!1,issues:[...c?.issues??[],...l]};return await h({home:t.home,type:e.apply?"plugin_install":"plugin_install_dry_run",details:p}),p}async function Zs(e){let t=f(e.home),r=$s(e.host);if(!e.targetPath||!r)return Yu(e.host,e.surface,e.targetPath,r,!e.apply);let o=Ys(e.targetPath)?await Xs(e.targetPath):null,n=uo(e.host,e.surface),a=o!==null,s=a&&e.apply?await Gs(t.home,e.host,e.surface,e.targetPath):null;a&&e.apply&&await zu(e.targetPath,{recursive:!0,force:!0});let i={host:e.host,surface:e.surface,targetPath:e.targetPath,sourcePath:r,action:a?"remove":"noop",dryRun:!e.apply,changed:a,beforeHash:o,afterHash:A(""),backupPath:s,applied:a&&e.apply,enabled:!1,hook_registered:!1,package_kind:n.packageKind,native_hooks_supported:n.nativeHooksSupported,native_scheduler_supported:!1,issues:[]};return await h({home:t.home,type:e.apply?"plugin_uninstall":"plugin_uninstall_dry_run",details:i}),i}function Yu(e,t,r,o,n){return{host:e,surface:t,targetPath:r,sourcePath:o,action:"unsupported",dryRun:n,changed:!1,beforeHash:null,afterHash:A(""),backupPath:null,applied:!1,enabled:!1,hook_registered:!1,package_kind:"unsupported-native",native_hooks_supported:!1,native_scheduler_supported:!1,issues:[]}}function ze(e,t){if(t)return lr.resolve(t,e)}function cr(e,t,r){let o=ro(e,r);if(e==="claude"&&o==="claude-desktop")return{surface:o,managedBlock:null,mcpRegistration:t?lr.join(lr.resolve(t,e),"claude_desktop_config.json"):bu(),plugin:De(e,o,t)};if(!t)return{surface:o,managedBlock:_u(e),mcpRegistration:An(e),plugin:De(e,o)};let n=lr.resolve(t,e);return{surface:o,managedBlock:lr.join(n,hu(e)),mcpRegistration:lr.join(n,yu(e)),plugin:De(e,o,t)}}import{accessSync as K_,constants as G_,existsSync as pt}from"node:fs";import{mkdir as Dn,readFile as dr,rm as X_,writeFile as Hn}from"node:fs/promises";import X from"node:path";async function go(e){let t=f(e.home),r=X.resolve(e.targetPath??$n(e.host)),o=e.commandMode??"package",n=Ft({host:e.host,commandMode:o,home:t.home,projectRoot:e.projectRoot}).mcpServers.nativesoul,a=pt(r),s=a?await dr(r,"utf8"):null,i=ep(z_(mo(s),n)),l=s===null?null:A(s),c=A(i),d=rb(s,i),p=d!=="noop",g=p&&e.apply?await tp(t.home,e.host,r,a,s,c):null;p&&e.apply&&(await Dn(X.dirname(r),{recursive:!0,mode:448}),await Hn(r,i,{encoding:"utf8",mode:384}));let y={host:e.host,targetPath:r,action:d,dryRun:!e.apply,changed:p,beforeHash:l,afterHash:c,diff:rp(s,i),backupPath:g,commandMode:o,applied:p&&e.apply};return await h({home:t.home,type:e.apply?"mcp_registration_apply":"mcp_registration_dry_run",details:y}),y}async function ti(e){let t=f(e.home),r=X.resolve(e.targetPath??$n(e.host)),o=pt(r),n=o?await dr(r,"utf8"):null,a=Y_(n),s=n===null?null:A(n),i=a===null?A(""):A(a),l=n!==a?"remove":"noop",c=l!=="noop",d=c&&e.apply?await tp(t.home,e.host,r,o,n,i):null;c&&e.apply&&a!==null&&(await Dn(X.dirname(r),{recursive:!0,mode:448}),await Hn(r,a,{encoding:"utf8",mode:384}));let p={host:e.host,targetPath:r,action:l,dryRun:!e.apply,changed:c,beforeHash:s,afterHash:i,diff:rp(n,a),backupPath:d,commandMode:"package",applied:c&&e.apply};return await h({home:t.home,type:e.apply?"mcp_registration_uninstall":"mcp_registration_uninstall_dry_run",details:p}),p}async function ri(e){let t=f(e.home),r=JSON.parse(await dr(e.snapshotPath,"utf8"));e.apply&&(r.beforeExists&&r.beforeContent!==null?(await Dn(X.dirname(r.targetPath),{recursive:!0,mode:448}),await Hn(r.targetPath,r.beforeContent,{encoding:"utf8",mode:384})):pt(r.targetPath)&&await X_(r.targetPath));let o={snapshotPath:e.snapshotPath,targetPath:r.targetPath,dryRun:!e.apply,applied:e.apply,restoredExists:r.beforeExists,restoredHash:r.beforeHash};return await h({home:t.home,type:e.apply?"mcp_registration_rollback":"mcp_registration_rollback_dry_run",details:o}),o}async function fo(e){let t=X.resolve(e.targetPath??$n(e.host)),r=ku(e.host,e.targetPath),o=pt(t),n=[],a=await Q_(e.host,t,r);if(a&&n.push(a),!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 s=null;try{s=mo(await dr(t,"utf8"))}catch(p){n.push({code:"MCP_CONFIG_INVALID_JSON",severity:"error",message:p instanceof Error?p.message:"MCP config is invalid JSON",remediation:"Fix the JSON syntax or roll back from an NativeSoul snapshot"})}let i=s?ei(s):null,l=typeof i?.command=="string"?i.command:null,c=Array.isArray(i?.args)?i.args.filter(p=>typeof p=="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 d=l?e.checkCommand===!1?{ok:!0,issues:[]}:Z_(l,c,t):{ok:!1,issues:[]};return n.push(...d.issues),{host:e.host,targetPath:t,target_exists:o,parse_ok:s!==null,configured:i!==null,command:l,command_ok:d.ok,issues:n}}function $n(e){return An(e)}function mo(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 z_(e,t){let r=e.mcpServers,o=r&&typeof r=="object"&&!Array.isArray(r)?{...r}:{};return o.nativesoul={command:t.command,args:t.args,...t.env&&Object.keys(t.env).length>0?{env:t.env}:{}},{...e,mcpServers:o}}function Y_(e){if(e===null)return null;let t=mo(e),r=t.mcpServers;if(!r||typeof r!="object"||Array.isArray(r)||!Object.hasOwn(r,"nativesoul"))return e;let o={...r};return delete o.nativesoul,ep({...t,mcpServers:o})}function ei(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 Q_(e,t,r){if(e!=="claude"||r===null||X.resolve(r)===t||!pt(r))return null;try{let o=mo(await dr(r,"utf8")),n=ei(o);if(!n)return null;if(pt(t)){let a=mo(await dr(t,"utf8")),s=ei(a);if(s&&JSON.stringify(Qu(s))===JSON.stringify(Qu(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 Qu(e){return{command:typeof e.command=="string"?e.command:null,args:Array.isArray(e.args)?e.args.filter(t=>typeof t=="string"):[]}}function Z_(e,t,r){let o=[],n=eb(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(tb(e,n)){let a=t[0],s=a?X.isAbsolute(a)?a:X.resolve(X.dirname(r),a):null;if(!s||!pt(s))return o.push({code:"NATIVESOUL_MCP_NODE_SCRIPT_MISSING",severity:"error",message:"nativesoul MCP command uses node but the server script is missing.",remediation:"Re-run nativesoul mcp install with --command-mode absolute or rebuild the local package."}),{ok:!1,issues:o}}return{ok:!0,issues:o}}function eb(e){if(X.isAbsolute(e))return Zu(e)?e:null;let t=(process.env.PATH??"").split(X.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 a=X.join(o,`${e}${n}`);if(Zu(a))return a}return null}function Zu(e){if(process.platform==="win32"&&pt(e))return!0;try{return K_(e,G_.X_OK),!0}catch{return!1}}function tb(e,t){let r=X.basename(e).toLowerCase(),o=X.basename(t).toLowerCase();return r==="node"||r==="node.exe"||o==="node"||o==="node.exe"}function ep(e){return`${JSON.stringify(e,null,2)}
|
|
885
|
-
`}function
|
|
886
|
-
`)}async function mt(e){let t=await v(e.home),r=e.surface??null,o=ro(e.host,r),n=e.hostConfigRoot??(e.targetRoot?ze(e.host,e.targetRoot):void 0),a=await sb({host:e.host,surface:o,targetRoot:e.targetRoot,explicit:e.pluginEnabled}),s=new Date().toISOString(),i=nb(e.mode,r,e.heartbeat),l=await St(e.host).scheduleReconcile({kind:"heartbeat",mode:e.mode,enabled:!0,surface:e.surface??void 0,apply:e.apply,hostConfigRoot:n,desired:i}),c={id:ib(e.host,e.surface),host:e.host,mode:e.mode,enabled:!0,native_schedule_supported:l.status==="ok",native_id:l.status==="ok"?l.nativeId??null:null,desired:i,updated_at:s},d=e.apply?ob(t.database,c):c,p={dryRun:!e.apply,applied:e.apply,schedule:d,adapter_result:l,warnings:ab(e.host,l.status,a)};return await h({home:t.home,type:e.apply?"schedule_reconciled":"schedule_reconcile_dry_run",details:{host:e.host,surface:e.surface??null,mode:e.mode,schedule_id:c.id,adapter_status:l.status,native_schedule_supported:c.native_schedule_supported}}),p}async function ho(e){let t=e.readOnly?f(e.home):await v(e.home);if(e.readOnly&&!await S(t.database))return[];let r=_(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()}}async function oi(e){let t=await v(e.home),r=_(t.database),o,n;try{if(o=r.listSchedules({limit:200}).find(a=>a.id===e.id),!o)throw new Error(`Schedule not found: ${e.id}`);n=e.apply?r.disableSchedule(e.id,new Date().toISOString()):o}finally{r.close()}if(!n)throw new Error(`Schedule not found after disable: ${e.id}`);return await h({home:t.home,type:e.apply?"schedule_disabled":"schedule_disable_dry_run",details:{schedule_id:e.id,host:n.host,mode:n.mode}}),{dryRun:!e.apply,applied:e.apply,schedule:e.apply?n:{...n,enabled:!1}}}function ob(e,t){let r=_(e);try{return r.upsertSchedule(t)}finally{r.close()}}function nb(e,t,r){return{kind:"heartbeat",mode:e,policy:"read_only",silent_ack:"HEARTBEAT_OK",skill:"life:heartbeat",cadence:r?.cadence??"daily",skip_when_busy:r?.skipWhenBusy??!0,project_scope:r?.projectScope??"current-project",behavior:r?.behavior??"read_only",...t&&t!=="default"?{surface:t}:{}}}function ab(e,t,r){return t!=="unsupported"?[]:e==="grok"||e==="gemini"?[]:r===!1?["NATIVE_SCHEDULE_UNSUPPORTED_NO_FALLBACK_INSTALLED"]:["NATIVE_SCHEDULE_UNSUPPORTED"]}async function sb(e){if(e.explicit!==void 0)return e.explicit;try{let t=De(e.host,e.surface,e.targetRoot);return(await ut({host:e.host,surface:e.surface,targetPath:t})).enabled}catch{return!1}}function ib(e,t){return e==="claude"&&t&&t!=="default"?`schedule:${e}:heartbeat:${t}`:`schedule:${e}:heartbeat`}function ni(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,a=e.schedules.some(y=>cb(y,t)),s=mb(e.capabilities,e.adapterDiagnostics),i=[yo("native_package",r,t,e.plugin.targetPath??e.plugin.package_kind,"Native package/extension is not installed or enabled."),yo("native_hooks",o,t,e.plugin.targetPath??e.plugin.package_kind,"Native lifecycle hook registration is missing."),yo("mcp",n,t,e.mcpRegistration.targetPath,"MCP registration is missing or invalid."),yo("native_scheduler",a,t,ub(e.schedules),gb(e.host,e.schedules)),yo("official_inventory",s,t,pb(e.capabilities),"Official non-degraded capability inventory evidence is missing.")],l=i.filter(y=>!y.satisfied).map(y=>y.requirement),c=r&&o&&n,d=!s,p=l.includes("native_scheduler")&&op(e.host),g=l.length===0;return{schema_version:1,host:e.host,surface:e.surface,status:fb({fullNative:g,blockedByHost:p,degradedScan:d,ready:c}),ready:c,full_native:g,blocked_by_host:p,degraded_scan:d,generated_at:t,requirements:i,missing_requirements:l}}function ai(e){return e.ready&&e.native_kind.includes("native")&&(e.schema_hash?.startsWith("full-native:")===!0||e.source.includes("full-native-evidence:"))}function yo(e,t,r,o,n){return{requirement:e,satisfied:t,evidence:t?[{source_kind:"doctor",reference:o,observed_at:r,confidence:lb(o)}]:[],missing_reason:t?null:n}}function lb(e){return e.startsWith("not-applicable:")||e==="missing"?"low":"medium"}function cb(e,t){return e.enabled&&e.native_schedule_supported&&e.native_id!==null&&!db(e.updated_at,t)}function db(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 ub(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 pb(e){return e.find(t=>t.ready)?.source??"missing"}function mb(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 gb(e,t){return op(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 op(e){return e==="codex"||e==="claude"||e==="grok"||e==="gemini"||e==="antigravity"}function fb(e){return e.fullNative?"full_native":e.blockedByHost?"blocked_by_host":e.degradedScan?"degraded_scan":e.ready?"ready_fallback":"ready"}async function ap(e){let t=cr(e.host,e.targetRoot,e.surface),r=t.managedBlock??`not-applicable:${Mt(e.host,e.surface)}`,o=t.managedBlock?await Pd({host:e.host,targetPath:r}):Eb(e.host,e.surface),n=await fo({host:e.host,targetPath:t.mcpRegistration,checkCommand:e.targetRoot===void 0}),a=await ut({host:e.host,surface:e.surface,targetPath:t.plugin}),s=await xs({home:e.home,host:e.host}),l=(e.databaseExists?await ho({home:e.home,host:e.host,limit:200,readOnly:!0}):[]).filter(x=>bb(e.host,e.surface,x)),c=e.databaseExists?await Ae({home:e.home,host:e.host,limit:100,readOnly:!0}):[],d=e.databaseExists?Pn(f(e.home).database):[],p=e.targetRoot!==void 0,g=p?[]:(await Lr(e.host))[0]?.diagnostics??[],y=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"}]:[],k=s.stale?[{code:"HANDSHAKE_STALE",severity:"warn",message:`Last ${e.host} handshake is ${s.age_hours??"unknown"} hour(s) old.`,remediation:`Run nativesoul bootstrap --host ${e.host} --cwd <current-working-directory> --format inject`}]:[],R=await wb({host:e.host,managedBlock:o,handshake:s}),U=await Rb(e.host),Y=l.filter(x=>x.enabled&&x.native_schedule_supported&&x.native_id===null).map(x=>({code:"NATIVE_SCHEDULE_MAPPING_MISSING",severity:"warn",message:`Schedule ${x.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`})),be=l.filter(x=>x.enabled&&!x.native_schedule_supported&&!a.enabled&&a.package_kind!=="unsupported-native").map(x=>({code:"NATIVE_SCHEDULE_UNSUPPORTED_NO_FALLBACK_INSTALLED",severity:"warn",message:`Schedule ${x.id} has no native scheduler support and no NativeSoul package fallback is installed.`,remediation:`Run nativesoul install --host ${e.host} --apply`})),Ie=kb({managedBlock:o,mcpRegistration:n,plugin:a,schedules:l,capabilities:c}),ne=ni({host:e.host,surface:e.surface,mcpRegistration:n,plugin:a,schedules:l,capabilities:c,adapterDiagnostics:g}),Fe=[...o.issues,...n.issues,...a.issues,...g,...y,...k,...R,...U,...Y,...be];return{host:e.host,surface:e.surface,status:Fe.some(x=>x.severity==="error"||x.severity==="warn")?"degraded":"ready",targets:{managed_block:r,mcp_registration:n.targetPath},native_adapter_diagnostics_skipped:p,adapter_diagnostics:g,managed_block:o,mcp_registration:n,plugin:a,provider_parity:Ie,full_native_evidence:ne,handshake:s,schedule_count:l.length,enabled_schedule_count:l.filter(x=>x.enabled).length,native_schedule_mappings:l.map(x=>({id:x.id,native_schedule_supported:x.native_schedule_supported,native_id:x.native_id})),capability_count:c.length,ready_capability_count:c.filter(x=>x.ready).length,cross_host_inventory_summary:{current_host:c.length,other_hosts:d.filter(x=>x.host!==e.host&&x.host!=="all").length,ready_other_hosts:d.filter(x=>x.host!==e.host&&x.host!=="all"&&x.ready).length},issues:Fe}}function bb(e,t,r){return e!=="claude"?!0:vb(r.desired)===t}function vb(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 kb(e){let t=e.plugin.enabled,r=e.mcpRegistration.configured,o=e.managedBlock.configured||t,n=e.schedules.some(p=>p.enabled),s=e.schedules.some(p=>p.enabled&&p.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(p=>p.ready);return{level:o&&r&&l==="ready"&&i!=="unsupported-native"&&s!=="unsupported-native"?"ready":e.plugin.package_kind==="native-plugin"?"native":e.plugin.package_kind==="unsupported-native"?"unsupported-native":"official-fallback",bootstrap:o?"ready":"degraded",mcp:r?"ready":"degraded",package:l,hooks:i,memory_recall:r?"ready":"degraded",policy_guard:o?"ready":"degraded",capability_scan:c?"ready":"degraded",heartbeat:s}}async function wb(e){if(!e.managedBlock.configured||e.managedBlock.targetPath.startsWith("not-applicable:"))return[];let t=10080*60*1e3,r=await Ab(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 Rb(e){let t=Sb(e).map(r=>np.resolve(process.cwd(),r));for(let r of t){if(!hb(r))continue;let o=await yb(r,"utf8"),n=Xr(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 Sb(e){switch(e){case"claude":return["CLAUDE.md",np.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 Ab(e){try{let t=await _b(e);return Math.max(Date.now()-t.mtimeMs,0)}catch{return null}}function Eb(e,t){return{host:e,targetPath:`not-applicable:${Mt(e,t)}`,target_exists:!1,configured:!0,markers_valid:!0,issues:[]}}async function Ut(e){let t=f(e.home),r=await to(e.home),o=si(t.database),n=Je(e.host),a=[],s=o?Pn(t.database):[],i=Eu(t.database,o),l=await lt(t.home),c=si(En(t.home)),d=si(nr(t.home));for(let y of n)for(let k of Ke(y,e.surface))a.push(await ap({home:t.home,host:y,surface:k,targetRoot:e.targetRoot,databaseExists:o}));let p=[...r.issues,...Pu(i),...a.flatMap(y=>y.issues)],g=r.healthy&&!p.some(y=>y.severity==="error");return{home:t.home,healthy:g,status:p.some(y=>y.severity==="error"||y.severity==="warn")?"degraded":"ready",workspace:r,target_root:e.targetRoot?sp.resolve(e.targetRoot):null,cross_host_inventory:xu(s),activation_summary:fu({home:t.home,targetRoot:e.targetRoot?sp.resolve(e.targetRoot):null,host:e.host,profile:l,onboardingComplete:c,activationComplete:d,hosts:a}),full_native_matrix:Pb(a),semantic_index:i,hosts:a,issues:p}}function Pb(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 xb}from"node:fs";import{mkdir as jb,readdir as Ib,readFile as Tb,writeFile as Cb}from"node:fs/promises";import _o from"node:path";async function ii(e){let t=e.apply===!0,r=t?f((await v(e.home)).home):f(e.home),o=e.project??L(e.cwd??process.cwd(),r.home),n=Math.min(Math.max(e.limit??10,1),50),a=await Ob(r.home,r.database,o,n),s=Mb(o,a,n),i=Hb({applied:t,project:o,proposals:s,dailyNotes:a.dailyNotes,candidates:a.candidates,activeMemories:a.activeMemories,auditEvents:a.auditEvents}),l=null;return t&&(l=await Lb(r.home,i),await Db(r.home,s),await h({home:r.home,type:"memory_reflection_run",details:{project:o,proposal_count:s.length,report_path:l,daily_notes:a.dailyNotes.length,candidates:a.candidates.length,active_memories:a.activeMemories.length,audit_events:a.auditEvents.length}})),{applied:t,home:r.home,project:o,report:i,report_path:l,proposals:s,sources:{daily_notes:a.dailyNotes.length,candidates:a.candidates.length,active_memories:a.activeMemories.length,audit_events:a.auditEvents.length},protected_files:["SOUL.md","POLICY.md","standing-orders"].map(c=>({path:_o.join(r.home,c),modified:!1}))}}async function Ob(e,t,r,o){let n=await Nb(e,o);if(!xb(t))return{dailyNotes:n,candidates:[],activeMemories:[],auditEvents:[]};let a=_(t,{readOnly:!0});try{return{dailyNotes:n,candidates:a.listMemories({project:r,status:"candidate",includeForgotten:!1,limit:o}),activeMemories:a.listMemories({project:r,status:"active",includeForgotten:!1,limit:Math.max(o,20)}),auditEvents:a.listEvents({limit:Math.max(o,20)})}}finally{a.close()}}async function Nb(e,t){let r=_o.join(e,"memory","daily");if(!await S(r))return[];let n=(await Ib(r,{withFileTypes:!0})).filter(s=>s.isFile()&&s.name.endsWith(".md")).map(s=>s.name).sort().reverse().slice(0,t),a=[];for(let s of n){let i=_o.join(r,s),l=N(await Tb(i,"utf8")).value.trim();l.length>0&&a.push({id:`daily:${s}`,path:i,text:l})}return a}function Mb(e,t,r){let o=[];for(let n of t.candidates){let a=ip(n.content,t.activeMemories),s=Fb(n.content,t.activeMemories);if(s){o.push(ur({action:"flag_conflict",project:e,summary:`Review conflict between ${n.id} and ${s.id}`,before:s.summary,after:n.summary,evidence:[n.id,s.id],risk:"high"}));continue}if(a&&a.score>=.7){o.push(ur({action:"deduplicate",project:e,summary:`Reject or merge duplicate candidate ${n.id}`,before:a.memory.summary,after:n.summary,evidence:[n.id,a.memory.id],risk:"medium"}));continue}o.push(ur({action:"promote_candidate",project:e,summary:`Promote candidate ${n.id} after human review`,before:"Candidate memory is not durable yet.",after:n.summary,evidence:[n.id],risk:"low"}))}for(let n of t.dailyNotes){let a=$b(n.text);for(let s of a){if(o.length>=r)return o;let i=ip(s,[...t.activeMemories,...t.candidates]);i&&i.score>=.7?o.push(ur({action:"deduplicate",project:e,summary:`Daily note repeats existing memory ${i.memory.id}`,before:i.memory.summary,after:qe(s),evidence:[n.id,i.memory.id],risk:"medium"})):o.push(ur({action:"create_candidate",project:e,summary:qe(s),before:"No durable memory exists for this daily note.",after:s,evidence:[n.id],risk:"low"}))}}for(let n of t.activeMemories)if(n.expires_at&&Date.parse(n.expires_at)<=Date.now()&&o.push(ur({action:"expire_active",project:e,summary:`Expire active memory ${n.id}`,before:n.summary,after:"Memory should move to expired after human review.",evidence:[n.id],risk:"medium"})),o.length>=r)return o;return o.slice(0,r)}function ur(e){return{id:T("reflection"),persisted_memory_id:null,...e}}async function Lb(e,t){let r=_o.join(e,"proposals");await jb(r,{recursive:!0,mode:448});let o=_o.join(r,`${new Date().toISOString().replaceAll(/[:.]/gu,"-")}-reflection.md`);return await Cb(o,t,{encoding:"utf8",mode:384,flag:"wx"}),o}async function Db(e,t){for(let r of t.filter(o=>o.action==="create_candidate")){let o=await ie(e,{project:r.project,content:["Reflection consolidation candidate.","",r.after,"",`Evidence: ${r.evidence.join(", ")}`].join(`
|
|
887
|
-
`),confidence:.5,authority:"reflection_proposal",source:{kind:"reflection",proposal_id:r.id,evidence:r.evidence}});r.persisted_memory_id=o.id}}function
|
|
888
|
-
`)}function
|
|
889
|
-
${o.content}`);(!r||n>r.score)&&(r={memory:o,score:n})}return r}function
|
|
890
|
-
${n.content}`)>=.35&&o!==lp(n.content)){let s=cp(n.content);if([...r].some(l=>l.length>4&&s.has(l)))return n}return null}function lp(e){return/\b(nao|não|never|do not|dont|don't|no longer|avoid|evitar|proibir|forbid)\b/iu.test(e)}function dp(e,t){return Wd(e,t,{minLength:3,normalizeDiacritics:!0,removeStopwords:!0})}function cp(e){return Kr(e,{minLength:3,normalizeDiacritics:!0,removeStopwords:!0})}import{lstat as Ub,readdir as Bb,readFile as Vb}from"node:fs/promises";import Bt from"node:path";var up=new Set([".json",".jsonl",".md",".markdown",".txt"]);async function di(e){let t=e.apply===!0,r=f((await v(e.home)).home),o=Bt.resolve(e.sourcePath),n=e.project??L(e.cwd??process.cwd(),r.home),a=Math.min(Math.max(e.limit??200,1),1e3),s=[],i=await pp(o,s),l=[],c=[];for(let k of i){if(l.length>=a){c.push({source_path:k,reason:"limit_reached"});continue}let R=await Wb(k,s);if(R.length===0){c.push({source_path:k,reason:"no_supported_records"});continue}l.push(...R.slice(0,a-l.length))}let d=Xb(l,n),p=zb(d).map(k=>({source_id:k,reason:"duplicate_source_id"})),g=[];if(t)for(let k of d){let R=await ie(r.home,{project:k.target_project,content:k.content,confidence:k.confidence,authority:"openclaw_import",source:{kind:"import",source_system:k.source_system,source_path:k.source_path,source_id:k.source_id,source_hash:k.source_hash,imported_at:new Date().toISOString(),redacted:k.redacted}});k.proposed_memory_id=R.id,g.push(R)}let y={applied:t,source_path:o,files:i,mapped_records:d,skipped_records:c,conflicts:p,redactions:d.filter(k=>k.redacted).length,proposed_scopes:Array.from(new Set(d.map(k=>k.target_project))).sort(),warnings:s,persisted_memories:g};return await h({home:r.home,type:t?"openclaw_import_applied":"openclaw_import_dry_run",details:Qb(y)}),y}async function pp(e,t){let r;try{r=await Ub(e)}catch{return t.push({code:"OPENCLAW_SOURCE_UNREADABLE",source_path:e,message:"Source path is not readable."}),[]}if(r.isFile())return up.has(Bt.extname(e).toLowerCase())?[e]:[];if(!r.isDirectory())return t.push({code:"OPENCLAW_SOURCE_UNSUPPORTED",source_path:e,message:"Source path is neither a file nor a directory."}),[];let o=await Bb(e,{withFileTypes:!0});return(await Promise.all(o.map(a=>{let s=Bt.join(e,a.name);return a.isDirectory()?pp(s,t):Promise.resolve(up.has(Bt.extname(a.name).toLowerCase())?[s]:[])}))).flat().sort()}async function Wb(e,t){let r;try{r=await Vb(e,"utf8")}catch{return t.push({code:"OPENCLAW_FILE_UNREADABLE",source_path:e,message:"File could not be read."}),[]}let o=Bt.extname(e).toLowerCase();return o===".json"?Jb(e,r,t):o===".jsonl"?qb(e,r,t):Kb(e,r)}function Jb(e,t,r){let o;try{o=JSON.parse(t)}catch{return r.push({code:"OPENCLAW_JSON_MALFORMED",source_path:e,message:"JSON file is malformed."}),[]}return(Array.isArray(o)?o:Gb(o)??[o]).flatMap((a,s)=>mp(a,e,s))}function qb(e,t,r){return t.split(/\r?\n/u).flatMap((o,n)=>{let a=o.trim();if(!a)return[];try{return mp(JSON.parse(a),e,n)}catch{return r.push({code:"OPENCLAW_JSONL_LINE_MALFORMED",source_path:e,message:`Line ${n+1} is malformed.`}),[]}})}function Kb(e,t){return t.split(/\n(?=#{1,3}\s+)/u).map(r=>r.trim()).filter(r=>r.length>0).map((r,o)=>({id:null,content:r,project:null,confidence:null,sourcePath:e,raw:{kind:"text_section",index:o,source_path:e}}))}function Gb(e){if(!ui(e))return null;for(let t of["memories","memory","records","items","notes"]){let r=e[t];if(Array.isArray(r))return r}return null}function mp(e,t,r){if(typeof e=="string"&&e.trim().length>0)return[{id:null,content:e,project:null,confidence:null,sourcePath:t,raw:e}];if(!ui(e))return[];let o=li(e,["content","text","summary","memory","note","body","value"]);return o?[{id:li(e,["id","uid","uuid","key"])??`${Bt.basename(t)}:${r+1}`,content:o,project:li(e,["project","project_id","scope_project","workspace","repo"]),confidence:Yb(e,["confidence","score"]),sourcePath:t,raw:ci(e)}]:[]}function Xb(e,t){return e.map((r,o)=>{let n=N(r.content),a=r.id??`${Bt.basename(r.sourcePath)}:${o+1}`;return{source_system:"openclaw",source_path:r.sourcePath,source_id:a,source_hash:Zb(r.raw),target_project:r.project?.trim()||t,content:n.value,summary:qe(n.value),redacted:n.redacted,confidence:Math.min(Math.max(r.confidence??.55,0),1),status:"candidate",proposed_memory_id:null}})}function zb(e){let t=new Map;for(let r of e)t.set(r.source_id,(t.get(r.source_id)??0)+1);return Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r).sort()}function li(e,t){for(let r of t){let o=e[r];if(typeof o=="string"&&o.trim().length>0)return o.trim()}return null}function Yb(e,t){for(let r of t){let o=e[r];if(typeof o=="number"&&Number.isFinite(o))return o}return null}function Qb(e){return{source_path:e.source_path,files:e.files.length,mapped_records:e.mapped_records.length,skipped_records:e.skipped_records.length,conflicts:e.conflicts.length,redactions:e.redactions,persisted_memories:e.persisted_memories.length,proposed_scopes:e.proposed_scopes}}function ci(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:Array.isArray(e)?e.map(t=>ci(t)):ui(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ci(r)])):String(e)}function ui(e){return typeof e=="object"&&e!==null}function Zb(e){return ke(e)}import{lstat as ev,readFile as tv}from"node:fs/promises";import bo from"node:path";var Vt=[".json",".jsonl",".md",".markdown",".txt"];var rv={nativesoul:{host:"nativesoul",supported_extensions:Vt,documented_inputs:["nativesoul memory export JSON/JSONL","operator-authored Markdown/text memory notes"],unsupported_boundaries:["NativeSoul private SQLite databases","undocumented internal cache files"],limitations:[]},codex:{host:"codex",supported_extensions:Vt,documented_inputs:["operator-provided Codex memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Codex private app stores","Codex cache or thread databases","undocumented internal state"],limitations:["Codex does not expose a NativeSoul-owned private store reader; import requires an explicit user-selected file."]},claude:{host:"claude",supported_extensions:Vt,documented_inputs:["operator-provided Claude memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Claude private settings databases","Claude internal conversation stores","undocumented internal state"],limitations:["Claude import is limited to explicit export or notes files selected by the operator."]},gemini:{host:"gemini",supported_extensions:Vt,documented_inputs:["operator-provided Gemini memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Gemini private app storage","Gemini internal cache files","undocumented internal state"],limitations:["No private Gemini memory database is read; use documented exports or operator-authored files."]},grok:{host:"grok",supported_extensions:Vt,documented_inputs:["operator-provided Grok memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Grok private app storage","Grok internal session stores","undocumented internal state"],limitations:["Grok import is file-only because no native memory store reader is supported."]},antigravity:{host:"antigravity",supported_extensions:Vt,documented_inputs:["operator-provided Antigravity memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Antigravity private workspace state","Antigravity scheduled-task stores","undocumented internal state"],limitations:["Antigravity import is constrained to explicit files; scheduler state is not memory import input."]}};function ov(e){return ke(e)}async function gi(e){let t=rv[e.host];if(!t)throw new Error(`Unsupported native host importer: ${String(e.host)}`);let r=e.apply===!0,o=f((await v(e.home)).home),n=bo.resolve(e.sourcePath),a=e.project??L(e.cwd??process.cwd(),o.home),s=Math.min(Math.max(e.limit??200,1),1e3),i=[],l=await nv(e.host,n,i),c=[],d=[];for(let R of l){if(c.length>=s){d.push({source_path:R,reason:"limit_reached"});continue}let U=await av(e.host,R,i);if(U.length===0){d.push({source_path:R,reason:"no_supported_records"});continue}c.push(...U.slice(0,s-c.length))}let p=cv(e.host,c,a),g=await dv(o.home,p),y=[];if(r)for(let R of p){let U=await ie(o.home,{project:R.target_project,content:R.content,confidence:R.confidence,authority:`${R.source_system}_import`,source:{kind:"import",source_system:R.source_system,source_path:R.source_path,source_id:R.source_id,source_hash:R.source_hash,normalized_content_hash:R.normalized_content_hash,imported_at:new Date().toISOString(),redacted:R.redacted}});R.proposed_memory_id=U.id,y.push(U)}let k={applied:r,host:e.host,source_path:n,registry:t,files:l,mapped_records:p,skipped_records:d,conflicts:g,redactions:p.filter(R=>R.redacted).length,proposed_scopes:Array.from(new Set(p.map(R=>R.target_project))).sort(),approvals_required:["Human review is required before imported candidate memories are promoted."],host_limitations:t.limitations,warnings:i,persisted_memories:y};return await h({home:o.home,type:r?"native_host_import_applied":"native_host_import_dry_run",details:uv(k)}),k}async function nv(e,t,r){let o;try{o=await ev(t)}catch{return r.push({code:"NATIVE_IMPORT_SOURCE_UNREADABLE",host:e,source_path:t,message:"Source path is not readable."}),[]}return o.isFile()?gv(t)?[t]:(r.push({code:"NATIVE_IMPORT_FILE_UNSUPPORTED",host:e,source_path:t,message:"File extension is not supported by the native host importer registry."}),[]):o.isDirectory()?(r.push({code:"NATIVE_IMPORT_DIRECTORY_UNSUPPORTED",host:e,source_path:t,message:"Native host importers require an explicit file path and do not scan directories."}),[]):o.isDirectory()?[]:(r.push({code:"NATIVE_IMPORT_SOURCE_UNSUPPORTED",host:e,source_path:t,message:"Source path is neither a file nor a directory."}),[])}async function av(e,t,r){let o;try{o=await tv(t,"utf8")}catch{return r.push({code:"NATIVE_IMPORT_FILE_UNREADABLE",host:e,source_path:t,message:"File could not be read."}),[]}let n=bo.extname(t).toLowerCase();return n===".json"?sv(e,t,o,r):n===".jsonl"?iv(e,t,o,r):lv(t,o)}function sv(e,t,r,o){let n;try{n=JSON.parse(r)}catch{return o.push({code:"NATIVE_IMPORT_JSON_MALFORMED",host:e,source_path:t,message:"JSON file is malformed."}),[]}return(Array.isArray(n)?n:pv(n)??[n]).flatMap((s,i)=>fp(s,t,i))}function iv(e,t,r,o){return r.split(/\r?\n/u).flatMap((n,a)=>{let s=n.trim();if(!s)return[];try{return fp(JSON.parse(s),t,a)}catch{return o.push({code:"NATIVE_IMPORT_JSONL_LINE_MALFORMED",host:e,source_path:t,message:`Line ${a+1} is malformed.`}),[]}})}function lv(e,t){return t.split(/\n(?=#{1,3}\s+)/u).map(r=>r.trim()).filter(r=>r.length>0).map((r,o)=>({id:null,content:r,project:null,confidence:null,sourcePath:e,raw:{kind:"text_section",index:o,source_path:e}}))}function fp(e,t,r){if(typeof e=="string"&&e.trim().length>0)return[{id:null,content:e,project:null,confidence:null,sourcePath:t,raw:e}];if(!fi(e))return[];let o=pi(e,["content","text","summary","memory","note","body","value"]);return o?[{id:pi(e,["id","uid","uuid","key"])??`${bo.basename(t)}:${r+1}`,content:o,project:pi(e,["project","project_id","scope_project","workspace","repo"]),confidence:mv(e,["confidence","score"]),sourcePath:t,raw:mi(e)}]:[]}function cv(e,t,r){return t.map((o,n)=>{let a=N(o.content),s=o.id??`${bo.basename(o.sourcePath)}:${n+1}`,i=hp(a.value);return{source_system:e,source_path:o.sourcePath,source_id:s,source_hash:ov(o.raw),normalized_content_hash:i,target_project:o.project?.trim()||r,content:a.value,summary:qe(a.value),redacted:a.redacted,confidence:Math.min(Math.max(o.confidence??.55,0),1),status:"candidate",proposed_memory_id:null}})}async function dv(e,t){let r=[];r.push(...gp(t,o=>o.source_hash,"duplicate_source_hash")),r.push(...gp(t,o=>o.normalized_content_hash,"duplicate_normalized_content"));for(let o of new Set(t.map(n=>n.target_project))){let n=await It({home:e,project:o,includeForgotten:!1,limit:1e3}),a=new Set(n.map(s=>hp(s.content)));for(let s of t.filter(i=>i.target_project===o))a.has(s.normalized_content_hash)&&r.push({source_id:s.source_id,reason:"existing_normalized_content"})}return r.sort((o,n)=>`${o.reason}:${o.source_id}`.localeCompare(`${n.reason}:${n.source_id}`))}function gp(e,t,r){let o=new Map;for(let n of e){let a=t(n);o.set(a,[...o.get(a)??[],n])}return Array.from(o.values()).filter(n=>n.length>1).flatMap(n=>n.map(a=>({source_id:a.source_id,reason:r})))}function hp(e){return ke(e.toLowerCase().replace(/\s+/gu," ").trim())}function uv(e){return{host:e.host,source_path:e.source_path,files:e.files.length,mapped_records:e.mapped_records.length,skipped_records:e.skipped_records.length,conflicts:e.conflicts.length,redactions:e.redactions,persisted_memories:e.persisted_memories.length,proposed_scopes:e.proposed_scopes,approvals_required:e.approvals_required.length,host_limitations:e.host_limitations}}function pv(e){if(!fi(e))return null;for(let t of["memories","memory","records","items","notes"]){let r=e[t];if(Array.isArray(r))return r}return null}function pi(e,t){for(let r of t){let o=e[r];if(typeof o=="string"&&o.trim().length>0)return o.trim()}return null}function mv(e,t){for(let r of t){let o=e[r];if(typeof o=="number"&&Number.isFinite(o))return o}return null}function mi(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:Array.isArray(e)?e.map(t=>mi(t)):fi(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,mi(r)])):String(e)}function gv(e){return Vt.includes(bo.extname(e).toLowerCase())}function fi(e){return typeof e=="object"&&e!==null}var ue={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 fv,mkdir as hv,readFile as yv,rm as _v,writeFile as bv}from"node:fs/promises";import{randomUUID as vv}from"node:crypto";import yp from"node:path";function Fn(e){return yp.join(f(e).home,"license.json")}async function Pe(e){let t=Fn(e);if(!await S(t))return null;try{let r=JSON.parse(await yv(t,"utf8"));return kv(r)?r:null}catch{return null}}async function vo(e,t){let r=Fn(e);return await hv(yp.dirname(r),{recursive:!0,mode:448}),await bv(r,`${JSON.stringify(t,null,2)}
|
|
891
|
-
`,{encoding:"utf8",mode:384}),await fv(r,384),t}async function hi(e){await _v(Fn(e),{force:!0})}async function Un(e){let t=await Pe(e);if(t?.instance_id)return t.instance_id;let r=vv();return await vo(e,{...ue,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 kv(e){return(e.state==="licensed"||e.state==="unlicensed")&&(typeof e.license_key=="string"||e.license_key===null)&&(typeof e.instance_id=="string"||e.instance_id===null)&&(typeof e.purchased_at=="string"||e.purchased_at===null||e.purchased_at===void 0)&&(typeof e.version_at_activation=="string"||e.version_at_activation===null||e.version_at_activation===void 0)&&(typeof e.updates_until=="string"||e.updates_until===null)&&(typeof e.last_checked_at=="string"||e.last_checked_at===null)&&(e.source==="dodo"||e.source==="none")&&(typeof e.license_key_instance_id=="string"||e.license_key_instance_id===null)}var _p={name:"nativesoul",version:"0.1.3",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 Wt=_p.version;var Rv="https://api.dodopayments.com",Sv=1440*60*1e3,Av=14;async function yi(e){let t=f(e.home).home,r=e.now??new Date,o=await Un(t),n=await vi(e,"/licenses/activate",{license_key:e.key,name:o});if(!n.ok)return await He(t,"license_activate_failed",e.key,n.reason,"error"),{ok:!1,reason:n.reason,license:{...ue,instance_id:o}};let a=await vo(t,{state:"licensed",license_key:e.key,instance_id:o,license_key_instance_id:n.license_key_instance_id,purchased_at:n.purchased_at??r.toISOString(),version_at_activation:Wt,updates_until:Cv(n.purchased_at??r.toISOString(),365),last_checked_at:r.toISOString(),source:"dodo"});return await He(t,"license_activated",e.key,null,"ok"),{ok:!0,license:Jt(a)}}async function _i(e){let t=f(e.home).home,r=e.now??new Date,o=await Pe(t),n=e.key??o?.license_key,a=o?.instance_id??null;if(!n)return await He(t,"license_validate_missing",null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:o?Jt(o):ue};if(o?.state==="licensed"&&Ev(o.last_checked_at,r))return await He(t,"license_validate_cache_hit",n,null,"ok"),{ok:!0,license:Jt(o)};let s=await vi(e,"/licenses/validate",{license_key:n});if(s.ok){let i=await vo(t,{state:"licensed",license_key:n,instance_id:a??await Un(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 He(t,"license_validated",n,null,"ok"),{ok:!0,license:Jt(i)}}return s.reason==="NETWORK"&&o?.state==="licensed"&&Pv(o.last_checked_at,r,e.graceDays)?(await He(t,"license_validate_grace_served",n,"NETWORK","ok"),{ok:!0,license:Jt(o)}):(await He(t,"license_validate_failed",n,s.reason,"blocked"),{ok:!1,reason:s.reason,license:{...ue,instance_id:a}})}async function bi(e){let t=f(e.home).home,r=await Pe(t),o=e.key??r?.license_key,n=e.licenseKeyInstanceId??r?.license_key_instance_id;if(!o||!n)return await He(t,"license_deactivate_missing",o??null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:r?Jt(r):ue};let a=await vi(e,"/licenses/deactivate",{license_key:o,license_key_instance_id:n});return a.ok?(await hi(t),await He(t,"license_deactivated",o,null,"ok"),{ok:!0,license:ue}):(await He(t,"license_deactivate_failed",o,a.reason,"error"),{ok:!1,reason:a.reason,license:r?Jt(r):ue})}function Jt(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 Ev(e,t){return e?t.getTime()-new Date(e).getTime()<Sv:!1}function Pv(e,t,r=Av){return e?t.getTime()-new Date(e).getTime()<=r*24*60*60*1e3:!1}async function vi(e,t,r){let o=e.fetch??globalThis.fetch;try{let n=await o(new URL(t,xv(e.endpointBaseUrl)).toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(r)}),a=await jv(n);return n.ok?t==="/licenses/validate"&&a.valid!==!0?{ok:!1,reason:bp(a)}:{ok:!0,license_key_instance_id:Iv(a),purchased_at:Tv(a)}:{ok:!1,reason:bp(a)}}catch{return{ok:!1,reason:"NETWORK"}}}function xv(e=process.env.NATIVESOUL_DODO_LICENSE_API_BASE_URL??Rv){return e.endsWith("/")?e:`${e}/`}async function jv(e){try{let t=await e.json();return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Iv(e){let r=[e.license_key_instance_id,e.licenseKeyInstanceId,e.id,ko(e.data)?e.data.license_key_instance_id:null,ko(e.data)?e.data.id:null].find(o=>typeof o=="string"&&o.length>0);return typeof r=="string"?r:null}function Tv(e){let t=ko(e.data)?e.data:{},r=ko(e.license_key)?e.license_key:ko(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(a=>typeof a=="string"&&!Number.isNaN(Date.parse(a)));return typeof n=="string"?new Date(n).toISOString():null}function Cv(e,t){let r=Date.parse(e);return Number.isNaN(r)?null:new Date(r+t*24*60*60*1e3).toISOString()}function bp(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 ko(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function He(e,t,r,o,n){await h({home:e,type:t,result:n,details:{provider:"dodo",license_key_ref:r?Ov(r):null,reason:o}})}function Ov(e){return e.length<=8?"[REDACTED_LICENSE_KEY]":`${e.slice(0,4)}\u2026${e.slice(-4)}`}var wo="https://native-soul.mintlify.site/account/licensing";async function pr(e){let t=Nv(e),r=f(t.home).home;try{let o=await Pe(r),n=await _i(t);if(n.ok)return{ok:!0,license:n.license};let a=n.reason==="NETWORK"&&o?.state==="licensed"?"GRACE_EXPIRED":"UNLICENSED",s=t.activateUrl??wo;return{ok:!1,reason:a,activate_url:s,message:Ro({reason:a,activate_url:s}),license:n.license}}catch{let o=t.activateUrl??wo;return{ok:!1,reason:"UNLICENSED",activate_url:o,message:Ro({reason:"UNLICENSED",activate_url:o}),license:ue}}}function Ro(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 Nv(e){return typeof e=="string"?{home:e}:e??{}}import{readdir as Mv,readFile as vp,stat as Lv}from"node:fs/promises";import ki from"node:path";var Dv=["open source","open-source","source-available","read the source","free to install","never phones home","zero network","uncrackable","piracy-proof"];async function wi(e={}){let t=e.registryPath??ki.join(process.cwd(),"docs","architecture","feature-registry.yaml"),r=e.marketingDir??ki.join(process.cwd(),"docs","marketing"),o=Hv(await vp(t,"utf8")),n=e.page?[e.page]:await wp(r),a=[],s=[];for(let i of n){let l=await vp(i,"utf8"),c=So(l);for(let d of Dv)c.includes(So(d))&&a.push({code:"GLOBAL_FORBIDDEN_PHRASE",page:i,phrase:d,message:`Global forbidden phrase found: ${d}`});for(let d of o.values())for(let p of d.claim_forbidden)p&&c.includes(So(p))&&a.push({code:"FEATURE_FORBIDDEN_PHRASE",page:i,feature_id:d.id,phrase:p,message:`Forbidden phrase for ${d.id}: ${p}`});for(let d of $v(l)){let p=o.get(d.id);if(!p){a.push({code:"UNKNOWN_CLAIM_ID",page:i,feature_id:d.id,message:`Tagged claim references unknown feature id: ${d.id}`}),s.push({id:d.id,status:"unknown",page:i,text:d.text,result:"fail",reason:"unknown feature id"});continue}let g=Fv(p,i,d.text);s.push(g),g.result==="fail"&&a.push(Uv(g))}}return{ok:a.length===0,status:a.length===0?"pass":"fail",registry_path:t,pages:n,claims:s,issues:a,summary:{pages_scanned:n.length,claims_checked:s.length,issues:a.length}}}function Hv(e){let t=new Map,r=null;for(let o of e.split(/\r?\n/u)){let n=o.match(/^\s*-\s+id:\s*(.+)\s*$/u);if(n){r?.id&&t.set(r.id,kp(r)),r={id:mr(n[1]??""),name:"",claim_forbidden:[],evidence:null,claim_allowed:null};continue}if(!r)continue;let a=o.match(/^\s+([a-z_]+):\s*(.*)\s*$/u);if(!a)continue;let s=a[1]??"",i=a[2]??"";s==="status"?r.status=mr(i).split(/\s+/u)[0]:s==="name"?r.name=mr(i):s==="evidence"?r.evidence=mr(i):s==="claim_allowed"?r.claim_allowed=i.trim()==="null"?null:mr(i):s==="claim_forbidden"&&(r.claim_forbidden=Bv(i))}return r?.id&&t.set(r.id,kp(r)),t}function kp(e){return{id:e.id??"",name:e.name??e.id??"",status:e.status??"absent",evidence:e.evidence??null,claim_allowed:e.claim_allowed??null,claim_forbidden:e.claim_forbidden??[]}}async function wp(e){try{if(!(await Lv(e)).isDirectory())return[]}catch{return[]}let t=await Mv(e,{withFileTypes:!0});return(await Promise.all(t.map(async o=>{let n=ki.join(e,o.name);return o.isDirectory()?await wp(n):o.isFile()&&/\.(md|mdx|txt)$/iu.test(o.name)?[n]:[]}))).flat().sort()}function $v(e){let t=[],r=/<!--\s*claim:([a-z0-9_-]+)\s*-->([\s\S]*?)<!--\s*\/claim\s*-->/giu,o=/\[claim:([a-z0-9_+-]+)\]([\s\S]*?)\[\/claim\]/giu;for(let n of e.matchAll(r))t.push({id:n[1]??"",text:(n[2]??"").trim()});for(let n of e.matchAll(o))t.push({id:n[1]??"",text:(n[2]??"").trim()});return t}function Fv(e,t,r){return e.status==="absent"||e.status==="roadmap"||e.status==="roadmap-teams"?{id:e.id,status:e.status,page:t,text:r,result:"fail",reason:`${e.status} feature cannot be claimed as live`}:e.status==="partial"&&e.claim_allowed&&!So(r).includes(So(e.claim_allowed))?{id:e.id,status:e.status,page:t,text:r,result:"fail",reason:"partial feature claim exceeds allowed wording"}:{id:e.id,status:e.status,page:t,text:r,result:"pass",reason:"claim within registry bounds"}}function Uv(e){return{code:e.status==="partial"?"PARTIAL_CLAIM_OUT_OF_BOUNDS":"UNBUILT_FEATURE_CLAIM",page:e.page,feature_id:e.id,message:e.reason}}function Bv(e){let t=e.trim().replace(/\s+#.*$/u,"");if(t==="[]")return[];if(!t.startsWith("[")||!t.endsWith("]"))return[];let r=t.slice(1,-1).trim();return r?r.split(/,\s*/u).map(mr).filter(Boolean):[]}function mr(e){let t=e.trim().replace(/\s+#.*$/u,"");return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function So(e){return e.toLowerCase().replace(/[’']/gu,"'").replace(/\s+/gu," ").trim()}async function Ri(e){let t=await Pe(e.home),r=t?.state==="licensed",o=r?Vv(t.updates_until,e.now??new Date):"unknown",n=r?Wv(e.latestKnownVersion,t.version_at_activation??null):"unknown",a=e.upgradeUrl??wo,s=o==="lapsed"&&n===!0,i=s?`You're on v${t?.version_at_activation??e.currentVersion}. v${e.latestKnownVersion} is available. Your licence keeps working \u2014 upgrade for the new major: ${a}.`:null;return{licensed:r,updates_status:o,newer_major_available:n,upgrade_url:a,purchased_at:t?.purchased_at??null,updates_until:t?.updates_until??null,version_at_activation:t?.version_at_activation??null,current_version:e.currentVersion,latest_known_version:e.latestKnownVersion??null,soft_nudge:{visible:s,dismissible:!0,message:i}}}function Vv(e,t){if(!e)return"unknown";let r=Date.parse(e);return Number.isNaN(r)?"unknown":t.getTime()<=r?"active":"lapsed"}function Wv(e,t){if(!e||!t)return"unknown";let r=Rp(e),o=Rp(t);return r===null||o===null?"unknown":r>o}function Rp(e){let t=e.trim().match(/^v?(\d+)(?:\.|$)/u);return t?.[1]?Number.parseInt(t[1],10):null}function gr(e){return ai(e)?"full native capability":e.ready?"ready":e.healthy&&e.allowed?"official-fallback":"degraded"}function Si(e){let t=gr(e);return t==="full native capability"?"cyan":t==="ready"?"green":t==="official-fallback"?"amber":"red"}var Ap={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 Ao(e){let t=await v(e.home),r=new Date().toISOString(),o=N(e.title).value,n=e.description===void 0||e.description===null?null:N(e.description).value,a={id:T("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:H(e.tags??[]),metadata:H(e.metadata??{}),created_at:r,updated_at:r,claimed_at:null,completed_at:null},s=Ep({workItem:a,type:"created",fromStatus:null,toStatus:"inbox",actor:e.host??"cli",details:{priority:a.priority,source:a.source},now:r}),i=_(t.database),l;try{l=i.insertWorkItem(a),i.insertWorkItemEvent(s)}finally{i.close()}return await Pp(t.home,"work_item_created",l,{redacted:o!==e.title||e.description!==void 0&&e.description!==null&&n!==e.description,event_id:s.id}),l}async function Eo(e){let t=e.readOnly?f(e.home):await v(e.home);if(e.readOnly&&!await S(t.database))return[];let r=_(t.database,{readOnly:e.readOnly}),o;try{o=r.listWorkItems({project:e.project,status:e.status,priority:e.priority,assignedHost:e.assignedHost,limit:qv(e.limit)})}finally{r.close()}return e.readOnly||await h({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 Po(e){return Ai({home:e.home,id:e.id,actor:e.host,eventType:"claimed",auditType:"work_item_claimed",mutate:(t,r)=>{if(Ei(t.status))throw new Error(`Work item already terminal: ${t.id} (${t.status})`);return Bn(t.status,"in_progress"),{status:"in_progress",assignedHost:e.host,claimedAt:t.claimed_at??r,updatedAt:r,details:{assigned_host:e.host}}}})}async function xo(e){return Ai({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&&Bn(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:H(e.tags),metadata:e.metadata===void 0?void 0:Gv(t.metadata,H(e.metadata)),completedAt:Ei(o)?r:void 0,updatedAt:r,details:{priority:e.priority??null,assigned_host:e.assignedHost??null,fields:Jv(e),redacted:e.description!==void 0&&e.description!==null&&n!==e.description}}}})}async function jo(e){let t=e.status??"done";return Ai({home:e.home,id:e.id,actor:"cli",eventType:"completed",auditType:"work_item_completed",mutate:(r,o)=>{if(Ei(r.status))throw new Error(`Work item already terminal: ${r.id} (${r.status})`);return Bn(r.status,t),{status:t,completedAt:o,updatedAt:o,details:{terminal_status:t}}}})}function Bn(e,t){if(e!==t&&!Ap[e].includes(t))throw new Error(`Illegal work item transition: ${e} -> ${t}`)}async function Ai(e){let t=await v(e.home),r=_(t.database),o,n;try{let a=r.getWorkItem(e.id);if(!a)throw new Error(`Work item not found: ${e.id}`);let s=new Date().toISOString(),i=e.mutate(a,s);n=Ep({workItem:a,type:e.eventType,fromStatus:a.status,toStatus:i.status??a.status,actor:e.actor,details:i.details,now:s}),o=r.updateWorkItem({id:a.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 Pp(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 Ep(e){return{id:T("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 Pp(e,t,r,o){await h({home:e,type:t,details:{id:r.id,project:r.project_id,status:r.status,...Kv(o)}})}function Jv(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 Ei(e){return e==="done"||e==="failed"}function qv(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),200)}function Kv(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Gv(e,t){return Sp(e)&&Sp(t)?{...e,...t}:t}function Sp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{readdir as Tk,readFile as Ck}from"node:fs/promises";import Bp from"node:path";import{existsSync as Xv}from"node:fs";var zv=50;function Io(e={}){let t=ak(e.limit),r=tk(e),o=e.groupBy??"host",n=new Date().toISOString();if(e.db)return xp(e.db,e,r,o,t,n);let a=f(e.home);if(!Xv(a.database))return nk(e,r,o,t,n);let s=_(a.database,{readOnly:!0});try{return xp(s,e,r,o,t,n)}finally{s.close()}}function xp(e,t,r,o,n,a){let s=e.listRunCostRows({project:t.project,host:t.host,since:r.since??void 0,until:r.until??void 0}),i=Vn(s,g=>({key:g.project_id,label:g.project_id})),l=Vn(s,g=>({key:g.host,label:g.host})),c=Vn(s,g=>{let y=Zv(g);return{key:y,label:y==="unattributed"?"unattributed":y}}),d=Vn(s,g=>{let y=g.completed_at?.slice(0,10)??"unknown";return{key:y,label:y}}),p=s.map(g=>Tp(g.id,g.id,[g]));return{schema_version:1,generated_at:a,filters:{project:t.project??null,host:t.host??null,since:r.since,until:r.until,group_by:o,limit:n},totals:Cp(s),groups:Qv(o,{byProject:i,byHost:l,bySession:c,byDay:d,byRun:p}).slice(0,n),by_project:i.slice(0,n),by_host:l.slice(0,n),by_session:c.slice(0,n),by_day:d.slice(0,n),by_run:p.slice(0,n)}}function Vn(e,t){let r=new Map;for(let o of e){let n=t(o),a=r.get(n.key)??{label:n.label,rows:[]};a.rows.push(o),r.set(n.key,a)}return Array.from(r.entries()).map(([o,n])=>Tp(o,n.label,n.rows))}function Tp(e,t,r){return{key:e,label:t,...Cp(r)}}function Cp(e){let t=0,r=0,o=0,n=0,a=0;for(let s of e){let i=Pr(s.cost_json);Yv(i)&&(t+=1),"tokens_in"in i&&typeof i.tokens_in=="number"&&(o+=i.tokens_in),"tokens_out"in i&&typeof i.tokens_out=="number"&&(n+=i.tokens_out),"cost_usd"in i&&typeof i.cost_usd=="number"&&(r+=1,a+=i.cost_usd)}return{total_runs:e.length,reported_runs:t,cost_reported_runs:r,not_reported_runs:e.length-t,tokens_in:o,tokens_out:n,total_usd:sk(a),coverage:e.length===0?0:t/e.length}}function Yv(e){return"source"in e&&e.source==="host-reported"}function Qv(e,t){switch(e){case"project":return t.byProject;case"host":return t.byHost;case"day":return t.byDay;case"session":return t.bySession;case"total":return[]}}function Zv(e){return ek(e.evidence_json)??e.session_id??"unattributed"}function ek(e){let t;try{t=JSON.parse(e)}catch{return null}return jp(t,"session_id")??jp(t,"session")}function jp(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e[t];return typeof r=="string"&&r.length>0?r:null}function tk(e){return{since:e.since?rk(e.since):null,until:e.until?Op(e.until,"until"):null}}function rk(e){let t=ok(e);return t!==null?new Date(Date.now()-t).toISOString():Op(e,"since")}function Op(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new Error(`cost --${t} must be an ISO timestamp or duration`);return new Date(r).toISOString()}function ok(e){let t=e.match(/^(\d+)(s|m|h|d|w)$/u);if(t?.[1]&&t[2])return Ip(Number(t[1]),t[2]);let r=e.match(/^(\d+)\s+(second|seconds|minute|minutes|hour|hours|day|days|week|weeks)$/u);return r?.[1]&&r[2]?Ip(Number(r[1]),r[2]):null}function Ip(e,t){return e*({s:1e3,second:1e3,seconds:1e3,m:6e4,minute:6e4,minutes:6e4,h:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,week:6048e5,weeks:6048e5}[t]??0)}function nk(e,t,r,o,n){let a={total_runs:0,reported_runs:0,cost_reported_runs:0,not_reported_runs:0,tokens_in:0,tokens_out:0,total_usd:0,coverage:0};return{schema_version:1,generated_at:n,filters:{project:e.project??null,host:e.host??null,since:t.since,until:t.until,group_by:r,limit:o},totals:a,groups:[],by_project:[],by_host:[],by_session:[],by_day:[],by_run:[]}}function ak(e){return e===void 0||!Number.isFinite(e)?zv:Math.max(1,Math.min(Math.trunc(e),500))}function sk(e){return Math.round(e*1e8)/1e8}import{mkdir as dk,readdir as uk,readFile as pk,writeFile as mk}from"node:fs/promises";import qt from"node:path";function Np(e){let t=Pi(e)?e:{},r=Pi(t.tool_input)?t.tool_input:Pi(t.input)?t.input:{},o=z(t.tool_name)??z(t.tool)??z(t.name)??"unknown_tool",n=z(t.action)??z(r.action)??o,a=z(t.target)??z(r.target)??z(r.file_path)??z(r.path)??z(r.url)??z(r.command),s=z(r.command)??z(t.command);return{action:n,className:ik(o,[a,s].filter(Boolean).join(" ")),target:a,project:z(t.project)??z(t.project_id)??z(r.project)??z(r.project_id)}}function ik(e,t){let r=`${e} ${t??""}`.toLowerCase();return/\b(bash|shell|sh|zsh|exec_command)\b/u.test(e.toLowerCase())?lk(t??""):/\b(rm\s+-[^\s]*[rf][^\s]*|delete|reset\s+--hard|destroy|purge|drop)\b/u.test(r)?"destructive":/(slack|gmail|outlook|github|gh\s+pr|gh\s+issue|git\s+push|vercel\s+deploy|deploy|publish|send|post|comment|merge|api|curl\s+.*(-x|--request|-d|--data|--data-raw|--form)\s*(post|put|patch|delete)?)/u.test(r)?"external_write":/(write|edit|patch|apply|create|move|rename|git\s+commit)/u.test(r)?"write_project":/(curl|fetch|browser|http|web)/u.test(r)?"probe_external":"read_local"}function lk(e){let t=e.toLowerCase();return/\b(rm\s+-[^\s]*[rf][^\s]*|delete|reset\s+--hard|destroy|purge|drop)\b/u.test(t)?"destructive":/(curl\s+.*(-x|--request|-d|--data|--data-raw|--form)\s*(post|put|patch|delete)?|gh\s+(pr|issue|release)|git\s+push|vercel\s+deploy|npm\s+publish|pnpm\s+publish|deploy|publish)/u.test(t)?"external_write":/(^|\s)(touch|mkdir|mv|cp|tee|chmod|chown|git\s+commit)\b|(^|[^>])>[^>]|>>/u.test(t)?"write_project":/^(pwd|ls|cat|head|tail|rg|grep|sed\s+-n|find\s+.*-print|git\s+(status|diff|log|show))(\s|$)/u.test(t.trim())?"read_local":/(curl|fetch|http|https?:\/\/)/u.test(t)?"probe_external":"write_project"}function Pi(e){return!!e&&!Array.isArray(e)&&typeof e=="object"}function z(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}var gk=new Set(["SOUL.MD","POLICY.MD"]),fk=5e3,Mp=new Map;async function ft(e){let t=f(e),r=Mp.get(t.home);if(r&&r.expiresAt>Date.now())return r.orders;let o=qt.join(t.home,"standing-orders"),n;try{n=await uk(o)}catch{return[]}let a=[];for(let s of n.filter(i=>i.endsWith(".yaml")||i.endsWith(".yml")).sort()){let i=qt.join(o,s),l=await pk(i,"utf8");a.push(hk(l,i))}return Mp.set(t.home,{expiresAt:Date.now()+fk,orders:a}),a}async function ht(e){let t=await ft(e.home),r=e.target??null,o=r?Lp(r):null,n=t.filter(i=>Ii(i,e)),a=n.find(i=>i.allowed.includes(e.action)),s=n.find(i=>i.approval_required.includes(e.action));if(o&&gk.has(o))return gt(e,"proposal_required",["PROTECTED_HUMAN_FILE"],null);if(e.className==="identity_policy_change")return gt(e,"proposal_required",["IDENTITY_POLICY_CHANGE"],null);if(e.className==="destructive")return gt(e,"denied",["DESTRUCTIVE_DENIED_BY_DEFAULT"],a?.id??s?.id??null);if(s)return gt(e,"approval_required",["STANDING_ORDER_REQUIRES_APPROVAL"],s.id);if(a)return gt(e,"allowed",["STANDING_ORDER_ALLOWED"],a.id);switch(e.className){case"read_local":case"probe_external":case"write_local":return gt(e,"allowed",["DEFAULT_ALLOWED"],null);case"write_project":return gt(e,"approval_required",["PROJECT_WRITE_REQUIRES_APPROVAL"],null);case"external_write":return gt(e,"approval_required",["EXTERNAL_WRITE_REQUIRES_APPROVAL"],null)}}async function xi(e){let t=Np(e.payload),r=await ht({home:e.home,action:t.action,className:t.className,target:t.target,project:t.project,host:e.host}),o=r.decision==="allowed",n={hook_event_name:"PreToolUse",host:e.host,allowed:o,blocked:!o,message:o?"NativeSoul policy allowed this tool use.":`NativeSoul policy blocked ${r.action}: ${r.decision} (${r.reasons.join(", ")}).`,evaluation:r};if(!o){let a=await v(e.home);await h({home:a.home,type:"policy_blocked",result:"blocked",details:{host:e.host,cwd:e.cwd??null,action:r.action,class:r.class,target:r.target,decision:r.decision,reasons:r.reasons,matched_standing_order:r.matched_standing_order}})}return n}async function ji(e){let t=await v(e.home),r=yk(e.target);if(!r)throw new Error("policy propose-change target must be SOUL.md or POLICY.md");let o=N(e.summary).value,n=new Date().toISOString(),a=T("proposal"),s=qt.join(t.home,"proposals",`${n.replaceAll(/[:.]/gu,"-")}-${r}.md`),i=["# Policy Change Proposal","",`ID: ${a}`,`Target: ${r}`,`Created At: ${n}`,"","## Summary","",o,""].join(`
|
|
892
|
-
`);return await dk(qt.dirname(s),{recursive:!0,mode:448}),Se(s,{root:t.home}),await mk(s,i,{encoding:"utf8",mode:384,flag:"wx"}),await h({home:t.home,type:"policy_change_proposed",details:{id:a,target:r,proposalPath:s,redacted:o!==e.summary}}),{id:a,target:r,summary:o,proposalPath:s,created_at:n}}function gt(e,t,r,o){return{action:e.action,class:e.className,target:e.target??null,decision:t,reasons:r,matched_standing_order:o}}function hk(e,t){return{id:_k(e,"id")??qt.basename(t,qt.extname(t)),allowed:fr(e,"allowed"),approval_required:fr(e,"approval_required"),scope_projects:fr(e,"projects").concat(fr(e,"scope_projects")),scope_hosts:fr(e,"hosts").concat(fr(e,"scope_hosts")),source:t}}function Ii(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 Lp(e){return qt.basename(e.replaceAll("\\","/")).toUpperCase()}function yk(e){let t=Lp(e);return t==="SOUL.MD"?"SOUL.md":t==="POLICY.MD"?"POLICY.md":null}function _k(e,t){let r=new RegExp(`^\\s*${t}:\\s*([^\\n#]+)`,"mu");return e.match(r)?.[1]?.trim().replace(/^["']|["']$/gu,"")??null}function fr(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=[],a=!1,s=0;for(let i of o){let l=i.trim();if(!a){let d=i.match(new RegExp(`^(\\s*)${t}:\\s*$`,"u"));d&&(a=!0,s=d[1]?.length??0);continue}let c=i.length-i.trimStart().length;if(l&&c<=s&&!l.startsWith("-"))break;l.startsWith("-")&&n.push(l.slice(1).trim().replace(/^["']|["']$/gu,""))}return n.filter(Boolean)}function le(e,t,r){if(e==null)return!1;if(Array.isArray(e))return e.some(o=>le(o,t,r));if(typeof e!="object")return!1;for(let[o,n]of Object.entries(e)){if(o===t){if(r===void 0)return!0;if(n===null)return r==="null";if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return String(n)===r;if(Array.isArray(n))return n.some(a=>String(a)===r)}if(le(n,t,r))return!0}return!1}var bk=/(?:sk-[A-Za-z0-9_-]{8,}|(?:api[_-]?key|token|secret|password)\s*[:=]\s*(?!\[REDACTED_SECRET\])[^"'\s]+)/iu;async function hr(e={}){let t=f(e.home),r=Ik(e.limit);if(!await S(t.database))return vk(e,r,!1);let n=_(t.database,{readOnly:!0});try{let a=n.listEvents({limit:r}),s=n.listCapabilities({host:e.host,includeShared:!0,limit:r}),i=n.listSchedules({host:e.host,limit:r}),l=n.listHeartbeatLeases({project:e.project,limit:r}),c=n.listHeartbeatRuns({project:e.project,host:e.host,limit:r}),d=a.filter(y=>jk(y,e)),p=s.filter(y=>Dp(y.host,e.host)),g=i.filter(y=>Dp(y.host,e.host));return Up({schema_version:1,generated_at:new Date().toISOString(),read_only:!0,external_telemetry_enabled:!1,initialized:!0,filters:Fp(e,r),retention:$p(r),metrics:{activation:kk(d),bootstrap:wk(d),recall:Rk(d),capability_readiness:Sk(p),heartbeat:Ak(l,c),no_op_suppression:Ek(d),rollback:Pk(d),secret_leakage_checks:Hp(d)},m7_gate:xk(d,p,g,c)})}finally{n.close()}}function vk(e,t,r){return Up({schema_version:1,generated_at:new Date().toISOString(),read_only:!0,external_telemetry_enabled:!1,initialized:r,filters:Fp(e,t),retention:$p(t),metrics:{activation:{workspace_initialized:0,onboarding_completed:0,install_applied:0},bootstrap:{succeeded:0,degraded:0,failed:0,cache_fallbacks:0},recall:{recalled:0,proposed:0,promoted:0},capability_readiness:{total:0,ready:0,full_native:0,official_fallback:0,degraded:0},heartbeat:{leases:0,completed_runs:0,silent_ok:0},no_op_suppression:{total:0,heartbeat_skipped:0,deduped:0,noop_actions:0},rollback:{total:0,policy_pack:0,mcp:0,managed_block:0},secret_leakage_checks:{checked:!0,leak_indicators:0,redaction_markers:0}},m7_gate:{recurring_use_validated:!1,feedback_validated:!1,privacy_validated:!0,notes:["NativeSoul database is not initialized; no local feedback evidence is available yet."]}})}function kk(e){return{workspace_initialized:pe(e,["workspace_initialized"]),onboarding_completed:pe(e,["onboarding_completed"]),install_applied:pe(e,["plugin_install","managed_block_applied","mcp_registration_installed"])}}function wk(e){return{succeeded:pe(e,["handshake_succeeded"]),degraded:pe(e,["handshake_degraded"]),failed:pe(e,["handshake_failed"]),cache_fallbacks:e.filter(t=>t.type.includes("bootstrap_context_cache")).length}}function Rk(e){return{recalled:pe(e,["memory_recalled"]),proposed:pe(e,["memory_proposed"]),promoted:pe(e,["memory_promoted"])}}function Sk(e){let t=e.map(gr);return{total:e.length,ready:t.filter(r=>r==="ready"||r==="full native capability").length,full_native:t.filter(r=>r==="full native capability").length,official_fallback:t.filter(r=>r==="official-fallback").length,degraded:t.filter(r=>r==="degraded").length}}function Ak(e,t){return{leases:e.length,completed_runs:t.length,silent_ok:t.filter(r=>r.result==="HEARTBEAT_OK"||le(r.result,"silent_ack","HEARTBEAT_OK")).length}}function Ek(e){let t=pe(e,["heartbeat_skipped"]),r=e.filter(n=>n.type.includes("deduped")).length,o=e.filter(n=>le(n.details,"action","noop")).length;return{total:t+r+o,heartbeat_skipped:t,deduped:r,noop_actions:o}}function Pk(e){let t=pe(e,["policy_pack_rollback"]),r=pe(e,["mcp_registration_rollback"]),o=pe(e,["managed_block_rollback"]);return{total:e.filter(n=>n.type.includes("rollback")).length,policy_pack:t,mcp:r,managed_block:o}}function Hp(e){let t=JSON.stringify(e.map(r=>({type:r.type,result:r.result,details:r.details})));return{checked:!0,leak_indicators:bk.test(t)?1:0,redaction_markers:(t.match(/\[REDACTED_/gu)??[]).length}}function xk(e,t,r,o){let n=o.length>0||r.some(l=>l.enabled),a=e.length>0&&t.length>0,s=Hp(e).leak_indicators===0;return{recurring_use_validated:n,feedback_validated:a,privacy_validated:s,notes:[n?"Recurring heartbeat/schedule evidence exists locally.":"No recurring heartbeat/schedule evidence yet.",a?"Feedback report has local audit and capability evidence.":"Feedback report needs audit and capability evidence.",s?"Report excludes raw prompts, memory bodies, and unredacted secret indicators.":"Potential secret indicators found in local audit details."]}}function pe(e,t){return e.filter(r=>t.includes(r.type)).length}function jk(e,t){let r=!t.host||!le(e.details,"host")||le(e.details,"host",t.host),o=!t.project||!le(e.details,"project")||le(e.details,"project",t.project);return r&&o}function Dp(e,t){return!t||e===t||e==="all"}function $p(e){return{source_event_limit:e,stores_raw_prompts:!1,stores_memory_content:!1,stores_raw_paths:!1}}function Fp(e,t){return{project:e.project??null,host:e.host??null,limit:t}}function Ik(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e??200),1),500):200}function Up(e){return Zt(H(e))}var Ok=["candidate","active","superseded","rejected","forgotten","expired"],Ti=["inbox","assigned","in_progress","review","blocked","done","failed"];async function To(e={}){let t=f(e.home),r=Qk(e.limit),o=Xk(e);if(!await S(t.database))return Wp(await Nk(t.home,t.database,e,r));let a=_(t.database,{readOnly:!0});try{let s=a.listMemories({project:e.project,includeForgotten:!0,limit:Math.max(r*4,50)}),i=a.listCapabilities({host:e.host,includeShared:!0,limit:r}),l=a.listCommitments({project:e.project,includeExpired:!0,limit:Math.max(r*2,50),now:new Date().toISOString(),skipExpire:!0}),c=a.listSchedules({host:e.host,limit:r}),d=a.listHeartbeatLeases({project:e.project,limit:r}),p=a.listHeartbeatRuns({project:e.project,host:e.host,limit:r}),g=a.listEvents({limit:Math.max(r*4,50)}),y=Kk(await ft(t.home),e),k=await Wk(t.home),R=Ye(s,o,D=>D.created_at),U=Ye(l,o,D=>D.updated_at).slice(0,r),Y=Ye(i,o,D=>D.last_seen_at).slice(0,r),be=Ye(c,o,D=>D.updated_at).slice(0,r),Ie=Ye(d,o,D=>D.created_at).slice(0,r),ne=Ye(p,o,D=>D.completed_at).slice(0,r),Fe=Ye(g,o,D=>D.created_at).filter(D=>!e.host||zk(D,{key:"host",value:e.host})).slice(0,r),x=Fe.filter(D=>D.type==="policy_blocked"),Ar=Fe.filter(D=>Yk(D)).length,Jo=Mk(a,e,o,r),Er=Dk(a,e,o,r,k,Ar),V=Fk(a,e,r),Mm={schema_version:2,generated_at:new Date().toISOString(),filters:Kp(e,r),read_only:!0,home:t.home,database:t.database,initialized:!0,memories:{summary:Gk(R),recent:R.filter(D=>D.status!=="candidate").slice(0,r),candidates:R.filter(D=>D.status==="candidate").slice(0,r)},commitments:U,capabilities:Y,schedules:be,heartbeat:{leases:Ie,runs:ne},audit:{events:Fe,policy_blocks:x},policy:{standing_orders:y,proposals:k,counts:{standing_orders:y.length,proposals:k.length,policy_blocks:x.length,approvals_required:Ar}},work:Jo,approvals:Er,cost:V,feedback:await hr({home:t.home,project:e.project,host:e.host,limit:r})};return Wp(Mm)}finally{a.close()}}async function Nk(e,t,r,o){return{schema_version:2,generated_at:new Date().toISOString(),filters:Kp(r,o),read_only:!0,home:e,database:t,initialized:!1,memories:{summary:qp(),recent:[],candidates:[]},commitments:[],capabilities:[],schedules:[],heartbeat:{leases:[],runs:[]},audit:{events:[],policy_blocks:[]},policy:{standing_orders:[],proposals:[],counts:{standing_orders:0,proposals:0,policy_blocks:0,approvals_required:0}},work:Jp(),approvals:Bk(),cost:Vk(),feedback:await hr({home:e,project:r.project,host:r.host,limit:o})}}function Mk(e,t,r,o){let n=Ye(e.listWorkItems({project:t.project,assignedHost:t.host,limit:Math.max(o*Ti.length,50)}),r,s=>s.updated_at).slice(0,Math.max(o*Ti.length,50));if(n.length===0)return Jp();let a=[];for(let s of Ti){let i=n.filter(l=>l.status===s).slice(0,o).map(l=>Lk(e,l));i.length>0&&a.push({status:s,count:i.length,items:i})}return{columns:a}}function Lk(e,t){let r=e.listHeartbeatRunsByWorkItem({workItemId:t.id,project:t.project_id,limit:1})[0];return{id:t.id,title:t.title,summary:t.description??t.title,status:t.status,project:t.project_id,host:t.assigned_host,linked_run_id:Uk(t.metadata,"run_id")??r?.id??null,priority:t.priority,updated_at:t.updated_at}}function Dk(e,t,r,o,n,a){let s=e.listApprovals("pending").approvals.filter(l=>$k(l,t)).filter(l=>Ye([l],r,c=>c.created_at).length>0).slice(0,o).map(Hk);if(s.length>0)return{pending:s,counts:{pending:s.length}};let i=n.slice(0,o).map(l=>({id:l.filename,action:l.summary??"Policy proposal pending review",class:"identity_policy_change",target:l.target,project:t.project??null,host:t.host??null,source:"policy_proposal",created_at:null}));return i.length===0&&a>0&&i.push({id:"policy-approval-required",action:"Policy event requires approval",class:"approval_required",target:null,project:t.project??null,host:t.host??null,source:"policy_event",created_at:null}),{pending:i,counts:{pending:i.length}}}function Hk(e){return{id:e.id,action:e.action,class:e.class,target:e.target,project:e.project,host:e.host,source:"approvals",created_at:e.created_at}}function $k(e,t){return(!t.project||e.project===t.project)&&(!t.host||e.host===t.host)}function Fk(e,t,r){let o=Io({db:e,project:t.project,host:t.host,since:t.since,until:t.until,groupBy:"host",limit:r});return{totals:{runs:o.totals.total_runs,reported_runs:o.totals.reported_runs,cost_reported_runs:o.totals.cost_reported_runs,not_reported_runs:o.totals.not_reported_runs,tokens_in:o.totals.tokens_in,tokens_out:o.totals.tokens_out,total_usd:o.totals.total_usd,coverage:o.totals.coverage},by_project:o.by_project.map(Wn),by_host:o.by_host.map(Wn),by_session:o.by_session.map(Wn),by_run:o.by_run.map(Wn)}}function Wn(e){return{key:e.key,label:e.label,runs:e.total_runs,reported_runs:e.reported_runs,cost_reported_runs:e.cost_reported_runs,not_reported_runs:e.not_reported_runs,tokens_in:e.tokens_in,tokens_out:e.tokens_out,total_usd:e.total_usd,coverage:e.coverage}}function Uk(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e[t];return typeof r=="string"&&r.length>0?r:null}function Jp(){return{columns:[]}}function Bk(){return{pending:[],counts:{pending:0}}}function Vk(){return{totals:{runs:0,reported_runs:0,cost_reported_runs:0,not_reported_runs:0,tokens_in:0,tokens_out:0,total_usd:0,coverage:0},by_project:[],by_host:[],by_session:[],by_run:[]}}async function Wk(e){let t=Bp.join(e,"proposals"),r;try{r=await Tk(t)}catch{return[]}let o=[];for(let n of r.filter(a=>a.endsWith(".md")).sort()){let a=await Ck(Bp.join(t,n),"utf8");o.push({filename:n,target:Jk(a,"Target"),summary:qk(a,"Summary")})}return o}function Jk(e,t){return e.match(new RegExp(`^${t}:\\s*(.+)$`,"mu"))?.[1]?.trim()??null}function qk(e,t){return e.match(new RegExp(`^## ${t}\\s*$\\n+([\\s\\S]*?)(?:\\n+## |$)`,"mu"))?.[1]?.trim()??null}function Kk(e,t){return e.filter(r=>{let o=!t.project||r.scope_projects.length===0||r.scope_projects.includes(t.project),n=!t.host||r.scope_hosts.length===0||r.scope_hosts.includes(t.host);return o&&n})}function Gk(e){let t=qp();for(let r of e)t[r.status]+=1;return t}function qp(){return Object.fromEntries(Ok.map(e=>[e,0]))}function Ye(e,t,r){return e.filter(o=>{let n=Date.parse(r(o));return!(!Number.isFinite(n)||t.since!==null&&n<t.since||t.until!==null&&n>t.until)})}function Xk(e){return{since:Vp(e.since,"since"),until:Vp(e.until,"until")}}function Vp(e,t){if(!e)return null;let r=Date.parse(e);if(!Number.isFinite(r))throw new Error(`dashboard data --${t} must be an ISO date/time`);return r}function zk(e,t){return le(e.details,t.key,t.value)}function Yk(e){return le(e.details,"decision","approval_required")||le(e.details,"approval_required")||le(e.details,"action","approval_required")}function Kp(e,t){return{project:e.project??null,host:e.host??null,limit:t,since:e.since??null,until:e.until??null}}function Qk(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e??50),1),200):50}function Wp(e){return Zt(H(e))}import{mkdir as Zk,writeFile as ew}from"node:fs/promises";import Ci from"node:path";async function Ni(e={}){let t=await To(e),r=Ci.resolve(e.output??Ci.join(f(e.home).home,"generated","dashboard","index.html"));return await Zk(Ci.dirname(r),{recursive:!0,mode:448}),await ew(r,Gp(t),{encoding:"utf8",mode:384}),{outputPath:r,generated_at:t.generated_at,read_only:!0,data:t}}function Gp(e){let t=dw(e.capabilities),r=e.audit.policy_blocks.length,o=e.policy.counts.approvals_required,n=tw(e),a=n?n.work.columns.reduce((s,i)=>s+i.items.length,0):0;return`<!doctype html>
|
|
881
|
+
${o}`.trimStart()}function __(e){return e.match(/\[agent\][\s\S]*?(?=\n\[|$)/u)?.[0]?.match(/\bname\s*=\s*["']([^"']+)["']/u)?.[1]??null}function co(e){return{hooks:[{type:"command",command:e,timeout:9}]}}function Vu(e,t){let r=Array.isArray(e)?e:[],o=Vs(t);return o&&r.some(n=>Vs(n)===o)?r:[...r,t]}function Vs(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 b_ from"node:path";var On=[{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"}],v_={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 uo(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 k_(e){return e==="grok"||e==="gemini"||e==="antigravity"?v_[e]:On}function Js(e){return e==="grok"||e==="gemini"?["hooks/hooks.json"]:e==="antigravity"?["hooks.json"]:[...new Set(On.map(t=>t.fileName).filter(t=>!!t))].map(t=>b_.join("hooks",t))}function Wu(e,t){return t==="official-extension"?typeof e.name=="string"&&e.name==="nativesoul":typeof e.name=="string"&&e.name.includes("nativesoul")}function Ju(e,t){return qs(e,t).length===0}function qs(e,t){return k_(e).filter(({event:r,commandFragment:o})=>!w_(t,r,o)).map(({event:r})=>r)}function po(e){return e==="claude"||e==="codex"||e==="gemini"||e==="grok"||e==="antigravity"}function Nn(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 Mn(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 w_(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(a=>{if(!a||Array.isArray(a)||typeof a!="object")return!1;let s=a.hooks;return!Array.isArray(s)||s.length===0?!1:s.some(i=>{if(!i||Array.isArray(i)||typeof i!="object")return!1;let l=i.command;return typeof l=="string"&&sr(l).includes(r)})})}async function ut(e){if(!e.targetPath||!io(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=uo(e.host,e.surface),r=dt(e.targetPath),o=jn(e.host,e.targetPath),n=dt(o),a=t.nativeHooksSupported&&e.targetPath?Js(e.host).filter(Y=>!dt(Ge.join(e.targetPath,Y))):Js(e.host),s=t.nativeHooksSupported?a.length===0:!0,i=[],l=!1,c=!t.nativeHooksSupported,d=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 Y=JSON.parse(await Ln(o,"utf8")),be=t.nativeHooksSupported?await R_(e.host,e.targetPath,Y):Y;if(l=t.nativeHooksSupported?e.host==="grok"?await Fu(e.targetPath):Ju(e.host,be):Wu(Y,t.packageKind),c=!t.nativeHooksSupported||await S_({host:e.host,targetPath:e.targetPath,manifest:Y}),d=e.host==="grok"?await Uu(e.targetPath):!0,e.host==="grok"&&!d&&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 Ie=qs(e.host,be);i.push({code:"PLUGIN_HOOK_MISSING",severity:"error",message:Ie.length>0?`NativeSoul plugin manifest is missing required hook registrations: ${Ie.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&&!s&&i.push({code:"PLUGIN_HOOK_FILE_MISSING",severity:"error",message:`NativeSoul required hook files are missing under ${e.targetPath}: ${a.join(", ")}`,remediation:"Reinstall the NativeSoul plugin"});let p=e.targetPath?Ge.join(e.targetPath,"shared","hooks","lib.cjs"):null;r&&t.nativeHooksSupported&&(!p||!dt(p))&&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?Ge.resolve(Ge.dirname(Ge.dirname(e.targetPath))):void 0,y=!t.nativeHooksSupported||p!==null&&dt(p),k=t.nativeHooksSupported?s&&y:!0,R=r&&n&&l&&k&&c&&d,U=e.host==="grok"?await $u(g):null;return e.host==="grok"&&R&&U===!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:R&&U!==!1,hook_registered:t.nativeHooksSupported?l&&s:!1,package_kind:t.packageKind,native_hooks_supported:t.nativeHooksSupported,native_scheduler_supported:!1,issues:i}}async function R_(e,t,r){let o=Mn(e);if(o.length===0)return r;let n=ct(t,jn(e,t)),a=o[0];if(!a||a===n)return r;let s=Ge.join(t,a);return dt(s)?JSON.parse(await Ln(s,"utf8")):{}}async function S_(e){let t=Nn(e.host),r=ct(e.targetPath,jn(e.host,e.targetPath));if(t.length>0&&!t.includes(r)){for(let o of t){let n=Ge.join(e.targetPath,o);if(dt(n)&&Ks(JSON.parse(await Ln(n,"utf8"))))return!0}return!1}if(e.host==="codex"){let o=Ge.join(e.targetPath,".mcp.json");return dt(o)?Ks(JSON.parse(await Ln(o,"utf8"))):!1}return Ks(e.manifest)}function Ks(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"||xn(o)||o===process.execPath?!0:Array.isArray(n)&&n.some(a=>typeof a=="string"&&Ge.isAbsolute(a))}import{cp as A_,mkdir as E_,readFile as P_,readdir as x_}from"node:fs/promises";import Gs from"node:path";async function Xs(e,t,r,o){let n=Gs.join(e,"backups","plugins");await E_(n,{recursive:!0,mode:448});let a=Gs.join(n,`${new Date().toISOString().replaceAll(/[:.]/gu,"-")}-${t}-${r}-${T("plugin")}`);return await A_(o,a,{recursive:!0}),a}async function zs(e){let t=await ir(e),r=await Promise.all(t.map(async o=>{let n=ct(e,o),a=await P_(o,"utf8");return`${n}\0${A(a)}`}));return A(r.sort().join(`
|
|
882
|
+
`))}async function ir(e){let t=await x_(e,{withFileTypes:!0});return(await Promise.all(t.map(async o=>{let n=Gs.join(e,o.name);return o.isDirectory()?ir(n):o.isFile()?[n]:[]}))).flat()}import{existsSync as H_}from"node:fs";import{cp as $_,mkdir as F_,readFile as Ys,writeFile as U_}from"node:fs/promises";import Xe from"node:path";import{fileURLToPath as B_}from"node:url";import{spawnSync as j_}from"node:child_process";import{accessSync as I_,constants as T_,existsSync as qu}from"node:fs";import $t from"node:path";function Ft(e){let t=C_(e.commandMode,e.projectRoot),r=t.command,o=[...t.args];e.home&&o.push("--home",e.home);let n={command:r,args:o,env:{}};return{serverName:"nativesoul",host:e.host,commandMode:e.commandMode,command:r,args:o,env:{},mcpServers:{nativesoul:n},snippet:D_(e.host,n),warnings:[...t.warnings,...e.host==="generic"?[]:[`${e.host.toUpperCase()}_MCP_REGISTRATION_NOT_APPLIED`]]}}function C_(e,t){let r=process.env.NATIVESOUL_MCP_COMMAND;return r&&r.trim().length>0?{command:r.trim(),args:[],warnings:["NATIVESOUL_MCP_COMMAND_ENV_OVERRIDE"]}:e==="local"?{command:process.execPath,args:[$t.join(t??process.cwd(),"dist","packages","mcp-server","src","index.js")],warnings:[]}:e==="absolute"?O_(t):{command:"nativesoul-mcp",args:[],warnings:Ku("nativesoul-mcp")?[]:["NATIVESOUL_MCP_COMMAND_NOT_ON_PATH"]}}function O_(e){let t=M_();if(t)return{command:t,args:[],warnings:[]};let r=Ku("nativesoul-mcp");if(r)return{command:r,args:[],warnings:[]};let o=N_(e);if(qu(o))return{command:process.execPath,args:[o],warnings:["NATIVESOUL_MCP_COMMAND_LOCAL_DIST"]};let n=L_();return n?{command:process.execPath,args:[n],warnings:["NATIVESOUL_MCP_COMMAND_NPM_ROOT_GLOBAL"]}:{command:"nativesoul-mcp",args:[],warnings:["NATIVESOUL_MCP_COMMAND_NOT_RESOLVED"]}}function N_(e){return $t.join(e??process.cwd(),"dist","packages","mcp-server","src","index.js")}function M_(){let e=process.argv[1];if(!e)return null;let t=process.platform==="win32"?".cmd":"",r=$t.join($t.dirname(e),`nativesoul-mcp${t}`);return Gu(r)?r:null}function Ku(e){let t=(process.env.PATH??"").split($t.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 a=$t.join(o,`${e}${n}`);if(Gu(a))return a}return null}function L_(){let e=j_("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(e.status!==0)return null;let t=e.stdout.trim();if(!t)return null;let r=$t.join(t,"nativesoul","dist","packages","mcp-server","src","index.js");return qu(r)?r:null}function Gu(e){try{return I_(e,T_.X_OK),!0}catch{return!1}}function D_(e,t){return e==="generic"?{mcpServers:{nativesoul:t}}:{host:e,review_only:!0,mcpServers:{nativesoul:t}}}async function Xu(e,t,r,o){let n=await ir(e),a=await Promise.all(n.map(async i=>{let l=ct(e,i),c=await Zu({host:t,relativePath:l,content:await Ys(i,"utf8"),home:r,targetPath:o});return`${l}\0${A(c)}`})),s=Qu();if(s&&po(t)){let i=await ir(s);for(let l of i){let c=Xe.posix.join("shared","hooks",ct(s,l)),d=await Ys(l,"utf8");a.push(`${c}\0${A(d)}`)}}return A(a.sort().join(`
|
|
883
|
+
`))}async function zu(e){let t=Qu();if(!t)return;let r=Xe.join(e,"shared","hooks");await F_(r,{recursive:!0,mode:448}),await $_(t,r,{recursive:!0})}async function Yu(e){let t=await ir(e.targetPath);await Promise.all(t.map(async r=>{let o=Xe.relative(e.targetPath,r),n=await Ys(r,"utf8"),a=await Zu({host:e.host,relativePath:o,content:n,home:e.home,targetPath:e.targetPath});a!==n&&await U_(r,a,"utf8")}))}function Qu(){let e=Xe.dirname(B_(import.meta.url));return[Xe.resolve(process.cwd(),"plugins","shared","hooks"),Xe.resolve(e,"../../../plugins/shared/hooks"),Xe.resolve(e,"../../../../plugins/shared/hooks")].find(r=>H_(r))??null}async function Zu(e){let t=sr(e.relativePath),r=Nn(e.host).includes(t),o=Mn(e.host).includes(t);if(!r&&!o)return e.content;let n=JSON.parse(e.content),a=r?V_(n,Ft({host:e.host,commandMode:"package",home:e.home}).mcpServers.nativesoul):n,s=o&&e.targetPath&&po(e.host)?W_(a,e.targetPath):a;return`${JSON.stringify(s,null,2)}
|
|
884
|
+
`}function V_(e,t){return{...e,mcpServers:{nativesoul:t}}}function W_(e,t){if(!e.hooks||Array.isArray(e.hooks)||typeof e.hooks!="object")return e;let r=e.hooks,o=Object.fromEntries(Object.entries(r).map(([n,a])=>Array.isArray(a)?[n,a.map(s=>J_(s,t))]:[n,a]));return{...e,hooks:o}}function J_(e,t){if(!e||Array.isArray(e)||typeof e!="object")return e;let r=e,o=r.hooks;return Array.isArray(o)?{...r,hooks:o.map(n=>q_(n,t))}:e}function q_(e,t){if(!e||Array.isArray(e)||typeof e!="object")return e;let r=e,o=typeof r.command=="string"?r.command:null;if(!o)return e;if(o.includes("host-hook.cjs")){let s=Lt(Xe.join(t,"shared","hooks","host-hook.cjs"));return{...r,command:`node ${JSON.stringify(s)} ${K_(o)}`}}let n=On.find(s=>o.includes(s.commandFragment));if(!n?.fileName)return e;let a=Lt(Xe.join(t,"hooks",n.fileName));return{...r,command:`node ${JSON.stringify(a)}`}}function K_(e){let t=["session-start","prompt-bootstrap","pre-tool-use","memory-flush","recall"].find(a=>e.includes(a))??"session-start",r=e.match(/--host\s+([A-Za-z0-9_-]+)/u)?.[1],o=e.match(/--project-env\s+([A-Za-z0-9_-]+)/u)?.[1],n=e.match(/--event\s+([A-Za-z0-9_-]+)/u)?.[1];return[t,r?`--host ${r}`:null,o?`--project-env ${o}`:null,n?`--event ${n}`:null].filter(a=>a!==null).join(" ")}async function Zs(e){let t=f(e.home),r=Fs(e.host);if(!e.targetPath||!r)return tp(e.host,e.surface,e.targetPath,r,!e.apply);let o=Qs(e.targetPath)?await zs(e.targetPath):null,n=await Xu(r,e.host,t.home,e.targetPath),a=o===null?"create":o===n?"noop":"replace",s=a!=="noop",i=s&&e.apply&&Qs(e.targetPath)?await Xs(t.home,e.host,e.surface,e.targetPath):null,l=[];if(s&&e.apply&&(Se(e.targetPath,{allowSymlinkTarget:!0}),await X_(z_.dirname(e.targetPath),{recursive:!0,mode:448}),await ep(e.targetPath,{recursive:!0,force:!0}),await G_(r,e.targetPath,{recursive:!0}),po(e.host)&&await zu(e.targetPath),await Yu({host:e.host,targetPath:e.targetPath,home:t.home})),e.apply){let g=Cu(e.host);g==="claude-settings-hooks"?await Mu(e.targetPath):g==="grok-host-wiring"&&(await Lu(e.targetPath),await Du(e.targetPath))}e.apply&&l.push(...Hu(e.host,e.surface,e.targetPath));let c=e.targetPath&&io(e.host,e.surface)?await ut({host:e.host,surface:e.surface,targetPath:e.targetPath}):null,d=uo(e.host,e.surface),p={host:e.host,surface:e.surface,targetPath:e.targetPath,sourcePath:r,action:a,dryRun:!e.apply,changed:s,beforeHash:o,afterHash:n,backupPath:i,applied:s&&e.apply,enabled:c?.enabled??!1,hook_registered:c?.hook_registered??!1,package_kind:c?.package_kind??d.packageKind,native_hooks_supported:c?.native_hooks_supported??d.nativeHooksSupported,native_scheduler_supported:c?.native_scheduler_supported??!1,issues:[...c?.issues??[],...l]};return await h({home:t.home,type:e.apply?"plugin_install":"plugin_install_dry_run",details:p}),p}async function ei(e){let t=f(e.home),r=Fs(e.host);if(!e.targetPath||!r)return tp(e.host,e.surface,e.targetPath,r,!e.apply);let o=Qs(e.targetPath)?await zs(e.targetPath):null,n=uo(e.host,e.surface),a=o!==null,s=a&&e.apply?await Xs(t.home,e.host,e.surface,e.targetPath):null;a&&e.apply&&await ep(e.targetPath,{recursive:!0,force:!0});let i={host:e.host,surface:e.surface,targetPath:e.targetPath,sourcePath:r,action:a?"remove":"noop",dryRun:!e.apply,changed:a,beforeHash:o,afterHash:A(""),backupPath:s,applied:a&&e.apply,enabled:!1,hook_registered:!1,package_kind:n.packageKind,native_hooks_supported:n.nativeHooksSupported,native_scheduler_supported:!1,issues:[]};return await h({home:t.home,type:e.apply?"plugin_uninstall":"plugin_uninstall_dry_run",details:i}),i}function tp(e,t,r,o,n){return{host:e,surface:t,targetPath:r,sourcePath:o,action:"unsupported",dryRun:n,changed:!1,beforeHash:null,afterHash:A(""),backupPath:null,applied:!1,enabled:!1,hook_registered:!1,package_kind:"unsupported-native",native_hooks_supported:!1,native_scheduler_supported:!1,issues:[]}}function ze(e,t){if(t)return lr.resolve(t,e)}function cr(e,t,r){let o=ro(e,r);if(e==="claude"&&o==="claude-desktop")return{surface:o,managedBlock:null,mcpRegistration:t?lr.join(lr.resolve(t,e),"claude_desktop_config.json"):vu(),plugin:De(e,o,t)};if(!t)return{surface:o,managedBlock:bu(e),mcpRegistration:An(e),plugin:De(e,o)};let n=lr.resolve(t,e);return{surface:o,managedBlock:lr.join(n,yu(e)),mcpRegistration:lr.join(n,_u(e)),plugin:De(e,o,t)}}import{accessSync as Y_,constants as Q_,existsSync as pt}from"node:fs";import{mkdir as Dn,readFile as dr,rm as Z_,writeFile as Hn}from"node:fs/promises";import X from"node:path";async function go(e){let t=f(e.home),r=X.resolve(e.targetPath??$n(e.host)),o=e.commandMode??"package",n=Ft({host:e.host,commandMode:o,home:t.home,projectRoot:e.projectRoot}).mcpServers.nativesoul,a=pt(r),s=a?await dr(r,"utf8"):null,i=np(eb(mo(s),n)),l=s===null?null:A(s),c=A(i),d=sb(s,i),p=d!=="noop",g=p&&e.apply?await ap(t.home,e.host,r,a,s,c):null;p&&e.apply&&(await Dn(X.dirname(r),{recursive:!0,mode:448}),await Hn(r,i,{encoding:"utf8",mode:384}));let y={host:e.host,targetPath:r,action:d,dryRun:!e.apply,changed:p,beforeHash:l,afterHash:c,diff:sp(s,i),backupPath:g,commandMode:o,applied:p&&e.apply};return await h({home:t.home,type:e.apply?"mcp_registration_apply":"mcp_registration_dry_run",details:y}),y}async function ri(e){let t=f(e.home),r=X.resolve(e.targetPath??$n(e.host)),o=pt(r),n=o?await dr(r,"utf8"):null,a=tb(n),s=n===null?null:A(n),i=a===null?A(""):A(a),l=n!==a?"remove":"noop",c=l!=="noop",d=c&&e.apply?await ap(t.home,e.host,r,o,n,i):null;c&&e.apply&&a!==null&&(await Dn(X.dirname(r),{recursive:!0,mode:448}),await Hn(r,a,{encoding:"utf8",mode:384}));let p={host:e.host,targetPath:r,action:l,dryRun:!e.apply,changed:c,beforeHash:s,afterHash:i,diff:sp(n,a),backupPath:d,commandMode:"package",applied:c&&e.apply};return await h({home:t.home,type:e.apply?"mcp_registration_uninstall":"mcp_registration_uninstall_dry_run",details:p}),p}async function oi(e){let t=f(e.home),r=JSON.parse(await dr(e.snapshotPath,"utf8"));e.apply&&(r.beforeExists&&r.beforeContent!==null?(await Dn(X.dirname(r.targetPath),{recursive:!0,mode:448}),await Hn(r.targetPath,r.beforeContent,{encoding:"utf8",mode:384})):pt(r.targetPath)&&await Z_(r.targetPath));let o={snapshotPath:e.snapshotPath,targetPath:r.targetPath,dryRun:!e.apply,applied:e.apply,restoredExists:r.beforeExists,restoredHash:r.beforeHash};return await h({home:t.home,type:e.apply?"mcp_registration_rollback":"mcp_registration_rollback_dry_run",details:o}),o}async function fo(e){let t=X.resolve(e.targetPath??$n(e.host)),r=wu(e.host,e.targetPath),o=pt(t),n=[],a=await rb(e.host,t,r);if(a&&n.push(a),!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 s=null;try{s=mo(await dr(t,"utf8"))}catch(p){n.push({code:"MCP_CONFIG_INVALID_JSON",severity:"error",message:p instanceof Error?p.message:"MCP config is invalid JSON",remediation:"Fix the JSON syntax or roll back from an NativeSoul snapshot"})}let i=s?ti(s):null,l=typeof i?.command=="string"?i.command:null,c=Array.isArray(i?.args)?i.args.filter(p=>typeof p=="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 d=l?e.checkCommand===!1?{ok:!0,issues:[]}:ob(l,c,t):{ok:!1,issues:[]};return n.push(...d.issues),{host:e.host,targetPath:t,target_exists:o,parse_ok:s!==null,configured:i!==null,command:l,command_ok:d.ok,issues:n}}function $n(e){return An(e)}function mo(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 eb(e,t){let r=e.mcpServers,o=r&&typeof r=="object"&&!Array.isArray(r)?{...r}:{};return o.nativesoul={command:t.command,args:t.args,...t.env&&Object.keys(t.env).length>0?{env:t.env}:{}},{...e,mcpServers:o}}function tb(e){if(e===null)return null;let t=mo(e),r=t.mcpServers;if(!r||typeof r!="object"||Array.isArray(r)||!Object.hasOwn(r,"nativesoul"))return e;let o={...r};return delete o.nativesoul,np({...t,mcpServers:o})}function ti(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 rb(e,t,r){if(e!=="claude"||r===null||X.resolve(r)===t||!pt(r))return null;try{let o=mo(await dr(r,"utf8")),n=ti(o);if(!n)return null;if(pt(t)){let a=mo(await dr(t,"utf8")),s=ti(a);if(s&&JSON.stringify(rp(s))===JSON.stringify(rp(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 rp(e){return{command:typeof e.command=="string"?e.command:null,args:Array.isArray(e.args)?e.args.filter(t=>typeof t=="string"):[]}}function ob(e,t,r){let o=[],n=nb(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(ab(e,n)){let a=t[0],s=a?X.isAbsolute(a)?a:X.resolve(X.dirname(r),a):null;if(!s||!pt(s))return o.push({code:"NATIVESOUL_MCP_NODE_SCRIPT_MISSING",severity:"error",message:"nativesoul MCP command uses node but the server script is missing.",remediation:"Re-run nativesoul mcp install with --command-mode absolute or rebuild the local package."}),{ok:!1,issues:o}}return{ok:!0,issues:o}}function nb(e){if(X.isAbsolute(e))return op(e)?e:null;let t=(process.env.PATH??"").split(X.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 a=X.join(o,`${e}${n}`);if(op(a))return a}return null}function op(e){if(process.platform==="win32"&&pt(e))return!0;try{return Y_(e,Q_.X_OK),!0}catch{return!1}}function ab(e,t){let r=X.basename(e).toLowerCase(),o=X.basename(t).toLowerCase();return r==="node"||r==="node.exe"||o==="node"||o==="node.exe"}function np(e){return`${JSON.stringify(e,null,2)}
|
|
885
|
+
`}function sb(e,t){return e===t?"noop":e===null||e.trim().length===0?"create":"update"}async function ap(e,t,r,o,n,a){let s=X.join(e,"backups","mcp-registration");await Dn(s,{recursive:!0,mode:448});let i=new Date().toISOString(),l={id:T("snapshot"),host:t,targetPath:r,beforeExists:o,beforeContent:n,beforeHash:n===null?null:A(n),afterHash:a,createdAt:i},c=X.join(s,`${i.replaceAll(/[:.]/gu,"-")}-${t}.json`);return await Hn(c,JSON.stringify(l,null,2),{encoding:"utf8",mode:384}),c}function sp(e,t){return e===t?"No changes.":[`before: ${e===null?"missing":A(e)}`,`after: ${t===null?"missing":A(t)}`,`lines_before: ${e===null?0:e.split(/\r?\n/u).length}`,`lines_after: ${t===null?0:t.split(/\r?\n/u).length}`].join(`
|
|
886
|
+
`)}async function mt(e){let t=await v(e.home),r=e.surface??null,o=ro(e.host,r),n=e.hostConfigRoot??(e.targetRoot?ze(e.host,e.targetRoot):void 0),a=await db({host:e.host,surface:o,targetRoot:e.targetRoot,explicit:e.pluginEnabled}),s=new Date().toISOString(),i=lb(e.mode,r,e.heartbeat),l=await St(e.host).scheduleReconcile({kind:"heartbeat",mode:e.mode,enabled:!0,surface:e.surface??void 0,apply:e.apply,hostConfigRoot:n,desired:i}),c={id:ub(e.host,e.surface),host:e.host,mode:e.mode,enabled:!0,native_schedule_supported:l.status==="ok",native_id:l.status==="ok"?l.nativeId??null:null,desired:i,updated_at:s},d=e.apply?ib(t.database,c):c,p={dryRun:!e.apply,applied:e.apply,schedule:d,adapter_result:l,warnings:cb(e.host,l.status,a)};return await h({home:t.home,type:e.apply?"schedule_reconciled":"schedule_reconcile_dry_run",details:{host:e.host,surface:e.surface??null,mode:e.mode,schedule_id:c.id,adapter_status:l.status,native_schedule_supported:c.native_schedule_supported}}),p}async function ho(e){let t=e.readOnly?f(e.home):await v(e.home);if(e.readOnly&&!await S(t.database))return[];let r=_(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()}}async function ni(e){let t=await v(e.home),r=_(t.database),o,n;try{if(o=r.listSchedules({limit:200}).find(a=>a.id===e.id),!o)throw new Error(`Schedule not found: ${e.id}`);n=e.apply?r.disableSchedule(e.id,new Date().toISOString()):o}finally{r.close()}if(!n)throw new Error(`Schedule not found after disable: ${e.id}`);return await h({home:t.home,type:e.apply?"schedule_disabled":"schedule_disable_dry_run",details:{schedule_id:e.id,host:n.host,mode:n.mode}}),{dryRun:!e.apply,applied:e.apply,schedule:e.apply?n:{...n,enabled:!1}}}function ib(e,t){let r=_(e);try{return r.upsertSchedule(t)}finally{r.close()}}function lb(e,t,r){return{kind:"heartbeat",mode:e,policy:"read_only",silent_ack:"HEARTBEAT_OK",skill:"life:heartbeat",cadence:r?.cadence??"daily",skip_when_busy:r?.skipWhenBusy??!0,project_scope:r?.projectScope??"current-project",behavior:r?.behavior??"read_only",...t&&t!=="default"?{surface:t}:{}}}function cb(e,t,r){return t!=="unsupported"?[]:Iu(e)?r===!1?["NATIVE_SCHEDULE_UNSUPPORTED_NO_FALLBACK_INSTALLED"]:["NATIVE_SCHEDULE_UNSUPPORTED"]:[]}async function db(e){if(e.explicit!==void 0)return e.explicit;try{let t=De(e.host,e.surface,e.targetRoot);return(await ut({host:e.host,surface:e.surface,targetPath:t})).enabled}catch{return!1}}function ub(e,t){return Tu(e)&&t&&t!=="default"?`schedule:${e}:heartbeat:${t}`:`schedule:${e}:heartbeat`}function ai(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,a=e.schedules.some(y=>mb(y,t)),s=yb(e.capabilities,e.adapterDiagnostics),i=[yo("native_package",r,t,e.plugin.targetPath??e.plugin.package_kind,"Native package/extension is not installed or enabled."),yo("native_hooks",o,t,e.plugin.targetPath??e.plugin.package_kind,"Native lifecycle hook registration is missing."),yo("mcp",n,t,e.mcpRegistration.targetPath,"MCP registration is missing or invalid."),yo("native_scheduler",a,t,fb(e.schedules),_b(e.host,e.schedules)),yo("official_inventory",s,t,hb(e.capabilities),"Official non-degraded capability inventory evidence is missing.")],l=i.filter(y=>!y.satisfied).map(y=>y.requirement),c=r&&o&&n,d=!s,p=l.includes("native_scheduler")&&ip(e.host),g=l.length===0;return{schema_version:1,host:e.host,surface:e.surface,status:bb({fullNative:g,blockedByHost:p,degradedScan:d,ready:c}),ready:c,full_native:g,blocked_by_host:p,degraded_scan:d,generated_at:t,requirements:i,missing_requirements:l}}function si(e){return e.ready&&e.native_kind.includes("native")&&(e.schema_hash?.startsWith("full-native:")===!0||e.source.includes("full-native-evidence:"))}function yo(e,t,r,o,n){return{requirement:e,satisfied:t,evidence:t?[{source_kind:"doctor",reference:o,observed_at:r,confidence:pb(o)}]:[],missing_reason:t?null:n}}function pb(e){return e.startsWith("not-applicable:")||e==="missing"?"low":"medium"}function mb(e,t){return e.enabled&&e.native_schedule_supported&&e.native_id!==null&&!gb(e.updated_at,t)}function gb(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 fb(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 hb(e){return e.find(t=>t.ready)?.source??"missing"}function yb(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 _b(e,t){return ip(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 ip(e){return e==="codex"||e==="claude"||e==="grok"||e==="gemini"||e==="antigravity"}function bb(e){return e.fullNative?"full_native":e.blockedByHost?"blocked_by_host":e.degradedScan?"degraded_scan":e.ready?"ready_fallback":"ready"}async function cp(e){let t=cr(e.host,e.targetRoot,e.surface),r=t.managedBlock??`not-applicable:${Mt(e.host,e.surface)}`,o=t.managedBlock?await xd({host:e.host,targetPath:r}):Ib(e.host,e.surface),n=await fo({host:e.host,targetPath:t.mcpRegistration,checkCommand:e.targetRoot===void 0}),a=await ut({host:e.host,surface:e.surface,targetPath:t.plugin}),s=await xs({home:e.home,host:e.host}),l=(e.databaseExists?await ho({home:e.home,host:e.host,limit:200,readOnly:!0}):[]).filter(x=>Rb(e.host,e.surface,x)),c=e.databaseExists?await Ae({home:e.home,host:e.host,limit:100,readOnly:!0}):[],d=e.databaseExists?Pn(f(e.home).database):[],p=e.targetRoot!==void 0,g=p?[]:(await Lr(e.host))[0]?.diagnostics??[],y=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"}]:[],k=s.stale?[{code:"HANDSHAKE_STALE",severity:"warn",message:`Last ${e.host} handshake is ${s.age_hours??"unknown"} hour(s) old.`,remediation:`Run nativesoul bootstrap --host ${e.host} --cwd <current-working-directory> --format inject`}]:[],R=await Eb({host:e.host,managedBlock:o,handshake:s}),U=await Pb(e.host),Y=l.filter(x=>x.enabled&&x.native_schedule_supported&&x.native_id===null).map(x=>({code:"NATIVE_SCHEDULE_MAPPING_MISSING",severity:"warn",message:`Schedule ${x.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`})),be=l.filter(x=>x.enabled&&!x.native_schedule_supported&&!a.enabled&&a.package_kind!=="unsupported-native").map(x=>({code:"NATIVE_SCHEDULE_UNSUPPORTED_NO_FALLBACK_INSTALLED",severity:"warn",message:`Schedule ${x.id} has no native scheduler support and no NativeSoul package fallback is installed.`,remediation:`Run nativesoul install --host ${e.host} --apply`})),Ie=Ab({managedBlock:o,mcpRegistration:n,plugin:a,schedules:l,capabilities:c}),ne=ai({host:e.host,surface:e.surface,mcpRegistration:n,plugin:a,schedules:l,capabilities:c,adapterDiagnostics:g}),Fe=[...o.issues,...n.issues,...a.issues,...g,...y,...k,...R,...U,...Y,...be];return{host:e.host,surface:e.surface,status:Fe.some(x=>x.severity==="error"||x.severity==="warn")?"degraded":"ready",targets:{managed_block:r,mcp_registration:n.targetPath},native_adapter_diagnostics_skipped:p,adapter_diagnostics:g,managed_block:o,mcp_registration:n,plugin:a,provider_parity:Ie,full_native_evidence:ne,handshake:s,schedule_count:l.length,enabled_schedule_count:l.filter(x=>x.enabled).length,native_schedule_mappings:l.map(x=>({id:x.id,native_schedule_supported:x.native_schedule_supported,native_id:x.native_id})),capability_count:c.length,ready_capability_count:c.filter(x=>x.ready).length,cross_host_inventory_summary:{current_host:c.length,other_hosts:d.filter(x=>x.host!==e.host&&x.host!=="all").length,ready_other_hosts:d.filter(x=>x.host!==e.host&&x.host!=="all"&&x.ready).length},issues:Fe}}function Rb(e,t,r){return e!=="claude"?!0:Sb(r.desired)===t}function Sb(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 Ab(e){let t=e.plugin.enabled,r=e.mcpRegistration.configured,o=e.managedBlock.configured||t,n=e.schedules.some(p=>p.enabled),s=e.schedules.some(p=>p.enabled&&p.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(p=>p.ready);return{level:o&&r&&l==="ready"&&i!=="unsupported-native"&&s!=="unsupported-native"?"ready":e.plugin.package_kind==="native-plugin"?"native":e.plugin.package_kind==="unsupported-native"?"unsupported-native":"official-fallback",bootstrap:o?"ready":"degraded",mcp:r?"ready":"degraded",package:l,hooks:i,memory_recall:r?"ready":"degraded",policy_guard:o?"ready":"degraded",capability_scan:c?"ready":"degraded",heartbeat:s}}async function Eb(e){if(!e.managedBlock.configured||e.managedBlock.targetPath.startsWith("not-applicable:"))return[];let t=10080*60*1e3,r=await jb(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 Pb(e){let t=xb(e).map(r=>lp.resolve(process.cwd(),r));for(let r of t){if(!vb(r))continue;let o=await kb(r,"utf8"),n=Xr(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 xb(e){switch(e){case"claude":return["CLAUDE.md",lp.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 jb(e){try{let t=await wb(e);return Math.max(Date.now()-t.mtimeMs,0)}catch{return null}}function Ib(e,t){return{host:e,targetPath:`not-applicable:${Mt(e,t)}`,target_exists:!1,configured:!0,markers_valid:!0,issues:[]}}async function Ut(e){let t=f(e.home),r=await to(e.home),o=ii(t.database),n=Je(e.host),a=[],s=o?Pn(t.database):[],i=Pu(t.database,o),l=await lt(t.home),c=ii(En(t.home)),d=ii(nr(t.home));for(let y of n)for(let k of Ke(y,e.surface))a.push(await cp({home:t.home,host:y,surface:k,targetRoot:e.targetRoot,databaseExists:o}));let p=[...r.issues,...xu(i),...a.flatMap(y=>y.issues)],g=r.healthy&&!p.some(y=>y.severity==="error");return{home:t.home,healthy:g,status:p.some(y=>y.severity==="error"||y.severity==="warn")?"degraded":"ready",workspace:r,target_root:e.targetRoot?dp.resolve(e.targetRoot):null,cross_host_inventory:ju(s),activation_summary:hu({home:t.home,targetRoot:e.targetRoot?dp.resolve(e.targetRoot):null,host:e.host,profile:l,onboardingComplete:c,activationComplete:d,hosts:a}),full_native_matrix:Tb(a),semantic_index:i,hosts:a,issues:p}}function Tb(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 Cb}from"node:fs";import{mkdir as Ob,readdir as Nb,readFile as Mb,writeFile as Lb}from"node:fs/promises";import _o from"node:path";async function li(e){let t=e.apply===!0,r=t?f((await v(e.home)).home):f(e.home),o=e.project??L(e.cwd??process.cwd(),r.home),n=Math.min(Math.max(e.limit??10,1),50),a=await Db(r.home,r.database,o,n),s=$b(o,a,n),i=Bb({applied:t,project:o,proposals:s,dailyNotes:a.dailyNotes,candidates:a.candidates,activeMemories:a.activeMemories,auditEvents:a.auditEvents}),l=null;return t&&(l=await Fb(r.home,i),await Ub(r.home,s),await h({home:r.home,type:"memory_reflection_run",details:{project:o,proposal_count:s.length,report_path:l,daily_notes:a.dailyNotes.length,candidates:a.candidates.length,active_memories:a.activeMemories.length,audit_events:a.auditEvents.length}})),{applied:t,home:r.home,project:o,report:i,report_path:l,proposals:s,sources:{daily_notes:a.dailyNotes.length,candidates:a.candidates.length,active_memories:a.activeMemories.length,audit_events:a.auditEvents.length},protected_files:["SOUL.md","POLICY.md","standing-orders"].map(c=>({path:_o.join(r.home,c),modified:!1}))}}async function Db(e,t,r,o){let n=await Hb(e,o);if(!Cb(t))return{dailyNotes:n,candidates:[],activeMemories:[],auditEvents:[]};let a=_(t,{readOnly:!0});try{return{dailyNotes:n,candidates:a.listMemories({project:r,status:"candidate",includeForgotten:!1,limit:o}),activeMemories:a.listMemories({project:r,status:"active",includeForgotten:!1,limit:Math.max(o,20)}),auditEvents:a.listEvents({limit:Math.max(o,20)})}}finally{a.close()}}async function Hb(e,t){let r=_o.join(e,"memory","daily");if(!await S(r))return[];let n=(await Nb(r,{withFileTypes:!0})).filter(s=>s.isFile()&&s.name.endsWith(".md")).map(s=>s.name).sort().reverse().slice(0,t),a=[];for(let s of n){let i=_o.join(r,s),l=N(await Mb(i,"utf8")).value.trim();l.length>0&&a.push({id:`daily:${s}`,path:i,text:l})}return a}function $b(e,t,r){let o=[];for(let n of t.candidates){let a=up(n.content,t.activeMemories),s=Wb(n.content,t.activeMemories);if(s){o.push(ur({action:"flag_conflict",project:e,summary:`Review conflict between ${n.id} and ${s.id}`,before:s.summary,after:n.summary,evidence:[n.id,s.id],risk:"high"}));continue}if(a&&a.score>=.7){o.push(ur({action:"deduplicate",project:e,summary:`Reject or merge duplicate candidate ${n.id}`,before:a.memory.summary,after:n.summary,evidence:[n.id,a.memory.id],risk:"medium"}));continue}o.push(ur({action:"promote_candidate",project:e,summary:`Promote candidate ${n.id} after human review`,before:"Candidate memory is not durable yet.",after:n.summary,evidence:[n.id],risk:"low"}))}for(let n of t.dailyNotes){let a=Vb(n.text);for(let s of a){if(o.length>=r)return o;let i=up(s,[...t.activeMemories,...t.candidates]);i&&i.score>=.7?o.push(ur({action:"deduplicate",project:e,summary:`Daily note repeats existing memory ${i.memory.id}`,before:i.memory.summary,after:qe(s),evidence:[n.id,i.memory.id],risk:"medium"})):o.push(ur({action:"create_candidate",project:e,summary:qe(s),before:"No durable memory exists for this daily note.",after:s,evidence:[n.id],risk:"low"}))}}for(let n of t.activeMemories)if(n.expires_at&&Date.parse(n.expires_at)<=Date.now()&&o.push(ur({action:"expire_active",project:e,summary:`Expire active memory ${n.id}`,before:n.summary,after:"Memory should move to expired after human review.",evidence:[n.id],risk:"medium"})),o.length>=r)return o;return o.slice(0,r)}function ur(e){return{id:T("reflection"),persisted_memory_id:null,...e}}async function Fb(e,t){let r=_o.join(e,"proposals");await Ob(r,{recursive:!0,mode:448});let o=_o.join(r,`${new Date().toISOString().replaceAll(/[:.]/gu,"-")}-reflection.md`);return await Lb(o,t,{encoding:"utf8",mode:384,flag:"wx"}),o}async function Ub(e,t){for(let r of t.filter(o=>o.action==="create_candidate")){let o=await ie(e,{project:r.project,content:["Reflection consolidation candidate.","",r.after,"",`Evidence: ${r.evidence.join(", ")}`].join(`
|
|
887
|
+
`),confidence:.5,authority:"reflection_proposal",source:{kind:"reflection",proposal_id:r.id,evidence:r.evidence}});r.persisted_memory_id=o.id}}function Bb(e){let t=["# NativeSoul Reflection Report","",`Mode: ${e.applied?"apply":"dry-run"}`,`Project: ${e.project}`,`Generated at: ${new Date().toISOString()}`,"","## Sources","",`- Daily notes: ${e.dailyNotes.length}`,`- Candidate memories: ${e.candidates.length}`,`- Active memories: ${e.activeMemories.length}`,`- Audit events: ${e.auditEvents.length}`,"","## Before","",...e.candidates.map(r=>`- Candidate ${r.id}: ${r.summary}`),...e.activeMemories.slice(0,10).map(r=>`- Active ${r.id}: ${r.summary}`),"","## Proposed After",""];e.proposals.length===0&&t.push("- No consolidation proposal found.");for(let r of e.proposals)t.push(`- ${r.id} [${r.action}] ${r.summary}`),t.push(` - Before: ${r.before}`),t.push(` - After: ${r.after}`),t.push(` - Evidence: ${r.evidence.join(", ")}`),t.push(` - Risk: ${r.risk}`);return t.push("","## Safety","","- SOUL.md, POLICY.md, and standing-orders are not edited by reflection."),t.join(`
|
|
888
|
+
`)}function Vb(e){return e.split(/\r?\n/u).map(t=>t.replace(/^\s*[-*]\s+/u,"").trim()).filter(t=>t.length>=20).filter(t=>!t.startsWith("#")).filter(t=>!/^(date|notes|observations|tasks):?$/iu.test(t)).slice(0,10)}function up(e,t){let r=null;for(let o of t){let n=gp(e,`${o.summary}
|
|
889
|
+
${o.content}`);(!r||n>r.score)&&(r={memory:o,score:n})}return r}function Wb(e,t){let r=mp(e),o=pp(e);for(let n of t)if(gp(e,`${n.summary}
|
|
890
|
+
${n.content}`)>=.35&&o!==pp(n.content)){let s=mp(n.content);if([...r].some(l=>l.length>4&&s.has(l)))return n}return null}function pp(e){return/\b(nao|não|never|do not|dont|don't|no longer|avoid|evitar|proibir|forbid)\b/iu.test(e)}function gp(e,t){return Jd(e,t,{minLength:3,normalizeDiacritics:!0,removeStopwords:!0})}function mp(e){return Kr(e,{minLength:3,normalizeDiacritics:!0,removeStopwords:!0})}import{lstat as Jb,readdir as qb,readFile as Kb}from"node:fs/promises";import Bt from"node:path";var fp=new Set([".json",".jsonl",".md",".markdown",".txt"]);async function ui(e){let t=e.apply===!0,r=f((await v(e.home)).home),o=Bt.resolve(e.sourcePath),n=e.project??L(e.cwd??process.cwd(),r.home),a=Math.min(Math.max(e.limit??200,1),1e3),s=[],i=await hp(o,s),l=[],c=[];for(let k of i){if(l.length>=a){c.push({source_path:k,reason:"limit_reached"});continue}let R=await Gb(k,s);if(R.length===0){c.push({source_path:k,reason:"no_supported_records"});continue}l.push(...R.slice(0,a-l.length))}let d=Zb(l,n),p=ev(d).map(k=>({source_id:k,reason:"duplicate_source_id"})),g=[];if(t)for(let k of d){let R=await ie(r.home,{project:k.target_project,content:k.content,confidence:k.confidence,authority:"openclaw_import",source:{kind:"import",source_system:k.source_system,source_path:k.source_path,source_id:k.source_id,source_hash:k.source_hash,imported_at:new Date().toISOString(),redacted:k.redacted}});k.proposed_memory_id=R.id,g.push(R)}let y={applied:t,source_path:o,files:i,mapped_records:d,skipped_records:c,conflicts:p,redactions:d.filter(k=>k.redacted).length,proposed_scopes:Array.from(new Set(d.map(k=>k.target_project))).sort(),warnings:s,persisted_memories:g};return await h({home:r.home,type:t?"openclaw_import_applied":"openclaw_import_dry_run",details:rv(y)}),y}async function hp(e,t){let r;try{r=await Jb(e)}catch{return t.push({code:"OPENCLAW_SOURCE_UNREADABLE",source_path:e,message:"Source path is not readable."}),[]}if(r.isFile())return fp.has(Bt.extname(e).toLowerCase())?[e]:[];if(!r.isDirectory())return t.push({code:"OPENCLAW_SOURCE_UNSUPPORTED",source_path:e,message:"Source path is neither a file nor a directory."}),[];let o=await qb(e,{withFileTypes:!0});return(await Promise.all(o.map(a=>{let s=Bt.join(e,a.name);return a.isDirectory()?hp(s,t):Promise.resolve(fp.has(Bt.extname(a.name).toLowerCase())?[s]:[])}))).flat().sort()}async function Gb(e,t){let r;try{r=await Kb(e,"utf8")}catch{return t.push({code:"OPENCLAW_FILE_UNREADABLE",source_path:e,message:"File could not be read."}),[]}let o=Bt.extname(e).toLowerCase();return o===".json"?Xb(e,r,t):o===".jsonl"?zb(e,r,t):Yb(e,r)}function Xb(e,t,r){let o;try{o=JSON.parse(t)}catch{return r.push({code:"OPENCLAW_JSON_MALFORMED",source_path:e,message:"JSON file is malformed."}),[]}return(Array.isArray(o)?o:Qb(o)??[o]).flatMap((a,s)=>yp(a,e,s))}function zb(e,t,r){return t.split(/\r?\n/u).flatMap((o,n)=>{let a=o.trim();if(!a)return[];try{return yp(JSON.parse(a),e,n)}catch{return r.push({code:"OPENCLAW_JSONL_LINE_MALFORMED",source_path:e,message:`Line ${n+1} is malformed.`}),[]}})}function Yb(e,t){return t.split(/\n(?=#{1,3}\s+)/u).map(r=>r.trim()).filter(r=>r.length>0).map((r,o)=>({id:null,content:r,project:null,confidence:null,sourcePath:e,raw:{kind:"text_section",index:o,source_path:e}}))}function Qb(e){if(!pi(e))return null;for(let t of["memories","memory","records","items","notes"]){let r=e[t];if(Array.isArray(r))return r}return null}function yp(e,t,r){if(typeof e=="string"&&e.trim().length>0)return[{id:null,content:e,project:null,confidence:null,sourcePath:t,raw:e}];if(!pi(e))return[];let o=ci(e,["content","text","summary","memory","note","body","value"]);return o?[{id:ci(e,["id","uid","uuid","key"])??`${Bt.basename(t)}:${r+1}`,content:o,project:ci(e,["project","project_id","scope_project","workspace","repo"]),confidence:tv(e,["confidence","score"]),sourcePath:t,raw:di(e)}]:[]}function Zb(e,t){return e.map((r,o)=>{let n=N(r.content),a=r.id??`${Bt.basename(r.sourcePath)}:${o+1}`;return{source_system:"openclaw",source_path:r.sourcePath,source_id:a,source_hash:ov(r.raw),target_project:r.project?.trim()||t,content:n.value,summary:qe(n.value),redacted:n.redacted,confidence:Math.min(Math.max(r.confidence??.55,0),1),status:"candidate",proposed_memory_id:null}})}function ev(e){let t=new Map;for(let r of e)t.set(r.source_id,(t.get(r.source_id)??0)+1);return Array.from(t.entries()).filter(([,r])=>r>1).map(([r])=>r).sort()}function ci(e,t){for(let r of t){let o=e[r];if(typeof o=="string"&&o.trim().length>0)return o.trim()}return null}function tv(e,t){for(let r of t){let o=e[r];if(typeof o=="number"&&Number.isFinite(o))return o}return null}function rv(e){return{source_path:e.source_path,files:e.files.length,mapped_records:e.mapped_records.length,skipped_records:e.skipped_records.length,conflicts:e.conflicts.length,redactions:e.redactions,persisted_memories:e.persisted_memories.length,proposed_scopes:e.proposed_scopes}}function di(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:Array.isArray(e)?e.map(t=>di(t)):pi(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,di(r)])):String(e)}function pi(e){return typeof e=="object"&&e!==null}function ov(e){return ke(e)}import{lstat as nv,readFile as av}from"node:fs/promises";import bo from"node:path";var Vt=[".json",".jsonl",".md",".markdown",".txt"];var sv={nativesoul:{host:"nativesoul",supported_extensions:Vt,documented_inputs:["nativesoul memory export JSON/JSONL","operator-authored Markdown/text memory notes"],unsupported_boundaries:["NativeSoul private SQLite databases","undocumented internal cache files"],limitations:[]},codex:{host:"codex",supported_extensions:Vt,documented_inputs:["operator-provided Codex memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Codex private app stores","Codex cache or thread databases","undocumented internal state"],limitations:["Codex does not expose a NativeSoul-owned private store reader; import requires an explicit user-selected file."]},claude:{host:"claude",supported_extensions:Vt,documented_inputs:["operator-provided Claude memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Claude private settings databases","Claude internal conversation stores","undocumented internal state"],limitations:["Claude import is limited to explicit export or notes files selected by the operator."]},gemini:{host:"gemini",supported_extensions:Vt,documented_inputs:["operator-provided Gemini memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Gemini private app storage","Gemini internal cache files","undocumented internal state"],limitations:["No private Gemini memory database is read; use documented exports or operator-authored files."]},grok:{host:"grok",supported_extensions:Vt,documented_inputs:["operator-provided Grok memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Grok private app storage","Grok internal session stores","undocumented internal state"],limitations:["Grok import is file-only because no native memory store reader is supported."]},antigravity:{host:"antigravity",supported_extensions:Vt,documented_inputs:["operator-provided Antigravity memory export files","operator-authored Markdown/text memory notes"],unsupported_boundaries:["Antigravity private workspace state","Antigravity scheduled-task stores","undocumented internal state"],limitations:["Antigravity import is constrained to explicit files; scheduler state is not memory import input."]}};function iv(e){return ke(e)}async function fi(e){let t=sv[e.host];if(!t)throw new Error(`Unsupported native host importer: ${String(e.host)}`);let r=e.apply===!0,o=f((await v(e.home)).home),n=bo.resolve(e.sourcePath),a=e.project??L(e.cwd??process.cwd(),o.home),s=Math.min(Math.max(e.limit??200,1),1e3),i=[],l=await lv(e.host,n,i),c=[],d=[];for(let R of l){if(c.length>=s){d.push({source_path:R,reason:"limit_reached"});continue}let U=await cv(e.host,R,i);if(U.length===0){d.push({source_path:R,reason:"no_supported_records"});continue}c.push(...U.slice(0,s-c.length))}let p=mv(e.host,c,a),g=await gv(o.home,p),y=[];if(r)for(let R of p){let U=await ie(o.home,{project:R.target_project,content:R.content,confidence:R.confidence,authority:`${R.source_system}_import`,source:{kind:"import",source_system:R.source_system,source_path:R.source_path,source_id:R.source_id,source_hash:R.source_hash,normalized_content_hash:R.normalized_content_hash,imported_at:new Date().toISOString(),redacted:R.redacted}});R.proposed_memory_id=U.id,y.push(U)}let k={applied:r,host:e.host,source_path:n,registry:t,files:l,mapped_records:p,skipped_records:d,conflicts:g,redactions:p.filter(R=>R.redacted).length,proposed_scopes:Array.from(new Set(p.map(R=>R.target_project))).sort(),approvals_required:["Human review is required before imported candidate memories are promoted."],host_limitations:t.limitations,warnings:i,persisted_memories:y};return await h({home:o.home,type:r?"native_host_import_applied":"native_host_import_dry_run",details:fv(k)}),k}async function lv(e,t,r){let o;try{o=await nv(t)}catch{return r.push({code:"NATIVE_IMPORT_SOURCE_UNREADABLE",host:e,source_path:t,message:"Source path is not readable."}),[]}return o.isFile()?_v(t)?[t]:(r.push({code:"NATIVE_IMPORT_FILE_UNSUPPORTED",host:e,source_path:t,message:"File extension is not supported by the native host importer registry."}),[]):o.isDirectory()?(r.push({code:"NATIVE_IMPORT_DIRECTORY_UNSUPPORTED",host:e,source_path:t,message:"Native host importers require an explicit file path and do not scan directories."}),[]):o.isDirectory()?[]:(r.push({code:"NATIVE_IMPORT_SOURCE_UNSUPPORTED",host:e,source_path:t,message:"Source path is neither a file nor a directory."}),[])}async function cv(e,t,r){let o;try{o=await av(t,"utf8")}catch{return r.push({code:"NATIVE_IMPORT_FILE_UNREADABLE",host:e,source_path:t,message:"File could not be read."}),[]}let n=bo.extname(t).toLowerCase();return n===".json"?dv(e,t,o,r):n===".jsonl"?uv(e,t,o,r):pv(t,o)}function dv(e,t,r,o){let n;try{n=JSON.parse(r)}catch{return o.push({code:"NATIVE_IMPORT_JSON_MALFORMED",host:e,source_path:t,message:"JSON file is malformed."}),[]}return(Array.isArray(n)?n:hv(n)??[n]).flatMap((s,i)=>bp(s,t,i))}function uv(e,t,r,o){return r.split(/\r?\n/u).flatMap((n,a)=>{let s=n.trim();if(!s)return[];try{return bp(JSON.parse(s),t,a)}catch{return o.push({code:"NATIVE_IMPORT_JSONL_LINE_MALFORMED",host:e,source_path:t,message:`Line ${a+1} is malformed.`}),[]}})}function pv(e,t){return t.split(/\n(?=#{1,3}\s+)/u).map(r=>r.trim()).filter(r=>r.length>0).map((r,o)=>({id:null,content:r,project:null,confidence:null,sourcePath:e,raw:{kind:"text_section",index:o,source_path:e}}))}function bp(e,t,r){if(typeof e=="string"&&e.trim().length>0)return[{id:null,content:e,project:null,confidence:null,sourcePath:t,raw:e}];if(!hi(e))return[];let o=mi(e,["content","text","summary","memory","note","body","value"]);return o?[{id:mi(e,["id","uid","uuid","key"])??`${bo.basename(t)}:${r+1}`,content:o,project:mi(e,["project","project_id","scope_project","workspace","repo"]),confidence:yv(e,["confidence","score"]),sourcePath:t,raw:gi(e)}]:[]}function mv(e,t,r){return t.map((o,n)=>{let a=N(o.content),s=o.id??`${bo.basename(o.sourcePath)}:${n+1}`,i=vp(a.value);return{source_system:e,source_path:o.sourcePath,source_id:s,source_hash:iv(o.raw),normalized_content_hash:i,target_project:o.project?.trim()||r,content:a.value,summary:qe(a.value),redacted:a.redacted,confidence:Math.min(Math.max(o.confidence??.55,0),1),status:"candidate",proposed_memory_id:null}})}async function gv(e,t){let r=[];r.push(..._p(t,o=>o.source_hash,"duplicate_source_hash")),r.push(..._p(t,o=>o.normalized_content_hash,"duplicate_normalized_content"));for(let o of new Set(t.map(n=>n.target_project))){let n=await It({home:e,project:o,includeForgotten:!1,limit:1e3}),a=new Set(n.map(s=>vp(s.content)));for(let s of t.filter(i=>i.target_project===o))a.has(s.normalized_content_hash)&&r.push({source_id:s.source_id,reason:"existing_normalized_content"})}return r.sort((o,n)=>`${o.reason}:${o.source_id}`.localeCompare(`${n.reason}:${n.source_id}`))}function _p(e,t,r){let o=new Map;for(let n of e){let a=t(n);o.set(a,[...o.get(a)??[],n])}return Array.from(o.values()).filter(n=>n.length>1).flatMap(n=>n.map(a=>({source_id:a.source_id,reason:r})))}function vp(e){return ke(e.toLowerCase().replace(/\s+/gu," ").trim())}function fv(e){return{host:e.host,source_path:e.source_path,files:e.files.length,mapped_records:e.mapped_records.length,skipped_records:e.skipped_records.length,conflicts:e.conflicts.length,redactions:e.redactions,persisted_memories:e.persisted_memories.length,proposed_scopes:e.proposed_scopes,approvals_required:e.approvals_required.length,host_limitations:e.host_limitations}}function hv(e){if(!hi(e))return null;for(let t of["memories","memory","records","items","notes"]){let r=e[t];if(Array.isArray(r))return r}return null}function mi(e,t){for(let r of t){let o=e[r];if(typeof o=="string"&&o.trim().length>0)return o.trim()}return null}function yv(e,t){for(let r of t){let o=e[r];if(typeof o=="number"&&Number.isFinite(o))return o}return null}function gi(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:Array.isArray(e)?e.map(t=>gi(t)):hi(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,gi(r)])):String(e)}function _v(e){return Vt.includes(bo.extname(e).toLowerCase())}function hi(e){return typeof e=="object"&&e!==null}var ue={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 bv,mkdir as vv,readFile as kv,rm as wv,writeFile as Rv}from"node:fs/promises";import{randomUUID as Sv}from"node:crypto";import kp from"node:path";function Fn(e){return kp.join(f(e).home,"license.json")}async function Pe(e){let t=Fn(e);if(!await S(t))return null;try{let r=JSON.parse(await kv(t,"utf8"));return Av(r)?r:null}catch{return null}}async function vo(e,t){let r=Fn(e);return await vv(kp.dirname(r),{recursive:!0,mode:448}),await Rv(r,`${JSON.stringify(t,null,2)}
|
|
891
|
+
`,{encoding:"utf8",mode:384}),await bv(r,384),t}async function yi(e){await wv(Fn(e),{force:!0})}async function Un(e){let t=await Pe(e);if(t?.instance_id)return t.instance_id;let r=Sv();return await vo(e,{...ue,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 Av(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 wp={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 Wt=wp.version;var Pv="https://api.dodopayments.com",xv=1440*60*1e3,jv=14;async function _i(e){let t=f(e.home).home,r=e.now??new Date,o=await Un(t),n=await ki(e,"/licenses/activate",{license_key:e.key,name:o});if(!n.ok)return await He(t,"license_activate_failed",e.key,n.reason,"error"),{ok:!1,reason:n.reason,license:{...ue,instance_id:o}};let a=await vo(t,{state:"licensed",license_key:e.key,instance_id:o,license_key_instance_id:n.license_key_instance_id,purchased_at:n.purchased_at??r.toISOString(),version_at_activation:Wt,updates_until:Lv(n.purchased_at??r.toISOString(),365),last_checked_at:r.toISOString(),source:"dodo"});return await He(t,"license_activated",e.key,null,"ok"),{ok:!0,license:Jt(a)}}async function bi(e){let t=f(e.home).home,r=e.now??new Date,o=await Pe(t),n=e.key??o?.license_key,a=o?.instance_id??null;if(!n)return await He(t,"license_validate_missing",null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:o?Jt(o):ue};if(o?.state==="licensed"&&Iv(o.last_checked_at,r))return await He(t,"license_validate_cache_hit",n,null,"ok"),{ok:!0,license:Jt(o)};let s=await ki(e,"/licenses/validate",{license_key:n});if(s.ok){let i=await vo(t,{state:"licensed",license_key:n,instance_id:a??await Un(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 He(t,"license_validated",n,null,"ok"),{ok:!0,license:Jt(i)}}return s.reason==="NETWORK"&&o?.state==="licensed"&&Tv(o.last_checked_at,r,e.graceDays)?(await He(t,"license_validate_grace_served",n,"NETWORK","ok"),{ok:!0,license:Jt(o)}):(await He(t,"license_validate_failed",n,s.reason,"blocked"),{ok:!1,reason:s.reason,license:{...ue,instance_id:a}})}async function vi(e){let t=f(e.home).home,r=await Pe(t),o=e.key??r?.license_key,n=e.licenseKeyInstanceId??r?.license_key_instance_id;if(!o||!n)return await He(t,"license_deactivate_missing",o??null,"INVALID_KEY","blocked"),{ok:!1,reason:"INVALID_KEY",license:r?Jt(r):ue};let a=await ki(e,"/licenses/deactivate",{license_key:o,license_key_instance_id:n});return a.ok?(await yi(t),await He(t,"license_deactivated",o,null,"ok"),{ok:!0,license:ue}):(await He(t,"license_deactivate_failed",o,a.reason,"error"),{ok:!1,reason:a.reason,license:r?Jt(r):ue})}function Jt(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 Iv(e,t){return e?t.getTime()-new Date(e).getTime()<xv:!1}function Tv(e,t,r=jv){return e?t.getTime()-new Date(e).getTime()<=r*24*60*60*1e3:!1}async function ki(e,t,r){let o=e.fetch??globalThis.fetch;try{let n=await o(new URL(t,Cv(e.endpointBaseUrl)).toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(r)}),a=await Ov(n);return n.ok?t==="/licenses/validate"&&a.valid!==!0?{ok:!1,reason:Rp(a)}:{ok:!0,license_key_instance_id:Nv(a),purchased_at:Mv(a)}:{ok:!1,reason:Rp(a)}}catch{return{ok:!1,reason:"NETWORK"}}}function Cv(e=process.env.NATIVESOUL_DODO_LICENSE_API_BASE_URL??Pv){return e.endsWith("/")?e:`${e}/`}async function Ov(e){try{let t=await e.json();return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Nv(e){let r=[e.license_key_instance_id,e.licenseKeyInstanceId,e.id,ko(e.data)?e.data.license_key_instance_id:null,ko(e.data)?e.data.id:null].find(o=>typeof o=="string"&&o.length>0);return typeof r=="string"?r:null}function Mv(e){let t=ko(e.data)?e.data:{},r=ko(e.license_key)?e.license_key:ko(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(a=>typeof a=="string"&&!Number.isNaN(Date.parse(a)));return typeof n=="string"?new Date(n).toISOString():null}function Lv(e,t){let r=Date.parse(e);return Number.isNaN(r)?null:new Date(r+t*24*60*60*1e3).toISOString()}function Rp(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 ko(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function He(e,t,r,o,n){await h({home:e,type:t,result:n,details:{provider:"dodo",license_key_ref:r?Dv(r):null,reason:o}})}function Dv(e){return e.length<=8?"[REDACTED_LICENSE_KEY]":`${e.slice(0,4)}\u2026${e.slice(-4)}`}var wo="https://docs.nativesoul.dev/account/licensing";async function pr(e){let t=Hv(e),r=f(t.home).home;try{let o=await Pe(r),n=await bi(t);if(n.ok)return{ok:!0,license:n.license};let a=n.reason==="NETWORK"&&o?.state==="licensed"?"GRACE_EXPIRED":"UNLICENSED",s=t.activateUrl??wo;return{ok:!1,reason:a,activate_url:s,message:Ro({reason:a,activate_url:s}),license:n.license}}catch{let o=t.activateUrl??wo;return{ok:!1,reason:"UNLICENSED",activate_url:o,message:Ro({reason:"UNLICENSED",activate_url:o}),license:ue}}}function Ro(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 Hv(e){return typeof e=="string"?{home:e}:e??{}}import{readdir as $v,readFile as Sp,stat as Fv}from"node:fs/promises";import wi from"node:path";var Uv=["open source","open-source","source-available","read the source","free to install","never phones home","zero network","uncrackable","piracy-proof"];async function Ri(e={}){let t=e.registryPath??wi.join(process.cwd(),"docs","architecture","feature-registry.yaml"),r=e.marketingDir??wi.join(process.cwd(),"docs","marketing"),o=Bv(await Sp(t,"utf8")),n=e.page?[e.page]:await Ep(r),a=[],s=[];for(let i of n){let l=await Sp(i,"utf8"),c=So(l);for(let d of Uv)c.includes(So(d))&&a.push({code:"GLOBAL_FORBIDDEN_PHRASE",page:i,phrase:d,message:`Global forbidden phrase found: ${d}`});for(let d of o.values())for(let p of d.claim_forbidden)p&&c.includes(So(p))&&a.push({code:"FEATURE_FORBIDDEN_PHRASE",page:i,feature_id:d.id,phrase:p,message:`Forbidden phrase for ${d.id}: ${p}`});for(let d of Vv(l)){let p=o.get(d.id);if(!p){a.push({code:"UNKNOWN_CLAIM_ID",page:i,feature_id:d.id,message:`Tagged claim references unknown feature id: ${d.id}`}),s.push({id:d.id,status:"unknown",page:i,text:d.text,result:"fail",reason:"unknown feature id"});continue}let g=Wv(p,i,d.text);s.push(g),g.result==="fail"&&a.push(Jv(g))}}return{ok:a.length===0,status:a.length===0?"pass":"fail",registry_path:t,pages:n,claims:s,issues:a,summary:{pages_scanned:n.length,claims_checked:s.length,issues:a.length}}}function Bv(e){let t=new Map,r=null;for(let o of e.split(/\r?\n/u)){let n=o.match(/^\s*-\s+id:\s*(.+)\s*$/u);if(n){r?.id&&t.set(r.id,Ap(r)),r={id:mr(n[1]??""),name:"",claim_forbidden:[],evidence:null,claim_allowed:null};continue}if(!r)continue;let a=o.match(/^\s+([a-z_]+):\s*(.*)\s*$/u);if(!a)continue;let s=a[1]??"",i=a[2]??"";s==="status"?r.status=mr(i).split(/\s+/u)[0]:s==="name"?r.name=mr(i):s==="evidence"?r.evidence=mr(i):s==="claim_allowed"?r.claim_allowed=i.trim()==="null"?null:mr(i):s==="claim_forbidden"&&(r.claim_forbidden=qv(i))}return r?.id&&t.set(r.id,Ap(r)),t}function Ap(e){return{id:e.id??"",name:e.name??e.id??"",status:e.status??"absent",evidence:e.evidence??null,claim_allowed:e.claim_allowed??null,claim_forbidden:e.claim_forbidden??[]}}async function Ep(e){try{if(!(await Fv(e)).isDirectory())return[]}catch{return[]}let t=await $v(e,{withFileTypes:!0});return(await Promise.all(t.map(async o=>{let n=wi.join(e,o.name);return o.isDirectory()?await Ep(n):o.isFile()&&/\.(md|mdx|txt)$/iu.test(o.name)?[n]:[]}))).flat().sort()}function Vv(e){let t=[],r=/<!--\s*claim:([a-z0-9_-]+)\s*-->([\s\S]*?)<!--\s*\/claim\s*-->/giu,o=/\[claim:([a-z0-9_+-]+)\]([\s\S]*?)\[\/claim\]/giu;for(let n of e.matchAll(r))t.push({id:n[1]??"",text:(n[2]??"").trim()});for(let n of e.matchAll(o))t.push({id:n[1]??"",text:(n[2]??"").trim()});return t}function Wv(e,t,r){return e.status==="absent"||e.status==="roadmap"||e.status==="roadmap-teams"?{id:e.id,status:e.status,page:t,text:r,result:"fail",reason:`${e.status} feature cannot be claimed as live`}:e.status==="partial"&&e.claim_allowed&&!So(r).includes(So(e.claim_allowed))?{id:e.id,status:e.status,page:t,text:r,result:"fail",reason:"partial feature claim exceeds allowed wording"}:{id:e.id,status:e.status,page:t,text:r,result:"pass",reason:"claim within registry bounds"}}function Jv(e){return{code:e.status==="partial"?"PARTIAL_CLAIM_OUT_OF_BOUNDS":"UNBUILT_FEATURE_CLAIM",page:e.page,feature_id:e.id,message:e.reason}}function qv(e){let t=e.trim().replace(/\s+#.*$/u,"");if(t==="[]")return[];if(!t.startsWith("[")||!t.endsWith("]"))return[];let r=t.slice(1,-1).trim();return r?r.split(/,\s*/u).map(mr).filter(Boolean):[]}function mr(e){let t=e.trim().replace(/\s+#.*$/u,"");return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function So(e){return e.toLowerCase().replace(/[’']/gu,"'").replace(/\s+/gu," ").trim()}async function Si(e){let t=await Pe(e.home),r=t?.state==="licensed",o=r?Kv(t.updates_until,e.now??new Date):"unknown",n=r?Gv(e.latestKnownVersion,t.version_at_activation??null):"unknown",a=e.upgradeUrl??wo,s=o==="lapsed"&&n===!0,i=s?`You're on v${t?.version_at_activation??e.currentVersion}. v${e.latestKnownVersion} is available. Your licence keeps working \u2014 upgrade for the new major: ${a}.`:null;return{licensed:r,updates_status:o,newer_major_available:n,upgrade_url:a,purchased_at:t?.purchased_at??null,updates_until:t?.updates_until??null,version_at_activation:t?.version_at_activation??null,current_version:e.currentVersion,latest_known_version:e.latestKnownVersion??null,soft_nudge:{visible:s,dismissible:!0,message:i}}}function Kv(e,t){if(!e)return"unknown";let r=Date.parse(e);return Number.isNaN(r)?"unknown":t.getTime()<=r?"active":"lapsed"}function Gv(e,t){if(!e||!t)return"unknown";let r=Pp(e),o=Pp(t);return r===null||o===null?"unknown":r>o}function Pp(e){let t=e.trim().match(/^v?(\d+)(?:\.|$)/u);return t?.[1]?Number.parseInt(t[1],10):null}function gr(e){return si(e)?"full native capability":e.ready?"ready":e.healthy&&e.allowed?"official-fallback":"degraded"}function Ai(e){let t=gr(e);return t==="full native capability"?"cyan":t==="ready"?"green":t==="official-fallback"?"amber":"red"}var jp={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 Ao(e){let t=await v(e.home),r=new Date().toISOString(),o=N(e.title).value,n=e.description===void 0||e.description===null?null:N(e.description).value,a={id:T("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:H(e.tags??[]),metadata:H(e.metadata??{}),created_at:r,updated_at:r,claimed_at:null,completed_at:null},s=Ip({workItem:a,type:"created",fromStatus:null,toStatus:"inbox",actor:e.host??"cli",details:{priority:a.priority,source:a.source},now:r}),i=_(t.database),l;try{l=i.insertWorkItem(a),i.insertWorkItemEvent(s)}finally{i.close()}return await Tp(t.home,"work_item_created",l,{redacted:o!==e.title||e.description!==void 0&&e.description!==null&&n!==e.description,event_id:s.id}),l}async function Eo(e){let t=e.readOnly?f(e.home):await v(e.home);if(e.readOnly&&!await S(t.database))return[];let r=_(t.database,{readOnly:e.readOnly}),o;try{o=r.listWorkItems({project:e.project,status:e.status,priority:e.priority,assignedHost:e.assignedHost,limit:zv(e.limit)})}finally{r.close()}return e.readOnly||await h({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 Po(e){return Ei({home:e.home,id:e.id,actor:e.host,eventType:"claimed",auditType:"work_item_claimed",mutate:(t,r)=>{if(Pi(t.status))throw new Error(`Work item already terminal: ${t.id} (${t.status})`);return Bn(t.status,"in_progress"),{status:"in_progress",assignedHost:e.host,claimedAt:t.claimed_at??r,updatedAt:r,details:{assigned_host:e.host}}}})}async function xo(e){return Ei({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&&Bn(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:H(e.tags),metadata:e.metadata===void 0?void 0:Qv(t.metadata,H(e.metadata)),completedAt:Pi(o)?r:void 0,updatedAt:r,details:{priority:e.priority??null,assigned_host:e.assignedHost??null,fields:Xv(e),redacted:e.description!==void 0&&e.description!==null&&n!==e.description}}}})}async function jo(e){let t=e.status??"done";return Ei({home:e.home,id:e.id,actor:"cli",eventType:"completed",auditType:"work_item_completed",mutate:(r,o)=>{if(Pi(r.status))throw new Error(`Work item already terminal: ${r.id} (${r.status})`);return Bn(r.status,t),{status:t,completedAt:o,updatedAt:o,details:{terminal_status:t}}}})}function Bn(e,t){if(e!==t&&!jp[e].includes(t))throw new Error(`Illegal work item transition: ${e} -> ${t}`)}async function Ei(e){let t=await v(e.home),r=_(t.database),o,n;try{let a=r.getWorkItem(e.id);if(!a)throw new Error(`Work item not found: ${e.id}`);let s=new Date().toISOString(),i=e.mutate(a,s);n=Ip({workItem:a,type:e.eventType,fromStatus:a.status,toStatus:i.status??a.status,actor:e.actor,details:i.details,now:s}),o=r.updateWorkItem({id:a.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 Tp(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 Ip(e){return{id:T("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 Tp(e,t,r,o){await h({home:e,type:t,details:{id:r.id,project:r.project_id,status:r.status,...Yv(o)}})}function Xv(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 Pi(e){return e==="done"||e==="failed"}function zv(e){return!e||!Number.isFinite(e)?50:Math.min(Math.max(Math.trunc(e),1),200)}function Yv(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Qv(e,t){return xp(e)&&xp(t)?{...e,...t}:t}function xp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{readdir as Mk,readFile as Lk}from"node:fs/promises";import qp from"node:path";import{existsSync as Zv}from"node:fs";var ek=50;function Io(e={}){let t=ck(e.limit),r=ak(e),o=e.groupBy??"host",n=new Date().toISOString();if(e.db)return Cp(e.db,e,r,o,t,n);let a=f(e.home);if(!Zv(a.database))return lk(e,r,o,t,n);let s=_(a.database,{readOnly:!0});try{return Cp(s,e,r,o,t,n)}finally{s.close()}}function Cp(e,t,r,o,n,a){let s=e.listRunCostRows({project:t.project,host:t.host,since:r.since??void 0,until:r.until??void 0}),i=Vn(s,g=>({key:g.project_id,label:g.project_id})),l=Vn(s,g=>({key:g.host,label:g.host})),c=Vn(s,g=>{let y=ok(g);return{key:y,label:y==="unattributed"?"unattributed":y}}),d=Vn(s,g=>{let y=g.completed_at?.slice(0,10)??"unknown";return{key:y,label:y}}),p=s.map(g=>Mp(g.id,g.id,[g]));return{schema_version:1,generated_at:a,filters:{project:t.project??null,host:t.host??null,since:r.since,until:r.until,group_by:o,limit:n},totals:Lp(s),groups:rk(o,{byProject:i,byHost:l,bySession:c,byDay:d,byRun:p}).slice(0,n),by_project:i.slice(0,n),by_host:l.slice(0,n),by_session:c.slice(0,n),by_day:d.slice(0,n),by_run:p.slice(0,n)}}function Vn(e,t){let r=new Map;for(let o of e){let n=t(o),a=r.get(n.key)??{label:n.label,rows:[]};a.rows.push(o),r.set(n.key,a)}return Array.from(r.entries()).map(([o,n])=>Mp(o,n.label,n.rows))}function Mp(e,t,r){return{key:e,label:t,...Lp(r)}}function Lp(e){let t=0,r=0,o=0,n=0,a=0;for(let s of e){let i=Pr(s.cost_json);tk(i)&&(t+=1),"tokens_in"in i&&typeof i.tokens_in=="number"&&(o+=i.tokens_in),"tokens_out"in i&&typeof i.tokens_out=="number"&&(n+=i.tokens_out),"cost_usd"in i&&typeof i.cost_usd=="number"&&(r+=1,a+=i.cost_usd)}return{total_runs:e.length,reported_runs:t,cost_reported_runs:r,not_reported_runs:e.length-t,tokens_in:o,tokens_out:n,total_usd:dk(a),coverage:e.length===0?0:t/e.length}}function tk(e){return"source"in e&&e.source==="host-reported"}function rk(e,t){switch(e){case"project":return t.byProject;case"host":return t.byHost;case"day":return t.byDay;case"session":return t.bySession;case"total":return[]}}function ok(e){return nk(e.evidence_json)??e.session_id??"unattributed"}function nk(e){let t;try{t=JSON.parse(e)}catch{return null}return Op(t,"session_id")??Op(t,"session")}function Op(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e[t];return typeof r=="string"&&r.length>0?r:null}function ak(e){return{since:e.since?sk(e.since):null,until:e.until?Dp(e.until,"until"):null}}function sk(e){let t=ik(e);return t!==null?new Date(Date.now()-t).toISOString():Dp(e,"since")}function Dp(e,t){let r=Date.parse(e);if(!Number.isFinite(r))throw new Error(`cost --${t} must be an ISO timestamp or duration`);return new Date(r).toISOString()}function ik(e){let t=e.match(/^(\d+)(s|m|h|d|w)$/u);if(t?.[1]&&t[2])return Np(Number(t[1]),t[2]);let r=e.match(/^(\d+)\s+(second|seconds|minute|minutes|hour|hours|day|days|week|weeks)$/u);return r?.[1]&&r[2]?Np(Number(r[1]),r[2]):null}function Np(e,t){return e*({s:1e3,second:1e3,seconds:1e3,m:6e4,minute:6e4,minutes:6e4,h:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,week:6048e5,weeks:6048e5}[t]??0)}function lk(e,t,r,o,n){let a={total_runs:0,reported_runs:0,cost_reported_runs:0,not_reported_runs:0,tokens_in:0,tokens_out:0,total_usd:0,coverage:0};return{schema_version:1,generated_at:n,filters:{project:e.project??null,host:e.host??null,since:t.since,until:t.until,group_by:r,limit:o},totals:a,groups:[],by_project:[],by_host:[],by_session:[],by_day:[],by_run:[]}}function ck(e){return e===void 0||!Number.isFinite(e)?ek:Math.max(1,Math.min(Math.trunc(e),500))}function dk(e){return Math.round(e*1e8)/1e8}import{mkdir as gk,readdir as fk,readFile as hk,writeFile as yk}from"node:fs/promises";import qt from"node:path";function Hp(e){let t=xi(e)?e:{},r=xi(t.tool_input)?t.tool_input:xi(t.input)?t.input:{},o=z(t.tool_name)??z(t.tool)??z(t.name)??"unknown_tool",n=z(t.action)??z(r.action)??o,a=z(t.target)??z(r.target)??z(r.file_path)??z(r.path)??z(r.url)??z(r.command),s=z(r.command)??z(t.command);return{action:n,className:uk(o,[a,s].filter(Boolean).join(" ")),target:a,project:z(t.project)??z(t.project_id)??z(r.project)??z(r.project_id)}}function uk(e,t){let r=`${e} ${t??""}`.toLowerCase();return/\b(bash|shell|sh|zsh|exec_command)\b/u.test(e.toLowerCase())?pk(t??""):/\b(rm\s+-[^\s]*[rf][^\s]*|delete|reset\s+--hard|destroy|purge|drop)\b/u.test(r)?"destructive":/(slack|gmail|outlook|github|gh\s+pr|gh\s+issue|git\s+push|vercel\s+deploy|deploy|publish|send|post|comment|merge|api|curl\s+.*(-x|--request|-d|--data|--data-raw|--form)\s*(post|put|patch|delete)?)/u.test(r)?"external_write":/(write|edit|patch|apply|create|move|rename|git\s+commit)/u.test(r)?"write_project":/(curl|fetch|browser|http|web)/u.test(r)?"probe_external":"read_local"}function pk(e){let t=e.toLowerCase();return/\b(rm\s+-[^\s]*[rf][^\s]*|delete|reset\s+--hard|destroy|purge|drop)\b/u.test(t)?"destructive":/(curl\s+.*(-x|--request|-d|--data|--data-raw|--form)\s*(post|put|patch|delete)?|gh\s+(pr|issue|release)|git\s+push|vercel\s+deploy|npm\s+publish|pnpm\s+publish|deploy|publish)/u.test(t)?"external_write":/(^|\s)(touch|mkdir|mv|cp|tee|chmod|chown|git\s+commit)\b|(^|[^>])>[^>]|>>/u.test(t)?"write_project":/^(pwd|ls|cat|head|tail|rg|grep|sed\s+-n|find\s+.*-print|git\s+(status|diff|log|show))(\s|$)/u.test(t.trim())?"read_local":/(curl|fetch|http|https?:\/\/)/u.test(t)?"probe_external":"write_project"}function xi(e){return!!e&&!Array.isArray(e)&&typeof e=="object"}function z(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}var _k=new Set(["SOUL.MD","POLICY.MD"]),bk=5e3,$p=new Map;async function ft(e){let t=f(e),r=$p.get(t.home);if(r&&r.expiresAt>Date.now())return r.orders;let o=qt.join(t.home,"standing-orders"),n;try{n=await fk(o)}catch{return[]}let a=[];for(let s of n.filter(i=>i.endsWith(".yaml")||i.endsWith(".yml")).sort()){let i=qt.join(o,s),l=await hk(i,"utf8");a.push(vk(l,i))}return $p.set(t.home,{expiresAt:Date.now()+bk,orders:a}),a}async function ht(e){let t=await ft(e.home),r=e.target??null,o=r?Fp(r):null,n=t.filter(i=>Ti(i,e)),a=n.find(i=>i.allowed.includes(e.action)),s=n.find(i=>i.approval_required.includes(e.action));if(o&&_k.has(o))return gt(e,"proposal_required",["PROTECTED_HUMAN_FILE"],null);if(e.className==="identity_policy_change")return gt(e,"proposal_required",["IDENTITY_POLICY_CHANGE"],null);if(e.className==="destructive")return gt(e,"denied",["DESTRUCTIVE_DENIED_BY_DEFAULT"],a?.id??s?.id??null);if(s)return gt(e,"approval_required",["STANDING_ORDER_REQUIRES_APPROVAL"],s.id);if(a)return gt(e,"allowed",["STANDING_ORDER_ALLOWED"],a.id);switch(e.className){case"read_local":case"probe_external":case"write_local":return gt(e,"allowed",["DEFAULT_ALLOWED"],null);case"write_project":return gt(e,"approval_required",["PROJECT_WRITE_REQUIRES_APPROVAL"],null);case"external_write":return gt(e,"approval_required",["EXTERNAL_WRITE_REQUIRES_APPROVAL"],null)}}async function ji(e){let t=Hp(e.payload),r=await ht({home:e.home,action:t.action,className:t.className,target:t.target,project:t.project,host:e.host}),o=r.decision==="allowed",n={hook_event_name:"PreToolUse",host:e.host,allowed:o,blocked:!o,message:o?"NativeSoul policy allowed this tool use.":`NativeSoul policy blocked ${r.action}: ${r.decision} (${r.reasons.join(", ")}).`,evaluation:r};if(!o){let a=await v(e.home);await h({home:a.home,type:"policy_blocked",result:"blocked",details:{host:e.host,cwd:e.cwd??null,action:r.action,class:r.class,target:r.target,decision:r.decision,reasons:r.reasons,matched_standing_order:r.matched_standing_order}})}return n}async function Ii(e){let t=await v(e.home),r=kk(e.target);if(!r)throw new Error("policy propose-change target must be SOUL.md or POLICY.md");let o=N(e.summary).value,n=new Date().toISOString(),a=T("proposal"),s=qt.join(t.home,"proposals",`${n.replaceAll(/[:.]/gu,"-")}-${r}.md`),i=["# Policy Change Proposal","",`ID: ${a}`,`Target: ${r}`,`Created At: ${n}`,"","## Summary","",o,""].join(`
|
|
892
|
+
`);return await gk(qt.dirname(s),{recursive:!0,mode:448}),Se(s,{root:t.home}),await yk(s,i,{encoding:"utf8",mode:384,flag:"wx"}),await h({home:t.home,type:"policy_change_proposed",details:{id:a,target:r,proposalPath:s,redacted:o!==e.summary}}),{id:a,target:r,summary:o,proposalPath:s,created_at:n}}function gt(e,t,r,o){return{action:e.action,class:e.className,target:e.target??null,decision:t,reasons:r,matched_standing_order:o}}function vk(e,t){return{id:wk(e,"id")??qt.basename(t,qt.extname(t)),allowed:fr(e,"allowed"),approval_required:fr(e,"approval_required"),scope_projects:fr(e,"projects").concat(fr(e,"scope_projects")),scope_hosts:fr(e,"hosts").concat(fr(e,"scope_hosts")),source:t}}function Ti(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 Fp(e){return qt.basename(e.replaceAll("\\","/")).toUpperCase()}function kk(e){let t=Fp(e);return t==="SOUL.MD"?"SOUL.md":t==="POLICY.MD"?"POLICY.md":null}function wk(e,t){let r=new RegExp(`^\\s*${t}:\\s*([^\\n#]+)`,"mu");return e.match(r)?.[1]?.trim().replace(/^["']|["']$/gu,"")??null}function fr(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=[],a=!1,s=0;for(let i of o){let l=i.trim();if(!a){let d=i.match(new RegExp(`^(\\s*)${t}:\\s*$`,"u"));d&&(a=!0,s=d[1]?.length??0);continue}let c=i.length-i.trimStart().length;if(l&&c<=s&&!l.startsWith("-"))break;l.startsWith("-")&&n.push(l.slice(1).trim().replace(/^["']|["']$/gu,""))}return n.filter(Boolean)}function le(e,t,r){if(e==null)return!1;if(Array.isArray(e))return e.some(o=>le(o,t,r));if(typeof e!="object")return!1;for(let[o,n]of Object.entries(e)){if(o===t){if(r===void 0)return!0;if(n===null)return r==="null";if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return String(n)===r;if(Array.isArray(n))return n.some(a=>String(a)===r)}if(le(n,t,r))return!0}return!1}var Rk=/(?:sk-[A-Za-z0-9_-]{8,}|(?:api[_-]?key|token|secret|password)\s*[:=]\s*(?!\[REDACTED_SECRET\])[^"'\s]+)/iu;async function hr(e={}){let t=f(e.home),r=Nk(e.limit);if(!await S(t.database))return Sk(e,r,!1);let n=_(t.database,{readOnly:!0});try{let a=n.listEvents({limit:r}),s=n.listCapabilities({host:e.host,includeShared:!0,limit:r}),i=n.listSchedules({host:e.host,limit:r}),l=n.listHeartbeatLeases({project:e.project,limit:r}),c=n.listHeartbeatRuns({project:e.project,host:e.host,limit:r}),d=a.filter(y=>Ok(y,e)),p=s.filter(y=>Up(y.host,e.host)),g=i.filter(y=>Up(y.host,e.host));return Jp({schema_version:1,generated_at:new Date().toISOString(),read_only:!0,external_telemetry_enabled:!1,initialized:!0,filters:Wp(e,r),retention:Vp(r),metrics:{activation:Ak(d),bootstrap:Ek(d),recall:Pk(d),capability_readiness:xk(p),heartbeat:jk(l,c),no_op_suppression:Ik(d),rollback:Tk(d),secret_leakage_checks:Bp(d)},m7_gate:Ck(d,p,g,c)})}finally{n.close()}}function Sk(e,t,r){return Jp({schema_version:1,generated_at:new Date().toISOString(),read_only:!0,external_telemetry_enabled:!1,initialized:r,filters:Wp(e,t),retention:Vp(t),metrics:{activation:{workspace_initialized:0,onboarding_completed:0,install_applied:0},bootstrap:{succeeded:0,degraded:0,failed:0,cache_fallbacks:0},recall:{recalled:0,proposed:0,promoted:0},capability_readiness:{total:0,ready:0,full_native:0,official_fallback:0,degraded:0},heartbeat:{leases:0,completed_runs:0,silent_ok:0},no_op_suppression:{total:0,heartbeat_skipped:0,deduped:0,noop_actions:0},rollback:{total:0,policy_pack:0,mcp:0,managed_block:0},secret_leakage_checks:{checked:!0,leak_indicators:0,redaction_markers:0}},m7_gate:{recurring_use_validated:!1,feedback_validated:!1,privacy_validated:!0,notes:["NativeSoul database is not initialized; no local feedback evidence is available yet."]}})}function Ak(e){return{workspace_initialized:pe(e,["workspace_initialized"]),onboarding_completed:pe(e,["onboarding_completed"]),install_applied:pe(e,["plugin_install","managed_block_applied","mcp_registration_installed"])}}function Ek(e){return{succeeded:pe(e,["handshake_succeeded"]),degraded:pe(e,["handshake_degraded"]),failed:pe(e,["handshake_failed"]),cache_fallbacks:e.filter(t=>t.type.includes("bootstrap_context_cache")).length}}function Pk(e){return{recalled:pe(e,["memory_recalled"]),proposed:pe(e,["memory_proposed"]),promoted:pe(e,["memory_promoted"])}}function xk(e){let t=e.map(gr);return{total:e.length,ready:t.filter(r=>r==="ready"||r==="full native capability").length,full_native:t.filter(r=>r==="full native capability").length,official_fallback:t.filter(r=>r==="official-fallback").length,degraded:t.filter(r=>r==="degraded").length}}function jk(e,t){return{leases:e.length,completed_runs:t.length,silent_ok:t.filter(r=>r.result==="HEARTBEAT_OK"||le(r.result,"silent_ack","HEARTBEAT_OK")).length}}function Ik(e){let t=pe(e,["heartbeat_skipped"]),r=e.filter(n=>n.type.includes("deduped")).length,o=e.filter(n=>le(n.details,"action","noop")).length;return{total:t+r+o,heartbeat_skipped:t,deduped:r,noop_actions:o}}function Tk(e){let t=pe(e,["policy_pack_rollback"]),r=pe(e,["mcp_registration_rollback"]),o=pe(e,["managed_block_rollback"]);return{total:e.filter(n=>n.type.includes("rollback")).length,policy_pack:t,mcp:r,managed_block:o}}function Bp(e){let t=JSON.stringify(e.map(r=>({type:r.type,result:r.result,details:r.details})));return{checked:!0,leak_indicators:Rk.test(t)?1:0,redaction_markers:(t.match(/\[REDACTED_/gu)??[]).length}}function Ck(e,t,r,o){let n=o.length>0||r.some(l=>l.enabled),a=e.length>0&&t.length>0,s=Bp(e).leak_indicators===0;return{recurring_use_validated:n,feedback_validated:a,privacy_validated:s,notes:[n?"Recurring heartbeat/schedule evidence exists locally.":"No recurring heartbeat/schedule evidence yet.",a?"Feedback report has local audit and capability evidence.":"Feedback report needs audit and capability evidence.",s?"Report excludes raw prompts, memory bodies, and unredacted secret indicators.":"Potential secret indicators found in local audit details."]}}function pe(e,t){return e.filter(r=>t.includes(r.type)).length}function Ok(e,t){let r=!t.host||!le(e.details,"host")||le(e.details,"host",t.host),o=!t.project||!le(e.details,"project")||le(e.details,"project",t.project);return r&&o}function Up(e,t){return!t||e===t||e==="all"}function Vp(e){return{source_event_limit:e,stores_raw_prompts:!1,stores_memory_content:!1,stores_raw_paths:!1}}function Wp(e,t){return{project:e.project??null,host:e.host??null,limit:t}}function Nk(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e??200),1),500):200}function Jp(e){return Zt(H(e))}var Dk=["candidate","active","superseded","rejected","forgotten","expired"],Ci=["inbox","assigned","in_progress","review","blocked","done","failed"];async function To(e={}){let t=f(e.home),r=rw(e.limit),o=Zk(e);if(!await S(t.database))return Gp(await Hk(t.home,t.database,e,r));let a=_(t.database,{readOnly:!0});try{let s=a.listMemories({project:e.project,includeForgotten:!0,limit:Math.max(r*4,50)}),i=a.listCapabilities({host:e.host,includeShared:!0,limit:r}),l=a.listCommitments({project:e.project,includeExpired:!0,limit:Math.max(r*2,50),now:new Date().toISOString(),skipExpire:!0}),c=a.listSchedules({host:e.host,limit:r}),d=a.listHeartbeatLeases({project:e.project,limit:r}),p=a.listHeartbeatRuns({project:e.project,host:e.host,limit:r}),g=a.listEvents({limit:Math.max(r*4,50)}),y=Yk(await ft(t.home),e),k=await Gk(t.home),R=Ye(s,o,D=>D.created_at),U=Ye(l,o,D=>D.updated_at).slice(0,r),Y=Ye(i,o,D=>D.last_seen_at).slice(0,r),be=Ye(c,o,D=>D.updated_at).slice(0,r),Ie=Ye(d,o,D=>D.created_at).slice(0,r),ne=Ye(p,o,D=>D.completed_at).slice(0,r),Fe=Ye(g,o,D=>D.created_at).filter(D=>!e.host||ew(D,{key:"host",value:e.host})).slice(0,r),x=Fe.filter(D=>D.type==="policy_blocked"),Ar=Fe.filter(D=>tw(D)).length,Jo=$k(a,e,o,r),Er=Uk(a,e,o,r,k,Ar),V=Wk(a,e,r),$m={schema_version:2,generated_at:new Date().toISOString(),filters:Yp(e,r),read_only:!0,home:t.home,database:t.database,initialized:!0,memories:{summary:Qk(R),recent:R.filter(D=>D.status!=="candidate").slice(0,r),candidates:R.filter(D=>D.status==="candidate").slice(0,r)},commitments:U,capabilities:Y,schedules:be,heartbeat:{leases:Ie,runs:ne},audit:{events:Fe,policy_blocks:x},policy:{standing_orders:y,proposals:k,counts:{standing_orders:y.length,proposals:k.length,policy_blocks:x.length,approvals_required:Ar}},work:Jo,approvals:Er,cost:V,feedback:await hr({home:t.home,project:e.project,host:e.host,limit:r})};return Gp($m)}finally{a.close()}}async function Hk(e,t,r,o){return{schema_version:2,generated_at:new Date().toISOString(),filters:Yp(r,o),read_only:!0,home:e,database:t,initialized:!1,memories:{summary:zp(),recent:[],candidates:[]},commitments:[],capabilities:[],schedules:[],heartbeat:{leases:[],runs:[]},audit:{events:[],policy_blocks:[]},policy:{standing_orders:[],proposals:[],counts:{standing_orders:0,proposals:0,policy_blocks:0,approvals_required:0}},work:Xp(),approvals:qk(),cost:Kk(),feedback:await hr({home:e,project:r.project,host:r.host,limit:o})}}function $k(e,t,r,o){let n=Ye(e.listWorkItems({project:t.project,assignedHost:t.host,limit:Math.max(o*Ci.length,50)}),r,s=>s.updated_at).slice(0,Math.max(o*Ci.length,50));if(n.length===0)return Xp();let a=[];for(let s of Ci){let i=n.filter(l=>l.status===s).slice(0,o).map(l=>Fk(e,l));i.length>0&&a.push({status:s,count:i.length,items:i})}return{columns:a}}function Fk(e,t){let r=e.listHeartbeatRunsByWorkItem({workItemId:t.id,project:t.project_id,limit:1})[0];return{id:t.id,title:t.title,summary:t.description??t.title,status:t.status,project:t.project_id,host:t.assigned_host,linked_run_id:Jk(t.metadata,"run_id")??r?.id??null,priority:t.priority,updated_at:t.updated_at}}function Uk(e,t,r,o,n,a){let s=e.listApprovals("pending").approvals.filter(l=>Vk(l,t)).filter(l=>Ye([l],r,c=>c.created_at).length>0).slice(0,o).map(Bk);if(s.length>0)return{pending:s,counts:{pending:s.length}};let i=n.slice(0,o).map(l=>({id:l.filename,action:l.summary??"Policy proposal pending review",class:"identity_policy_change",target:l.target,project:t.project??null,host:t.host??null,source:"policy_proposal",created_at:null}));return i.length===0&&a>0&&i.push({id:"policy-approval-required",action:"Policy event requires approval",class:"approval_required",target:null,project:t.project??null,host:t.host??null,source:"policy_event",created_at:null}),{pending:i,counts:{pending:i.length}}}function Bk(e){return{id:e.id,action:e.action,class:e.class,target:e.target,project:e.project,host:e.host,source:"approvals",created_at:e.created_at}}function Vk(e,t){return(!t.project||e.project===t.project)&&(!t.host||e.host===t.host)}function Wk(e,t,r){let o=Io({db:e,project:t.project,host:t.host,since:t.since,until:t.until,groupBy:"host",limit:r});return{totals:{runs:o.totals.total_runs,reported_runs:o.totals.reported_runs,cost_reported_runs:o.totals.cost_reported_runs,not_reported_runs:o.totals.not_reported_runs,tokens_in:o.totals.tokens_in,tokens_out:o.totals.tokens_out,total_usd:o.totals.total_usd,coverage:o.totals.coverage},by_project:o.by_project.map(Wn),by_host:o.by_host.map(Wn),by_session:o.by_session.map(Wn),by_run:o.by_run.map(Wn)}}function Wn(e){return{key:e.key,label:e.label,runs:e.total_runs,reported_runs:e.reported_runs,cost_reported_runs:e.cost_reported_runs,not_reported_runs:e.not_reported_runs,tokens_in:e.tokens_in,tokens_out:e.tokens_out,total_usd:e.total_usd,coverage:e.coverage}}function Jk(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e[t];return typeof r=="string"&&r.length>0?r:null}function Xp(){return{columns:[]}}function qk(){return{pending:[],counts:{pending:0}}}function Kk(){return{totals:{runs:0,reported_runs:0,cost_reported_runs:0,not_reported_runs:0,tokens_in:0,tokens_out:0,total_usd:0,coverage:0},by_project:[],by_host:[],by_session:[],by_run:[]}}async function Gk(e){let t=qp.join(e,"proposals"),r;try{r=await Mk(t)}catch{return[]}let o=[];for(let n of r.filter(a=>a.endsWith(".md")).sort()){let a=await Lk(qp.join(t,n),"utf8");o.push({filename:n,target:Xk(a,"Target"),summary:zk(a,"Summary")})}return o}function Xk(e,t){return e.match(new RegExp(`^${t}:\\s*(.+)$`,"mu"))?.[1]?.trim()??null}function zk(e,t){return e.match(new RegExp(`^## ${t}\\s*$\\n+([\\s\\S]*?)(?:\\n+## |$)`,"mu"))?.[1]?.trim()??null}function Yk(e,t){return e.filter(r=>{let o=!t.project||r.scope_projects.length===0||r.scope_projects.includes(t.project),n=!t.host||r.scope_hosts.length===0||r.scope_hosts.includes(t.host);return o&&n})}function Qk(e){let t=zp();for(let r of e)t[r.status]+=1;return t}function zp(){return Object.fromEntries(Dk.map(e=>[e,0]))}function Ye(e,t,r){return e.filter(o=>{let n=Date.parse(r(o));return!(!Number.isFinite(n)||t.since!==null&&n<t.since||t.until!==null&&n>t.until)})}function Zk(e){return{since:Kp(e.since,"since"),until:Kp(e.until,"until")}}function Kp(e,t){if(!e)return null;let r=Date.parse(e);if(!Number.isFinite(r))throw new Error(`dashboard data --${t} must be an ISO date/time`);return r}function ew(e,t){return le(e.details,t.key,t.value)}function tw(e){return le(e.details,"decision","approval_required")||le(e.details,"approval_required")||le(e.details,"action","approval_required")}function Yp(e,t){return{project:e.project??null,host:e.host??null,limit:t,since:e.since??null,until:e.until??null}}function rw(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e??50),1),200):50}function Gp(e){return Zt(H(e))}import{mkdir as ow,writeFile as nw}from"node:fs/promises";import Oi from"node:path";async function Mi(e={}){let t=await To(e),r=Oi.resolve(e.output??Oi.join(f(e.home).home,"generated","dashboard","index.html"));return await ow(Oi.dirname(r),{recursive:!0,mode:448}),await nw(r,Qp(t),{encoding:"utf8",mode:384}),{outputPath:r,generated_at:t.generated_at,read_only:!0,data:t}}function Qp(e){let t=gw(e.capabilities),r=e.audit.policy_blocks.length,o=e.policy.counts.approvals_required,n=aw(e),a=n?n.work.columns.reduce((s,i)=>s+i.items.length,0):0;return`<!doctype html>
|
|
893
893
|
<html lang="en">
|
|
894
894
|
<head>
|
|
895
895
|
<meta charset="utf-8">
|
|
896
896
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
897
897
|
<title>NativeSoul Local Dashboard</title>
|
|
898
|
-
<style>${
|
|
898
|
+
<style>${yw()}</style>
|
|
899
899
|
</head>
|
|
900
900
|
<body>
|
|
901
901
|
<main class="shell">
|
|
@@ -921,26 +921,26 @@ ${n.content}`)>=.35&&o!==lp(n.content)){let s=cp(n.content);if([...r].some(l=>l.
|
|
|
921
921
|
</section>
|
|
922
922
|
|
|
923
923
|
<section class="layout">
|
|
924
|
-
${n?
|
|
925
|
-
${n?
|
|
926
|
-
${n?
|
|
924
|
+
${n?sw(n):""}
|
|
925
|
+
${n?iw(n):""}
|
|
926
|
+
${n?lw(n):""}
|
|
927
927
|
|
|
928
|
-
${xe("Memory Lifecycle",[
|
|
928
|
+
${xe("Memory Lifecycle",[pw(e.memories.summary),$e(e.memories.recent,s=>`
|
|
929
929
|
<li>
|
|
930
930
|
<div><strong>${w(s.summary)}</strong><small>${w(s.scope.project)} · ${w(s.status)}</small></div>
|
|
931
|
-
<span class="chip ${
|
|
931
|
+
<span class="chip ${fw(s.status)}">${w(s.authority)}</span>
|
|
932
932
|
</li>`),Kt(e.memories.recent,"No active/recent memories in this scope.")].join(""))}
|
|
933
933
|
|
|
934
|
-
${xe("Capability Readiness",[
|
|
934
|
+
${xe("Capability Readiness",[mw(),$e(e.capabilities,s=>`
|
|
935
935
|
<li>
|
|
936
936
|
<div><strong>${w(s.uid)}</strong><small>${w(s.host)} · ${w(s.normalized_kind)} · ${w(s.source)}</small></div>
|
|
937
|
-
<span class="chip ${
|
|
937
|
+
<span class="chip ${Ai(s)}">${gr(s)}</span>
|
|
938
938
|
</li>`),Kt(e.capabilities,"No capability records match these filters.")].join(""))}
|
|
939
939
|
|
|
940
940
|
${xe("Commitments",[$e(e.commitments,s=>`
|
|
941
941
|
<li>
|
|
942
942
|
<div><strong>${w(s.summary)}</strong><small>${w(s.project_id)} · ${w(s.status)}${s.due_at?` · due ${w(s.due_at)}`:""}</small></div>
|
|
943
|
-
<span class="chip ${
|
|
943
|
+
<span class="chip ${hw(s.status)}">${w(s.status)}</span>
|
|
944
944
|
</li>`),Kt(e.commitments,"No commitments match these filters.")].join(""))}
|
|
945
945
|
|
|
946
946
|
${xe("Heartbeat And Runs",[Jn([["Leases",e.heartbeat.leases.length],["Runs",e.heartbeat.runs.length],["Schedules",e.schedules.length]]),$e(e.heartbeat.runs,s=>`
|
|
@@ -984,37 +984,37 @@ ${n.content}`)>=.35&&o!==lp(n.content)){let s=cp(n.content);if([...r].some(l=>l.
|
|
|
984
984
|
<span>${w(e)}</span>
|
|
985
985
|
<strong>${t}</strong>
|
|
986
986
|
<small>${w(o)}</small>
|
|
987
|
-
</article>`}function
|
|
987
|
+
</article>`}function aw(e){return e.schema_version>=2&&"work"in e&&"approvals"in e&&"cost"in e?e:null}function sw(e){if(e.work.columns.length===0)return"";let t=`<div class="board-grid">${e.work.columns.map(r=>`
|
|
988
988
|
<section class="board-column">
|
|
989
989
|
<div class="board-column-head">
|
|
990
|
-
<strong>${w(
|
|
990
|
+
<strong>${w(dw(r.status))}</strong>
|
|
991
991
|
<span class="chip neutral">${r.count}</span>
|
|
992
992
|
</div>
|
|
993
993
|
${$e(r.items,o=>`
|
|
994
994
|
<li>
|
|
995
995
|
<div><strong>${w(o.title)}</strong><small>${w(o.project)}${o.host?` · ${w(o.host)}`:""}${o.linked_run_id?` · run ${w(o.linked_run_id)}`:""}</small></div>
|
|
996
|
-
<span class="chip ${
|
|
996
|
+
<span class="chip ${uw(o.status)}">${w(o.priority)}</span>
|
|
997
997
|
</li>`)}
|
|
998
|
-
</section>`).join("")}</div>`;return xe("Work Board",t)}function
|
|
998
|
+
</section>`).join("")}</div>`;return xe("Work Board",t)}function iw(e){return e.approvals.pending.length===0?"":xe("Pending Approvals",[$e(e.approvals.pending,t=>`
|
|
999
999
|
<li>
|
|
1000
1000
|
<div><strong>${w(t.action)}</strong><small>${w(t.class)}${t.project?` · ${w(t.project)}`:""}${t.host?` · ${w(t.host)}`:""}${t.target?` · ${w(t.target)}`:""}</small></div>
|
|
1001
1001
|
<span class="chip amber">${w(t.source)}</span>
|
|
1002
|
-
</li>`),'<p class="helper">approve via: nativesoul approvals approve <id> --confirm</p>'].join(""))}function
|
|
1002
|
+
</li>`),'<p class="helper">approve via: nativesoul approvals approve <id> --confirm</p>'].join(""))}function lw(e){if(e.cost.totals.cost_reported_runs===0)return"";let t=[Jn([["Reported",e.cost.totals.reported_runs],["Not reported",e.cost.totals.not_reported_runs],["Coverage %",Math.round(e.cost.totals.coverage*100)]]),`<div class="cost-total"><span>Total reported</span><strong>${w(Zp(e.cost.totals.total_usd))}</strong></div>`,Ni("By Host",e.cost.by_host),Ni("By Session",e.cost.by_session),Ni("By Run",e.cost.by_run)].filter(Boolean);return xe("Cost",t.join(""))}function Ni(e,t){let r=t.filter(o=>o.reported_runs>0||o.not_reported_runs>0);return r.length===0?"":`<div class="cost-group">
|
|
1003
1003
|
<h2>${w(e)}</h2>
|
|
1004
1004
|
${$e(r,o=>`
|
|
1005
1005
|
<li>
|
|
1006
|
-
<div><strong>${w(o.label)}</strong><small>${w(
|
|
1007
|
-
<span class="chip ${o.cost_reported_runs>0?"green":"neutral"}">${w(o.cost_reported_runs>0?
|
|
1006
|
+
<div><strong>${w(o.label)}</strong><small>${w(cw(o))}${o.not_reported_runs>0?" · not reported by host":""}</small></div>
|
|
1007
|
+
<span class="chip ${o.cost_reported_runs>0?"green":"neutral"}">${w(o.cost_reported_runs>0?Zp(o.total_usd):"not reported")}</span>
|
|
1008
1008
|
</li>`)}
|
|
1009
|
-
</div>`}function
|
|
1009
|
+
</div>`}function Zp(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4}).format(e)}function cw(e){return`${e.reported_runs}/${e.runs} reported (${Math.round(e.coverage*100)}%)`}function dw(e){return e.replaceAll("_"," ").replace(/\b\w/g,t=>t.toUpperCase())}function uw(e){return e==="done"?"green":e==="blocked"||e==="failed"?"red":e==="in_progress"||e==="review"?"cyan":"amber"}function xe(e,t){return`<section class="panel">
|
|
1010
1010
|
<div class="panel-head"><p class="eyebrow"><span>›</span> ${w(e)}</p></div>
|
|
1011
1011
|
${t}
|
|
1012
|
-
</section>`}function $e(e,t){return e.length===0?"":`<ul class="records">${e.map(t).join("")}</ul>`}function Kt(e,t){return e.length===0?`<p class="empty">${w(t)}</p>`:""}function Jn(e){return`<div class="split-stats">${e.map(([t,r])=>`<div><strong>${r}</strong><span>${w(t)}</span></div>`).join("")}</div>`}function
|
|
1012
|
+
</section>`}function $e(e,t){return e.length===0?"":`<ul class="records">${e.map(t).join("")}</ul>`}function Kt(e,t){return e.length===0?`<p class="empty">${w(t)}</p>`:""}function Jn(e){return`<div class="split-stats">${e.map(([t,r])=>`<div><strong>${r}</strong><span>${w(t)}</span></div>`).join("")}</div>`}function pw(e){let t=Object.values(e).reduce((o,n)=>o+n,0);return`<div class="lifecycle" aria-label="memory lifecycle">${[["active","green"],["candidate","amber"],["rejected","red"],["expired","neutral"],["forgotten","neutral"],["superseded","neutral"]].map(([o,n])=>{let a=e[o],s=t===0?0:Math.max(6,Math.round(a/t*100));return`<span class="${n}" style="width:${s}%" title="${o}: ${a}"></span>`}).join("")}</div>`}function mw(){return`<div class="legend">
|
|
1013
1013
|
<span><i class="green"></i>ready</span>
|
|
1014
1014
|
<span><i class="cyan"></i>full native capability</span>
|
|
1015
1015
|
<span><i class="amber"></i>official-fallback</span>
|
|
1016
1016
|
<span><i class="red"></i>degraded</span>
|
|
1017
|
-
</div>`}function
|
|
1017
|
+
</div>`}function gw(e){return{total:e.length,ready:e.filter(t=>t.ready).length}}function fw(e){return e==="active"?"green":e==="candidate"?"amber":e==="rejected"||e==="forgotten"?"red":"neutral"}function hw(e){return e==="open"?"amber":e==="completed"?"green":"neutral"}function w(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function yw(){return`
|
|
1018
1018
|
:root {
|
|
1019
1019
|
--red-400:#ff6b6b; --red-500:#ff4444; --red-600:#f02d3a; --red-glow:rgba(255,68,68,.45); --red-glow-soft:rgba(255,68,68,.16);
|
|
1020
1020
|
--ink-950:#06070d; --ink-900:#0a0c14; --ink-850:#0e1019; --ink-800:#12151f; --ink-700:#1c202d; --ink-600:#262b3a;
|
|
@@ -1041,35 +1041,35 @@ h1{margin:0;color:var(--text-100);font:700 44px/1.05 var(--font-display);letter-
|
|
|
1041
1041
|
.empty{margin:0;color:var(--text-500);font:500 13px/1.5 var(--font-mono);border:1px dashed var(--ink-600);border-radius:10px;padding:14px}footer{display:flex;justify-content:space-between;gap:16px;margin-top:18px;padding-top:18px;border-top:1px solid rgba(255,255,255,.06);color:var(--text-500);font:600 11px/1.4 var(--font-mono);text-transform:uppercase}
|
|
1042
1042
|
@media (max-width: 900px){.topbar,.layout{grid-template-columns:1fr}.summary-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.terminal code{white-space:normal}.records small{max-width:260px}}
|
|
1043
1043
|
@media (max-width: 560px){.summary-grid{grid-template-columns:1fr}.shell{padding:22px 12px}h1{font-size:34px}.records li{align-items:flex-start;flex-direction:column}.records small{max-width:100%}footer{flex-direction:column}.split-stats{grid-template-columns:1fr}}
|
|
1044
|
-
`}import{readFile as gw}from"node:fs/promises";import fw from"node:path";var qn=1500;async function Co(e){let t=await v(e.home),r=await _w(t.home),o=new Date,n=hw(e.ttlSeconds??r.ttlSeconds),a=new Date(o.getTime()+n*1e3).toISOString(),s=Di(e.project,e.slot),i=_(t.database),l;try{l=i.claimHeartbeatLease({id:T("lease"),slot:e.slot,holder:e.host,idempotencyKey:s,now:o.toISOString(),expiresAt:a})}finally{i.close()}return await h({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 Oo(e){let t=await v(e.home),r=new Date().toISOString(),o=Di(e.project,e.slot),n=H(e.result??"HEARTBEAT_OK"),a=H(yw(e.evidence??{},e.workItemId)),s=H(e.cost??{}),i=Xt(s),l=_(t.database),c;try{c=l.completeHeartbeatLease({idempotencyKey:o,host:e.host,project:e.project,result:n,evidence:a,cost:i,completedAt:r,runId:T("run")})}finally{l.close()}return await h({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}}async function Li(e){let t=await v(e.home),r=_(t.database);try{return r.listHeartbeatLeases({project:e.project,limit:Math.min(Math.max(e.limit??20,1),100)})}finally{r.close()}}function Di(e,t){return`heartbeat:${e}:${t}`}function hw(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),1440*60):qn}function yw(e,t){return t?{...e&&typeof e=="object"&&!Array.isArray(e)?e:{},work_item_id:t}:e}async function _w(e){let t;try{t=await gw(fw.join(e,"config.yaml"),"utf8")}catch{return{ttlSeconds:qn,skipWhenBusy:!0}}return{ttlSeconds:bw(t),skipWhenBusy:vw(t,"skip_when_busy",!0)}}function bw(e){let t=Mi(e,"ttl_seconds"),r=Mi(e,"lease_ttl"),o=kw(e,"heartbeat_ttl_seconds"),n=ww(t??r??o);return Number.isFinite(n)?n:qn}function vw(e,t,r){let o=Mi(e,t);return o?/^(true|yes|1)$/i.test(o)?!0:/^(false|no|0)$/i.test(o)?!1:r:r}function Mi(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 kw(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function ww(e){if(!e)return qn;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}async function Hi(e){let t=await v(e.home);_(t.database).close();let o=Je(e.host),n=(await Promise.all(o.map(s=>Mr(s)))).flat(),a=[];for(let s of o){let i=Ke(s,e.surface);for(let l of i){let c=n.find(ne=>ne.host===s),d=cr(s,e.targetRoot,l),p=d.managedBlock?await Hr({home:t.home,host:s,apply:e.apply,targetPath:d.managedBlock}):Rw(s,l,!e.apply),g=await go({home:t.home,host:s,apply:e.apply,targetPath:d.mcpRegistration,commandMode:"package"}),y=await Qs({home:t.home,host:s,surface:l,apply:e.apply,targetPath:d.plugin}),k=await mt({home:t.home,host:s,surface:l,mode:"leader",apply:e.apply,pluginEnabled:y.enabled,hostConfigRoot:ze(s,e.targetRoot),targetRoot:e.targetRoot}),R=e.apply?await At({home:t.home,host:s}):[],U=e.apply?R.reduce((ne,Fe)=>ne+Fe.count,0):c?.sources.length??0,Y=[...k.warnings,...y.issues.map(ne=>ne.code),...c?.detected?[]:[`${s.toUpperCase()}_NOT_DETECTED`]],be=[p.backupPath,g.backupPath,y.backupPath].filter(ne=>ne!==null),Ie=Y.length===0&&U>0?"ready":"degraded";a.push({host:s,surface:l,detected:c?.detected??!1,status:Ie,managed_block:p,mcp_registration:g,plugin:y,schedule:k,capability_count:U,snapshots:be,warnings:Y})}}return{dryRun:!e.apply,applied:e.apply,home:t.home,hosts:a,status:a.every(s=>s.status==="ready")?"ready":"degraded"}}function Rw(e,t,r){let o=A("");return{host:e,targetPath:`not-applicable:${Mt(e,t)}`,action:"noop",dryRun:r,changed:!1,beforeHash:null,afterHash:o,diff:"No managed instruction block for this host surface.",backupPath:null,applied:!1}}import Sw from"node:path";import{rm as zp}from"node:fs/promises";var $i="DELETE_NATIVESOUL_HOME";async function Fi(e){if(e.purgeData===!0&&e.confirmPurge!==$i)throw new Error(`--purge-data requires --confirm-purge-nativesoul-data ${$i}`);let t=await v(e.home);_(t.database).close();let o=Je(e.host);if(e.apply)for(let l of o)for(let c of Ke(l,e.surface))await Yp({home:t.home,host:l,surface:c,apply:!1,targetRoot:e.targetRoot});let n=[];for(let l of o)for(let c of Ke(l,e.surface))n.push(await Yp({home:t.home,host:l,surface:c,apply:e.apply,targetRoot:e.targetRoot}));let a={requested:e.purgeData===!0,confirmed:e.confirmPurge===$i,applied:e.apply&&e.purgeData===!0,preserved:!(e.apply&&e.purgeData===!0)},s=Sw.join(t.home,"backups"),i={path:s,applied:e.apply,preserved:!e.apply};return i.applied&&await zp(s,{recursive:!0,force:!0}),a.applied&&await zp(t.home,{recursive:!0,force:!0}),{dryRun:!e.apply,applied:e.apply,home:t.home,hosts:n,backups_purge:i,data_purge:a,status:n.every(l=>l.status==="ready")?"ready":"degraded"}}async function Yp(e){let t=cr(e.host,e.targetRoot,e.surface),r=t.managedBlock?await os({home:e.home,host:e.host,apply:e.apply,targetPath:t.managedBlock}):Aw(e.host,e.surface,!e.apply),o=await ti({home:e.home,host:e.host,apply:e.apply,targetPath:t.mcpRegistration}),n=await Zs({home:e.home,host:e.host,surface:e.surface,apply:e.apply,targetPath:t.plugin}),a=[r.backupPath,o.backupPath,n.backupPath].filter(s=>s!==null);return{host:e.host,surface:e.surface,status:"ready",managed_block:r,mcp_registration:o,plugin:n,snapshots:a,warnings:["SCHEDULE_TEARDOWN_NOT_PERFORMED"]}}function Aw(e,t,r){let o=A("");return{host:e,targetPath:`not-applicable:${Mt(e,t)}`,action:"noop",dryRun:r,changed:!1,beforeHash:null,afterHash:o,diff:"No managed instruction block for this host surface.",backupPath:null,applied:!1}}async function Bi(e){let t=f(e.home),r=_(t.database),o;try{let n=r.findPendingApprovalMatch(Ui(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 a=r.createApproval({id:T("approval"),...Ui(e)});o={approval:a.approval,created:!!a.approval,available:a.available,warning:a.warning}}finally{r.close()}return o.created&&o.approval&&await h({home:t.home,type:"approval_requested",details:Wi(o.approval)}),o}async function _r(e){let t=f(e.home),r=_(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 Ce,n}finally{r.close()}return o.approval&&await h({home:t.home,type:o.approval.status==="approved"?"approval_approved":"approval_rejected",details:Wi(o.approval)}),o}async function Vi(e){let t=f(e.home),r=_(t.database),o;try{let n=r.createDecidedApproval({id:T("approval"),...Ui(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 h({home:t.home,type:"approval_auto_approved",details:{...Wi(o.approval),standing_order:e.standingOrderId}}),o}function Kn(e){let t=_(f(e.home).database);try{let r=t.getApproval(e.id);return{approval:r.approval,available:r.available,warning:r.warning}}finally{t.close()}}function Gn(e={}){let t=_(f(e.home).database);try{return t.listApprovals(e.status)}finally{t.close()}}function Ui(e){return{action:e.action,class:e.class,target:e.target??null,project:e.project??null,host:e.host??null}}function Wi(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 No(e){let t=await ht(e),r=await Ew(e,t);if(r){let n=await Vi({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 Bi({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 Ew(e,t){return t.decision!=="allowed"||!t.matched_standing_order||!Pw(e.className)?null:(await ft(e.home)).find(o=>o.id===t.matched_standing_order&&o.allowed.includes(e.action)&&Ii(o,e))??null}function Pw(e){return e==="write_project"||e==="external_write"}var Zp={"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 Gt(e,t={}){let r=Zp[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,a,s,i;try{let l=await No(o);n=l.evaluation,a=l.approval?.id??null,s=l.approval_created,i=l.warning}catch(l){return await Qp(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:a,approvalCreated:s,warning:i,evaluation:n}:(await Qp(r,t,n.reasons,"blocked"),{status:"deny",decision:n.decision,reason:`${r.action} ${n.decision}: ${n.reasons.join(", ")}`,evaluation:n})}async function Qp(e,t,r,o){try{let n=await v(t.home);await h({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 zi}from"node:fs";import{mkdir as sm,readFile as zn,rm as Gw,writeFile as im}from"node:fs/promises";import _e from"node:path";import{existsSync as Vw}from"node:fs";import{readdir as Ww,readFile as Ji}from"node:fs/promises";import yt from"node:path";import{fileURLToPath as Jw}from"node:url";import em from"node:path";var xw=new Set(["id","version","title","description","intended_use","approvals","standing_orders","policy_proposals","managed_blocks","rollback","metadata"]),jw=new Set(["id","action","authority","allowed","approval_required","scope_projects","scope_hosts","reason"]),Iw=new Set(["target","summary","rationale","rollback_note"]),Tw=new Set(["target","marker","content","rollback_key"]),Cw=new Set(["strategy","restores","notes"]),Ow=new Set(["maturity","owner","source"]),Nw=new Set(["SOUL.MD","POLICY.MD"]),tm=["AGENTS.md","CLAUDE.md","GEMINI.md","Agents.md",".claude/CLAUDE.md"],Mw=new Set(tm);function vr(e){let t=[];return Qe(e)?(kr(e,xw,"pack",t),oe(e,"id","pack",t,/^[a-z0-9][a-z0-9-]{2,63}$/u),oe(e,"version","pack",t,/^[0-9]+\.[0-9]+\.[0-9]+$/u),oe(e,"title","pack",t),oe(e,"description","pack",t),oe(e,"intended_use","pack",t),br(e.approvals,"pack.approvals",t,!1),Lw(e.standing_orders,t),Dw(e.policy_proposals,t),Hw(e.managed_blocks,t),$w(e.rollback,t),Fw(e.metadata,t),Bw(e,t),t):["Policy pack must be an object"]}function Qe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function rm(e){return typeof e=="string"?e:null}function Lw(e,t){if(!Array.isArray(e)){t.push("pack.standing_orders must be an array");return}for(let[r,o]of e.entries()){let n=`pack.standing_orders[${r}]`;if(!Qe(o)){t.push(`${n} must be an object`);continue}kr(o,jw,n,t),oe(o,"id",n,t,/^[a-z0-9][a-z0-9-]{2,63}$/u),Xn(o,"action",n,["add","propose"],t),Xn(o,"authority",n,["operator-approved","proposal"],t),br(o.allowed,`${n}.allowed`,t,!0),br(o.approval_required,`${n}.approval_required`,t,!0),br(o.scope_projects,`${n}.scope_projects`,t,!0),br(o.scope_hosts,`${n}.scope_hosts`,t,!0),oe(o,"reason",n,t);let a=Array.isArray(o.allowed)?o.allowed:[],s=Array.isArray(o.approval_required)?o.approval_required:[];a.length===0&&s.length===0&&t.push(`${n} must declare at least one allowed or approval_required action`)}}function Dw(e,t){if(!Array.isArray(e)){t.push("pack.policy_proposals must be an array");return}for(let[r,o]of e.entries()){let n=`pack.policy_proposals[${r}]`;if(!Qe(o)){t.push(`${n} must be an object`);continue}kr(o,Iw,n,t),Xn(o,"target",n,["SOUL.md","POLICY.md"],t),oe(o,"summary",n,t),oe(o,"rationale",n,t),oe(o,"rollback_note",n,t)}}function Hw(e,t){if(!Array.isArray(e)){t.push("pack.managed_blocks must be an array");return}for(let[r,o]of e.entries()){let n=`pack.managed_blocks[${r}]`;if(!Qe(o)){t.push(`${n} must be an object`);continue}kr(o,Tw,n,t),oe(o,"target",n,t),oe(o,"marker",n,t),oe(o,"content",n,t),oe(o,"rollback_key",n,t),typeof o.target=="string"&&Uw(o.target,n,t)}}function $w(e,t){if(!Qe(e)){t.push("pack.rollback must be an object");return}kr(e,Cw,"pack.rollback",t),Xn(e,"strategy","pack.rollback",["proposal-only","managed-block","snapshot-required"],t),br(e.restores,"pack.rollback.restores",t,!0),Array.isArray(e.restores)&&e.restores.length===0&&t.push("pack.rollback.restores must include at least one rollback item"),oe(e,"notes","pack.rollback",t)}function Fw(e,t){if(e!==void 0){if(!Qe(e)){t.push("pack.metadata must be an object");return}kr(e,Ow,"pack.metadata",t);for(let[r,o]of Object.entries(e))o!==null&&typeof o!="string"&&typeof o!="number"&&typeof o!="boolean"&&t.push(`pack.metadata.${r} must be a scalar value`)}}function Uw(e,t,r){let o=e.replaceAll("\\","/"),n=em.basename(o).toUpperCase();(em.isAbsolute(e)||o.includes("../")||o.startsWith("../"))&&r.push(`${t}.target must be a relative managed host file path`),Nw.has(n)&&r.push(`${t}.target must not target protected SOUL.md or POLICY.md`),Mw.has(o)||r.push(`${t}.target is outside supported managed-block scope`)}function Bw(e,t){let r=JSON.stringify(e);/(sk-[A-Za-z0-9_-]{8,}|api[_-]?key\s*[:=]|secret\s*[:=]|token\s*[:=]|password\s*[:=])/iu.test(r)&&t.push("pack must not contain credential-like material"),/https?:\/\//iu.test(r)&&t.push("pack must not require trust in external URLs")}function kr(e,t,r,o){for(let n of Object.keys(e))t.has(n)||o.push(`${r}.${n} is not allowed`)}function oe(e,t,r,o,n){let a=e[t];if(typeof a!="string"||a.trim()===""){o.push(`${r}.${t} must be a non-empty string`);return}n&&!n.test(a)&&o.push(`${r}.${t} has invalid format`)}function Xn(e,t,r,o,n){let a=e[t];(typeof a!="string"||!o.includes(a))&&n.push(`${r}.${t} must be one of ${o.join(", ")}`)}function br(e,t,r,o){e===void 0&&!o||(!Array.isArray(e)||!e.every(n=>typeof n=="string"))&&r.push(`${t} must be an array of strings`)}async function qi(){return(await om()).map(({pack:t,source:r})=>({id:t.id,version:t.version,title:t.title,description:t.description,intended_use:t.intended_use,source:r})).sort((t,r)=>t.id.localeCompare(r.id))}async function Mo(e){let r=(await om()).find(o=>o.pack.id===e);if(!r)throw new Error(`Policy pack not found: ${e}`);return{...r.pack,source:r.source}}async function Ki(e){try{let{value:t,source:r}=e.file?{value:JSON.parse(await Ji(e.file,"utf8")),source:yt.resolve(e.file)}:await qw(e.id),o=vr(t),n=Qe(t)?rm(t.id):null;return{valid:o.length===0,id:n,source:r,errors:o,warnings:[]}}catch(t){return{valid:!1,id:e.id??null,source:e.file?yt.resolve(e.file):null,errors:[t instanceof Error?t.message:"Unknown policy pack validation error"],warnings:[]}}}async function om(){let e=await nm(),t=[];for(let r of e){let o=JSON.parse(await Ji(r,"utf8")),n=vr(o);if(n.length>0)throw new Error(`Invalid built-in policy pack ${r}: ${n.join("; ")}`);t.push({pack:o,source:r})}return t}async function qw(e){if(!e)throw new Error("policy packs validate requires <id> or --file <path>");let t=await nm();for(let r of t){let o=JSON.parse(await Ji(r,"utf8"));if(Qe(o)&&o.id===e)return{value:o,source:r}}throw new Error(`Policy pack not found: ${e}`)}async function nm(){let e=Kw(),t=(await Ww(e)).filter(r=>r.endsWith(".json")).map(r=>yt.join(e,r)).sort();if(t.length===0)throw new Error(`No policy packs found in ${e}`);return t}function Kw(){let e=yt.dirname(Jw(import.meta.url)),r=[yt.resolve(process.cwd(),"policy-packs"),yt.resolve(e,"../../../policy-packs"),yt.resolve(e,"../../../../policy-packs"),yt.resolve(e,"../../../../../policy-packs")].find(o=>Vw(o));if(!r)throw new Error("Built-in policy pack catalog not found");return r}async function Yi(e){if(e.apply&&!e.reviewed)throw new Error("policy packs apply requires a prior dry-run review; pass --reviewed with --apply after reviewing the plan");let t=await v(e.home),r=await Xw(e),o=_e.resolve(e.targetRoot??process.cwd()),n=new Date().toISOString(),a=await zw({home:t.home,pack:r.pack,targetRoot:o,createdAt:n}),s=a.map(am),i=a.filter(p=>p.changed),l=uR(r.pack),c=e.apply&&i.length>0?await aR({home:t.home,pack:r.pack,source:r.source,targetRoot:o,files:i,approvalEvidence:e.approvalEvidence??null,createdAt:n}):null;if(e.apply){let p=[];try{for(let g of i)await Zi(g,"after"),p.push(g)}catch(g){throw await tR(p),await h({home:t.home,type:"policy_pack_apply_failed",result:"error",details:{pack:{id:r.pack.id,version:r.pack.version,source:r.source},targetRoot:o,snapshotPath:c,rolledBackFiles:p.map(y=>am(y)),error:g instanceof Error?g.message:String(g)}}),g}}let d={pack:{id:r.pack.id,version:r.pack.version,title:r.pack.title,source:r.source},dryRun:!e.apply,applied:e.apply,reviewed:e.reviewed,targetRoot:o,files:s,standingOrderChanges:r.pack.standing_orders.length,policyProposals:r.pack.policy_proposals.length,managedBlocks:r.pack.managed_blocks.length,warnings:l,snapshotRequired:i.length>0,snapshotPath:c};return await h({home:t.home,type:e.apply?"policy_pack_apply":"policy_pack_apply_dry_run",details:pR(d,e.approvalEvidence)}),d}async function Qi(e){let t=await v(e.home),r=rR(await zn(e.snapshotPath,"utf8"),e.snapshotPath),o=r.files.map(a=>eR(a));if(e.apply)for(let a of r.files)await Zi(a,"before");let n={snapshotPath:e.snapshotPath,pack:{id:r.pack.id,version:r.pack.version},dryRun:!e.apply,applied:e.apply,files:o};return await h({home:t.home,type:e.apply?"policy_pack_rollback":"policy_pack_rollback_dry_run",details:{snapshotPath:e.snapshotPath,pack:n.pack,dryRun:n.dryRun,applied:n.applied,files:n.files}}),n}async function Xw(e){if(e.file){let r=_e.resolve(e.file),o=JSON.parse(await zn(r,"utf8")),n=vr(o);if(n.length>0)throw new Error(`Invalid policy pack ${r}: ${n.join("; ")}`);return{pack:o,source:r}}if(!e.id)throw new Error("policy packs apply requires <id> or --file <path>");let t=await Mo(e.id);return{pack:t,source:t.source}}async function zw(e){let t=[];for(let r of e.pack.standing_orders)t.push(await Yw(e.home,e.pack,r));for(let r of e.pack.policy_proposals)t.push(await Qw(e.home,e.pack,r,e.createdAt));for(let r of e.pack.managed_blocks)t.push(await Zw(e.targetRoot,e.pack,r));return t}async function Yw(e,t,r){if(r.action==="add"&&r.authority==="operator-approved"){let n=_e.join(e,"standing-orders",`${r.id}.yaml`);return await Gi("standing_order",n,sR(r,t))}let o=_e.join(e,"proposals",`standing-order-${t.id}-${r.id}.md`);return await Gi("standing_order",o,iR(r,t))}async function Qw(e,t,r,o){let n=o.replaceAll(/[:.]/gu,"-"),a=_e.join(e,"proposals",`${n}-${t.id}-${r.target}.md`);return await Gi("policy_proposal",a,lR(r,t,o))}async function Zw(e,t,r){let o=_e.resolve(e,r.target);if(!gR(e,o))throw new Error(`Policy pack managed block target escapes target root: ${r.target}`);let n=zi(o),a=n?await zn(o,"utf8"):null,s=cR(a,t,r);return lm("managed_block",o,n,a,s)}async function Gi(e,t,r){let o=zi(t),n=o?await zn(t,"utf8"):null;return lm(e,t,o,n,r)}function lm(e,t,r,o,n){let a=o===null?null:A(o),s=n===null?null:A(n),i=o!==n;return{kind:e,targetPath:t,action:i?r?"replace":"create":"noop",changed:i,beforeHash:a,afterHash:s,diff:mR(o,n),beforeExists:r,beforeContent:o,afterContent:n}}function am(e){return{kind:e.kind,targetPath:e.targetPath,action:e.action,changed:e.changed,beforeHash:e.beforeHash,afterHash:e.afterHash,diff:e.diff}}function eR(e){return{kind:e.kind,targetPath:e.targetPath,action:e.beforeExists?"replace":"remove",changed:!0,beforeHash:e.afterHash,afterHash:e.beforeHash,diff:dm(e.afterHash,e.beforeHash)}}async function Zi(e,t){let r=t==="before"?e.beforeExists:e.afterHash!==null,o=t==="before"?e.beforeContent:e.afterContent;r&&o!==null?(await sm(_e.dirname(e.targetPath),{recursive:!0,mode:448}),Se(e.targetPath,{allowSymlinkTarget:!0}),await im(e.targetPath,o,{encoding:"utf8",mode:384})):zi(e.targetPath)&&await Gw(e.targetPath)}async function tR(e){for(let t of[...e].reverse())await Zi(t,"before")}function rR(e,t){let r;try{r=JSON.parse(e)}catch(n){throw new Error(`Invalid policy pack snapshot ${t}: ${n instanceof Error?n.message:String(n)}`,{cause:n})}let o=oR(r);if(o.length>0)throw new Error(`Invalid policy pack snapshot ${t}: ${o.join("; ")}`);return r}function oR(e){let t=[];if(!Xi(e))return["snapshot must be an object"];(typeof e.id!="string"||!e.id)&&t.push("id must be a non-empty string");let r=e.pack;return Xi(r)?((typeof r.id!="string"||!r.id)&&t.push("pack.id must be a non-empty string"),(typeof r.version!="string"||!r.version)&&t.push("pack.version must be a non-empty string"),typeof r.source=="string"||r.source===null||t.push("pack.source must be a string or null")):t.push("pack must be an object"),(typeof e.targetRoot!="string"||!e.targetRoot)&&t.push("targetRoot must be a non-empty string"),(typeof e.createdAt!="string"||!e.createdAt)&&t.push("createdAt must be a non-empty string"),typeof e.approvalEvidence=="string"||e.approvalEvidence===null||t.push("approvalEvidence must be a string or null"),Array.isArray(e.files)?e.files.forEach((o,n)=>{t.push(...nR(o,`files[${n}]`))}):t.push("files must be an array"),t}function nR(e,t){let r=[];if(!Xi(e))return[`${t} must be an object`];["standing_order","policy_proposal","managed_block"].includes(typeof e.kind=="string"?e.kind:"")||r.push(`${t}.kind is invalid`),(typeof e.targetPath!="string"||!_e.isAbsolute(e.targetPath))&&r.push(`${t}.targetPath must be an absolute path`),["create","replace","noop","remove"].includes(typeof e.action=="string"?e.action:"")||r.push(`${t}.action is invalid`),typeof e.changed!="boolean"&&r.push(`${t}.changed must be boolean`),typeof e.beforeExists!="boolean"&&r.push(`${t}.beforeExists must be boolean`);for(let o of["beforeHash","afterHash","beforeContent","afterContent"])typeof e[o]=="string"||e[o]===null||r.push(`${t}.${o} must be a string or null`);return typeof e.diff!="string"&&r.push(`${t}.diff must be a string`),r}function Xi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function aR(e){let t=_e.join(e.home,"backups","policy-packs");await sm(t,{recursive:!0,mode:448});let r={id:T("policy_pack_snapshot"),pack:{id:e.pack.id,version:e.pack.version,source:e.source},targetRoot:e.targetRoot,createdAt:e.createdAt,files:e.files,approvalEvidence:e.approvalEvidence},o=`${e.createdAt.replaceAll(/[:.]/gu,"-")}-${e.pack.id}.json`,n=_e.join(t,o);return await im(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384,flag:"wx"}),n}function sR(e,t){return[`id: ${e.id}`,`source: policy-pack:${t.id}@${t.version}`,`allowed: ${JSON.stringify(e.allowed)}`,`approval_required: ${JSON.stringify(e.approval_required)}`,`scope_projects: ${JSON.stringify(e.scope_projects)}`,`scope_hosts: ${JSON.stringify(e.scope_hosts)}`,`reason: ${JSON.stringify(e.reason)}`,""].join(`
|
|
1045
|
-
`)}function
|
|
1046
|
-
`)}function
|
|
1047
|
-
`)}function
|
|
1044
|
+
`}import{readFile as _w}from"node:fs/promises";import bw from"node:path";var qn=1500;async function Co(e){let t=await v(e.home),r=await ww(t.home),o=new Date,n=vw(e.ttlSeconds??r.ttlSeconds),a=new Date(o.getTime()+n*1e3).toISOString(),s=Hi(e.project,e.slot),i=_(t.database),l;try{l=i.claimHeartbeatLease({id:T("lease"),slot:e.slot,holder:e.host,idempotencyKey:s,now:o.toISOString(),expiresAt:a})}finally{i.close()}return await h({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 Oo(e){let t=await v(e.home),r=new Date().toISOString(),o=Hi(e.project,e.slot),n=H(e.result??"HEARTBEAT_OK"),a=H(kw(e.evidence??{},e.workItemId)),s=H(e.cost??{}),i=Xt(s),l=_(t.database),c;try{c=l.completeHeartbeatLease({idempotencyKey:o,host:e.host,project:e.project,result:n,evidence:a,cost:i,completedAt:r,runId:T("run")})}finally{l.close()}return await h({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}}async function Di(e){let t=await v(e.home),r=_(t.database);try{return r.listHeartbeatLeases({project:e.project,limit:Math.min(Math.max(e.limit??20,1),100)})}finally{r.close()}}function Hi(e,t){return`heartbeat:${e}:${t}`}function vw(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),1440*60):qn}function kw(e,t){return t?{...e&&typeof e=="object"&&!Array.isArray(e)?e:{},work_item_id:t}:e}async function ww(e){let t;try{t=await _w(bw.join(e,"config.yaml"),"utf8")}catch{return{ttlSeconds:qn,skipWhenBusy:!0}}return{ttlSeconds:Rw(t),skipWhenBusy:Sw(t,"skip_when_busy",!0)}}function Rw(e){let t=Li(e,"ttl_seconds"),r=Li(e,"lease_ttl"),o=Aw(e,"heartbeat_ttl_seconds"),n=Ew(t??r??o);return Number.isFinite(n)?n:qn}function Sw(e,t,r){let o=Li(e,t);return o?/^(true|yes|1)$/i.test(o)?!0:/^(false|no|0)$/i.test(o)?!1:r:r}function Li(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 Aw(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.match(new RegExp(`^\\s*${r}:\\s*([^#\\n]+)`,"mu"))?.[1]?.trim().replace(/^["']|["']$/g,"")??null}function Ew(e){if(!e)return qn;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}async function $i(e){let t=await v(e.home);_(t.database).close();let o=Je(e.host),n=(await Promise.all(o.map(s=>Mr(s)))).flat(),a=[];for(let s of o){let i=Ke(s,e.surface);for(let l of i){let c=n.find(ne=>ne.host===s),d=cr(s,e.targetRoot,l),p=d.managedBlock?await Hr({home:t.home,host:s,apply:e.apply,targetPath:d.managedBlock}):Pw(s,l,!e.apply),g=await go({home:t.home,host:s,apply:e.apply,targetPath:d.mcpRegistration,commandMode:"package"}),y=await Zs({home:t.home,host:s,surface:l,apply:e.apply,targetPath:d.plugin}),k=await mt({home:t.home,host:s,surface:l,mode:"leader",apply:e.apply,pluginEnabled:y.enabled,hostConfigRoot:ze(s,e.targetRoot),targetRoot:e.targetRoot}),R=e.apply?await At({home:t.home,host:s}):[],U=e.apply?R.reduce((ne,Fe)=>ne+Fe.count,0):c?.sources.length??0,Y=[...k.warnings,...y.issues.map(ne=>ne.code),...c?.detected?[]:[`${s.toUpperCase()}_NOT_DETECTED`]],be=[p.backupPath,g.backupPath,y.backupPath].filter(ne=>ne!==null),Ie=Y.length===0&&U>0?"ready":"degraded";a.push({host:s,surface:l,detected:c?.detected??!1,status:Ie,managed_block:p,mcp_registration:g,plugin:y,schedule:k,capability_count:U,snapshots:be,warnings:Y})}}return{dryRun:!e.apply,applied:e.apply,home:t.home,hosts:a,status:a.every(s=>s.status==="ready")?"ready":"degraded"}}function Pw(e,t,r){let o=A("");return{host:e,targetPath:`not-applicable:${Mt(e,t)}`,action:"noop",dryRun:r,changed:!1,beforeHash:null,afterHash:o,diff:"No managed instruction block for this host surface.",backupPath:null,applied:!1}}import xw from"node:path";import{rm as em}from"node:fs/promises";var Fi="DELETE_NATIVESOUL_HOME";async function Ui(e){if(e.purgeData===!0&&e.confirmPurge!==Fi)throw new Error(`--purge-data requires --confirm-purge-nativesoul-data ${Fi}`);let t=await v(e.home);_(t.database).close();let o=Je(e.host);if(e.apply)for(let l of o)for(let c of Ke(l,e.surface))await tm({home:t.home,host:l,surface:c,apply:!1,targetRoot:e.targetRoot});let n=[];for(let l of o)for(let c of Ke(l,e.surface))n.push(await tm({home:t.home,host:l,surface:c,apply:e.apply,targetRoot:e.targetRoot}));let a={requested:e.purgeData===!0,confirmed:e.confirmPurge===Fi,applied:e.apply&&e.purgeData===!0,preserved:!(e.apply&&e.purgeData===!0)},s=xw.join(t.home,"backups"),i={path:s,applied:e.apply,preserved:!e.apply};return i.applied&&await em(s,{recursive:!0,force:!0}),a.applied&&await em(t.home,{recursive:!0,force:!0}),{dryRun:!e.apply,applied:e.apply,home:t.home,hosts:n,backups_purge:i,data_purge:a,status:n.every(l=>l.status==="ready")?"ready":"degraded"}}async function tm(e){let t=cr(e.host,e.targetRoot,e.surface),r=t.managedBlock?await os({home:e.home,host:e.host,apply:e.apply,targetPath:t.managedBlock}):jw(e.host,e.surface,!e.apply),o=await ri({home:e.home,host:e.host,apply:e.apply,targetPath:t.mcpRegistration}),n=await ei({home:e.home,host:e.host,surface:e.surface,apply:e.apply,targetPath:t.plugin}),a=[r.backupPath,o.backupPath,n.backupPath].filter(s=>s!==null);return{host:e.host,surface:e.surface,status:"ready",managed_block:r,mcp_registration:o,plugin:n,snapshots:a,warnings:["SCHEDULE_TEARDOWN_NOT_PERFORMED"]}}function jw(e,t,r){let o=A("");return{host:e,targetPath:`not-applicable:${Mt(e,t)}`,action:"noop",dryRun:r,changed:!1,beforeHash:null,afterHash:o,diff:"No managed instruction block for this host surface.",backupPath:null,applied:!1}}async function Vi(e){let t=f(e.home),r=_(t.database),o;try{let n=r.findPendingApprovalMatch(Bi(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 a=r.createApproval({id:T("approval"),...Bi(e)});o={approval:a.approval,created:!!a.approval,available:a.available,warning:a.warning}}finally{r.close()}return o.created&&o.approval&&await h({home:t.home,type:"approval_requested",details:Ji(o.approval)}),o}async function _r(e){let t=f(e.home),r=_(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 Ce,n}finally{r.close()}return o.approval&&await h({home:t.home,type:o.approval.status==="approved"?"approval_approved":"approval_rejected",details:Ji(o.approval)}),o}async function Wi(e){let t=f(e.home),r=_(t.database),o;try{let n=r.createDecidedApproval({id:T("approval"),...Bi(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 h({home:t.home,type:"approval_auto_approved",details:{...Ji(o.approval),standing_order:e.standingOrderId}}),o}function Kn(e){let t=_(f(e.home).database);try{let r=t.getApproval(e.id);return{approval:r.approval,available:r.available,warning:r.warning}}finally{t.close()}}function Gn(e={}){let t=_(f(e.home).database);try{return t.listApprovals(e.status)}finally{t.close()}}function Bi(e){return{action:e.action,class:e.class,target:e.target??null,project:e.project??null,host:e.host??null}}function Ji(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 No(e){let t=await ht(e),r=await Iw(e,t);if(r){let n=await Wi({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 Vi({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 Iw(e,t){return t.decision!=="allowed"||!t.matched_standing_order||!Tw(e.className)?null:(await ft(e.home)).find(o=>o.id===t.matched_standing_order&&o.allowed.includes(e.action)&&Ti(o,e))??null}function Tw(e){return e==="write_project"||e==="external_write"}var om={"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 Gt(e,t={}){let r=om[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,a,s,i;try{let l=await No(o);n=l.evaluation,a=l.approval?.id??null,s=l.approval_created,i=l.warning}catch(l){return await rm(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:a,approvalCreated:s,warning:i,evaluation:n}:(await rm(r,t,n.reasons,"blocked"),{status:"deny",decision:n.decision,reason:`${r.action} ${n.decision}: ${n.reasons.join(", ")}`,evaluation:n})}async function rm(e,t,r,o){try{let n=await v(t.home);await h({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 Yi}from"node:fs";import{mkdir as dm,readFile as zn,rm as Qw,writeFile as um}from"node:fs/promises";import _e from"node:path";import{existsSync as Kw}from"node:fs";import{readdir as Gw,readFile as qi}from"node:fs/promises";import yt from"node:path";import{fileURLToPath as Xw}from"node:url";import nm from"node:path";var Cw=new Set(["id","version","title","description","intended_use","approvals","standing_orders","policy_proposals","managed_blocks","rollback","metadata"]),Ow=new Set(["id","action","authority","allowed","approval_required","scope_projects","scope_hosts","reason"]),Nw=new Set(["target","summary","rationale","rollback_note"]),Mw=new Set(["target","marker","content","rollback_key"]),Lw=new Set(["strategy","restores","notes"]),Dw=new Set(["maturity","owner","source"]),Hw=new Set(["SOUL.MD","POLICY.MD"]),am=["AGENTS.md","CLAUDE.md","GEMINI.md","Agents.md",".claude/CLAUDE.md"],$w=new Set(am);function vr(e){let t=[];return Qe(e)?(kr(e,Cw,"pack",t),oe(e,"id","pack",t,/^[a-z0-9][a-z0-9-]{2,63}$/u),oe(e,"version","pack",t,/^[0-9]+\.[0-9]+\.[0-9]+$/u),oe(e,"title","pack",t),oe(e,"description","pack",t),oe(e,"intended_use","pack",t),br(e.approvals,"pack.approvals",t,!1),Fw(e.standing_orders,t),Uw(e.policy_proposals,t),Bw(e.managed_blocks,t),Vw(e.rollback,t),Ww(e.metadata,t),qw(e,t),t):["Policy pack must be an object"]}function Qe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function sm(e){return typeof e=="string"?e:null}function Fw(e,t){if(!Array.isArray(e)){t.push("pack.standing_orders must be an array");return}for(let[r,o]of e.entries()){let n=`pack.standing_orders[${r}]`;if(!Qe(o)){t.push(`${n} must be an object`);continue}kr(o,Ow,n,t),oe(o,"id",n,t,/^[a-z0-9][a-z0-9-]{2,63}$/u),Xn(o,"action",n,["add","propose"],t),Xn(o,"authority",n,["operator-approved","proposal"],t),br(o.allowed,`${n}.allowed`,t,!0),br(o.approval_required,`${n}.approval_required`,t,!0),br(o.scope_projects,`${n}.scope_projects`,t,!0),br(o.scope_hosts,`${n}.scope_hosts`,t,!0),oe(o,"reason",n,t);let a=Array.isArray(o.allowed)?o.allowed:[],s=Array.isArray(o.approval_required)?o.approval_required:[];a.length===0&&s.length===0&&t.push(`${n} must declare at least one allowed or approval_required action`)}}function Uw(e,t){if(!Array.isArray(e)){t.push("pack.policy_proposals must be an array");return}for(let[r,o]of e.entries()){let n=`pack.policy_proposals[${r}]`;if(!Qe(o)){t.push(`${n} must be an object`);continue}kr(o,Nw,n,t),Xn(o,"target",n,["SOUL.md","POLICY.md"],t),oe(o,"summary",n,t),oe(o,"rationale",n,t),oe(o,"rollback_note",n,t)}}function Bw(e,t){if(!Array.isArray(e)){t.push("pack.managed_blocks must be an array");return}for(let[r,o]of e.entries()){let n=`pack.managed_blocks[${r}]`;if(!Qe(o)){t.push(`${n} must be an object`);continue}kr(o,Mw,n,t),oe(o,"target",n,t),oe(o,"marker",n,t),oe(o,"content",n,t),oe(o,"rollback_key",n,t),typeof o.target=="string"&&Jw(o.target,n,t)}}function Vw(e,t){if(!Qe(e)){t.push("pack.rollback must be an object");return}kr(e,Lw,"pack.rollback",t),Xn(e,"strategy","pack.rollback",["proposal-only","managed-block","snapshot-required"],t),br(e.restores,"pack.rollback.restores",t,!0),Array.isArray(e.restores)&&e.restores.length===0&&t.push("pack.rollback.restores must include at least one rollback item"),oe(e,"notes","pack.rollback",t)}function Ww(e,t){if(e!==void 0){if(!Qe(e)){t.push("pack.metadata must be an object");return}kr(e,Dw,"pack.metadata",t);for(let[r,o]of Object.entries(e))o!==null&&typeof o!="string"&&typeof o!="number"&&typeof o!="boolean"&&t.push(`pack.metadata.${r} must be a scalar value`)}}function Jw(e,t,r){let o=e.replaceAll("\\","/"),n=nm.basename(o).toUpperCase();(nm.isAbsolute(e)||o.includes("../")||o.startsWith("../"))&&r.push(`${t}.target must be a relative managed host file path`),Hw.has(n)&&r.push(`${t}.target must not target protected SOUL.md or POLICY.md`),$w.has(o)||r.push(`${t}.target is outside supported managed-block scope`)}function qw(e,t){let r=JSON.stringify(e);/(sk-[A-Za-z0-9_-]{8,}|api[_-]?key\s*[:=]|secret\s*[:=]|token\s*[:=]|password\s*[:=])/iu.test(r)&&t.push("pack must not contain credential-like material"),/https?:\/\//iu.test(r)&&t.push("pack must not require trust in external URLs")}function kr(e,t,r,o){for(let n of Object.keys(e))t.has(n)||o.push(`${r}.${n} is not allowed`)}function oe(e,t,r,o,n){let a=e[t];if(typeof a!="string"||a.trim()===""){o.push(`${r}.${t} must be a non-empty string`);return}n&&!n.test(a)&&o.push(`${r}.${t} has invalid format`)}function Xn(e,t,r,o,n){let a=e[t];(typeof a!="string"||!o.includes(a))&&n.push(`${r}.${t} must be one of ${o.join(", ")}`)}function br(e,t,r,o){e===void 0&&!o||(!Array.isArray(e)||!e.every(n=>typeof n=="string"))&&r.push(`${t} must be an array of strings`)}async function Ki(){return(await im()).map(({pack:t,source:r})=>({id:t.id,version:t.version,title:t.title,description:t.description,intended_use:t.intended_use,source:r})).sort((t,r)=>t.id.localeCompare(r.id))}async function Mo(e){let r=(await im()).find(o=>o.pack.id===e);if(!r)throw new Error(`Policy pack not found: ${e}`);return{...r.pack,source:r.source}}async function Gi(e){try{let{value:t,source:r}=e.file?{value:JSON.parse(await qi(e.file,"utf8")),source:yt.resolve(e.file)}:await zw(e.id),o=vr(t),n=Qe(t)?sm(t.id):null;return{valid:o.length===0,id:n,source:r,errors:o,warnings:[]}}catch(t){return{valid:!1,id:e.id??null,source:e.file?yt.resolve(e.file):null,errors:[t instanceof Error?t.message:"Unknown policy pack validation error"],warnings:[]}}}async function im(){let e=await lm(),t=[];for(let r of e){let o=JSON.parse(await qi(r,"utf8")),n=vr(o);if(n.length>0)throw new Error(`Invalid built-in policy pack ${r}: ${n.join("; ")}`);t.push({pack:o,source:r})}return t}async function zw(e){if(!e)throw new Error("policy packs validate requires <id> or --file <path>");let t=await lm();for(let r of t){let o=JSON.parse(await qi(r,"utf8"));if(Qe(o)&&o.id===e)return{value:o,source:r}}throw new Error(`Policy pack not found: ${e}`)}async function lm(){let e=Yw(),t=(await Gw(e)).filter(r=>r.endsWith(".json")).map(r=>yt.join(e,r)).sort();if(t.length===0)throw new Error(`No policy packs found in ${e}`);return t}function Yw(){let e=yt.dirname(Xw(import.meta.url)),r=[yt.resolve(process.cwd(),"policy-packs"),yt.resolve(e,"../../../policy-packs"),yt.resolve(e,"../../../../policy-packs"),yt.resolve(e,"../../../../../policy-packs")].find(o=>Kw(o));if(!r)throw new Error("Built-in policy pack catalog not found");return r}async function Qi(e){if(e.apply&&!e.reviewed)throw new Error("policy packs apply requires a prior dry-run review; pass --reviewed with --apply after reviewing the plan");let t=await v(e.home),r=await Zw(e),o=_e.resolve(e.targetRoot??process.cwd()),n=new Date().toISOString(),a=await eR({home:t.home,pack:r.pack,targetRoot:o,createdAt:n}),s=a.map(cm),i=a.filter(p=>p.changed),l=fR(r.pack),c=e.apply&&i.length>0?await cR({home:t.home,pack:r.pack,source:r.source,targetRoot:o,files:i,approvalEvidence:e.approvalEvidence??null,createdAt:n}):null;if(e.apply){let p=[];try{for(let g of i)await el(g,"after"),p.push(g)}catch(g){throw await aR(p),await h({home:t.home,type:"policy_pack_apply_failed",result:"error",details:{pack:{id:r.pack.id,version:r.pack.version,source:r.source},targetRoot:o,snapshotPath:c,rolledBackFiles:p.map(y=>cm(y)),error:g instanceof Error?g.message:String(g)}}),g}}let d={pack:{id:r.pack.id,version:r.pack.version,title:r.pack.title,source:r.source},dryRun:!e.apply,applied:e.apply,reviewed:e.reviewed,targetRoot:o,files:s,standingOrderChanges:r.pack.standing_orders.length,policyProposals:r.pack.policy_proposals.length,managedBlocks:r.pack.managed_blocks.length,warnings:l,snapshotRequired:i.length>0,snapshotPath:c};return await h({home:t.home,type:e.apply?"policy_pack_apply":"policy_pack_apply_dry_run",details:hR(d,e.approvalEvidence)}),d}async function Zi(e){let t=await v(e.home),r=sR(await zn(e.snapshotPath,"utf8"),e.snapshotPath),o=r.files.map(a=>nR(a));if(e.apply)for(let a of r.files)await el(a,"before");let n={snapshotPath:e.snapshotPath,pack:{id:r.pack.id,version:r.pack.version},dryRun:!e.apply,applied:e.apply,files:o};return await h({home:t.home,type:e.apply?"policy_pack_rollback":"policy_pack_rollback_dry_run",details:{snapshotPath:e.snapshotPath,pack:n.pack,dryRun:n.dryRun,applied:n.applied,files:n.files}}),n}async function Zw(e){if(e.file){let r=_e.resolve(e.file),o=JSON.parse(await zn(r,"utf8")),n=vr(o);if(n.length>0)throw new Error(`Invalid policy pack ${r}: ${n.join("; ")}`);return{pack:o,source:r}}if(!e.id)throw new Error("policy packs apply requires <id> or --file <path>");let t=await Mo(e.id);return{pack:t,source:t.source}}async function eR(e){let t=[];for(let r of e.pack.standing_orders)t.push(await tR(e.home,e.pack,r));for(let r of e.pack.policy_proposals)t.push(await rR(e.home,e.pack,r,e.createdAt));for(let r of e.pack.managed_blocks)t.push(await oR(e.targetRoot,e.pack,r));return t}async function tR(e,t,r){if(r.action==="add"&&r.authority==="operator-approved"){let n=_e.join(e,"standing-orders",`${r.id}.yaml`);return await Xi("standing_order",n,dR(r,t))}let o=_e.join(e,"proposals",`standing-order-${t.id}-${r.id}.md`);return await Xi("standing_order",o,uR(r,t))}async function rR(e,t,r,o){let n=o.replaceAll(/[:.]/gu,"-"),a=_e.join(e,"proposals",`${n}-${t.id}-${r.target}.md`);return await Xi("policy_proposal",a,pR(r,t,o))}async function oR(e,t,r){let o=_e.resolve(e,r.target);if(!_R(e,o))throw new Error(`Policy pack managed block target escapes target root: ${r.target}`);let n=Yi(o),a=n?await zn(o,"utf8"):null,s=mR(a,t,r);return pm("managed_block",o,n,a,s)}async function Xi(e,t,r){let o=Yi(t),n=o?await zn(t,"utf8"):null;return pm(e,t,o,n,r)}function pm(e,t,r,o,n){let a=o===null?null:A(o),s=n===null?null:A(n),i=o!==n;return{kind:e,targetPath:t,action:i?r?"replace":"create":"noop",changed:i,beforeHash:a,afterHash:s,diff:yR(o,n),beforeExists:r,beforeContent:o,afterContent:n}}function cm(e){return{kind:e.kind,targetPath:e.targetPath,action:e.action,changed:e.changed,beforeHash:e.beforeHash,afterHash:e.afterHash,diff:e.diff}}function nR(e){return{kind:e.kind,targetPath:e.targetPath,action:e.beforeExists?"replace":"remove",changed:!0,beforeHash:e.afterHash,afterHash:e.beforeHash,diff:gm(e.afterHash,e.beforeHash)}}async function el(e,t){let r=t==="before"?e.beforeExists:e.afterHash!==null,o=t==="before"?e.beforeContent:e.afterContent;r&&o!==null?(await dm(_e.dirname(e.targetPath),{recursive:!0,mode:448}),Se(e.targetPath,{allowSymlinkTarget:!0}),await um(e.targetPath,o,{encoding:"utf8",mode:384})):Yi(e.targetPath)&&await Qw(e.targetPath)}async function aR(e){for(let t of[...e].reverse())await el(t,"before")}function sR(e,t){let r;try{r=JSON.parse(e)}catch(n){throw new Error(`Invalid policy pack snapshot ${t}: ${n instanceof Error?n.message:String(n)}`,{cause:n})}let o=iR(r);if(o.length>0)throw new Error(`Invalid policy pack snapshot ${t}: ${o.join("; ")}`);return r}function iR(e){let t=[];if(!zi(e))return["snapshot must be an object"];(typeof e.id!="string"||!e.id)&&t.push("id must be a non-empty string");let r=e.pack;return zi(r)?((typeof r.id!="string"||!r.id)&&t.push("pack.id must be a non-empty string"),(typeof r.version!="string"||!r.version)&&t.push("pack.version must be a non-empty string"),typeof r.source=="string"||r.source===null||t.push("pack.source must be a string or null")):t.push("pack must be an object"),(typeof e.targetRoot!="string"||!e.targetRoot)&&t.push("targetRoot must be a non-empty string"),(typeof e.createdAt!="string"||!e.createdAt)&&t.push("createdAt must be a non-empty string"),typeof e.approvalEvidence=="string"||e.approvalEvidence===null||t.push("approvalEvidence must be a string or null"),Array.isArray(e.files)?e.files.forEach((o,n)=>{t.push(...lR(o,`files[${n}]`))}):t.push("files must be an array"),t}function lR(e,t){let r=[];if(!zi(e))return[`${t} must be an object`];["standing_order","policy_proposal","managed_block"].includes(typeof e.kind=="string"?e.kind:"")||r.push(`${t}.kind is invalid`),(typeof e.targetPath!="string"||!_e.isAbsolute(e.targetPath))&&r.push(`${t}.targetPath must be an absolute path`),["create","replace","noop","remove"].includes(typeof e.action=="string"?e.action:"")||r.push(`${t}.action is invalid`),typeof e.changed!="boolean"&&r.push(`${t}.changed must be boolean`),typeof e.beforeExists!="boolean"&&r.push(`${t}.beforeExists must be boolean`);for(let o of["beforeHash","afterHash","beforeContent","afterContent"])typeof e[o]=="string"||e[o]===null||r.push(`${t}.${o} must be a string or null`);return typeof e.diff!="string"&&r.push(`${t}.diff must be a string`),r}function zi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function cR(e){let t=_e.join(e.home,"backups","policy-packs");await dm(t,{recursive:!0,mode:448});let r={id:T("policy_pack_snapshot"),pack:{id:e.pack.id,version:e.pack.version,source:e.source},targetRoot:e.targetRoot,createdAt:e.createdAt,files:e.files,approvalEvidence:e.approvalEvidence},o=`${e.createdAt.replaceAll(/[:.]/gu,"-")}-${e.pack.id}.json`,n=_e.join(t,o);return await um(n,JSON.stringify(r,null,2),{encoding:"utf8",mode:384,flag:"wx"}),n}function dR(e,t){return[`id: ${e.id}`,`source: policy-pack:${t.id}@${t.version}`,`allowed: ${JSON.stringify(e.allowed)}`,`approval_required: ${JSON.stringify(e.approval_required)}`,`scope_projects: ${JSON.stringify(e.scope_projects)}`,`scope_hosts: ${JSON.stringify(e.scope_hosts)}`,`reason: ${JSON.stringify(e.reason)}`,""].join(`
|
|
1045
|
+
`)}function uR(e,t){return["# Standing Order Proposal","",`Policy Pack: ${t.id}@${t.version}`,`Standing Order: ${e.id}`,`Action: ${e.action}`,`Authority: ${e.authority}`,"","## Allowed","",...e.allowed.map(r=>`- ${r}`),"","## Approval Required","",...e.approval_required.map(r=>`- ${r}`),"","## Reason","",e.reason,""].join(`
|
|
1046
|
+
`)}function pR(e,t,r){return["# Policy Pack Proposal","",`Policy Pack: ${t.id}@${t.version}`,`Target: ${e.target}`,`Created At: ${r}`,"","## Summary","",e.summary,"","## Rationale","",e.rationale,"","## Rollback Note","",e.rollback_note,""].join(`
|
|
1047
|
+
`)}function mR(e,t,r){let o=gR(t,r);if(e===null||e.length===0)return o;let n=mm(t,r),a=e.indexOf(n.start),s=e.indexOf(n.end);if(a>=0&&s>a){let l=s+n.end.length,c=e.slice(l).replace(/^\n/u,"");return`${e.slice(0,a)}${o}${c}`}let i=e.endsWith(`
|
|
1048
1048
|
`)?`
|
|
1049
1049
|
`:`
|
|
1050
1050
|
|
|
1051
|
-
`;return`${e}${i}${o}`}function
|
|
1051
|
+
`;return`${e}${i}${o}`}function gR(e,t){let r=mm(e,t),o=t.content.endsWith(`
|
|
1052
1052
|
`)?t.content:`${t.content}
|
|
1053
1053
|
`;return`${r.start}
|
|
1054
1054
|
${o}${r.end}
|
|
1055
|
-
`}function
|
|
1056
|
-
`)}function
|
|
1055
|
+
`}function mm(e,t){return{start:`<!-- nativesoul:policy-pack:${e.id}:${t.marker}:start v1 -->`,end:`<!-- nativesoul:policy-pack:${e.id}:${t.marker}:end -->`}}function fR(e){let t=[];return e.policy_proposals.length>0&&t.push("Protected SOUL.md/POLICY.md changes are written as proposals only."),e.standing_orders.some(r=>r.authority==="proposal"||r.action==="propose")&&t.push("Proposal-only standing orders are written to proposals/ and do not change authority automatically."),t}function hR(e,t){return{pack:e.pack,dryRun:e.dryRun,applied:e.applied,reviewed:e.reviewed,targetRoot:e.targetRoot,snapshotPath:e.snapshotPath,approvalEvidence:t??null,files:e.files,warnings:e.warnings}}function yR(e,t){return e===t?"No changes.":gm(e===null?null:A(e),t===null?null:A(t),e===null?0:e.split(/\r?\n/u).length,t===null?0:t.split(/\r?\n/u).length)}function gm(e,t,r=0,o=0){return[`before: ${e??"missing"}`,`after: ${t??"missing"}`,`lines_before: ${r}`,`lines_after: ${o}`].join(`
|
|
1056
|
+
`)}function _R(e,t){let r=_e.relative(e,t);return r===""||!r.startsWith("..")&&!_e.isAbsolute(r)}import bR from"node:path";async function wr(e={}){let t=f(e.home),r=e.host??"all",[o,n,a,s]=await Promise.all([lt(t.home),S(En(t.home)),S(nr(t.home)),Ut({home:t.home,host:r,surface:e.surface,targetRoot:e.targetRoot})]);return Ds({home:t.home,targetRoot:e.targetRoot?bR.resolve(e.targetRoot):null,host:r,profile:o,onboardingComplete:n,activationComplete:a,hosts:s.hosts})}async function Lo(e={}){let t=await wr(e);if(!e.profile||t.profile?.profile===e.profile)return t;let r={...t.profile??Sn,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]}}var vR=["codex","claude","antigravity","gemini","grok"];async function Yn(e={}){let t=await v(e.home),r=await lt(t.home),o=e.leaderHost??ER(r?.scheduler_host),n=o??e.host??"all",a=kR({cadence:e.cadence??r?.heartbeat_cadence,projectScope:e.projectScope??L(process.cwd(),t.home),behavior:e.behavior,mode:e.mode}),s=await wR({home:t.home,host:n,surface:e.surface,mode:a.mode,heartbeat:hm(a),targetRoot:e.targetRoot}),i=RR(s,o),l=i?[]:s.length===0?["HEARTBEAT_NO_HOSTS_EVALUATED"]:["HEARTBEAT_NATIVE_SCHEDULER_BLOCKED_BY_HOST"];return{dry_run:!0,action:i?"recommend":"blocked_by_host",recommended_leader:i?{host:i.host,surface:i.surface,native_id:i.native_id??""}:null,profile:a,candidates:s,warnings:l}}async function tl(e={}){let t=await v(e.home),r=e.dry_run!==!1,o=e.user_confirmed===!0,n=await Yn({...e,home:t.home}),a=n.recommended_leader?n.candidates.find(i=>i.host===n.recommended_leader?.host&&i.surface===n.recommended_leader.surface)?.dry_run??null:null;if(!n.recommended_leader)return{dry_run:r,applied:!1,user_confirmed:o,action:"blocked_by_host",plan:n,dry_run_reconcile:a,applied_reconcile:null,warnings:n.warnings};if(r)return{dry_run:!0,applied:!1,user_confirmed:o,action:"planned",plan:n,dry_run_reconcile:a,applied_reconcile:null,warnings:[]};if(!o)return{dry_run:!1,applied:!1,user_confirmed:!1,action:"rejected",plan:n,dry_run_reconcile:a,applied_reconcile:null,warnings:["HEARTBEAT_ACTIVATION_REQUIRES_USER_CONFIRMED"]};let s=await mt({home:t.home,host:n.recommended_leader.host,surface:n.recommended_leader.surface,mode:n.profile.mode,apply:!0,heartbeat:hm(n.profile),hostConfigRoot:ze(n.recommended_leader.host,e.targetRoot),targetRoot:e.targetRoot});return await h({home:t.home,type:"activation.heartbeat.applied",details:{host:n.recommended_leader.host,surface:n.recommended_leader.surface,mode:n.profile.mode,cadence:n.profile.cadence,project_scope:n.profile.project_scope,native_schedule_supported:s.schedule.native_schedule_supported,native_id:s.schedule.native_id}}),{dry_run:!1,applied:!0,user_confirmed:!0,action:"applied",plan:n,dry_run_reconcile:a,applied_reconcile:s,warnings:s.warnings}}function kR(e){return{cadence:e.cadence??"daily",skip_when_busy:!0,project_scope:e.projectScope??"current-project",behavior:e.behavior??"read_only",mode:e.mode??"leader",silent_ack:"HEARTBEAT_OK",hidden_fallback_scheduler:!1}}async function wR(e){let t=[];for(let r of Je(e.host))for(let o of Ke(r,e.surface)){let n=await mt({home:e.home,host:r,surface:o,mode:e.mode,apply:!1,heartbeat:e.heartbeat,hostConfigRoot:ze(r,e.targetRoot),targetRoot:e.targetRoot});t.push({host:r,surface:o,status:SR(n),native_schedule_supported:n.schedule.native_schedule_supported,native_id:n.schedule.native_id,reason:AR(n),dry_run:n})}return t}function RR(e,t){let r=e.filter(o=>o.status==="supported"&&o.native_id);return t?r.find(o=>o.host===t)??null:r.sort((o,n)=>fm(o)-fm(n))[0]??null}function fm(e){let t=vR.indexOf(e.host),r=e.surface==="claude-desktop"?-.25:e.surface==="claude-code"?0:.25;return(t===-1?99:t)+r}function SR(e){return e.adapter_result.status==="ok"&&e.schedule.native_schedule_supported&&e.schedule.native_id?"supported":e.adapter_result.status==="degraded"?"degraded":"blocked_by_host"}function AR(e){switch(e.adapter_result.status){case"ok":return"native_scheduler_supported";case"degraded":return e.adapter_result.reason;case"unsupported":return e.adapter_result.reason;case"error":return e.adapter_result.message}}function hm(e){return{cadence:e.cadence,skipWhenBusy:e.skip_when_busy,projectScope:e.project_scope,behavior:e.behavior}}function ER(e){return e==="codex"||e==="claude"||e==="grok"||e==="antigravity"||e==="gemini"?e:null}import{randomUUID as PR}from"node:crypto";import xR from"node:path";var jR="NativeSoul activation verification marker";async function Do(e={}){let t=OR(e),r=te(t.projectCwd,e.home),o=await Ut({home:e.home,host:e.host??"all",surface:e.surface,targetRoot:e.targetRoot}),n=[];for(let c of o.hosts)n.push(await IR({home:o.home,inputHost:c,testCwd:t.projectCwd}));let a=await CR({home:e.home,testProject:`${r.id}-${PR()}`,apply:e.apply===!0,userConfirmed:e.userConfirmed===!0,retainTestData:e.retainTestData===!0}),s=[...new Set([...n.flatMap(c=>c.recommendations),...a.status==="failed"?["Review memory persistence and rerun verification."]:[]])],i=n.map(c=>c.status),l=MR(i,a.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:a,hosts:n,recommendations:s}}async function IR(e){let t=[],r=await TR({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=NR(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 s=e.inputHost.provider_parity.heartbeat==="unsupported-native"&&e.inputHost.host!=="codex"?"blocked_by_host":r.status==="failed"||r.status==="degraded"||r.cache.status==="degraded"||r.cache.status==="missing"||!e.inputHost.plugin.enabled?"degraded":"ready";return{host:e.inputHost.host,surface:e.inputHost.surface,status:s,mcp:{configured:e.inputHost.mcp_registration.configured,issues:e.inputHost.mcp_registration.issues.map(i=>i.message)},bootstrap:r,heartbeat:{status:o,requirements:n},recommendations:t}}async function TR(e){let t=[...e.warnings],r=[],o="ready",n=!1,a="",s="ready";try{let i=await it({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")&&(s="degraded")}catch(i){t.push(`bootstrap_injection_failed:${rl(i)}`),s="failed"}try{let i=await Is({home:e.home,host:e.host,projectCwd:e.cwd,recordTelemetry:!1});a=i.targetPath,n=i.stale,r.push(...i.warnings),r.length>0&&(o=i.warnings.some(l=>l==="BOOTSTRAP_CACHE_MISSING")?"missing":"degraded",s==="ready"&&(s="degraded"))}catch{r.push("bootstrap_cache_check_failed"),o="missing",s==="ready"&&(s="degraded")}return{status:s,warnings:t,cache:{status:o,warnings:r,targetPath:a,stale:n}}}async function CR(e){let t=[],r=null,o=!1,n=!1;try{let a=`verify-${e.testProject}`,s=`${jR} ${e.testProject}`;r=await ie(e.home,{project:a,content:s,confidence:.91,source:{host:"activation-verification",session_id:`verification-${e.testProject}`}});let i=await Tt(e.home,s,a,8),l=await It({home:e.home,project:a,status:"candidate",limit:8}),c=i.some(d=>d.id===r?.id)||l.some(d=>d.id===r?.id);if(e.apply&&e.userConfirmed&&r){let d=await Pt(e.home,r.id);r=d,n=r.id===d.id&&r.status==="active"}if(!e.retainTestData&&r)try{r.status==="candidate"?await xt(e.home,r.id):await jt(e.home,r.id),o=!0}catch(d){t.push(`memory_cleanup_failed:${rl(d)}`)}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(a){return t.push(`memory_recall_check_failed:${rl(a)}`),{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 OR(e){return{projectCwd:xR.resolve(e.projectCwd??process.cwd())}}function NR(e){return e==="native"?"native":e==="official-fallback"?"official_fallback":"unsupported"}function MR(e,t){return e.includes("blocked_by_host")?"blocked_by_host":e.includes("degraded")||t==="failed"?"degraded":e.length>0?"ready":"degraded"}function rl(e){return e instanceof Error?e.message:String(e)}async function ym(e){let t=await v(e),r=_(t.database);try{r.integrityCheck()}finally{r.close()}return await h({home:t.home,type:"workspace_initialized",details:{createdDirectories:t.createdDirectories.length,createdFiles:t.createdFiles.length,preservedFiles:t.preservedFiles.length}}),t}function Qn(e){let t=f(e);if(!LR(t.database))return{home:t.home,initialized:!1,database:t.database,migrations:0,memories:0,events:0,capabilities:0,ledger:DR()};let r=_(t.database,{readOnly:!0});try{return{home:t.home,initialized:!0,database:t.database,...r.counts()}}finally{r.close()}}function DR(){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}}function m(e,t,r){t?process.stdout.write(`${JSON.stringify(HR(e),null,2)}
|
|
1057
1057
|
`):process.stdout.write(`${r}
|
|
1058
|
-
`)}function
|
|
1059
|
-
`)}function
|
|
1060
|
-
`)}async function
|
|
1058
|
+
`)}function HR(e){return e===void 0?null:JSON.parse(JSON.stringify(e))}async function Ho(){if(process.stdin.isTTY)return"";let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function $o(e){let t=e.trim();if(t.length!==0)try{return JSON.parse(t)}catch{return t}}function _m(e){if(typeof e=="string")return e;if(!e||Array.isArray(e)||typeof e!="object")return"";for(let t of["prompt","user_prompt","message","text","content"]){let r=e[t];if(typeof r=="string")return r}return""}function ol(e){if(e[0]==="--help"||e[0]==="-h")return{command:"help",rest:[],flags:new Map([["help",!0]])};let[t,...r]=e,o=[],n=new Map;for(let a=0;a<r.length;a+=1){let s=r[a];if(s)if(s==="-h")n.set("help",!0);else if(s.startsWith("--")){let i=s.slice(2),l=r[a+1];l&&!l.startsWith("--")?(n.set(i,l),a+=1):n.set(i,!0)}else o.push(s)}return{command:t,rest:o,flags:n}}function nl(e){return e.command==="help"||b(e.flags,"help")}function b(e,t){return e.get(t)===!0}function u(e,t){let r=e.get(t);return typeof r=="string"?r:void 0}function E(e,t){let r=u(e,t);if(!r)return;let o=Number(r);return Number.isFinite(o)?o:void 0}var Rr=new Set(["codex","claude","grok","antigravity","gemini"]);function Fo(e){let t=u(e,"host")??"all";if(t==="all"||Rr.has(t))return t;throw new Error(`Unsupported adapter host: ${t}`)}function bm(e){let t=u(e,"host");if(t&&Rr.has(t))return t;throw new Error("This command requires --host codex|claude|grok|antigravity|gemini")}function Ze(e){if(b(e,"all-hosts"))return"all";let t=u(e,"host")??"all";if(t==="all"||Rr.has(t))return t;throw new Error(`Unsupported install host: ${t}`)}function je(e){let t=u(e,"surface");if(t!==void 0){if(t==="desktop"||t==="claude-desktop")return"claude-desktop";if(t==="claude-code")return"claude-code";throw new Error("install surface must be claude-code, desktop, or claude-desktop")}}function Uo(e){let t=u(e,"host");if(t&&Rr.has(t))return t;throw new Error("This command requires --host codex|claude|grok|antigravity|gemini")}function Bo(e){let t=u(e,"host");if(t!==void 0){if(Rr.has(t))return t;throw new Error("This command accepts --host codex|claude|grok|antigravity|gemini")}}function vm(e){let t=u(e,"result");if(t!==void 0){if(t==="ok"||t==="error"||t==="blocked")return t;throw new Error("audit --result must be ok, error, or blocked")}}function km(e){let t=u(e,"status");if(t!==void 0){if(t==="pending"||t==="approved"||t==="rejected")return t;throw new Error("approvals --status must be pending, approved, or rejected")}}function wm(e){let t=u(e,"format")??"json";if(t==="json"||t==="jsonl")return t;throw new Error("audit export --format must be json or jsonl")}function Rm(e){let t=u(e,"status");if(t!==void 0){if(t==="open"||t==="completed"||t==="dismissed"||t==="expired")return t;throw new Error("commitments --status must be open, completed, dismissed, or expired")}}function Zn(e){let t=u(e,"status");if(t!==void 0){if(t==="inbox"||t==="assigned"||t==="in_progress"||t==="review"||t==="blocked"||t==="done"||t==="failed")return t;throw new Error("work --status must be inbox, assigned, in_progress, review, blocked, done, or failed")}}function ea(e){let t=u(e,"priority");if(t!==void 0){if(t==="low"||t==="normal"||t==="high"||t==="urgent")return t;throw new Error("work --priority must be low, normal, high, or urgent")}}function al(e,t){let r=u(e,t);if(r!==void 0)return r.split(",").map(o=>o.trim()).filter(Boolean)}function Sm(e){let t=u(e,"status");if(t!==void 0){if(t==="active"||t==="archived"||t==="forgotten"||t==="all")return t;throw new Error("project list --status must be active, archived, forgotten, or all")}}function Am(e){let t=u(e,"class");if(t==="read_local"||t==="probe_external"||t==="write_local"||t==="write_project"||t==="external_write"||t==="destructive"||t==="identity_policy_change")return t;throw new Error("policy evaluate requires --class read_local|probe_external|write_local|write_project|external_write|destructive|identity_policy_change")}function ta(e){let t=u(e,"mode")??"leader";if(t==="leader"||t==="federated"||t==="per-project")return t;throw new Error("schedule --mode must be leader, federated, or per-project")}function Em(e){let t=u(e,"host")??"generic";if(t==="generic"||Rr.has(t))return t;throw new Error(`Unsupported MCP manifest host: ${t}`)}function sl(e){return Uo(e)}function il(e){let t=u(e,"command-mode")??"package";if(t==="package"||t==="local"||t==="absolute")return t;throw new Error(`Unsupported MCP command mode: ${t}`)}function Pm(e){let t=u(e,"format")??"json";if(t==="json"||t==="inject"||t==="cache")return t;throw new Error("bootstrap --format must be json, inject, or cache")}async function ll(e,t,r){let o=e.rest[0]??"status",n={home:t,host:Ze(e.flags),surface:je(e.flags),targetRoot:u(e.flags,"target-root")};if(o==="status"){let a=await wr(n);m(a,r,`Activation status: ${a.overall_status}`);return}if(o==="plan"){let a=await Lo({...n,profile:$R(e)});m(a,r,`Activation plan: ${a.plan.length} dry-run action(s)`);return}if(o==="heartbeat"){let a=e.rest[1]??"plan",s={home:t,host:Ze(e.flags),surface:je(e.flags),targetRoot:u(e.flags,"target-root"),leaderHost:FR(e),mode:ta(e.flags),cadence:u(e.flags,"cadence"),projectScope:u(e.flags,"project")??u(e.flags,"project-scope"),behavior:UR(e),user_confirmed:b(e.flags,"user-confirmed")};if(a==="plan"){let i=await Yn(s);m(i,r,i.recommended_leader?`Heartbeat leader recommended: ${i.recommended_leader.host}`:"Heartbeat native scheduler blocked by host");return}if(a==="apply"){let i=await tl({...s,dry_run:!b(e.flags,"apply")});m(i,r,i.applied?"Heartbeat activation applied":`Heartbeat activation ${i.action}`);return}throw new Error("activate heartbeat requires plan or apply")}throw new Error("activate requires status, plan, or heartbeat")}function $R(e){let t=u(e.flags,"profile");if(t!==void 0){if(t==="quickstart"||t==="advanced")return t;throw new Error("activate plan requires --profile quickstart|advanced")}}function FR(e){let t=u(e.flags,"leader-host");if(t!==void 0){if(t==="codex"||t==="claude"||t==="grok"||t==="antigravity"||t==="gemini")return t;throw new Error("activate heartbeat requires --leader-host codex|claude|grok|antigravity|gemini")}}function UR(e){let t=u(e.flags,"behavior");if(t!==void 0){if(t==="read_only"||t==="approval_required")return t;throw new Error("activate heartbeat requires --behavior read_only|approval_required")}}async function cl(e,t){let r=e.rest[0],o=Fo(e.flags);if(r==="hot-scan"){let n=await At({home:u(e.flags,"home"),host:o,delta:b(e.flags,"delta"),ttlSeconds:E(e.flags,"ttl-seconds")}),a=n.reduce((s,i)=>s+i.count,0);m(n,t,`Hot-scanned ${a} capability record(s)`);return}if(r==="scan"){let n=await Mr(o);m(n,t,`Scanned ${n.length} adapter(s)`);return}if(r==="doctor"){let n=await Lr(o),a=n.reduce((s,i)=>s+i.diagnostics.length,0);m(n,t,`Adapter doctor found ${a} diagnostic(s)`);return}if(r==="managed-block"){let n=bm(e.flags),a=await Dr(n);m(a,t,`Managed block preview for ${a.host}: ${a.targetPath}`);return}if(r==="install-managed-block"){let n=Uo(e.flags),a=await Hr({home:u(e.flags,"home"),host:n,apply:b(e.flags,"apply"),targetPath:u(e.flags,"target")});m(a,t,`${a.dryRun?"Planned":"Applied"} managed block for ${a.host}: ${a.action}`);return}if(r==="rollback-managed-block"){let n=u(e.flags,"snapshot");if(!n)throw new Error("adapters rollback-managed-block requires --snapshot <path>");let a=await rs({home:u(e.flags,"home"),snapshotPath:n,apply:b(e.flags,"apply")});m(a,t,`${a.dryRun?"Planned rollback":"Rolled back"} managed block target ${a.targetPath}`);return}throw new Error("adapters requires scan, hot-scan, doctor, or managed-block")}async function dl(e,t,r){let o=e.rest[0];if(o==="list"){let n=Gn({home:t,status:km(e.flags)});m(n,r,VR(n.approvals,n.warning));return}if(o==="show"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("approvals show requires <id|.>");let a=n==="."?BR(t):Kn({home:t,id:n}).approval;m(a,r,a?WR(a):`Approval not found: ${n}`),a||(process.exitCode=1);return}if(o==="approve"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("approvals approve requires <id>");let a=Kn({home:t,id:n}).approval;if(!a){m({approval:null,applied:!1,action:"approve",warning:"approval_not_found"},r,`Approval not found: ${n}`),process.exitCode=1;return}if(!b(e.flags,"confirm")){m({approval:a,applied:!1,action:"approve",warning:"requires --confirm"},r,`Approval approve dry-run: ${a.id} (${a.action}); rerun with --confirm to apply.`);return}let s=await _r({home:t,id:n,status:"approved",reviewer:"cli",reason:u(e.flags,"reason")??null});m(s.approval,r,s.approval?`Approval approved: ${s.approval.id}`:`Approval not found: ${n}`),s.approval||(process.exitCode=1);return}if(o==="reject"){let n=e.rest[1]??u(e.flags,"id"),a=u(e.flags,"reason");if(!n||!a)throw new Error("approvals reject requires <id> --reason <text>");let s=await _r({home:t,id:n,status:"rejected",reviewer:"cli",reason:a});m(s.approval,r,s.approval?`Approval rejected: ${s.approval.id}`:`Approval not found: ${n}`),s.approval||(process.exitCode=1);return}throw new Error("approvals requires list, show, approve, or reject")}function BR(e){return Gn({home:e,status:"pending"}).approvals[0]??null}function VR(e,t){return t?`Approvals unavailable: ${t}`:e.length===0?"No approvals found":[`${e.length} approval(s)`,...e.map(r=>`${r.id} ${r.action} ${r.class} ${r.target??"-"} ${r.status} ${r.reviewer??"-"} ${r.created_at}`)].join(`
|
|
1059
|
+
`)}function WR(e){return[`Approval ${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: ${e.created_at}`,`Decided: ${e.decided_at??"-"}`].join(`
|
|
1060
|
+
`)}async function ul(e,t,r){let o=e.rest[0],n={home:t,type:u(e.flags,"type"),result:vm(e.flags),limit:E(e.flags,"limit")};if(o==="list"){let a=await Zo(n);m(a,r,`${a.length} audit event(s)`);return}if(o==="export"){let a=wm(e.flags),s=await La({...n,format:a});if(a==="jsonl"){process.stdout.write(s.events.map(i=>JSON.stringify(i)).join(`
|
|
1061
1061
|
`)),s.events.length>0&&process.stdout.write(`
|
|
1062
1062
|
`);return}process.stdout.write(`${JSON.stringify(s.events,null,2)}
|
|
1063
|
-
`);return}throw new Error("audit requires list or export")}async function
|
|
1064
|
-
`)}function
|
|
1065
|
-
`)}async function wl(e,t,r){let o=await wi({page:u(e.flags,"page")});m(o,r,o.ok?`Marketing audit PASS: ${o.summary.claims_checked} claim(s), ${o.summary.pages_scanned} page(s)`:`Marketing audit FAIL: ${o.issues.length} issue(s)`),o.ok||(process.exitCode=1)}var Sm={life_activation_status:async(e,t)=>await wr({home:t,host:Rl(e.host),targetRoot:_t(e.target_root)??_t(e.targetRoot)}),life_activation_plan:async(e,t)=>await Lo({home:t,host:Rl(e.host),targetRoot:_t(e.target_root)??_t(e.targetRoot),profile:QR(e.profile)}),life_activation_verify:async(e,t)=>await Do({home:t,host:Rl(e.host),surface:ZR(e.surface),targetRoot:_t(e.target_root)??_t(e.targetRoot),projectCwd:_t(e.project_cwd)??_t(e.projectCwd),apply:Sl(e.apply),userConfirmed:Sl(e["user-confirmed"]),retainTestData:Sl(e["retain-test-data"])})},Am=[{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 Rl(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 QR(e){if(e!==void 0){if(e==="quickstart"||e==="advanced")return e;throw new Error("Invalid activation profile")}}function ZR(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 _t(e){return typeof e=="string"?e:void 0}function Sl(e){return e===!0}var eS=["2025-11-25","2024-11-05","2024-10-07"],Im={...Sm,life_status:(e,t)=>Qn(t),life_bootstrap:async(e,t)=>await sS({home:t,host:C(e.host,"codex"),cwd:C(e.cwd,process.cwd()),query:F(e.query)}),life_recall:async(e,t)=>await Tt(t,C(e.query,""),C(e.project,"default"),oa(e.limit,5)),life_remember_propose:async(e,t)=>await ie(t,{project:C(e.project,"default"),content:C(e.content,""),type:F(e.type),confidence:Em(e.confidence),source:{host:"mcp",session_id:"local"}}),life_memory_promote:async(e,t)=>await Pt(t,C(e.id,"")),life_memory_reject:async(e,t)=>await xt(t,C(e.id,"")),life_memory_forget:async(e,t)=>await jt(t,C(e.id,"")),life_memory_expire:async(e,t)=>await zr(t,C(e.id,"")),life_capability_search:async(e,t)=>await Ur({home:t,query:C(e.query,""),host:cS(e)?void 0:F(e.host)??"codex",readyOnly:Sr(e.readyOnly,!1),limit:oa(e.limit,8)}),life_capability_status:async(e,t)=>{let r=C(e.uid,""),o=r?await Br({home:t,uid:r}):null;if(!o)throw new Error(`Capability not found: ${r}`);return o},life_policy_evaluate:async(e,t)=>await ht({home:t,action:C(e.action,""),className:jm(e.class),target:F(e.target)}),life_approval_request:async(e,t)=>await mS({home:t,action:C(e.action,""),className:jm(e.class),target:F(e.target),project:F(e.project),host:F(e.host)}),life_approval_decide:async(e,t)=>{let r=C(e.id,""),o=await _r({home:t,id:r,status:pS(e.status),reviewer:C(e.host,"mcp"),reason:F(e.reason)??null});if(!o.approval)throw new Error(`Approval not found: ${r}`);return o},life_commitment_create:async(e,t)=>await Vr({home:t,project:C(e.project,"default"),summary:C(e.summary,""),dueAt:F(e.due_at),ttlSeconds:Em(e.ttl_seconds),source:{host:"mcp",session_id:"local"}}),life_commitment_complete:async(e,t)=>await Jr(t,C(e.id,"")),life_work_item_create:async(e,t)=>await Ao({home:t,project:C(e.project,"default"),title:C(e.title,""),description:F(e.description),priority:Al(e.priority),source:"mcp",tags:Pm(e.tags),host:F(e.host)}),life_work_item_list:async(e,t)=>await Eo({home:t,project:F(e.project),status:xm(e.status),priority:Al(e.priority),assignedHost:F(e.host),limit:oa(e.limit,50)}),life_work_item_claim:async(e,t)=>await Po({home:t,id:C(e.id,""),host:C(e.host,"mcp")}),life_work_item_update:async(e,t)=>await xo({home:t,id:C(e.id,""),status:xm(e.status),priority:Al(e.priority),assignedHost:F(e.host),description:F(e.description),tags:e.tags===void 0?void 0:Pm(e.tags)}),life_work_item_complete:async(e,t)=>await jo({home:t,id:C(e.id,""),status:lS(e.status)}),life_heartbeat_claim:async(e,t)=>await Co({home:t,slot:C(e.slot,""),host:C(e.host,"codex"),project:C(e.project,"default"),ttlSeconds:oa(e.ttl_seconds,1500)}),life_heartbeat_complete:async(e,t)=>await Oo({home:t,slot:C(e.slot,""),host:C(e.host,"codex"),project:C(e.project,"default"),result:e.result??"HEARTBEAT_OK",evidence:e.evidence??{},workItemId:F(e.work_item_id)}),life_onboarding_status:async(e,t)=>await oo(t),life_onboard_apply:async(e,t)=>await no({home:t,dry_run:Sr(e.dry_run,!0),user_confirmed:Sr(e.user_confirmed,!1),files:dS(e.files),config_patch:uS(e.config_patch)}),life_onboard_complete:async(e,t)=>await ao({home:t,archive:e.archive===void 0?!0:Sr(e.archive,!0)})},tS=new Set(Object.keys(Im));function rS(e){return e.method?.startsWith("notifications/")?!0:!Object.prototype.hasOwnProperty.call(e,"id")}async function na(e,t){if(rS(e))return null;let r=e.id??null;try{if(e.method==="initialize"){let o=Wo(e.params),n=F(o.protocolVersion),a=n&&eS.includes(n)?n:"2024-11-05";return et(r,{protocolVersion:a,serverInfo:{name:"nativesoul",version:"0.1.0"},capabilities:{tools:{}}})}if(e.method==="ping")return et(r,{});if(e.method==="resources/list")return et(r,{resources:[]});if(e.method==="prompts/list")return et(r,{prompts:[]});if(e.method==="tools/list")return et(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"}},...Am,{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 pr(t);if(!o.ok)return et(r,o);let n=iS(e.params);return et(r,await nS(n.name??"",n.arguments??{},t))}if(tS.has(e.method)){let o=await pr(t);return o.ok?et(r,await Cm(e.method,Wo(e.params),t)):et(r,o)}return ra(r,-32601,`Unknown method: ${e.method}`)}catch(o){return o instanceof Et?ra(r,-32010,o.message,{code:o.code,id:o.id,from:o.from,to:o.to}):o instanceof Ce?ra(r,-32011,o.message,{code:o.code,id:o.id,status:o.status}):ra(r,-32603,o instanceof Error?o.message:"Unknown MCP error")}}async function Tm(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 a=n.trim();a&&oS(a,e).catch(s=>{process.stderr.write(`NativeSoul MCP response error: ${gS(s)}
|
|
1066
|
-
`)})}})}async function
|
|
1063
|
+
`);return}throw new Error("audit requires list or export")}async function pl(e,t,r){let o=e.rest[0];if(o==="refresh"){let n=await At({home:t,host:Fo(e.flags),delta:b(e.flags,"delta"),ttlSeconds:E(e.flags,"ttl-seconds")}),a=n.reduce((s,i)=>s+i.count,0);m(n,r,`Refreshed ${a} capability record(s)`);return}if(o==="learn"){let n=await ss({home:t,host:Fo(e.flags),limit:E(e.flags,"limit")});m(n,r,`Learned ${n.generated} capability card(s), changed ${n.changed}`);return}if(o==="list"){let n=await Ae({home:t,host:Bo(e.flags),readyOnly:b(e.flags,"ready-only"),limit:E(e.flags,"limit")});m(n,r,`${n.length} capability record(s)`);return}if(o==="search"){let n=e.rest.slice(1).join(" ")||(u(e.flags,"query")??""),a=await Ur({home:t,query:n,host:b(e.flags,"all-hosts")?void 0:Bo(e.flags)??"codex",readyOnly:b(e.flags,"ready-only"),limit:E(e.flags,"limit")});m(a,r,`${a.length} capability record(s) found`);return}if(o==="show"){let n=e.rest[1]??u(e.flags,"uid");if(!n)throw new Error("capabilities show requires <uid> or --uid <uid>");let a=await Br({home:t,uid:n});if(!a)throw new Error(`Capability not found: ${n}`);m(a,r,`Capability ${a.uid}: ready=${a.ready}`);return}throw new Error("capabilities requires refresh, learn, list, search, or show")}async function ml(e,t,r){let o=e.rest[0];if(o==="create"){let n=u(e.flags,"summary")??u(e.flags,"text");if(!n)throw new Error("commitments create requires --summary <text>");let a=u(e.flags,"project")??L(process.cwd(),t),s=await Vr({home:t,project:a,summary:n,dueAt:u(e.flags,"due-at")??null,ttlSeconds:E(e.flags,"ttl-seconds")});m(s,r,s.created?`Commitment created: ${s.commitment.id}`:`Commitment deduped: ${s.commitment.id}`);return}if(o==="list"){let n=await Wr({home:t,project:u(e.flags,"project"),status:Rm(e.flags),includeExpired:b(e.flags,"include-expired"),limit:E(e.flags,"limit")});m(n,r,`${n.length} commitment(s)`);return}if(o==="complete"||o==="dismiss"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error(`commitments ${o} requires <id> or --id <id>`);let a=o==="complete"?await Jr(t,n):await is(t,n);m(a,r,`Commitment ${o}d: ${a.id}`);return}throw new Error("commitments requires create, list, complete, or dismiss")}async function hl(e,t,r){let o=u(e.flags,"project")??te(process.cwd(),t).id,n=Io({home:t,project:o,host:u(e.flags,"host"),since:u(e.flags,"since"),until:u(e.flags,"until"),groupBy:JR(e.flags),limit:E(e.flags,"limit")});m(n,r,qR(n))}function JR(e){let t=u(e,"group-by");if(t===void 0)return"total";if(t==="project"||t==="host"||t==="day")return t;throw new Error("cost --group-by must be project, host, or day")}function qR(e){let t=[`NativeSoul cost report (${e.filters.group_by})`,`Project: ${e.filters.project??"all"}`,`Host: ${e.filters.host??"all"}`,`Window: ${e.filters.since??"beginning"} -> ${e.filters.until??"now"}`,`Total reported: ${gl(e.totals)}`,`Coverage: ${fl(e.totals.reported_runs,e.totals.total_runs)}`],r=e.groups.length>0?e.groups:e.by_host;if(r.length>0){t.push("Groups:");for(let o of r)t.push(`- ${o.label}: ${gl(o)} (${fl(o.reported_runs,o.total_runs)})`)}if(e.by_session.length>0){t.push("Sessions:");for(let o of e.by_session)t.push(`- ${o.label}: ${gl(o)} (${fl(o.reported_runs,o.total_runs)})`)}return t.join(`
|
|
1064
|
+
`)}function gl(e){return e.cost_reported_runs===0?"not reported by host":KR(e.total_usd)}function fl(e,t){let r=t===0?0:Math.round(e/t*100);return`${e}/${t} reported (${r}%)`}function KR(e){return`$${e.toFixed(2)}`}async function yl(e,t,r){let o=e.rest[0];if(o==="data"){let n=GR(e.flags),a=await To({home:t,project:u(e.flags,"project"),host:u(e.flags,"host"),limit:E(e.flags,"limit"),since:u(e.flags,"since"),until:u(e.flags,"until")});m(n?XR(a,n):a,r,`Dashboard data ready: ${a.initialized?"initialized":"not initialized"}`);return}if(o==="viewer"){let n=await Mi({home:t,project:u(e.flags,"project"),host:u(e.flags,"host"),limit:E(e.flags,"limit"),since:u(e.flags,"since"),until:u(e.flags,"until"),output:u(e.flags,"output")});m(n,r,`Dashboard viewer written: ${n.outputPath}`);return}throw new Error("dashboard requires data or viewer")}function GR(e){let t=u(e,"section");if(t!==void 0){if(t==="work"||t==="approvals"||t==="cost")return t;throw new Error("dashboard --section must be work, approvals, or cost")}}function XR(e,t){return{schema_version:e.schema_version,generated_at:e.generated_at,filters:e.filters,read_only:e.read_only,[t]:e[t]}}async function _l(e,t,r){let o=e.rest[0];if(o==="m7"||o==="report"){let n=await hr({home:t,project:u(e.flags,"project"),host:u(e.flags,"host"),limit:E(e.flags,"limit")});m(n,r,n.m7_gate.feedback_validated?"M7 feedback report ready":"M7 feedback report has gaps");return}throw new Error("feedback requires m7 or report")}async function bl(e,t,r){let o=e.rest[0];if(o==="claim"){let n=u(e.flags,"slot")??e.rest[1];if(!n)throw new Error("heartbeat claim requires --slot <id>");let a=u(e.flags,"project")??L(process.cwd(),t),s=u(e.flags,"host")??"codex",i=await Co({home:t,slot:n,host:s,project:a,ttlSeconds:E(e.flags,"ttl-seconds")});m(i,r,i.claimed?`Heartbeat lease claimed: ${i.lease.id}`:"HEARTBEAT_OK");return}if(o==="complete"){let n=u(e.flags,"slot")??e.rest[1];if(!n)throw new Error("heartbeat complete requires --slot <id>");let a=u(e.flags,"project")??L(process.cwd(),t),s=u(e.flags,"host")??"codex",i=await Oo({home:t,slot:n,host:s,project:a,result:u(e.flags,"result")??"HEARTBEAT_OK",evidence:u(e.flags,"evidence")?{note:u(e.flags,"evidence")??""}:{},workItemId:u(e.flags,"work-item")});m(i,r,`Heartbeat completed: ${i.lease.id}`);return}if(o==="status"){let n=await Di({home:t,project:u(e.flags,"project"),limit:E(e.flags,"limit")});m(n,r,`${n.length} heartbeat lease(s)`);return}throw new Error("heartbeat requires claim, complete, or status")}async function vl(e,t,r){let o=e.rest[0];if(o==="reconcile"){let n=Uo(e.flags),a=u(e.flags,"target-root"),s=await mt({home:t,host:n,surface:je(e.flags),mode:ta(e.flags),apply:b(e.flags,"apply"),hostConfigRoot:a?ze(n,a):void 0,targetRoot:a});m(s,r,s.applied?`Schedule reconciled: ${s.schedule.id}`:`Schedule reconcile planned: ${s.schedule.id}`);return}if(o==="list"){let n=await ho({home:t,host:Bo(e.flags),limit:E(e.flags,"limit")});m(n,r,`${n.length} schedule record(s)`);return}if(o==="disable"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("schedule disable requires <id> or --id <id>");let a=await ni({home:t,id:n,apply:b(e.flags,"apply")});m(a,r,a.applied?`Schedule disabled: ${n}`:`Schedule disable planned: ${n}`);return}throw new Error("schedule requires reconcile, list, or disable")}async function kl(e,t,r){if(e.rest[0]==="openclaw"){let a=u(e.flags,"source")??e.rest[1];if(!a)throw new Error("import openclaw requires --source <path>");let s=await ui({home:t,sourcePath:a,cwd:u(e.flags,"cwd")??process.cwd(),project:u(e.flags,"project"),apply:b(e.flags,"apply"),limit:E(e.flags,"limit")});m(s,r,s.applied?`OpenClaw import applied: ${s.persisted_memories.length} candidate(s), ${s.warnings.length} warning(s)`:`OpenClaw import dry-run: ${s.mapped_records.length} mapped, ${s.skipped_records.length} skipped, ${s.warnings.length} warning(s)`);return}let n=zR(e);if(n){let a=u(e.flags,"source")??e.rest[1];if(!a)throw new Error("import native requires --source <path>");let s=await fi({home:t,host:n,sourcePath:a,cwd:u(e.flags,"cwd")??process.cwd(),project:u(e.flags,"project"),apply:b(e.flags,"apply"),limit:E(e.flags,"limit")});m(s,r,s.applied?`${n} import applied: ${s.persisted_memories.length} candidate(s), ${s.warnings.length} warning(s), ${s.conflicts.length} conflict(s)`:`${n} import dry-run: ${s.mapped_records.length} mapped, ${s.skipped_records.length} skipped, ${s.conflicts.length} conflict(s), ${s.warnings.length} warning(s)`);return}throw new Error("import requires openclaw, native --host <host>, or a supported host alias")}function zR(e){let t=e.rest[0],r=t==="native"?u(e.flags,"host"):t;return r==="nativesoul"||r==="codex"||r==="claude"||r==="gemini"||r==="grok"||r==="antigravity"?r:null}import{spawnSync as YR}from"node:child_process";async function wl(e,t,r){let[o,n]=e.rest;if(o==="activate"){if(!n)throw new Error("license activate requires a license key");let a=await _i({home:t,key:n}),s=a.ok?{ok:!0,action:"activate",license:Vo(a.license),message:"License activated via Dodo"}:{ok:!1,action:"activate",reason:a.reason,license:Vo(a.license),message:`License activation failed: ${a.reason}`};m(s,r,s.message??"License activated via Dodo"),s.ok||(process.exitCode=1);return}if(o==="status"){let a=await Pe(t),s=a?QR(a):ue,i=await eS(e),l=await Si({home:t,currentVersion:Wt,latestKnownVersion:i}),c={ok:!0,action:"status",license:Vo(s),update_entitlement:l,message:tS(s,l,b(e.flags,"check-updates"))};m(c,r,c.message??`License status: ${s.state}`);return}if(o==="deactivate"){let a=await vi({home:t}),s=a.ok?{ok:!0,action:"deactivate",license:Vo(a.license),message:"License deactivated via Dodo; local NativeSoul data was not removed"}:{ok:!1,action:"deactivate",reason:a.reason,license:Vo(a.license),message:`License deactivation failed: ${a.reason}`};m(s,r,s.message??"License deactivated via Dodo; local NativeSoul data was not removed"),s.ok||(process.exitCode=1);return}throw new Error("license requires activate, status, or deactivate")}function QR(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 Vo(e){return{...e,license_key:e.license_key?ZR(e.license_key):null}}function ZR(e){return e.length<=8?"[REDACTED_LICENSE_KEY]":`${e.slice(0,4)}\u2026${e.slice(-4)}`}async function eS(e){let t=u(e.flags,"latest-known-version");if(t)return t;if(!b(e.flags,"check-updates"))return;let r=process.platform==="win32"?"npm.cmd":"npm",o=YR(r,["view","nativesoul","version","--registry=https://registry.npmjs.org/"],{encoding:"utf8",timeout:15e3,shell:process.platform==="win32"});if(o.status===0)return o.stdout.trim()||void 0}function tS(e,t,r){let o=t.updates_status==="unknown"?"unknown":t.updates_until??"unknown",n=t.newer_major_available==="unknown"?r?"unknown":"unknown \u2014 run with `--check-updates`":t.newer_major_available?"available":"not detected",a=[`License status: ${e.state}`,e.state==="licensed"?"Perpetual build: active \u2014 your licence keeps working.":"Perpetual build: unavailable until activated.",`Updates window: ${o}`,`Newer major: ${n}`];return t.soft_nudge.visible&&t.soft_nudge.message&&a.push(t.soft_nudge.message),a.join(`
|
|
1065
|
+
`)}async function Rl(e,t,r){let o=await Ri({page:u(e.flags,"page")});m(o,r,o.ok?`Marketing audit PASS: ${o.summary.claims_checked} claim(s), ${o.summary.pages_scanned} page(s)`:`Marketing audit FAIL: ${o.issues.length} issue(s)`),o.ok||(process.exitCode=1)}var xm={life_activation_status:async(e,t)=>await wr({home:t,host:Sl(e.host),targetRoot:_t(e.target_root)??_t(e.targetRoot)}),life_activation_plan:async(e,t)=>await Lo({home:t,host:Sl(e.host),targetRoot:_t(e.target_root)??_t(e.targetRoot),profile:rS(e.profile)}),life_activation_verify:async(e,t)=>await Do({home:t,host:Sl(e.host),surface:oS(e.surface),targetRoot:_t(e.target_root)??_t(e.targetRoot),projectCwd:_t(e.project_cwd)??_t(e.projectCwd),apply:Al(e.apply),userConfirmed:Al(e["user-confirmed"]),retainTestData:Al(e["retain-test-data"])})},jm=[{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 Sl(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 rS(e){if(e!==void 0){if(e==="quickstart"||e==="advanced")return e;throw new Error("Invalid activation profile")}}function oS(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 _t(e){return typeof e=="string"?e:void 0}function Al(e){return e===!0}var nS=["2025-11-25","2024-11-05","2024-10-07"],Nm={...xm,life_status:(e,t)=>Qn(t),life_bootstrap:async(e,t)=>await dS({home:t,host:C(e.host,"codex"),cwd:C(e.cwd,process.cwd()),query:F(e.query)}),life_recall:async(e,t)=>await Tt(t,C(e.query,""),C(e.project,"default"),oa(e.limit,5)),life_remember_propose:async(e,t)=>await ie(t,{project:C(e.project,"default"),content:C(e.content,""),type:F(e.type),confidence:Im(e.confidence),source:{host:"mcp",session_id:"local"}}),life_memory_promote:async(e,t)=>await Pt(t,C(e.id,"")),life_memory_reject:async(e,t)=>await xt(t,C(e.id,"")),life_memory_forget:async(e,t)=>await jt(t,C(e.id,"")),life_memory_expire:async(e,t)=>await zr(t,C(e.id,"")),life_capability_search:async(e,t)=>await Ur({home:t,query:C(e.query,""),host:mS(e)?void 0:F(e.host)??"codex",readyOnly:Sr(e.readyOnly,!1),limit:oa(e.limit,8)}),life_capability_status:async(e,t)=>{let r=C(e.uid,""),o=r?await Br({home:t,uid:r}):null;if(!o)throw new Error(`Capability not found: ${r}`);return o},life_policy_evaluate:async(e,t)=>await ht({home:t,action:C(e.action,""),className:Om(e.class),target:F(e.target)}),life_approval_request:async(e,t)=>await yS({home:t,action:C(e.action,""),className:Om(e.class),target:F(e.target),project:F(e.project),host:F(e.host)}),life_approval_decide:async(e,t)=>{let r=C(e.id,""),o=await _r({home:t,id:r,status:hS(e.status),reviewer:C(e.host,"mcp"),reason:F(e.reason)??null});if(!o.approval)throw new Error(`Approval not found: ${r}`);return o},life_commitment_create:async(e,t)=>await Vr({home:t,project:C(e.project,"default"),summary:C(e.summary,""),dueAt:F(e.due_at),ttlSeconds:Im(e.ttl_seconds),source:{host:"mcp",session_id:"local"}}),life_commitment_complete:async(e,t)=>await Jr(t,C(e.id,"")),life_work_item_create:async(e,t)=>await Ao({home:t,project:C(e.project,"default"),title:C(e.title,""),description:F(e.description),priority:El(e.priority),source:"mcp",tags:Tm(e.tags),host:F(e.host)}),life_work_item_list:async(e,t)=>await Eo({home:t,project:F(e.project),status:Cm(e.status),priority:El(e.priority),assignedHost:F(e.host),limit:oa(e.limit,50)}),life_work_item_claim:async(e,t)=>await Po({home:t,id:C(e.id,""),host:C(e.host,"mcp")}),life_work_item_update:async(e,t)=>await xo({home:t,id:C(e.id,""),status:Cm(e.status),priority:El(e.priority),assignedHost:F(e.host),description:F(e.description),tags:e.tags===void 0?void 0:Tm(e.tags)}),life_work_item_complete:async(e,t)=>await jo({home:t,id:C(e.id,""),status:pS(e.status)}),life_heartbeat_claim:async(e,t)=>await Co({home:t,slot:C(e.slot,""),host:C(e.host,"codex"),project:C(e.project,"default"),ttlSeconds:oa(e.ttl_seconds,1500)}),life_heartbeat_complete:async(e,t)=>await Oo({home:t,slot:C(e.slot,""),host:C(e.host,"codex"),project:C(e.project,"default"),result:e.result??"HEARTBEAT_OK",evidence:e.evidence??{},workItemId:F(e.work_item_id)}),life_onboarding_status:async(e,t)=>await oo(t),life_onboard_apply:async(e,t)=>await no({home:t,dry_run:Sr(e.dry_run,!0),user_confirmed:Sr(e.user_confirmed,!1),files:gS(e.files),config_patch:fS(e.config_patch)}),life_onboard_complete:async(e,t)=>await ao({home:t,archive:e.archive===void 0?!0:Sr(e.archive,!0)})},aS=new Set(Object.keys(Nm));function sS(e){return e.method?.startsWith("notifications/")?!0:!Object.prototype.hasOwnProperty.call(e,"id")}async function na(e,t){if(sS(e))return null;let r=e.id??null;try{if(e.method==="initialize"){let o=Wo(e.params),n=F(o.protocolVersion),a=n&&nS.includes(n)?n:"2024-11-05";return et(r,{protocolVersion:a,serverInfo:{name:"nativesoul",version:"0.1.0"},capabilities:{tools:{}}})}if(e.method==="ping")return et(r,{});if(e.method==="resources/list")return et(r,{resources:[]});if(e.method==="prompts/list")return et(r,{prompts:[]});if(e.method==="tools/list")return et(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"}},...jm,{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 pr(t);if(!o.ok)return et(r,o);let n=uS(e.params);return et(r,await lS(n.name??"",n.arguments??{},t))}if(aS.has(e.method)){let o=await pr(t);return o.ok?et(r,await Lm(e.method,Wo(e.params),t)):et(r,o)}return ra(r,-32601,`Unknown method: ${e.method}`)}catch(o){return o instanceof Et?ra(r,-32010,o.message,{code:o.code,id:o.id,from:o.from,to:o.to}):o instanceof Ce?ra(r,-32011,o.message,{code:o.code,id:o.id,status:o.status}):ra(r,-32603,o instanceof Error?o.message:"Unknown MCP error")}}async function Mm(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 a=n.trim();a&&iS(a,e).catch(s=>{process.stderr.write(`NativeSoul MCP response error: ${_S(s)}
|
|
1066
|
+
`)})}})}async function iS(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"}})}
|
|
1067
1067
|
`);return}let o=await na(r,t);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
1068
|
-
`)}async function nS(e,t,r){let o=await Cm(e,t,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}var aS={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 Cm(e,t,r){let o=Im[e];if(!o)throw new Error(`Unknown tool: ${e}`);let n=aS[e];if(n){let a=await Gt(n,{home:r,target:F(t.id)??F(t.title)??null,project:F(t.project),host:F(t.host)});if(a.status==="deny")throw new Error(`Blocked by policy gate: ${a.reason}`);if(a.status==="approval_required")return{blocked:!0,allowed:!1,decision:"approval_required",approval_id:a.approvalId,approval_created:a.approvalCreated,wait:"human",instruction:a.approvalId?`approval ${a.approvalId} pending - run: nativesoul approvals approve ${a.approvalId} --confirm`:"approval pending but unavailable - inspect NativeSoul approval storage",warning:a.warning}}return await o(t,r)}async function sS(e){try{let t=await it({...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 et(e,t){return{jsonrpc:"2.0",id:e,result:t}}function ra(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 iS(e){return Wo(e)}function Wo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function C(e,t){return typeof e=="string"?e:t}function F(e){return typeof e=="string"?e:void 0}function oa(e,t){return typeof e=="number"?e:t}function Em(e){return typeof e=="number"?e:void 0}function Pm(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function xm(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 lS(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 Al(e){if(e!==void 0){if(e==="low"||e==="normal"||e==="high"||e==="urgent")return e;throw new Error("Invalid work item priority")}}function Sr(e,t){return typeof e=="boolean"?e:t}function cS(e){return Sr(e.allHosts,!1)||Sr(e.all_hosts,!1)}function dS(e){let t=Wo(e),r={};for(let[o,n]of Object.entries(t))typeof n=="string"&&(r[o]=n);return r}function uS(e){let r=Wo(e).hosts;if(!Array.isArray(r))return;let o=r.filter(n=>typeof n=="string");return o.length>0?{hosts:o}:void 0}function jm(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 pS(e){if(e==="approved"||e==="rejected")return e;throw new Error("life_approval_decide status must be approved or rejected")}async function mS(e){let t=await No(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 gS(e){return e instanceof Error?e.message:"Unknown MCP response error"}async function El(e,t,r){let o=e.rest[0];if(!o){await Tm(t);return}if(o==="manifest"){let n=Ft({host:wm(e.flags),commandMode:sl(e.flags),home:t,projectRoot:u(e.flags,"project-root")});m(n,r,`MCP manifest generated for ${n.host}`);return}if(o==="smoke"){let n=await na({jsonrpc:"2.0",id:1,method:"initialize"},t),a=await na({jsonrpc:"2.0",id:2,method:"life_status"},t),s={ok:n!==null&&a!==null&&"result"in n&&"result"in a,initialize:n,status:a};m(s,r,s.ok?"MCP smoke passed":"MCP smoke failed");return}if(o==="install"){let n=await go({home:t,host:al(e.flags),targetPath:u(e.flags,"target"),apply:b(e.flags,"apply"),commandMode:sl(e.flags),projectRoot:u(e.flags,"project-root")});m(n,r,`${n.dryRun?"Planned":"Applied"} MCP registration for ${n.host}: ${n.action}`);return}if(o==="rollback"){let n=u(e.flags,"snapshot");if(!n)throw new Error("mcp rollback requires --snapshot <path>");let a=await ri({home:t,snapshotPath:n,apply:b(e.flags,"apply")});m(a,r,`${a.dryRun?"Planned rollback":"Rolled back"} MCP target ${a.targetPath}`);return}if(o==="doctor"){let n=await fo({host:al(e.flags),targetPath:u(e.flags,"target")});m(n,r,n.configured?`MCP configured for ${n.host}`:`MCP not configured for ${n.host}`);return}throw new Error("mcp requires manifest, smoke, install, rollback, doctor, or stdio mode with no subcommand")}async function Pl(e,t,r){let o=e.rest[0];if(o==="flush-hook"){let n=u(e.flags,"text")?"":await Ho(),a=$o(n),s=u(e.flags,"text")??(typeof a=="string"?a:void 0),i=await hs({home:t,host:u(e.flags,"host")??"codex",cwd:u(e.flags,"cwd")??process.cwd(),event:u(e.flags,"event")??e.rest[1],text:s,payload:typeof a=="string"?void 0:a});m(i,r,`Memory candidate proposed from ${i.host} ${i.event}: ${i.memory.id}`);return}if(o==="recall-hook"){let n=u(e.flags,"prompt")?"":await Ho(),a=$o(n),s=u(e.flags,"prompt")??gm(a),i=await ys({home:t,host:u(e.flags,"host")??"codex",cwd:u(e.flags,"cwd")??process.cwd(),prompt:s,limit:E(e.flags,"limit")});m(i,r,i.context||`Memory recall skipped: ${i.decision.reason}`);return}if(o==="index"){let n=await gs({home:t,limit:E(e.flags,"limit")});m(n,r,`Semantic index updated: ${n.indexed_count} indexed, ${n.skipped_unchanged} unchanged`);return}if(o==="reflect"){let n=await ii({home:t,cwd:u(e.flags,"cwd")??process.cwd(),project:u(e.flags,"project"),limit:E(e.flags,"limit"),apply:b(e.flags,"apply")});m(n,r,n.applied?`Reflection report applied: ${n.proposals.length} proposal(s), ${n.report_path}`:n.report);return}if(o==="add"){let n=u(e.flags,"text");if(!n)throw new Error("memory add requires --text");let a=u(e.flags,"project")??u(e.flags,"scope")??L(process.cwd(),t),s=await fs(t,{content:n,project:a});m(s,r,`Memory added: ${s.id}`);return}if(o==="propose"){let n=u(e.flags,"text");if(!n)throw new Error("memory propose requires --text");let a=u(e.flags,"project")??u(e.flags,"scope")??L(process.cwd(),t),s=await ie(t,{content:n,project:a});m(s,r,`Memory proposed: ${s.id}`);return}if(o==="promote"||o==="reject"||o==="forget"||o==="expire"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error(`memory ${o} requires <id> or --id <id>`);let a=o==="promote"?await Pt(t,n):o==="reject"?await xt(t,n):o==="forget"?await jt(t,n):await zr(t,n);m(a,r,`Memory ${o}d: ${a.id}`);return}if(o==="export"){let n=u(e.flags,"project")??u(e.flags,"scope"),a=await It({home:t,project:n,includeForgotten:b(e.flags,"include-forgotten"),limit:E(e.flags,"limit")});m(a,r,`${a.length} memor${a.length===1?"y":"ies"} exported`);return}if(o==="search"){let n=e.rest.slice(1).join(" ")||(u(e.flags,"query")??""),a=u(e.flags,"project")??L(process.cwd(),t),s=E(e.flags,"limit")??5,i=await Tt(t,n,a,s);m(i,r,`${i.length} memor${i.length===1?"y":"ies"} found`);return}throw new Error("memory requires add, propose, flush-hook, recall-hook, index, reflect, promote, reject, forget, expire, export, or search")}async function xl(e,t,r){let o=e.rest[0];if(o==="list"){let n=await bs({home:t,status:vm(e.flags),limit:E(e.flags,"limit")});m(n,r,fS(n.projects,n.warning));return}if(o==="show"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("project show requires <id|.>");let a=await vs({home:t,id:n,cwd:u(e.flags,"cwd")??process.cwd()});m(a,r,hS(a)),a.registry_available&&!a.registry&&(process.exitCode=1);return}if(o==="rename"){let n=e.rest[1]??u(e.flags,"id"),a=u(e.flags,"name");if(!n||!a)throw new Error("project rename requires <id|.> --name <display>");let s=await ks({home:t,id:n,name:a,cwd:u(e.flags,"cwd")??process.cwd()});m(s,r,s.found?`Project renamed: ${s.id} -> ${s.new_name}`:`Project not found: ${s.id}`),s.found||(process.exitCode=1);return}if(o==="alias"){let n=e.rest[1];if(n==="list"){let a=await Ss({home:t});m(a,r,Object.keys(a.aliases).length===0?"No project aliases":_S(a.aliases));return}if(n==="add"){let a=e.rest[2],s=u(e.flags,"as");if(!a||!s)throw new Error("project alias add requires <id> --as <custom-id>");let i=await As({home:t,id:a,alias:s,apply:b(e.flags,"apply")});m(i,r,Om(i));return}if(n==="remove"){let a=e.rest[2]??u(e.flags,"as");if(!a)throw new Error("project alias remove requires <custom-id>");let s=await Es({home:t,alias:a,apply:b(e.flags,"apply")});m(s,r,Om(s));return}throw new Error("project alias requires add, remove, or list")}if(o==="forget"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("project forget requires <id>");let a=await ws({home:t,id:n,includeMemories:b(e.flags,"include-memories"),apply:b(e.flags,"apply"),confirm:u(e.flags,"confirm")});m(a,r,bS(a)),(!a.found||a.mode==="forget_memories"&&!a.guard_ok)&&(process.exitCode=1);return}if(o==="reactivate"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("project reactivate requires <id>");let a=await Rs({home:t,id:n});m(a,r,vS(a)),a.found||(process.exitCode=1);return}if(o==="pin"){let n=u(e.flags,"cwd")??process.cwd(),a=await cs({cwd:n,home:t,apply:b(e.flags,"apply")});m(a,r,a.applied?`Project marker pinned at ${a.marker_path} (${a.base_id})`:`Project pin dry-run: would write ${a.marker_path} (${a.base_id})`);return}throw new Error("project requires list, show, rename, alias, forget, reactivate, or pin")}function fS(e,t){if(t)return`Project registry unavailable: ${t}`;if(e.length===0)return"No projects found";let r=e.map(o=>{let n=o.counts;return`${o.id} ${o.display_name} ${o.status} memories:${n.memories.active}/${n.memories.total} commitments:${n.commitments.open}/${n.commitments.total} semantic:${n.semantic_memory_index.total} runs:${n.runs.total} sessions:${n.sessions.total}`});return[`${e.length} project(s)`,...r].join(`
|
|
1069
|
-
`)}function
|
|
1070
|
-
`)}function
|
|
1071
|
-
`)}function
|
|
1072
|
-
`):e.mode==="forget_memories"?`Project forgotten: ${e.id}; memories affected: ${e.memories_affected}`:`Project archived: ${e.id}`:`Project not found: ${e.id}`}function
|
|
1068
|
+
`)}async function lS(e,t,r){let o=await Lm(e,t,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}var cS={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 Lm(e,t,r){let o=Nm[e];if(!o)throw new Error(`Unknown tool: ${e}`);let n=cS[e];if(n){let a=await Gt(n,{home:r,target:F(t.id)??F(t.title)??null,project:F(t.project),host:F(t.host)});if(a.status==="deny")throw new Error(`Blocked by policy gate: ${a.reason}`);if(a.status==="approval_required")return{blocked:!0,allowed:!1,decision:"approval_required",approval_id:a.approvalId,approval_created:a.approvalCreated,wait:"human",instruction:a.approvalId?`approval ${a.approvalId} pending - run: nativesoul approvals approve ${a.approvalId} --confirm`:"approval pending but unavailable - inspect NativeSoul approval storage",warning:a.warning}}return await o(t,r)}async function dS(e){try{let t=await it({...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 et(e,t){return{jsonrpc:"2.0",id:e,result:t}}function ra(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 uS(e){return Wo(e)}function Wo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function C(e,t){return typeof e=="string"?e:t}function F(e){return typeof e=="string"?e:void 0}function oa(e,t){return typeof e=="number"?e:t}function Im(e){return typeof e=="number"?e:void 0}function Tm(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Cm(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 pS(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 El(e){if(e!==void 0){if(e==="low"||e==="normal"||e==="high"||e==="urgent")return e;throw new Error("Invalid work item priority")}}function Sr(e,t){return typeof e=="boolean"?e:t}function mS(e){return Sr(e.allHosts,!1)||Sr(e.all_hosts,!1)}function gS(e){let t=Wo(e),r={};for(let[o,n]of Object.entries(t))typeof n=="string"&&(r[o]=n);return r}function fS(e){let r=Wo(e).hosts;if(!Array.isArray(r))return;let o=r.filter(n=>typeof n=="string");return o.length>0?{hosts:o}:void 0}function Om(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 hS(e){if(e==="approved"||e==="rejected")return e;throw new Error("life_approval_decide status must be approved or rejected")}async function yS(e){let t=await No(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 _S(e){return e instanceof Error?e.message:"Unknown MCP response error"}async function Pl(e,t,r){let o=e.rest[0];if(!o){await Mm(t);return}if(o==="manifest"){let n=Ft({host:Em(e.flags),commandMode:il(e.flags),home:t,projectRoot:u(e.flags,"project-root")});m(n,r,`MCP manifest generated for ${n.host}`);return}if(o==="smoke"){let n=await na({jsonrpc:"2.0",id:1,method:"initialize"},t),a=await na({jsonrpc:"2.0",id:2,method:"life_status"},t),s={ok:n!==null&&a!==null&&"result"in n&&"result"in a,initialize:n,status:a};m(s,r,s.ok?"MCP smoke passed":"MCP smoke failed");return}if(o==="install"){let n=await go({home:t,host:sl(e.flags),targetPath:u(e.flags,"target"),apply:b(e.flags,"apply"),commandMode:il(e.flags),projectRoot:u(e.flags,"project-root")});m(n,r,`${n.dryRun?"Planned":"Applied"} MCP registration for ${n.host}: ${n.action}`);return}if(o==="rollback"){let n=u(e.flags,"snapshot");if(!n)throw new Error("mcp rollback requires --snapshot <path>");let a=await oi({home:t,snapshotPath:n,apply:b(e.flags,"apply")});m(a,r,`${a.dryRun?"Planned rollback":"Rolled back"} MCP target ${a.targetPath}`);return}if(o==="doctor"){let n=await fo({host:sl(e.flags),targetPath:u(e.flags,"target")});m(n,r,n.configured?`MCP configured for ${n.host}`:`MCP not configured for ${n.host}`);return}throw new Error("mcp requires manifest, smoke, install, rollback, doctor, or stdio mode with no subcommand")}async function xl(e,t,r){let o=e.rest[0];if(o==="flush-hook"){let n=u(e.flags,"text")?"":await Ho(),a=$o(n),s=u(e.flags,"text")??(typeof a=="string"?a:void 0),i=await hs({home:t,host:u(e.flags,"host")??"codex",cwd:u(e.flags,"cwd")??process.cwd(),event:u(e.flags,"event")??e.rest[1],text:s,payload:typeof a=="string"?void 0:a});m(i,r,`Memory candidate proposed from ${i.host} ${i.event}: ${i.memory.id}`);return}if(o==="recall-hook"){let n=u(e.flags,"prompt")?"":await Ho(),a=$o(n),s=u(e.flags,"prompt")??_m(a),i=await ys({home:t,host:u(e.flags,"host")??"codex",cwd:u(e.flags,"cwd")??process.cwd(),prompt:s,limit:E(e.flags,"limit")});m(i,r,i.context||`Memory recall skipped: ${i.decision.reason}`);return}if(o==="index"){let n=await gs({home:t,limit:E(e.flags,"limit")});m(n,r,`Semantic index updated: ${n.indexed_count} indexed, ${n.skipped_unchanged} unchanged`);return}if(o==="reflect"){let n=await li({home:t,cwd:u(e.flags,"cwd")??process.cwd(),project:u(e.flags,"project"),limit:E(e.flags,"limit"),apply:b(e.flags,"apply")});m(n,r,n.applied?`Reflection report applied: ${n.proposals.length} proposal(s), ${n.report_path}`:n.report);return}if(o==="add"){let n=u(e.flags,"text");if(!n)throw new Error("memory add requires --text");let a=u(e.flags,"project")??u(e.flags,"scope")??L(process.cwd(),t),s=await fs(t,{content:n,project:a});m(s,r,`Memory added: ${s.id}`);return}if(o==="propose"){let n=u(e.flags,"text");if(!n)throw new Error("memory propose requires --text");let a=u(e.flags,"project")??u(e.flags,"scope")??L(process.cwd(),t),s=await ie(t,{content:n,project:a});m(s,r,`Memory proposed: ${s.id}`);return}if(o==="promote"||o==="reject"||o==="forget"||o==="expire"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error(`memory ${o} requires <id> or --id <id>`);let a=o==="promote"?await Pt(t,n):o==="reject"?await xt(t,n):o==="forget"?await jt(t,n):await zr(t,n);m(a,r,`Memory ${o}d: ${a.id}`);return}if(o==="export"){let n=u(e.flags,"project")??u(e.flags,"scope"),a=await It({home:t,project:n,includeForgotten:b(e.flags,"include-forgotten"),limit:E(e.flags,"limit")});m(a,r,`${a.length} memor${a.length===1?"y":"ies"} exported`);return}if(o==="search"){let n=e.rest.slice(1).join(" ")||(u(e.flags,"query")??""),a=u(e.flags,"project")??L(process.cwd(),t),s=E(e.flags,"limit")??5,i=await Tt(t,n,a,s);m(i,r,`${i.length} memor${i.length===1?"y":"ies"} found`);return}throw new Error("memory requires add, propose, flush-hook, recall-hook, index, reflect, promote, reject, forget, expire, export, or search")}async function jl(e,t,r){let o=e.rest[0];if(o==="list"){let n=await bs({home:t,status:Sm(e.flags),limit:E(e.flags,"limit")});m(n,r,bS(n.projects,n.warning));return}if(o==="show"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("project show requires <id|.>");let a=await vs({home:t,id:n,cwd:u(e.flags,"cwd")??process.cwd()});m(a,r,vS(a)),a.registry_available&&!a.registry&&(process.exitCode=1);return}if(o==="rename"){let n=e.rest[1]??u(e.flags,"id"),a=u(e.flags,"name");if(!n||!a)throw new Error("project rename requires <id|.> --name <display>");let s=await ks({home:t,id:n,name:a,cwd:u(e.flags,"cwd")??process.cwd()});m(s,r,s.found?`Project renamed: ${s.id} -> ${s.new_name}`:`Project not found: ${s.id}`),s.found||(process.exitCode=1);return}if(o==="alias"){let n=e.rest[1];if(n==="list"){let a=await Ss({home:t});m(a,r,Object.keys(a.aliases).length===0?"No project aliases":wS(a.aliases));return}if(n==="add"){let a=e.rest[2],s=u(e.flags,"as");if(!a||!s)throw new Error("project alias add requires <id> --as <custom-id>");let i=await As({home:t,id:a,alias:s,apply:b(e.flags,"apply")});m(i,r,Dm(i));return}if(n==="remove"){let a=e.rest[2]??u(e.flags,"as");if(!a)throw new Error("project alias remove requires <custom-id>");let s=await Es({home:t,alias:a,apply:b(e.flags,"apply")});m(s,r,Dm(s));return}throw new Error("project alias requires add, remove, or list")}if(o==="forget"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("project forget requires <id>");let a=await ws({home:t,id:n,includeMemories:b(e.flags,"include-memories"),apply:b(e.flags,"apply"),confirm:u(e.flags,"confirm")});m(a,r,RS(a)),(!a.found||a.mode==="forget_memories"&&!a.guard_ok)&&(process.exitCode=1);return}if(o==="reactivate"){let n=e.rest[1]??u(e.flags,"id");if(!n)throw new Error("project reactivate requires <id>");let a=await Rs({home:t,id:n});m(a,r,SS(a)),a.found||(process.exitCode=1);return}if(o==="pin"){let n=u(e.flags,"cwd")??process.cwd(),a=await cs({cwd:n,home:t,apply:b(e.flags,"apply")});m(a,r,a.applied?`Project marker pinned at ${a.marker_path} (${a.base_id})`:`Project pin dry-run: would write ${a.marker_path} (${a.base_id})`);return}throw new Error("project requires list, show, rename, alias, forget, reactivate, or pin")}function bS(e,t){if(t)return`Project registry unavailable: ${t}`;if(e.length===0)return"No projects found";let r=e.map(o=>{let n=o.counts;return`${o.id} ${o.display_name} ${o.status} memories:${n.memories.active}/${n.memories.total} commitments:${n.commitments.open}/${n.commitments.total} semantic:${n.semantic_memory_index.total} runs:${n.runs.total} sessions:${n.sessions.total}`});return[`${e.length} project(s)`,...r].join(`
|
|
1069
|
+
`)}function vS(e){if(!e.registry_available)return`Project registry unavailable: ${e.warning??"unknown"}`;if(!e.registry)return`Project not found: ${e.effective_id}`;let t=e.counts??kS();return[`Project ${e.registry.id}`,`Name: ${e.registry.display_name}`,`Status: ${e.registry.status}`,`Effective id: ${e.effective_id}`,`Base id: ${e.registry.base_id}`,`Source: ${e.registry.source}; live source: ${e.live_resolution.source}`,`Alias active: ${e.live_resolution.alias_key??"no"}`,`Marker active: ${e.live_resolution.marker_path??"no"}`,`Counts: memories ${t.memories.active}/${t.memories.total}, semantic ${t.semantic_memory_index.total}, commitments ${t.commitments.open}/${t.commitments.total}, runs ${t.runs.total}, sessions ${t.sessions.total}`,`Continuity gap: ${e.continuity_gap?"yes":"no"}`].join(`
|
|
1070
|
+
`)}function kS(){return{memories:{total:0,active:0,last_activity_at:null},semantic_memory_index:{total:0,last_activity_at:null},commitments:{total:0,open:0,last_activity_at:null},runs:{total:0,last_activity_at:null},sessions:{total:0,last_activity_at:null}}}function wS(e){return Object.entries(e).map(([t,r])=>`${t} -> ${r}`).join(`
|
|
1071
|
+
`)}function Dm(e){let t=e.applied?"applied":"dry-run";if(e.action==="add"){let r=e.previous_id&&e.previous_id!==e.project_id?` replacing ${e.previous_id}`:"";return`Project alias ${t}: ${e.alias_key} -> ${e.project_id}${r}`}return`Project alias removal ${t}: ${e.alias_key}`}function RS(e){return e.found?e.mode==="forget_memories"&&!e.guard_ok?[`Project forget dry-run refused: ${e.id}`,`Would transition ${e.memories_affected} memory record(s) to forgotten.`,`Run with --include-memories --apply --confirm ${e.id} to apply.`].join(`
|
|
1072
|
+
`):e.mode==="forget_memories"?`Project forgotten: ${e.id}; memories affected: ${e.memories_affected}`:`Project archived: ${e.id}`:`Project not found: ${e.id}`}function SS(e){return e.found?`Project reactivated: ${e.id}`:`Project not found: ${e.id}`}import{readFile as AS}from"node:fs/promises";async function Tl(e,t,r){let o=e.rest[0];if(o==="status"){let n=await oo(t);m(n,r,n.ritual_pending?"Onboarding ritual pending":"Onboarding complete");return}if(o==="activation"){let n=ES(e),a=await Ls({home:t,profile:n,dry_run:!b(e.flags,"apply"),user_confirmed:b(e.flags,"user-confirmed"),reset:b(e.flags,"reset"),options:{scheduler_host:u(e.flags,"scheduler-host"),heartbeat_cadence:u(e.flags,"heartbeat-cadence"),recall_auto_trigger:b(e.flags,"recall-auto-trigger")||void 0,memory_candidates:b(e.flags,"memory-candidates")||void 0,auto_promotion:b(e.flags,"auto-promotion")||void 0,promotion_policy:PS(e.flags),recall_auto_trigger_keywords:Il(e.flags,"recall-keywords"),recall_auto_trigger_denylist:Il(e.flags,"recall-denylist"),candidate_auto_promotion_threshold:xS(e.flags),standing_order_templates:Il(e.flags,"standing-order-templates")}});m(a,r,a.applied?"Activation profile applied":"Activation profile dry-run planned");return}if(o==="verify"){let n=await Do({home:t,host:Ze(e.flags),surface:je(e.flags),targetRoot:u(e.flags,"target-root"),projectCwd:u(e.flags,"project-cwd"),apply:b(e.flags,"apply"),userConfirmed:b(e.flags,"user-confirmed"),retainTestData:b(e.flags,"retain-test-data")});m(n,r,n.overall_status==="ready"?"Cross-host verification passed":`Cross-host verification ${n.overall_status}`);return}if(o==="apply"){let n=u(e.flags,"payload-file")??e.rest[1];if(!n)throw new Error("onboard apply requires --payload-file <path>");let a=JSON.parse(await AS(n,"utf8")),s=await no({home:t,dry_run:b(e.flags,"apply")?!1:a.dry_run!==!1,user_confirmed:b(e.flags,"user-confirmed")||a.user_confirmed===!0,files:a.files,config_patch:a.config_patch});m(s,r,s.applied?"Onboarding files applied":"Onboarding dry-run planned");return}if(o==="complete"){let n=await ao({home:t,archive:!b(e.flags,"no-archive")});m(n,r,n.already_complete?"Onboarding already complete":"Onboarding ritual completed");return}throw new Error("onboard requires status, activation, verify, apply, or complete")}function ES(e){let t=u(e.flags,"profile")??e.rest[1]??"quickstart";if(t==="quickstart"||t==="advanced")return t;throw new Error("onboard activation requires --profile quickstart|advanced")}function PS(e){let t=u(e,"promotion-policy");if(t!==void 0){if(t==="manual"||t==="explicit_approval")return t;throw new Error("onboard activation --promotion-policy requires manual|explicit_approval")}}function xS(e){let t=u(e,"candidate-confidence-threshold");if(t===void 0)return;let r=E(new Map([["candidate-confidence-threshold",t]]),"candidate-confidence-threshold");if(r===void 0)throw new Error("onboard activation --candidate-confidence-threshold must be a number");if(r>=0&&r<=1)return r;throw new Error("onboard activation --candidate-confidence-threshold must be between 0 and 1")}function Il(e,t){let r=u(e,t);if(r)return r.split(",").map(o=>o.trim()).filter(Boolean)}async function Cl(e,t,r){let o=e.rest[0];if(o==="evaluate"){let n=u(e.flags,"action")??e.rest[1];if(!n)throw new Error("policy evaluate requires --action <id>");let a=await ht({home:t,action:n,className:Am(e.flags),target:u(e.flags,"target")});m(a,r,`Policy decision for ${a.action}: ${a.decision}`);return}if(o==="standing-orders"&&e.rest[1]==="list"){let n=await ft(t);m(n,r,`${n.length} standing order(s)`);return}if(o==="packs"){await jS(e,t,r);return}if(o==="pretooluse-hook"){let n=await Ho(),a=$o(n)??{},s=await ji({home:t,host:u(e.flags,"host")??"codex",cwd:u(e.flags,"cwd"),payload:a});m(s,r,s.message);return}if(o==="propose-change"){let n=u(e.flags,"target")??e.rest[1],a=u(e.flags,"summary");if(!n||!a)throw new Error("policy propose-change requires --target SOUL.md|POLICY.md and --summary <text>");let s=await Ii({home:t,target:n,summary:a});m(s,r,`Policy change proposal created: ${s.proposalPath}`);return}throw new Error("policy requires evaluate, standing-orders list, packs list|show|validate|apply|rollback, pretooluse-hook, or propose-change")}async function jS(e,t,r){let o=e.rest[1];if(o==="list"){let n=await Ki();m(n,r,`${n.length} policy pack(s)`);return}if(o==="show"){let n=e.rest[2]??u(e.flags,"id");if(!n)throw new Error("policy packs show requires <id> or --id <id>");let a=await Mo(n);m(a,r,`Policy pack ${a.id} ${a.version}`);return}if(o==="validate"){let n=e.rest[2]??u(e.flags,"id"),a=await Gi({id:n,file:u(e.flags,"file")});m(a,r,a.valid?`Policy pack valid: ${a.id}`:`Policy pack invalid: ${a.errors.join("; ")}`);return}if(o==="apply"){let n=e.rest[2]??u(e.flags,"id");if(b(e.flags,"apply")){let s=await Gt("policy_pack.apply",{home:t,target:n??u(e.flags,"file")??null});if(s.status==="deny")throw new Error(`Blocked by policy gate: ${s.reason}`);if(s.status==="approval_required"){m({blocked:!0,allowed:!1,decision:"approval_required",approval_id:s.approvalId,instruction:s.approvalId?`approval ${s.approvalId} pending - run: nativesoul approvals approve ${s.approvalId} --confirm`:"approval pending but unavailable"},r,`policy pack apply blocked: approval required${s.approvalId?` (${s.approvalId})`:""}`);return}}let a=await Qi({home:t,id:n,file:u(e.flags,"file"),targetRoot:u(e.flags,"target-root"),apply:b(e.flags,"apply"),reviewed:b(e.flags,"reviewed"),approvalEvidence:u(e.flags,"approval")});m(a,r,`${a.dryRun?"Planned":"Applied"} policy pack ${a.pack.id}: ${a.files.filter(s=>s.changed).length} file change(s)`);return}if(o==="rollback"){let n=u(e.flags,"snapshot")??e.rest[2];if(!n)throw new Error("policy packs rollback requires --snapshot <path>");let a=await Zi({home:t,snapshotPath:n,apply:b(e.flags,"apply")});m(a,r,`${a.dryRun?"Planned rollback":"Rolled back"} policy pack ${a.pack.id}: ${a.files.length} file change(s)`);return}throw new Error("policy packs requires list, show, validate, apply, or rollback")}async function Nl(e,t,r){let o=e.rest[0];if(o==="create"){let n=u(e.flags,"title");if(!n)throw new Error("work create requires --title <text>");let a=await Ao({home:t,project:u(e.flags,"project")??L(process.cwd(),t),title:n,description:u(e.flags,"description")??null,priority:ea(e.flags),source:"cli",tags:al(e.flags,"tags"),host:u(e.flags,"host")??null});m(a,r,`Work item created: ${a.id}`);return}if(o==="list"){let n=await Eo({home:t,project:u(e.flags,"project"),status:Zn(e.flags),priority:ea(e.flags),assignedHost:u(e.flags,"host"),limit:E(e.flags,"limit")});m(n,r,`${n.length} work item(s)`);return}if(o==="claim"){let n=Ol(e,"claim"),a=u(e.flags,"host")??"cli",s=await Po({home:t,id:n,host:a});m(s,r,`Work item ${s.id} claimed by host ${a}`);return}if(o==="update"){let n=Ol(e,"update"),a=Zn(e.flags),s=ea(e.flags),i=u(e.flags,"host"),l=u(e.flags,"description"),c=al(e.flags,"tags"),d=u(e.flags,"run");if(a===void 0&&s===void 0&&i===void 0&&l===void 0&&c===void 0&&d===void 0)throw new Error("work update requires at least one of --status, --priority, --host, --description, --tags, or --run");let p=await xo({home:t,id:n,status:a,priority:s,assignedHost:i,description:l,tags:c,metadata:d===void 0?void 0:{run_id:d}});m(p,r,`Work item updated: ${p.id}`);return}if(o==="complete"){let n=Ol(e,"complete"),a=Zn(e.flags);if(a!==void 0&&a!=="done"&&a!=="failed")throw new Error("work complete --status must be done or failed");let s=await jo({home:t,id:n,status:a});m(s,r,`Work item completed: ${s.id} (${s.status})`);return}throw new Error("work requires create, list, claim, update, or complete")}function Ol(e,t){let r=e.rest[1]??u(e.flags,"id");if(!r)throw new Error(`work ${t} requires <id> or --id <id>`);return r}function Ml(){process.stdout.write(`nativesoul
|
|
1073
1073
|
|
|
1074
1074
|
Commands:
|
|
1075
1075
|
init [--home <path>] [--json]
|
|
@@ -1166,7 +1166,7 @@ Commands:
|
|
|
1166
1166
|
onboard apply --payload-file <path> [--apply] [--user-confirmed] [--home <path>] [--json]
|
|
1167
1167
|
onboard complete [--no-archive] [--home <path>] [--json]
|
|
1168
1168
|
mcp [--home <path>]
|
|
1169
|
-
`)}async function
|
|
1170
|
-
`);return}if(
|
|
1171
|
-
`)}async function
|
|
1172
|
-
`),process.exitCode=1});export{
|
|
1169
|
+
`)}async function CS(e){let t=ol(e);if(LS(t)){process.stdout.write(`${Wt}
|
|
1170
|
+
`);return}if(nl(t)){Ml();return}let r=u(t.flags,"home"),o=b(t.flags,"json");if(!DS(t)){let n=await pr(r);if(!n.ok){m(n,o,Ro(n)),process.exitCode=1;return}}switch(t.command){case"init":{let n=await ym(r);m(n,o,`NativeSoul initialized at ${n.home}`);return}case"status":{let n=Qn(r);m(n,o,`NativeSoul ${n.initialized?"initialized":"not initialized"} at ${n.home}`);return}case"doctor":{if(b(t.flags,"deep")){let a=b(t.flags,"require-full-native"),s=await Ut({home:r,host:Ze(t.flags),surface:je(t.flags),targetRoot:u(t.flags,"target-root")}),i=`full-native ${s.full_native_matrix.full_native_count}/${s.full_native_matrix.host_count}`;m(s,o,s.healthy?`NativeSoul deep doctor healthy: ${s.status}; ${i}`:`NativeSoul deep doctor found ${s.issues.length} issue(s); ${i}`),a&&!s.full_native_matrix.require_full_native_ready&&(process.exitCode=1);return}let n=await to(r);m(n,o,n.healthy?`NativeSoul healthy at ${n.home}`:`NativeSoul has ${n.issues.length} issue(s)`);return}case"install":{if(b(t.flags,"apply")){let a=await Gt("install.apply",{home:r,target:u(t.flags,"target-root")??null});if(a.status==="deny")throw new Error(`Blocked by policy gate: ${a.reason}`);if(a.status==="approval_required"){m({blocked:!0,allowed:!1,decision:"approval_required",approval_id:a.approvalId,instruction:a.approvalId?`approval ${a.approvalId} pending - run: nativesoul approvals approve ${a.approvalId} --confirm`:"approval pending but unavailable"},o,`install apply blocked: approval required${a.approvalId?` (${a.approvalId})`:""}`);return}}let n=await $i({home:r,host:Ze(t.flags),surface:je(t.flags),apply:b(t.flags,"apply"),targetRoot:u(t.flags,"target-root")});m(n,o,n.applied?`NativeSoul install applied: ${n.status}`:`NativeSoul install planned: ${n.status}`);return}case"uninstall":{let n=await Ui({home:r,host:Ze(t.flags),surface:je(t.flags),apply:b(t.flags,"apply"),targetRoot:u(t.flags,"target-root"),purgeData:b(t.flags,"purge-data"),confirmPurge:u(t.flags,"confirm-purge-nativesoul-data")});m(n,o,n.applied?`NativeSoul uninstall applied: ${n.status}`:`NativeSoul uninstall planned: ${n.status}`);return}case"memory":{await xl(t,r,o);return}case"project":{await jl(t,r,o);return}case"import":{await kl(t,r,o);return}case"license":{await wl(t,r,o);return}case"marketing-audit":{await Rl(t,r,o);return}case"commitments":{await ml(t,r,o);return}case"work":{await Nl(t,r,o);return}case"dashboard":{await yl(t,r,o);return}case"cost":{await hl(t,r,o);return}case"feedback":{await _l(t,r,o);return}case"adapters":{await cl(t,o);return}case"activate":{await ll(t,r,o);return}case"capabilities":{await pl(t,r,o);return}case"audit":{await ul(t,r,o);return}case"approvals":{await dl(t,r,o);return}case"policy":{await Cl(t,r,o);return}case"heartbeat":{await bl(t,r,o);return}case"schedule":{await vl(t,r,o);return}case"bootstrap":{let n=u(t.flags,"cwd")??process.cwd(),a=u(t.flags,"host")??"codex",s=Pm(t.flags);if(b(t.flags,"plan")){let l=await Ns({home:r,host:a,cwd:n,query:u(t.flags,"query")});m(l,o,OS(l));return}if(s==="cache"){try{let l=await rr({home:r,host:a,recordTelemetry:!1});m(l,o,l.content)}catch(l){try{let c=await rr({home:Qr(n),host:a,recordTelemetry:!1});m(c,o,c.content);return}catch{}throw await NS({home:r,host:a,cwd:n,source:"bootstrap-cache",error:l}),l}return}let i=await it({home:r,host:a,cwd:n,query:u(t.flags,"query"),readOnly:s==="inject"});if(s==="inject"){try{let l=await Rn({home:r,host:a,payload:i});m(l,o,l.content)}catch(l){try{let d=await Rn({home:Qr(n),host:a,payload:i,recordTelemetry:!1});m(d,o,d.content);return}catch{}let c=or({host:a,payload:i,degraded:!0,warnings:[`BOOTSTRAP_CACHE_WRITE_SKIPPED:${MS(l)}`]});m(c,o,c.content)}return}m(i,o,`Bootstrap ready for ${a} in project ${i.project.id}`);return}case"onboard":{await Tl(t,r,o);return}case"mcp":{await Pl(t,r,o);return}case"help":case void 0:Ml();return;default:throw new Error(`Unknown command: ${t.command}`)}}function OS(e){let t=e.budget.softMax>0?Math.round(e.budget.used/e.budget.softMax*100):0,r=e.files.filter(a=>a.included).length,o=e.warnings.length,n=e.files.map(a=>{let s=a.included?"included":"omitted",i=a.truncated?" truncated":"";return`- ${a.role}: ${s}${i} - ${a.reason} (${a.injectedChars}/${a.rawChars} chars)`});return[`Context: ${e.budget.used}/${e.budget.softMax} ${e.budget.unit} (${t}%) \xB7 ${r} files \xB7 ${e.memoryRecall.returned} memories \xB7 ${o} warnings \xB7 policy: strict`,`Project: ${e.project.id}`,`Cache: ${e.cache.hit?"hit":"miss"}${e.cache.key?` (${e.cache.key})`:""}`,"Files:",...n,`Memory recall: ${e.memoryRecall.mode} \xB7 limit ${e.memoryRecall.limit} \xB7 returned ${e.memoryRecall.returned}${e.memoryRecall.query?` \xB7 query "${e.memoryRecall.query}"`:""}`,"Warnings:",...e.warnings.length>0?e.warnings.map(a=>`- ${a}`):["- none"]].join(`
|
|
1171
|
+
`)}async function NS(e){try{await Me({home:e.home,host:e.host,outcome:"failed",tier:"D",cwd:e.cwd,project:L(e.cwd,e.home),source:e.source,error:e.error})}catch{}}function MS(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:"unavailable"}function LS(e){return e.command==="--version"||e.command==="-v"||e.command==="version"}function DS(e){if(e.command==="license"){let t=e.rest[0];return t==="activate"||t==="status"}return!1}function HS(){if(process.argv[1]===void 0)return!1;let e=TS(import.meta.url);try{return Hm(process.argv[1])===Hm(e)}catch{return IS.resolve(process.argv[1])===e}}HS()&&CS(process.argv.slice(2)).catch(e=>{let t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`nativesoul error: ${t}
|
|
1172
|
+
`),process.exitCode=1});export{CS as main,ol as parseArgs,nl as shouldPrintHelp};
|