@letterblack/lbe-exec 1.2.18 → 1.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/TRUST.md +90 -0
  2. package/dist/cli.js +47 -28
  3. package/package.json +2 -1
package/TRUST.md ADDED
@@ -0,0 +1,90 @@
1
+ # Trust Model
2
+
3
+ This document states plainly what you can and cannot verify about `@letterblack/lbe-exec` and `@letterblack/lbe-sdk`. It is written for agents and developers who want to reason about the trust surface before depending on this package.
4
+
5
+ ---
6
+
7
+ ## What this package does
8
+
9
+ LBE intercepts Node.js file system and shell operations at the process level via a CJS preload hook (`--require`). Every intercepted action is evaluated against a local policy file and appended to an audit log. The governance engine runs inside a compiled WASM binary shipped with the package.
10
+
11
+ ---
12
+
13
+ ## What you can verify independently
14
+
15
+ ### 1. Hook behavior (fully verifiable)
16
+
17
+ The preload hook (`hooks/register.cjs`) is client-side JavaScript. You can read it, run it in isolation, and confirm it patches the APIs it claims to patch. The minified form is smaller but not protected — it can be formatted and read.
18
+
19
+ ```bash
20
+ # Confirm hook patches fs and child_process
21
+ node --require ./node_modules/@letterblack/lbe-exec/hooks/register.cjs \
22
+ -e "require('fs').writeFileSync('test.txt','x')"
23
+ cat .lbe/events.jsonl
24
+ ```
25
+
26
+ ### 2. Audit log integrity (partially verifiable)
27
+
28
+ `audit.jsonl` is append-only JSONL in `.lbe/`. You can read every entry. The format is stable and human-readable. There is no cryptographic hash chain on the events.jsonl written by the hook — entries can be deleted without detection at the file level.
29
+
30
+ ### 3. WASM hash lock (tamper-detection, not supply-chain proof)
31
+
32
+ `dist/wasm.lock.json` contains a SHA-256 hash of `dist/lbe_engine.wasm`. The CLI verifies this at runtime.
33
+
34
+ **What this protects against:** post-install tampering — if someone modifies the WASM binary on your machine after installation, the hash check fails and the CLI refuses to run.
35
+
36
+ **What this does not protect against:** the initial install. If the package on npm is compromised before you install it, the hash in `wasm.lock.json` will match the compromised binary. This is standard supply-chain trust, not an additional guarantee.
37
+
38
+ ### 4. Commit signatures (verifiable from 2026-06-21 forward)
39
+
40
+ Commits to this repository are GPG-signed with key `B902B3111F7D01BA` (Ed25519, expires 2028-06-20). You can verify:
41
+
42
+ ```bash
43
+ git log --show-signature
44
+ ```
45
+
46
+ This confirms that commits were made by the key holder. It does not make the code open source.
47
+
48
+ ---
49
+
50
+ ## What you cannot verify
51
+
52
+ ### The WASM runtime is closed source
53
+
54
+ `dist/lbe_engine.wasm` is a compiled binary. Its source is not published. You cannot audit the governance engine logic — policy evaluation, signature verification, rate limiting, nonce replay protection — from the shipped artifact.
55
+
56
+ The trust chain for the runtime is: **you trust the binary or you don't.** There is no open-source alternative at this time.
57
+
58
+ ### Minified JS is not hidden
59
+
60
+ `hooks/register.cjs` and `dist/cli.js` are minified. Minified means smaller and harder to read — not protected, not encrypted, not obfuscated beyond whitespace and name compression. A motivated reader can format and read the full implementation.
61
+
62
+ ---
63
+
64
+ ## What the hook does and does not govern
65
+
66
+ **Governed:** Node.js processes that load the hook via `--require` or `NODE_OPTIONS`.
67
+
68
+ **Not governed:** Python, Go, Rust, native binaries, PowerShell scripts, subprocess spawns that bypass `child_process`, or any process that runs outside the hooked Node.js environment.
69
+
70
+ The hook is a best-effort governance layer for Node.js agents, not a sandbox or kernel-level enforcement mechanism.
71
+
72
+ ---
73
+
74
+ ## Verification surface summary
75
+
76
+ | Claim | Verifiable? | How |
77
+ |---|---|---|
78
+ | Hook patches fs and child_process | Yes | Run it, read the audit log |
79
+ | Audit log captures intercepted actions | Yes | Read `.lbe/events.jsonl` |
80
+ | WASM binary not tampered post-install | Yes | Hash in `wasm.lock.json` |
81
+ | WASM binary not tampered at publish time | No | Closed source, standard npm trust |
82
+ | Governance engine logic is correct | No | WASM is not open source |
83
+ | Commits are from the stated author | Yes | GPG signatures on git history |
84
+ | Hook cannot be bypassed by Node.js code | No | JS is not a sandbox |
85
+
86
+ ---
87
+
88
+ ## Reporting
89
+
90
+ If you find behaviour that contradicts this document — the hook not logging, the hash check not failing on a modified binary, or audit entries missing — open an issue on the public repository.
package/dist/cli.js CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- var jt=Object.defineProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var $t=(e,t)=>{for(var o in t)jt(e,o,{get:t[o],enumerable:!0})};import pe from"tweetnacl";import{canonicalize as Le}from"json-canonicalize";function ue(e){return Buffer.from(e,"base64")}function fe(e){return Buffer.from(e).toString("base64")}function me({payloadObj:e,sigB64:t,pubKeyB64:o}){try{let n=Buffer.from(Le(e),"utf8"),r=ue(t),s=ue(o),i=pe.sign.detached.verify(new Uint8Array(n),new Uint8Array(r),new Uint8Array(s));return{valid:i,message:i?"Signature verified":"Signature verification failed"}}catch(n){return{valid:!1,message:`Signature verification error: ${n.message}`}}}function ne(){let e=pe.sign.keyPair();return{publicKey:fe(e.publicKey),secretKey:fe(e.secretKey)}}function re({payloadObj:e,secretKeyB64:t}){try{let o=Buffer.from(Le(e),"utf8"),n=ue(t),r=pe.sign.detached(new Uint8Array(o),new Uint8Array(n));return{signature:fe(r),error:null}}catch(o){return{signature:null,error:`Signing failed: ${o.message}`}}}var Z=L(()=>{});import R from"fs";import he from"path";import fo from"crypto";function mo(e){return e+".lock"}function Ke(e){try{let t=R.openSync(e,"wx");return R.writeSync(t,`pid:${process.pid}:${Date.now()}`),R.closeSync(t),!0}catch(t){if(t.code==="EEXIST"||t.code==="EPERM"||t.code==="EBUSY"||t.code==="EACCES")return!1;throw t}}function qe(e,t){try{let o=R.statSync(e);if(Date.now()-o.mtimeMs>t)try{R.unlinkSync(e)}catch{}}catch{}}function yo(e){let t=Date.now()+e;for(;Date.now()<t;)try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.max(1,t-Date.now()))}catch{}}function Me(e,t,o){let n=typeof t=="function"?t:o,r=typeof t=="function"?{}:t||{},{timeoutMs:s,pollMs:i,staleMs:a}={...po,...r},c=he.dirname(e);R.existsSync(c)||R.mkdirSync(c,{recursive:!0});let l=mo(e),p=Date.now()+s,f=!1;for(;!f&&(f=Ke(l),!f);){if(Date.now()>=p){if(qe(l,a),f=Ke(l),f)break;let y=new Error(`withFileLock: timeout acquiring ${l} after ${s}ms`);throw y.code="ELOCKTIMEOUT",y}qe(l,a);let m=Math.floor(Math.random()*i);yo(i+m)}try{return n()}finally{try{R.unlinkSync(l)}catch{}}}function D(e,t,o={}){let n=he.dirname(e);R.existsSync(n)||R.mkdirSync(n,{recursive:!0});let r=he.join(n,`.tmp-${Date.now()}-${fo.randomBytes(4).toString("hex")}`);try{R.writeFileSync(r,t,o),R.renameSync(r,e)}catch(s){try{R.existsSync(r)&&R.unlinkSync(r)}catch{}throw s}}var po,z=L(()=>{po={timeoutMs:5e3,pollMs:15,staleMs:3e4}});import q from"fs";import Se from"path";import go from"crypto";function Ve(e){return go.createHash("sha256").update(e).digest("hex")}function ho(e){try{if(!q.existsSync(e))return"GENESIS";let t=q.readFileSync(e,"utf8").trim();if(!t)return"GENESIS";let o=t.split(`
3
- `),n=o[o.length-1];try{return JSON.parse(n).hash||"GENESIS"}catch{return"GENESIS"}}catch{return"GENESIS"}}function ee(e,t){let o=Se.dirname(e);q.existsSync(o)||q.mkdirSync(o,{recursive:!0});let n;return Me(e,()=>{let r=ho(e),s={...t,prevHash:r,timestamp:new Date().toISOString()};delete s.hash;let i=JSON.stringify(s),a=Ve(i),c=JSON.stringify({...s,hash:a}),l="";q.existsSync(e)&&(l=q.readFileSync(e,"utf8"));try{D(e,l+c+`
4
- `,{encoding:"utf8"})}catch(p){throw new Error(`Audit log write failed: ${p.message}`)}n={success:!0,hash:a,prevHash:r,message:"Audit entry appended"}}),n}function Be(e,t={}){let o=t.failFast!==!1,n=Number.isFinite(t.maxEntries)&&t.maxEntries>0?Math.floor(t.maxEntries):null,r={ok:!0,file:Se.resolve(e),entries:0,valid:!0,firstInvalidIndex:null,reason:null,errors:[],message:"Audit log verified"};try{if(!q.existsSync(e))return r.message="Audit log file not found (treated as empty)",r;let s=q.readFileSync(e,"utf8").trim();if(!s)return r.message="Empty audit log",r;let i=s.split(`
5
- `),a=n?i.slice(0,n):i;r.entries=a.length;let c="GENESIS";for(let l=0;l<a.length;l++){let p;try{p=JSON.parse(a[l])}catch{let h={index:l,reason:"INVALID_JSON_LINE",message:`Line ${l} is not valid JSON`};if(r.valid=!1,r.ok=!1,r.firstInvalidIndex??=l,r.reason??=h.reason,r.errors.push(h),o)break;continue}if(p.prevHash!==c){let h={index:l,reason:"PREV_HASH_MISMATCH",message:`Expected prevHash '${c}', got '${p.prevHash}'`};if(r.valid=!1,r.ok=!1,r.firstInvalidIndex??=l,r.reason??=h.reason,r.errors.push(h),o)break}let f={...p},m=f.hash;delete f.hash;let y=Ve(JSON.stringify(f));if(m!==y){let h={index:l,reason:"HASH_MISMATCH",message:`Expected hash '${y}', got '${m}'`};if(r.valid=!1,r.ok=!1,r.firstInvalidIndex??=l,r.reason??=h.reason,r.errors.push(h),o)break}c=m}return r.message=r.valid?`Audit log verified: ${r.entries} entries`:`Audit log integrity failed at index ${r.firstInvalidIndex}`,r}catch(s){return{ok:!1,file:Se.resolve(e),entries:0,valid:!1,firstInvalidIndex:null,reason:"AUDIT_VERIFY_ERROR",errors:[{index:null,reason:"AUDIT_VERIFY_ERROR",message:s.message}],message:`Integrity check failed: ${s.message}`}}}var ke=L(()=>{z()});import Ye from"fs";import W from"path";import So from"crypto";function Eo(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*\*\//g,"(?:.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")+"$")}function Io(e,t){return W.relative(e,W.resolve(t)).split(W.sep).join("/")}function Ee(e){let t=W.resolve(e||process.cwd());return{root:t,policyPath:W.join(t,Ue),auditPath:W.join(t,ko)}}function G(e,t="observe"){let o=Ee(e);if(!Ye.existsSync(o.policyPath))return{...o,policy:{version:1,mode:t,workspace:o.root,rules:[]}};let n=JSON.parse(Ye.readFileSync(o.policyPath,"utf8"));if(n?.version!==1||!["observe","enforce"].includes(n.mode)||!Array.isArray(n.rules))throw new Error(`Invalid ${Ue}`);return{...o,policy:n}}function Ie(e,t){let{policyPath:o,root:n}=Ee(e),r={...t,version:1,workspace:n,rules:Array.isArray(t.rules)?t.rules:[]};return D(o,JSON.stringify(r,null,2)+`
6
- `,{encoding:"utf8"}),r}function We(e,t,o){if(!t||!["allow","deny"].includes(t.effect)||!["path","command"].includes(t.type)||typeof t.pattern!="string"||!t.pattern||typeof t.from!="string"||!t.from)throw new Error("Rule requires effect, type, pattern, and from");let n=G(e,o),r={id:t.id||So.randomUUID(),effect:t.effect,type:t.type,pattern:t.pattern,from:t.from,at:t.at||new Date().toISOString()};return Ie(n.root,{...n.policy,mode:o||n.policy.mode,rules:[...n.policy.rules,r]}),{id:r.id,added:!0,rule:r}}function Ge(e){return{...e,proposed:!0,at:new Date().toISOString()}}function be(e,t,{target:o,command:n}={}){let r=W.resolve(t),s=[];o&&s.push({type:"path",value:Io(r,o)}),n&&s.push({type:"command",value:n});let i=e.rules.filter(c=>s.some(l=>l.type===c.type&&Eo(c.pattern).test(l.value))),a=i.filter(c=>c.effect==="deny");return{allowed:a.length===0,matched:i,winningRules:a.length?a:i.filter(c=>c.effect==="allow"),reason:a.length?"LOCAL_POLICY_DENY":null}}function He(e,t){let{auditPath:o}=Ee(e);ee(o,{kind:"local_policy",timestamp:new Date().toISOString(),...t})}var Ue,ko,ve=L(()=>{ke();z();Ue=".lbe/policy.json",ko=".lbe/audit.jsonl"});import ze from"fs";import bo from"path";function Xe(e){if(typeof e=="number"&&Number.isFinite(e))return{ok:!0,kind:"int",parts:[Math.floor(e)],raw:String(e)};if(typeof e!="string"||!e.trim())return{ok:!1,reason:"POLICY_VERSION_INVALID",message:"Policy version is required"};let t=e.trim();if(/^\d+$/.test(t))return{ok:!0,kind:"int",parts:[Number(t)],raw:t};let o=t.replace(/^v/i,"");if(/^\d+(\.\d+){0,2}$/.test(o)){let n=o.split(".").map(r=>Number(r));for(;n.length<3;)n.push(0);return{ok:!0,kind:"semver",parts:n,raw:t}}return{ok:!1,reason:"POLICY_VERSION_INVALID",message:`Unsupported policy version format '${e}' (use integer or semver)`}}function vo(e,t){let o=Math.max(e.parts.length,t.parts.length);for(let n=0;n<o;n++){let r=e.parts[n]??0,s=t.parts[n]??0;if(r>s)return 1;if(r<s)return-1}return 0}function Qe(e){if(typeof e=="number"&&Number.isFinite(e))return{ok:!0,epochSec:e>1e12?Math.floor(e/1e3):Math.floor(e)};if(typeof e!="string"||!e.trim())return{ok:!1,reason:"POLICY_CREATED_AT_INVALID",message:"Policy createdAt is required"};let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,reason:"POLICY_CREATED_AT_INVALID",message:`Invalid policy createdAt '${e}'`}:{ok:!0,epochSec:Math.floor(t/1e3)}}function xo(e){if(!ze.existsSync(e))return{schemaVersion:"1",lastAccepted:null,updatedAt:null};try{let t=JSON.parse(ze.readFileSync(e,"utf8"));if(!t||typeof t!="object")throw new Error("Policy state file has invalid structure");return{schemaVersion:String(t.schemaVersion||"1"),lastAccepted:t.lastAccepted&&typeof t.lastAccepted=="object"?t.lastAccepted:null,updatedAt:t.updatedAt||null}}catch(t){throw new Error(`Policy state at ${e} is corrupt or unreadable: ${t.message}`)}}function wo(e,t){let o=JSON.stringify(t,null,2);D(e,o,{encoding:"utf8"})}function Ze({policyObj:e,statePath:t=bo.resolve(".lbe/data/policy.state.json"),maxCreatedAtSkewSec:o=31536e3,nowSec:n=Math.floor(Date.now()/1e3),persist:r=!0}){let s=Xe(e?.version);if(!s.ok)return{ok:!1,reason:s.reason,message:s.message,updated:!1};let i=Qe(e?.createdAt);if(!i.ok)return{ok:!1,reason:i.reason,message:i.message,updated:!1};let a=Math.abs(n-i.epochSec),c=Number.isFinite(o)&&o>0?Math.floor(o):31536e3;if(a>c)return{ok:!1,reason:"POLICY_CREATED_AT_SKEW_EXCEEDED",message:`Policy createdAt skew ${a}s exceeds allowed ${c}s`,updated:!1};let l;try{l=xo(t)}catch(u){return{ok:!1,reason:"POLICY_STATE_CORRUPT",message:u.message,updated:!1}}let p=l.lastAccepted,f=null,m=null,y=0;if(p&&(f=Xe(p.version),m=Qe(p.createdAt),f.ok&&m.ok)){if(y=vo(s,f),y<0)return{ok:!1,reason:"POLICY_VERSION_REGRESSION",message:`Policy version regression: current '${s.raw}' < last '${f.raw}'`,updated:!1};if(y===0&&i.epochSec<m.epochSec)return{ok:!1,reason:"POLICY_CREATED_AT_REGRESSION",message:`Policy createdAt regression: current '${e.createdAt}' < last '${p.createdAt}'`,updated:!1};if(y>0&&i.epochSec<m.epochSec)return{ok:!1,reason:"POLICY_CREATED_AT_REGRESSION",message:"Policy createdAt must be monotonic when version increases",updated:!1}}let h=!p||!f?.ok||!m?.ok||y>0||y===0&&i.epochSec>m.epochSec;if(r&&h){let u={schemaVersion:"1",lastAccepted:{version:e.version,createdAt:e.createdAt,environment:e.environment||null},updatedAt:new Date().toISOString()};wo(t,u)}return{ok:!0,reason:null,message:"Policy version guard passed",updated:h}}var et=L(()=>{z()});import tt from"fs";import nt from"path";import{fileURLToPath as _o}from"url";function M(){if(se)return se;if(!tt.existsSync(xe))throw new Error(`LBE engine missing: ${xe}`);let e=tt.readFileSync(xe);return se=new WebAssembly.Instance(new WebAssembly.Module(e),{}),se}function ie(){return new Uint8Array(M().exports.memory.buffer)}function rt(){return M().exports.lbe_in_ptr()}function st(){return M().exports.lbe_out_ptr()}function To(){return M().exports.lbe_buf_size()}function it(e){let t=new TextEncoder().encode(e),o=ie(),n=rt();o.set(t,n),o[n+t.length]=0}function at(){let e=ie(),t=st(),o=t;for(;e[o]!==0&&o-t<To();)o++;return new TextDecoder().decode(e.slice(t,o))}function Co(e){let t=ie(),o=rt(),n=new DataView(t.buffer,o);e.forEach((r,s)=>n.setUint32(s*4,r>>>0,!0))}function Po(){let e=ie(),t=st(),o=new DataView(e.buffer,t);return{stage:o.getUint32(0,!0),code:o.getUint32(4,!0)}}function ct(e){Co([e.hasId?1:0,e.idValid?1:0,e.hasCommandId?1:0,e.commandIdValid?1:0,e.hasRequesterId?1:0,e.requesterIdValid?1:0,e.hasSessionId?1:0,e.sessionIdValid?1:0,e.hasTimestamp?1:0,e.timestampValid?1:0,e.hasNonce?1:0,e.nonceValid?1:0,e.hasRequires?1:0,e.requiresValid?1:0,e.hasPayload?1:0,e.hasPayloadAdapter?1:0,e.payloadAdapterValid?1:0,e.hasSignature?1:0,e.hasSignatureAlg?1:0,e.signatureAlgValid?1:0,e.hasSignatureKeyId?1:0,e.hasSignatureSig?1:0,e.signatureSigValid?1:0,e.hasRisk?1:0,e.riskValid?1:0,e.cmdTimestamp>>>0,e.nowSec>>>0,e.maxClockSkewSec>>>0,e.keyIdFormatValid?1:0,e.keyFound?1:0,e.keyNotDeprecated?1:0,e.keyRequesterMatches?1:0,e.keyNotBeforeOk?1:0,e.keyNotExpired?1:0,e.keyLifecycleFieldsPresent?1:0,e.signatureValid?1:0,e.rateLimitOk?1:0,e.rateLimitRetryAfterSec>>>0,e.nonceOk?1:0,e.policyConfigured?1:0,e.requesterConfigured?1:0,e.commandAllowed?1:0,e.adapterAllowed?1:0,e.filesystemRequired?1:0,e.filesystemRootsDefined?1:0,e.filesystemOk?1:0,e.pathDenied?1:0,e.shellRequired?1:0,e.shellCommandOk?1:0]),M().exports.lbe_validate_pipeline();let{stage:t,code:o}=Po();return{ok:t===255,stage:t,stageLabel:Ro[t]||"unknown",code:o,schemaError:t===0?Oo[o]?.error||"Schema invalid":null,keyReason:t===2?No[o]||"KEY_ERROR":null,policyResult:t===6?{...ot[o]||ot[1],code:o}:null,retryAfterSec:t===4?o:0,skewSec:t===1?o:0}}function we({ttlSec:e,nowSec:t,newKey:o,existingEntries:n}){let r=[`${e}:${t}`,o,...n].join(`
2
+ var jt=Object.defineProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var $t=(e,t)=>{for(var o in t)jt(e,o,{get:t[o],enumerable:!0})};import pe from"tweetnacl";import{canonicalize as Le}from"json-canonicalize";function ue(e){return Buffer.from(e,"base64")}function fe(e){return Buffer.from(e).toString("base64")}function me({payloadObj:e,sigB64:t,pubKeyB64:o}){try{let n=Buffer.from(Le(e),"utf8"),r=ue(t),s=ue(o),i=pe.sign.detached.verify(new Uint8Array(n),new Uint8Array(r),new Uint8Array(s));return{valid:i,message:i?"Signature verified":"Signature verification failed"}}catch(n){return{valid:!1,message:`Signature verification error: ${n.message}`}}}function ne(){let e=pe.sign.keyPair();return{publicKey:fe(e.publicKey),secretKey:fe(e.secretKey)}}function re({payloadObj:e,secretKeyB64:t}){try{let o=Buffer.from(Le(e),"utf8"),n=ue(t),r=pe.sign.detached(new Uint8Array(o),new Uint8Array(n));return{signature:fe(r),error:null}}catch(o){return{signature:null,error:`Signing failed: ${o.message}`}}}var Z=L(()=>{});import R from"fs";import he from"path";import fo from"crypto";function mo(e){return e+".lock"}function Ke(e){try{let t=R.openSync(e,"wx");return R.writeSync(t,`pid:${process.pid}:${Date.now()}`),R.closeSync(t),!0}catch(t){if(t.code==="EEXIST"||t.code==="EPERM"||t.code==="EBUSY"||t.code==="EACCES")return!1;throw t}}function Me(e,t){try{let o=R.statSync(e);if(Date.now()-o.mtimeMs>t)try{R.unlinkSync(e)}catch{}}catch{}}function yo(e){let t=Date.now()+e;for(;Date.now()<t;)try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.max(1,t-Date.now()))}catch{}}function qe(e,t,o){let n=typeof t=="function"?t:o,r=typeof t=="function"?{}:t||{},{timeoutMs:s,pollMs:i,staleMs:a}={...po,...r},l=he.dirname(e);R.existsSync(l)||R.mkdirSync(l,{recursive:!0});let c=mo(e),p=Date.now()+s,f=!1;for(;!f&&(f=Ke(c),!f);){if(Date.now()>=p){if(Me(c,a),f=Ke(c),f)break;let y=new Error(`withFileLock: timeout acquiring ${c} after ${s}ms`);throw y.code="ELOCKTIMEOUT",y}Me(c,a);let m=Math.floor(Math.random()*i);yo(i+m)}try{return n()}finally{try{R.unlinkSync(c)}catch{}}}function D(e,t,o={}){let n=he.dirname(e);R.existsSync(n)||R.mkdirSync(n,{recursive:!0});let r=he.join(n,`.tmp-${Date.now()}-${fo.randomBytes(4).toString("hex")}`);try{R.writeFileSync(r,t,o),R.renameSync(r,e)}catch(s){try{R.existsSync(r)&&R.unlinkSync(r)}catch{}throw s}}var po,z=L(()=>{po={timeoutMs:5e3,pollMs:15,staleMs:3e4}});import q from"fs";import ke from"path";import go from"crypto";function Be(e){return go.createHash("sha256").update(e).digest("hex")}function ho(e){try{if(!q.existsSync(e))return"GENESIS";let t=q.readFileSync(e,"utf8").trim();if(!t)return"GENESIS";let o=t.split(`
3
+ `),n=o[o.length-1];try{return JSON.parse(n).hash||"GENESIS"}catch{return"GENESIS"}}catch{return"GENESIS"}}function ee(e,t){let o=ke.dirname(e);q.existsSync(o)||q.mkdirSync(o,{recursive:!0});let n;return qe(e,()=>{let r=ho(e),s={...t,prevHash:r,timestamp:new Date().toISOString()};delete s.hash;let i=JSON.stringify(s),a=Be(i),l=JSON.stringify({...s,hash:a}),c="";q.existsSync(e)&&(c=q.readFileSync(e,"utf8"));try{D(e,c+l+`
4
+ `,{encoding:"utf8"})}catch(p){throw new Error(`Audit log write failed: ${p.message}`)}n={success:!0,hash:a,prevHash:r,message:"Audit entry appended"}}),n}function Ve(e,t={}){let o=t.failFast!==!1,n=Number.isFinite(t.maxEntries)&&t.maxEntries>0?Math.floor(t.maxEntries):null,r={ok:!0,file:ke.resolve(e),entries:0,valid:!0,firstInvalidIndex:null,reason:null,errors:[],message:"Audit log verified"};try{if(!q.existsSync(e))return r.message="Audit log file not found (treated as empty)",r;let s=q.readFileSync(e,"utf8").trim();if(!s)return r.message="Empty audit log",r;let i=s.split(`
5
+ `),a=n?i.slice(0,n):i;r.entries=a.length;let l="GENESIS";for(let c=0;c<a.length;c++){let p;try{p=JSON.parse(a[c])}catch{let h={index:c,reason:"INVALID_JSON_LINE",message:`Line ${c} is not valid JSON`};if(r.valid=!1,r.ok=!1,r.firstInvalidIndex??=c,r.reason??=h.reason,r.errors.push(h),o)break;continue}if(p.prevHash!==l){let h={index:c,reason:"PREV_HASH_MISMATCH",message:`Expected prevHash '${l}', got '${p.prevHash}'`};if(r.valid=!1,r.ok=!1,r.firstInvalidIndex??=c,r.reason??=h.reason,r.errors.push(h),o)break}let f={...p},m=f.hash;delete f.hash;let y=Be(JSON.stringify(f));if(m!==y){let h={index:c,reason:"HASH_MISMATCH",message:`Expected hash '${y}', got '${m}'`};if(r.valid=!1,r.ok=!1,r.firstInvalidIndex??=c,r.reason??=h.reason,r.errors.push(h),o)break}l=m}return r.message=r.valid?`Audit log verified: ${r.entries} entries`:`Audit log integrity failed at index ${r.firstInvalidIndex}`,r}catch(s){return{ok:!1,file:ke.resolve(e),entries:0,valid:!1,firstInvalidIndex:null,reason:"AUDIT_VERIFY_ERROR",errors:[{index:null,reason:"AUDIT_VERIFY_ERROR",message:s.message}],message:`Integrity check failed: ${s.message}`}}}var Se=L(()=>{z()});import Ye from"fs";import W from"path";import ko from"crypto";function Eo(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*\*\//g,"(?:.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")+"$")}function Io(e,t){return W.relative(e,W.resolve(t)).split(W.sep).join("/")}function Ee(e){let t=W.resolve(e||process.cwd());return{root:t,policyPath:W.join(t,Ue),auditPath:W.join(t,So)}}function G(e,t="observe"){let o=Ee(e);if(!Ye.existsSync(o.policyPath))return{...o,policy:{version:1,mode:t,workspace:o.root,rules:[]}};let n=JSON.parse(Ye.readFileSync(o.policyPath,"utf8"));if(n?.version!==1||!["observe","enforce"].includes(n.mode)||!Array.isArray(n.rules))throw new Error(`Invalid ${Ue}`);return{...o,policy:n}}function Ie(e,t){let{policyPath:o,root:n}=Ee(e),r={...t,version:1,workspace:n,rules:Array.isArray(t.rules)?t.rules:[]};return D(o,JSON.stringify(r,null,2)+`
6
+ `,{encoding:"utf8"}),r}function We(e,t,o){if(!t||!["allow","deny"].includes(t.effect)||!["path","command"].includes(t.type)||typeof t.pattern!="string"||!t.pattern||typeof t.from!="string"||!t.from)throw new Error("Rule requires effect, type, pattern, and from");let n=G(e,o),r={id:t.id||ko.randomUUID(),effect:t.effect,type:t.type,pattern:t.pattern,from:t.from,at:t.at||new Date().toISOString()};return Ie(n.root,{...n.policy,mode:o||n.policy.mode,rules:[...n.policy.rules,r]}),{id:r.id,added:!0,rule:r}}function Ge(e){return{...e,proposed:!0,at:new Date().toISOString()}}function be(e,t,{target:o,command:n}={}){let r=W.resolve(t),s=[];o&&s.push({type:"path",value:Io(r,o)}),n&&s.push({type:"command",value:n});let i=e.rules.filter(l=>s.some(c=>c.type===l.type&&Eo(l.pattern).test(c.value))),a=i.filter(l=>l.effect==="deny");return{allowed:a.length===0,matched:i,winningRules:a.length?a:i.filter(l=>l.effect==="allow"),reason:a.length?"LOCAL_POLICY_DENY":null}}function He(e,t){let{auditPath:o}=Ee(e);ee(o,{kind:"local_policy",timestamp:new Date().toISOString(),...t})}var Ue,So,ve=L(()=>{Se();z();Ue=".lbe/policy.json",So=".lbe/audit.jsonl"});import ze from"fs";import bo from"path";function Xe(e){if(typeof e=="number"&&Number.isFinite(e))return{ok:!0,kind:"int",parts:[Math.floor(e)],raw:String(e)};if(typeof e!="string"||!e.trim())return{ok:!1,reason:"POLICY_VERSION_INVALID",message:"Policy version is required"};let t=e.trim();if(/^\d+$/.test(t))return{ok:!0,kind:"int",parts:[Number(t)],raw:t};let o=t.replace(/^v/i,"");if(/^\d+(\.\d+){0,2}$/.test(o)){let n=o.split(".").map(r=>Number(r));for(;n.length<3;)n.push(0);return{ok:!0,kind:"semver",parts:n,raw:t}}return{ok:!1,reason:"POLICY_VERSION_INVALID",message:`Unsupported policy version format '${e}' (use integer or semver)`}}function vo(e,t){let o=Math.max(e.parts.length,t.parts.length);for(let n=0;n<o;n++){let r=e.parts[n]??0,s=t.parts[n]??0;if(r>s)return 1;if(r<s)return-1}return 0}function Qe(e){if(typeof e=="number"&&Number.isFinite(e))return{ok:!0,epochSec:e>1e12?Math.floor(e/1e3):Math.floor(e)};if(typeof e!="string"||!e.trim())return{ok:!1,reason:"POLICY_CREATED_AT_INVALID",message:"Policy createdAt is required"};let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,reason:"POLICY_CREATED_AT_INVALID",message:`Invalid policy createdAt '${e}'`}:{ok:!0,epochSec:Math.floor(t/1e3)}}function xo(e){if(!ze.existsSync(e))return{schemaVersion:"1",lastAccepted:null,updatedAt:null};try{let t=JSON.parse(ze.readFileSync(e,"utf8"));if(!t||typeof t!="object")throw new Error("Policy state file has invalid structure");return{schemaVersion:String(t.schemaVersion||"1"),lastAccepted:t.lastAccepted&&typeof t.lastAccepted=="object"?t.lastAccepted:null,updatedAt:t.updatedAt||null}}catch(t){throw new Error(`Policy state at ${e} is corrupt or unreadable: ${t.message}`)}}function wo(e,t){let o=JSON.stringify(t,null,2);D(e,o,{encoding:"utf8"})}function Ze({policyObj:e,statePath:t=bo.resolve(".lbe/data/policy.state.json"),maxCreatedAtSkewSec:o=31536e3,nowSec:n=Math.floor(Date.now()/1e3),persist:r=!0}){let s=Xe(e?.version);if(!s.ok)return{ok:!1,reason:s.reason,message:s.message,updated:!1};let i=Qe(e?.createdAt);if(!i.ok)return{ok:!1,reason:i.reason,message:i.message,updated:!1};let a=Math.abs(n-i.epochSec),l=Number.isFinite(o)&&o>0?Math.floor(o):31536e3;if(a>l)return{ok:!1,reason:"POLICY_CREATED_AT_SKEW_EXCEEDED",message:`Policy createdAt skew ${a}s exceeds allowed ${l}s`,updated:!1};let c;try{c=xo(t)}catch(u){return{ok:!1,reason:"POLICY_STATE_CORRUPT",message:u.message,updated:!1}}let p=c.lastAccepted,f=null,m=null,y=0;if(p&&(f=Xe(p.version),m=Qe(p.createdAt),f.ok&&m.ok)){if(y=vo(s,f),y<0)return{ok:!1,reason:"POLICY_VERSION_REGRESSION",message:`Policy version regression: current '${s.raw}' < last '${f.raw}'`,updated:!1};if(y===0&&i.epochSec<m.epochSec)return{ok:!1,reason:"POLICY_CREATED_AT_REGRESSION",message:`Policy createdAt regression: current '${e.createdAt}' < last '${p.createdAt}'`,updated:!1};if(y>0&&i.epochSec<m.epochSec)return{ok:!1,reason:"POLICY_CREATED_AT_REGRESSION",message:"Policy createdAt must be monotonic when version increases",updated:!1}}let h=!p||!f?.ok||!m?.ok||y>0||y===0&&i.epochSec>m.epochSec;if(r&&h){let u={schemaVersion:"1",lastAccepted:{version:e.version,createdAt:e.createdAt,environment:e.environment||null},updatedAt:new Date().toISOString()};wo(t,u)}return{ok:!0,reason:null,message:"Policy version guard passed",updated:h}}var et=L(()=>{z()});import tt from"fs";import nt from"path";import{fileURLToPath as _o}from"url";function B(){if(se)return se;if(!tt.existsSync(xe))throw new Error(`LBE engine missing: ${xe}`);let e=tt.readFileSync(xe);return se=new WebAssembly.Instance(new WebAssembly.Module(e),{}),se}function ie(){return new Uint8Array(B().exports.memory.buffer)}function rt(){return B().exports.lbe_in_ptr()}function st(){return B().exports.lbe_out_ptr()}function To(){return B().exports.lbe_buf_size()}function it(e){let t=new TextEncoder().encode(e),o=ie(),n=rt();o.set(t,n),o[n+t.length]=0}function at(){let e=ie(),t=st(),o=t;for(;e[o]!==0&&o-t<To();)o++;return new TextDecoder().decode(e.slice(t,o))}function Co(e){let t=ie(),o=rt(),n=new DataView(t.buffer,o);e.forEach((r,s)=>n.setUint32(s*4,r>>>0,!0))}function Po(){let e=ie(),t=st(),o=new DataView(e.buffer,t);return{stage:o.getUint32(0,!0),code:o.getUint32(4,!0)}}function ct(e){Co([e.hasId?1:0,e.idValid?1:0,e.hasCommandId?1:0,e.commandIdValid?1:0,e.hasRequesterId?1:0,e.requesterIdValid?1:0,e.hasSessionId?1:0,e.sessionIdValid?1:0,e.hasTimestamp?1:0,e.timestampValid?1:0,e.hasNonce?1:0,e.nonceValid?1:0,e.hasRequires?1:0,e.requiresValid?1:0,e.hasPayload?1:0,e.hasPayloadAdapter?1:0,e.payloadAdapterValid?1:0,e.hasSignature?1:0,e.hasSignatureAlg?1:0,e.signatureAlgValid?1:0,e.hasSignatureKeyId?1:0,e.hasSignatureSig?1:0,e.signatureSigValid?1:0,e.hasRisk?1:0,e.riskValid?1:0,e.cmdTimestamp>>>0,e.nowSec>>>0,e.maxClockSkewSec>>>0,e.keyIdFormatValid?1:0,e.keyFound?1:0,e.keyNotDeprecated?1:0,e.keyRequesterMatches?1:0,e.keyNotBeforeOk?1:0,e.keyNotExpired?1:0,e.keyLifecycleFieldsPresent?1:0,e.signatureValid?1:0,e.rateLimitOk?1:0,e.rateLimitRetryAfterSec>>>0,e.nonceOk?1:0,e.policyConfigured?1:0,e.requesterConfigured?1:0,e.commandAllowed?1:0,e.adapterAllowed?1:0,e.filesystemRequired?1:0,e.filesystemRootsDefined?1:0,e.filesystemOk?1:0,e.pathDenied?1:0,e.shellRequired?1:0,e.shellCommandOk?1:0]),B().exports.lbe_validate_pipeline();let{stage:t,code:o}=Po();return{ok:t===255,stage:t,stageLabel:Ro[t]||"unknown",code:o,schemaError:t===0?Oo[o]?.error||"Schema invalid":null,keyReason:t===2?No[o]||"KEY_ERROR":null,policyResult:t===6?{...ot[o]||ot[1],code:o}:null,retryAfterSec:t===4?o:0,skewSec:t===1?o:0}}function we({ttlSec:e,nowSec:t,newKey:o,existingEntries:n}){let r=[`${e}:${t}`,o,...n].join(`
7
7
  `)+`
8
- `;if(it(r),M().exports.lbe_nonce_check()!==0)return{ok:!1,updatedEntriesText:null};let i=at();return{ok:!0,updatedEntriesText:i.startsWith(`OK
8
+ `;if(it(r),B().exports.lbe_nonce_check()!==0)return{ok:!1,updatedEntriesText:null};let i=at();return{ok:!0,updatedEntriesText:i.startsWith(`OK
9
9
  `)?i.slice(3):i}}function lt({windowSec:e,maxRequests:t,nowSec:o,requesterId:n,existingEntries:r}){let s=[`${e}:${t}:${o}`,n,...r].join(`
10
10
  `)+`
11
- `;it(s);let i=M().exports.lbe_rate_check()!==0,a=at();if(i){let c=parseInt(a.match(/^EXCEEDED:(\d+)/)?.[1]??"1",10),l=a.replace(/^EXCEEDED:\d+\n/,"");return{ok:!1,retryAfterSec:c,updatedEntriesText:l}}return{ok:!0,retryAfterSec:0,updatedEntriesText:a.startsWith(`OK
12
- `)?a.slice(3):a}}function dt(e,t=!1){let o=Do[e]??0,n=M().exports.lbe_classify_risk(o,t?1:0);return Lo[n]??"LOW"}var Ao,xe,ot,Oo,No,Ro,Lo,Do,se,ut=L(()=>{Ao=nt.dirname(_o(import.meta.url)),xe=nt.join(Ao,"lbe_engine.wasm"),ot={0:{allowed:!0,reason:null,message:"Policy check passed"},1:{allowed:!1,reason:"POLICY_NOT_CONFIGURED",message:"No policy configured"},2:{allowed:!1,reason:"REQUESTER_NOT_ALLOWED",message:"Requester not in policy"},3:{allowed:!1,reason:"COMMAND_NOT_ALLOWED",message:"Command not allowed for requester"},4:{allowed:!1,reason:"ADAPTER_NOT_ALLOWED",message:"Adapter not allowed"},5:{allowed:!1,reason:"NO_FILESYSTEM_ROOTS_DEFINED",message:"No filesystem roots defined for requester"},6:{allowed:!1,reason:"CWD_OUTSIDE_ALLOWED_ROOT",message:"Path not under allowed roots"},7:{allowed:!1,reason:"PATH_DENIED_BY_PATTERN",message:"Path matches deny pattern"},8:{allowed:!1,reason:"SHELL_CMD_DENIED",message:"Shell command not allowed"}},Oo={0:{valid:!0,error:null},1:{valid:!1,error:"Missing required field: id"},2:{valid:!1,error:"Missing required field: commandId"},3:{valid:!1,error:"Missing required field: requesterId"},4:{valid:!1,error:"Missing required field: sessionId"},5:{valid:!1,error:"Missing required field: timestamp"},6:{valid:!1,error:"Missing required field: nonce"},7:{valid:!1,error:"Missing required field: requires"},8:{valid:!1,error:"Missing required field: payload"},9:{valid:!1,error:"Missing required field: signature"},10:{valid:!1,error:"Field 'id' is invalid"},11:{valid:!1,error:"Field 'commandId' is invalid"},12:{valid:!1,error:"Field 'requesterId' is invalid"},13:{valid:!1,error:"Field 'sessionId' is invalid"},14:{valid:!1,error:"Field 'timestamp' is invalid"},15:{valid:!1,error:"Field 'nonce' is invalid"},16:{valid:!1,error:"Field 'requires' is invalid"},17:{valid:!1,error:"payload: missing required field: adapter"},18:{valid:!1,error:"payload: field 'adapter' is invalid"},19:{valid:!1,error:"signature: missing required field: alg"},20:{valid:!1,error:"signature: missing required field: keyId"},21:{valid:!1,error:"signature: missing required field: sig"},22:{valid:!1,error:"signature: field 'alg' must be ed25519"},23:{valid:!1,error:"signature: field 'sig' is invalid"},24:{valid:!1,error:"Field 'risk' is invalid"}},No={1:"KEY_ID_INVALID",2:"KEY_NOT_TRUSTED",3:"KEY_DEPRECATED",4:"KEY_REQUESTER_MISMATCH",5:"KEY_LIFECYCLE_INVALID",6:"KEY_NOT_YET_VALID",7:"KEY_EXPIRED"},Ro={0:"schema",1:"timestamp",2:"key",3:"signature",4:"rate_limit",5:"nonce",6:"policy",255:"ok"},Lo=["LOW","MEDIUM","HIGH","CRITICAL"],Do={ECHO:0,READ_FILE:1,WRITE_FILE:2,PATCH_FILE:3,DELETE_FILE:4,RUN_SHELL:5},se=null});import _e from"path";function Fo(e){let t=s=>e!=null&&Object.prototype.hasOwnProperty.call(e,s),o=s=>typeof s=="string",n=e?.payload,r=e?.signature;return{hasId:t("id"),idValid:o(e?.id)&&/^[A-Z_]+$/.test(e.id)&&e.id.length>=1&&e.id.length<=50,hasCommandId:t("commandId"),commandIdValid:o(e?.commandId)&&/^[a-f0-9-]+$/.test(e.commandId)&&e.commandId.length===36,hasRequesterId:t("requesterId"),requesterIdValid:o(e?.requesterId)&&e.requesterId.length>=3&&e.requesterId.length<=100,hasSessionId:t("sessionId"),sessionIdValid:o(e?.sessionId)&&e.sessionId.length>=3,hasTimestamp:t("timestamp"),timestampValid:typeof e?.timestamp=="number"&&e.timestamp>=1e9,hasNonce:t("nonce"),nonceValid:o(e?.nonce)&&e.nonce.length>=32&&e.nonce.length<=128,hasRequires:t("requires"),requiresValid:Array.isArray(e?.requires)&&e.requires.length>=1&&e.requires.every(o),hasPayload:t("payload")&&typeof n=="object"&&n!==null&&!Array.isArray(n),hasPayloadAdapter:n!=null&&Object.prototype.hasOwnProperty.call(n,"adapter"),payloadAdapterValid:o(n?.adapter),hasSignature:t("signature")&&typeof r=="object"&&r!==null&&!Array.isArray(r),hasSignatureAlg:r!=null&&Object.prototype.hasOwnProperty.call(r,"alg"),signatureAlgValid:r?.alg==="ed25519",hasSignatureKeyId:r!=null&&Object.prototype.hasOwnProperty.call(r,"keyId"),hasSignatureSig:r!=null&&Object.prototype.hasOwnProperty.call(r,"sig"),signatureSigValid:o(r?.sig)&&r.sig.length>=10,hasRisk:t("risk"),riskValid:["LOW","MEDIUM","HIGH","CRITICAL"].includes(e?.risk)}}function jo(e,t){let o=!!(e&&e.default==="DENY"&&e.requesters&&typeof e.requesters=="object"),n=e?.requesters?.[t.requesterId],r=t.id?.toLowerCase()??"",s=!!n?.allowCommands?.some(y=>y.toLowerCase()===r),i=!!n?.allowAdapters?.includes(t.payload?.adapter),a=!!t.payload?.cwd,c=!1,l=!1,p=!1;if(a){let y=n?.filesystem?.roots??[];if(c=y.length>0,c){let h=_e.resolve(t.payload.cwd);l=y.some(d=>{let g=_e.resolve(d);return h===g||h.startsWith(g+_e.sep)}),p=(n?.filesystem?.denyPatterns??[]).some(d=>new RegExp("^"+d.replace(/\./g,"\\.").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")+"$").test(h))}}let f=!1,m=!0;if(t.id==="RUN_SHELL"){f=!0;let y=n?.exec?.allowCmds??[],h=n?.exec?.denyCmds??[],u=t.payload?.cmd;h.includes(u)?m=!1:m=y.length===0||y.includes(u)}return{policyConfigured:o,requesterConfigured:!!n,commandAllowed:s,adapterAllowed:i,filesystemRequired:a,filesystemRootsDefined:c,filesystemOk:l,pathDenied:p,shellRequired:f,shellCommandOk:m}}function $o(e,t,o,n=new Date){if(!e||!t)return{keyIdFormatValid:!1,keyFound:!1,keyNotDeprecated:!1,keyRequesterMatches:!1,keyNotBeforeOk:!1,keyNotExpired:!1,keyLifecycleFieldsPresent:!1,publicKey:null};let s=/^[A-Za-z0-9:_-]{3,128}$/.test(t)&&t!=="default";if(!s)return{keyIdFormatValid:s,keyFound:!1,keyNotDeprecated:!1,keyRequesterMatches:!1,keyNotBeforeOk:!1,keyNotExpired:!1,keyLifecycleFieldsPresent:!1,publicKey:null};let i=e.trustedKeys?.[t],a=!!i;if(!a)return{keyIdFormatValid:s,keyFound:a,keyNotDeprecated:!1,keyRequesterMatches:!1,keyNotBeforeOk:!1,keyNotExpired:!1,keyLifecycleFieldsPresent:!1,publicKey:null};let c=!i.deprecated,l=!i.requesterId||i.requesterId===o,p=i.notBefore||i.validFrom,f=i.expiresAt||i.validUntil,m=typeof p=="string"&&typeof f=="string",y=!1,h=!1;if(m){let u=new Date(p),d=new Date(f);!isNaN(u.getTime())&&!isNaN(d.getTime())&&u<d&&(y=n>=u,h=n<d)}return{keyIdFormatValid:s,keyFound:a,keyNotDeprecated:c,keyRequesterMatches:l,keyNotBeforeOk:y,keyNotExpired:h,keyLifecycleFieldsPresent:m,publicKey:i.publicKey??null}}function ft(e){return(e?.entries??[]).map(t=>`${t.key}:${t.timestamp}`)}function pt(e){return e.split(`
13
- `).filter(Boolean).map(t=>{let o=t.lastIndexOf(":");return{key:t.slice(0,o),timestamp:parseInt(t.slice(o+1),10)||0}})}function Ko(e){return(e?.entries??[]).map(t=>`${t.requesterId}:${t.timestamp}`)}function qo(e){return e.split(`
14
- `).filter(Boolean).map(t=>{let o=t.lastIndexOf(":");return{requesterId:t.slice(0,o),timestamp:parseInt(t.slice(o+1),10)||0}})}function mt({commandObj:e,pubKeyB64:t,keyStore:o,nonceDb:n,policy:r,rateLimiter:s,policyStatePath:i}){let a={valid:!1,commandId:e?.commandId,checks:{},errors:[]},c=Math.floor(Date.now()/1e3),l=new Date,p=Number.isFinite(r?.security?.maxClockSkewSec)?r.security.maxClockSkewSec:600;if(i&&r?.version!==void 0)try{let k=Ze({policyObj:r,statePath:i});if(a.checks.policyVersion=k.ok,!k.ok)return a.errors.push({type:"POLICY_VERSION_INVALID",message:k.message}),a}catch{a.checks.policyVersion=!0}else a.checks.policyVersion=!0;let f=Fo(e),m=e?.signature?.keyId,y=$o(o,m,e?.requesterId,l),h=!1,u=y.publicKey;if(!u&&t&&(u=t),u){let k={...e};delete k.signature,h=me({payloadObj:k,sigB64:e?.signature?.sig,pubKeyB64:u}).valid}let d=!0,g=0;if(h&&s&&typeof s.db<"u"){let k=r?.requesters?.[e.requesterId]?.rateLimit||{},_=r?.security?.defaultRateLimit||{},K=k.windowSec??_.windowSec??60,Ft=k.maxRequests??_.maxRequests??30,oe=lt({windowSec:K,maxRequests:Ft,nowSec:c,requesterId:e.requesterId,existingEntries:Ko(s.db)});d=oe.ok,g=oe.retryAfterSec,oe.ok&&(s.db.entries=qo(oe.updatedEntriesText))}else if(h&&s&&typeof s.checkAndRecord=="function"){let k=r?.requesters?.[e.requesterId]?.rateLimit||{},_=r?.security?.defaultRateLimit||{},K=s.checkAndRecord({requesterId:e.requesterId,nowSec:c,windowSec:k.windowSec??_.windowSec??60,maxRequests:k.maxRequests??_.maxRequests??30});d=K.ok,g=K.retryAfterSec??0}let I=!0,b=`${e?.requesterId}|${e?.sessionId}|${e?.nonce}`,$=3600;if(h&&d&&n)if(typeof n.checkAndRecord=="function")if(n.db){let k=we({ttlSec:$,nowSec:c,newKey:b,existingEntries:ft(n.db)});I=k.ok,k.ok&&(n.db.entries=pt(k.updatedEntriesText))}else I=n.checkAndRecord({requesterId:e.requesterId,sessionId:e.sessionId,nonce:e.nonce}).ok;else{let k=we({ttlSec:$,nowSec:c,newKey:b,existingEntries:ft(n)});I=k.ok,k.ok&&(n.entries=pt(k.updatedEntriesText))}let O=jo(r,e??{}),w=ct({...f,cmdTimestamp:e?.timestamp??0,nowSec:c,maxClockSkewSec:p,...y,signatureValid:h,rateLimitOk:d,rateLimitRetryAfterSec:g,nonceOk:I,...O}),x=w.stage;if(a.checks.schema=x!==0,x>=1&&(a.checks.timestamp=x!==1),x>=2&&(a.checks.keyId=x!==2),x>=2&&(a.checks.signature=x!==2&&x!==3),x>=4&&(a.checks.rateLimit=x!==4),x>=5&&(a.checks.nonce=x!==5),(x>=6||w.ok)&&(a.checks.policy=x!==6),!w.ok){let k=w.stageLabel;if(k==="schema")a.errors.push({type:"SCHEMA_ERROR",message:w.schemaError||"Schema invalid"});else if(k==="timestamp")a.errors.push({type:"TIMESTAMP_SKEW_EXCEEDED",message:`Command timestamp skew ${w.skewSec}s exceeds allowed ${p}s`});else if(k==="key"){let _=w.keyReason||"KEY_ERROR",K={KEY_ID_INVALID:`Invalid keyId '${m}'`,KEY_NOT_TRUSTED:`Key '${m}' is not in trusted key store`,KEY_DEPRECATED:`Key '${m}' is deprecated`,KEY_REQUESTER_MISMATCH:`Key '${m}' is not authorized for requester '${e?.requesterId}'`,KEY_LIFECYCLE_INVALID:`Key '${m}' must define notBefore and expiresAt`,KEY_NOT_YET_VALID:`Key '${m}' is not yet valid`,KEY_EXPIRED:`Key '${m}' has expired`};a.errors.push({type:_,message:K[_]||_})}else k==="signature"?a.errors.push({type:"SIGNATURE_INVALID",message:u?"Signature verification failed":"No public key available"}):k==="rate_limit"?a.errors.push({type:"RATE_LIMIT_EXCEEDED",message:`Rate limit exceeded. Retry after ${w.retryAfterSec}s`}):k==="nonce"?a.errors.push({type:"REPLAY_NONCE",message:"Nonce has already been used"}):k==="policy"&&w.policyResult?a.errors.push({type:w.policyResult.reason,message:w.policyResult.message}):a.errors.push({type:"VALIDATION_FAILED",message:`Failed at stage: ${k}`});return a}return a.valid=!0,a.risk=dt(e.id,e.payload?.cmd==="rm"),a.message="Command validation successful",a}var yt=L(()=>{Z();et();ut()});async function gt(e){return{adapter:"noop",commandId:e.commandId||"unknown",command:e.id||"unknown",status:"completed",output:`[NOOP] Would execute: ${e.id||"unknown"} on adapter: ${e.payload?.adapter||"unknown"}`,exitCode:0,timestamp:new Date().toISOString()}}var ht=L(()=>{});import{spawnSync as Mo}from"child_process";import Ae from"path";import Vo from"fs";function St(e){try{return Vo.realpathSync(Ae.resolve(e))}catch{return Ae.resolve(e)}}function Bo(e){if(e===void 0)return{ok:!0,args:[]};if(!Array.isArray(e))return{ok:!1,error:"payload.args must be an array"};let t=[];for(let o of e){if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")return{ok:!1,error:"payload.args may only contain string, number, or boolean values"};t.push(String(o))}return{ok:!0,args:t}}async function kt(e,t,o){let n=e.payload,r=Math.min(Math.max(Number(n.timeoutMs)||3e4,1),3e4),s=Math.min(Math.max(Number(n.maxOutputBytes)||1024*1024,1024),1024*1024);if(n.adapter!=="shell")return{adapter:"shell",commandId:e.commandId,status:"error",error:"Adapter mismatch",exitCode:1};let i=o?.exec?.allowCmds||[];if((o?.exec?.denyCmds||[]).includes(n.cmd))return{adapter:"shell",commandId:e.commandId,status:"blocked",error:`Command '${n.cmd}' is denied`,exitCode:2};if(i.length>0&&!i.includes(n.cmd))return{adapter:"shell",commandId:e.commandId,status:"blocked",error:`Command '${n.cmd}' not in allowlist`,exitCode:2};if(!(o?.filesystem?.roots||[]).some(f=>{let m=St(f),y=St(n.cwd);return y===m||y.startsWith(m+Ae.sep)}))return{adapter:"shell",commandId:e.commandId,status:"blocked",error:`CWD '${n.cwd}' not authorized`,exitCode:2};let p=Bo(n.args);if(!p.ok)return{adapter:"shell",commandId:e.commandId,status:"blocked",error:p.error,exitCode:2};try{let f=Mo(n.cmd,p.args,{cwd:n.cwd,timeout:r,encoding:"utf8",maxBuffer:s,stdio:["pipe","pipe","pipe"],shell:!1});if(f.error)throw f.error;let m=`${f.stdout||""}${f.stderr||""}`,y=f.status??1;return y!==0?{adapter:"shell",commandId:e.commandId,command:n.cmd,status:"error",error:m.substring(0,s)||`Command exited with code ${y}`,exitCode:y,timestamp:new Date().toISOString()}:{adapter:"shell",commandId:e.commandId,command:n.cmd,status:"completed",output:m.substring(0,s),exitCode:0,timestamp:new Date().toISOString()}}catch(f){return{adapter:"shell",commandId:e.commandId,command:n.cmd,status:"error",error:f.message,exitCode:f.status||1,timestamp:new Date().toISOString()}}}var Et=L(()=>{});import V from"fs";import ae from"path";import Yo from"crypto";function It(e,t){let o=t||ae.resolve(".lbe/data/backups");V.existsSync(o)||V.mkdirSync(o,{recursive:!0});let n=ae.resolve(e),r=V.existsSync(n),s=null,i=null;r&&(s=V.readFileSync(n),i=Yo.createHash("sha256").update(s).digest("hex"));let a=ae.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_"),c=`${Date.now()}-${i?i.slice(0,8):"new"}-${a}`,l=r?ae.join(o,c):null;return r&&s!==null&&D(l,s),{originalPath:n,backupPath:l,existed:r,hash:i,createdAt:new Date().toISOString()}}function ce(e){if(!e)return{restored:!1,error:"No backup metadata"};let{originalPath:t,backupPath:o,existed:n}=e;if(!n)try{return V.existsSync(t)&&V.unlinkSync(t),{restored:!0,action:"deleted"}}catch(r){return{restored:!1,error:r.message}}if(!o||!V.existsSync(o))return{restored:!1,error:"Backup file not found at: "+o};try{let r=V.readFileSync(o);return D(t,r),{restored:!0,action:"restored"}}catch(r){return{restored:!1,error:r.message}}}var bt=L(()=>{z()});import H from"fs";import B from"path";function Wo(e,t){return e?B.isAbsolute(e)?B.resolve(e):B.resolve(t||process.cwd(),e):null}function Go(e,t){let o=vt(e);return t.some(n=>{let r=vt(n);return o===r||o.startsWith(r+B.sep)})}function vt(e){let t=B.resolve(e),o=[];for(;!H.existsSync(t);){let n=B.dirname(t);if(n===t)break;o.unshift(B.basename(t)),t=n}try{t=H.realpathSync(t)}catch{}return B.join(t,...o)}function Ho(e,t){for(let o of t||[])if(new RegExp("^"+o.replace(/\./g,"\\.").replace(/\*\*/g,".*").replace(/\*/g,"[^/\\\\]*")+"$").test(e))return o;return null}function X(e,t,o,n=2){return{adapter:"file",commandId:e.commandId,status:"blocked",errorCode:t,error:o,exitCode:n}}function j(e,t,o,n=null,r=1){return{adapter:"file",commandId:e.commandId,status:"error",errorCode:t,error:o,backup:n?le(n):null,exitCode:r}}function le(e){return e?{path:e.backupPath,existed:e.existed,hash:e.hash,createdAt:e.createdAt}:null}async function xt(e,t,o){let n=e.payload,r=n.action,s=n.cwd||process.cwd(),i=Wo(n.target,s);if(!r)return X(e,"FILE_NO_ACTION","payload.action is required");if(!i&&r!=="noop")return X(e,"FILE_NO_TARGET","payload.target is required");let a=o?.filesystem?.roots||[];if(a.length===0)return X(e,"FILE_NO_ROOTS","No filesystem roots defined for requester");if(!Go(i,a))return X(e,"FILE_OUTSIDE_ROOT",`'${i}' is outside allowed roots`);let c=Ho(i,o?.filesystem?.denyPatterns);if(c)return X(e,"FILE_PATH_DENIED",`'${i}' matches deny pattern: ${c}`);switch(r){case"read":return Jo(e,i);case"write":return zo(e,i,n);case"patch":return Xo(e,i,n);case"delete":return Qo(e,i);default:return X(e,"FILE_UNKNOWN_ACTION",`Unknown action: '${r}'`)}}function Jo(e,t){if(!H.existsSync(t))return j(e,"FILE_NOT_FOUND",`Not found: ${t}`);try{let o=H.statSync(t);if(o.size>Uo)return j(e,"FILE_TOO_LARGE","File exceeds 10 MB read limit");let n=H.readFileSync(t,"utf8");return{adapter:"file",action:"read",commandId:e.commandId,status:"completed",target:t,output:n,bytesRead:o.size,exitCode:0}}catch(o){return j(e,"FILE_READ_ERROR",o.message)}}function zo(e,t,o){let n=o.content;if(n==null)return j(e,"FILE_MISSING_CONTENT","payload.content is required for write");let r=Oe(t);try{return D(t,n,{encoding:"utf8"}),{adapter:"file",action:"write",commandId:e.commandId,status:"completed",target:t,backup:le(r),output:`Wrote ${Buffer.byteLength(n,"utf8")} bytes to ${t}`,exitCode:0}}catch(s){return ce(r),j(e,"FILE_WRITE_ERROR",s.message,r)}}function Xo(e,t,o){let n=o.content;if(n==null)return j(e,"FILE_MISSING_CONTENT","payload.content is required for patch");let r=Oe(t);try{return D(t,n,{encoding:"utf8"}),{adapter:"file",action:"patch",commandId:e.commandId,status:"completed",target:t,backup:le(r),output:`Patched ${t} (${Buffer.byteLength(n,"utf8")} bytes)`,exitCode:0}}catch(s){return ce(r),j(e,"FILE_PATCH_ERROR",s.message,r)}}function Qo(e,t){if(!H.existsSync(t))return j(e,"FILE_NOT_FOUND",`Not found: ${t}`);let o=Oe(t);try{return H.unlinkSync(t),{adapter:"file",action:"delete",commandId:e.commandId,status:"completed",target:t,backup:le(o),output:`Deleted ${t}`,exitCode:0}}catch(n){return ce(o),j(e,"FILE_DELETE_ERROR",n.message,o)}}function Oe(e){try{return It(e)}catch{return null}}var Uo,wt=L(()=>{z();bt();Uo=10*1024*1024});function Zo(e){return _t[e]}async function At(e,t,o,n){let r=Zo(e);if(!r)return{adapter:e,commandId:t.commandId,status:"error",error:`Adapter '${e}' not found`,exitCode:1};try{return await r(t,o,n)}catch(s){return{adapter:e,commandId:t.commandId,status:"error",error:`Adapter execution failed: ${s.message}`,exitCode:9}}}var _t,Dr,Ot=L(()=>{ht();Et();wt();_t={noop:gt,shell:kt,file:xt};Dr=Object.keys(_t)});var Dt={};$t(Dt,{createLocalExecutor:()=>sn});import Nt from"crypto";import J from"fs";import N from"path";function T(e,t,o=!1){return{ok:!1,decision:"deny",executed:!1,dryRun:!1,error:{code:e,message:t,recoverable:o}}}function en(e,t,o={}){let n=new Date,r=new Date(n.getTime()+365*24*60*60*1e3);return{version:1,default:"DENY",requesters:{[t]:{allowCommands:Object.values(Lt).map(s=>s.id),allowAdapters:["file","shell"],filesystem:{roots:[e],denyPatterns:[]},exec:{allowCmds:o.allowCommands||[],denyCmds:o.denyCommands||[]},rateLimit:{windowSec:60,maxRequests:o.maxRequests||60}}},security:{maxClockSkewSec:600,defaultRateLimit:{windowSec:60,maxRequests:60}},_keyWindow:{notBefore:n.toISOString(),expiresAt:r.toISOString()}}}function Rt(e){let t=N.resolve(e),o=[];for(;!J.existsSync(t);){let n=N.dirname(t);if(n===t)break;o.unshift(N.basename(t)),t=n}try{t=J.realpathSync(t)}catch{}return N.join(t,...o)}function Re(e,t){let o=Rt(e),n=Rt(t);return o===n||o.startsWith(n+N.sep)}function on(e,t){if(typeof e!="string")return null;for(let o of tn)if(o.test(e))return T("PAYLOAD_CONTENT_REJECTED",`Forbidden pattern in ${t}: ${o}`);return null}function nn(e,t,o={}){if(!t||typeof t!="object")return{error:T("REQUEST_INVALID","request must be an object")};let n=Lt[t.intent];if(!n)return{error:T("INTENT_UNSUPPORTED",`Unsupported intent '${t.intent}'`)};let r=typeof t.actor=="string"&&t.actor?t.actor:"agent:local",s=null;if(n.adapter==="file"){if(typeof t.target!="string"||!t.target)return{error:T("TARGET_REQUIRED","target is required for file intents")};if(s=N.resolve(e,t.target),!Re(s,e))return{error:T("PATH_OUTSIDE_ROOT","target is outside project root")};if(["write_file","patch_file"].includes(t.intent)&&typeof t.content!="string")return{error:T("CONTENT_REQUIRED","content is required for write and patch")};let a=on(t.content,"content");if(a)return{error:a}}let i=null;if(n.adapter==="shell"){if(i=t.command,!i||typeof i.cmd!="string"||!Array.isArray(i.args)||i.args.some(c=>typeof c!="string"))return{error:T("COMMAND_INVALID","command requires cmd and string args")};let a=N.resolve(e,i.cwd||".");if(!Re(a,e))return{error:T("CWD_OUTSIDE_ROOT","command cwd is outside project root")};if(!Array.isArray(o.allowCommands)||!o.allowCommands.includes(i.cmd))return{error:T("SHELL_NOT_ALLOWLISTED",`command '${i.cmd}' is not explicitly allowlisted`)};if(o.denyCommands?.includes(i.cmd))return{error:T("SHELL_DENIED",`command '${i.cmd}' is denied`)};i={...i,cwd:a,timeoutMs:Math.min(Math.max(i.timeoutMs||3e4,1),3e4),maxOutputBytes:Math.min(Math.max(i.maxOutputBytes||1024*1024,1024),1024*1024)}}return{actor:r,detail:n,target:s,command:i,request:t}}function rn(e,t,o){let{actor:n,detail:r,target:s,command:i,request:a}=e,c={id:r.id,risk:Ne.has(a.intent)?"MEDIUM":"LOW",commandId:Nt.randomUUID(),requesterId:n,sessionId:"local-host",timestamp:Math.floor(Date.now()/1e3),nonce:Nt.randomBytes(32).toString("hex"),requires:["policy","signature"],payload:{adapter:r.adapter,action:r.action,target:s,content:a.content,cmd:i?.cmd,args:i?.args,timeoutMs:i?.timeoutMs,maxOutputBytes:i?.maxOutputBytes,cwd:i?.cwd||(s?N.dirname(s):process.cwd())}},l=re({payloadObj:c,secretKeyB64:o});if(l.error)throw new Error(l.error);return{...c,signature:{alg:"ed25519",keyId:t,sig:l.signature}}}function sn(e={}){let t=N.resolve(e.rootDir||process.cwd()),o=e.keyId||"host:local-exec",n=e.keyPair||ne(),r=e.shell||{};function s(u,{recordNonce:d=!1}={}){let g=nn(t,u,r);if(g.error)return g;let I=G(t,e.mode||"enforce"),b=be(I.policy,t,{target:g.target,command:g.command?.cmd});if(I.policy.mode==="enforce"&&!b.allowed)return{error:T("LOCAL_POLICY_DENY",`Blocked by rule(s): ${b.winningRules.map(K=>K.id).join(", ")}`),local:I,localDecision:b,normalized:g};let O=en(t,g.actor,r),w={defaultKeyId:o,trustedKeys:{[o]:{publicKey:n.publicKey,notBefore:O._keyWindow.notBefore,expiresAt:O._keyWindow.expiresAt,deprecated:!1}}};delete O._keyWindow;let x=rn(g,o,n.secretKey),_=mt({commandObj:x,keyStore:w,nonceDb:d?{entries:[]}:{entries:[]},policy:O});return _.valid?{local:I,localDecision:b,normalized:g,proposal:x,policy:O,validation:_}:{error:T(_.errors[0]?.type||"VALIDATION_FAILED",_.errors[0]?.message||"Validation failed"),local:I,localDecision:b,normalized:g,proposal:x,policy:O,validation:_}}function i(u){let d=G(t,e.mode||"observe"),g=d.policy.mode,I=null,b=null;if(u.path)try{if(I=N.resolve(t,u.path),!Re(I,t))return{decision:"deny",deny:!0,matchedRules:["path:outside_root"],mode:g,enforced:g==="enforce",reason:"PATH_OUTSIDE_ROOT"}}catch{}u.cmd&&(b=u.cmd);let $=be(d.policy,t,{target:I,command:b}),O=!$.allowed;return{decision:O?"deny":"allow",deny:O,matchedRules:$.winningRules.map(w=>w.id),mode:g,enforced:g==="enforce"}}function a(u){let d=N.join(t,".lbe","events.jsonl"),g=N.dirname(d);J.existsSync(g)||J.mkdirSync(g,{recursive:!0});let I=JSON.stringify({ts:Math.floor(Date.now()/1e3),...u})+`
15
- `,b=J.openSync(d,"a");try{J.writeSync(b,I)}finally{J.closeSync(b)}}async function c(u){let d=s(u);return d.error?{...d.error,dryRun:!0}:{ok:!0,decision:d.local.policy.mode==="observe"?"observe":"allow",executed:!1,dryRun:!0,matchedRules:d.localDecision.winningRules.map(g=>g.id),rollback:{available:Ne.has(d.normalized.request.intent),performed:!1}}}async function l(u){let d=s(u,{recordNonce:!0});if(d.error)return He(t,{action:u?.intent,actor:u?.actor||"agent:local",decision:"deny",error:d.error.error.code}),d.error;if(d.local.policy.mode==="observe")return ee(N.join(t,".lbe/audit.jsonl"),{kind:"local_execution",commandId:d.proposal.commandId,requesterId:d.normalized.actor,intent:d.normalized.request.intent,decision:"observe",status:"observed"}),{ok:!0,decision:"observe",executed:!1,dryRun:!1,matchedRules:d.localDecision.winningRules.map(O=>O.id),rollback:{available:!1,performed:!1}};let g=d.policy.requesters[d.normalized.actor],I=await At(d.normalized.detail.adapter,d.proposal,d.policy,g),b=I.status==="completed",$=ee(N.join(t,".lbe/audit.jsonl"),{kind:"local_execution",commandId:d.proposal.commandId,requesterId:d.normalized.actor,intent:d.normalized.request.intent,decision:b?"allow":"deny",status:I.status});return{ok:b,decision:b?"allow":"deny",executed:b,dryRun:!1,matchedRules:d.localDecision.winningRules.map(O=>O.id),auditId:$.hash,rollback:{available:Ne.has(d.normalized.request.intent),performed:!1,backupId:I.backup?.hash},...b?{}:{error:{code:I.errorCode||"EXECUTION_FAILED",message:I.error||"Execution failed",recoverable:!0}}}}return{rootDir:t,writeFile:(u,d)=>l({intent:"write_file",target:u,content:d}),readFile:u=>l({intent:"read_file",target:u}),patchFile:(u,d)=>l({intent:"patch_file",target:u,content:d}),deleteFile:u=>l({intent:"delete_file",target:u}),runShell:(u,d=[],g={})=>l({intent:"run_shell",command:{cmd:u,args:d,...g}}),validate:async u=>({...await c(u),dryRun:!1,executed:!1}),dryRun:c,execute:l,policy:{read:()=>G(t,e.mode||"enforce").policy,proposeRule:Ge,addRule:u=>We(t,u,e.mode||"enforce")},audit:{verify:()=>Be(N.join(t,".lbe/audit.jsonl"))},evaluateSync:i,auditSync:a}}var Lt,Ne,tn,Tt=L(()=>{Z();yt();Ot();ke();ve();Lt={read_file:{id:"READ_FILE",adapter:"file",action:"read"},write_file:{id:"WRITE_FILE",adapter:"file",action:"write"},patch_file:{id:"PATCH_FILE",adapter:"file",action:"patch"},delete_file:{id:"DELETE_FILE",adapter:"file",action:"delete"},run_shell:{id:"RUN_SHELL",adapter:"shell",action:"run"}},Ne=new Set(["write_file","patch_file","delete_file"]);tn=[/\beval\s*\(/i,/\bFunction\s*\(/i,/\bexec\s*\(/i,/\brequire\s*\(/,/\bimport\s*\(/,/\bchild_process\b/,/\b__proto__\b/,/\bconstructor\s*\[/,/evalScript/i]});import E from"fs";import A from"path";import{spawn as de}from"child_process";import{fileURLToPath as an}from"url";Z();import S from"fs";import v from"path";import no from"readline";Z();import bn from"fs";import xn from"path";import gn from"fs";import Sn from"path";function De({policyObj:e,secretKeyB64:t,keyId:o}){let n=re({payloadObj:e,secretKeyB64:t});return n.error?{ok:!1,reason:"POLICY_SIGNATURE_CREATE_FAILED",message:n.error,envelope:null}:{ok:!0,reason:null,message:"Policy signature created",envelope:{alg:"ed25519",keyId:o,sig:n.signature,createdAt:Math.floor(Date.now()/1e3)}}}import ye from"fs";import C from"path";var Kt=[{file:"package.json",type:"node"},{file:"pyproject.toml",type:"python"},{file:"requirements.txt",type:"python"},{file:"go.mod",type:"go"},{file:"Cargo.toml",type:"rust"},{file:"pom.xml",type:"java"},{file:"build.gradle",type:"java"},{file:"build.gradle.kts",type:"java"},{file:"Dockerfile",type:"docker"},{file:"docker-compose.yml",type:"docker"},{dir:".github/workflows",type:"ci"},{file:".gitlab-ci.yml",type:"ci"},{dir:".circleci",type:"ci"},{file:"Jenkinsfile",type:"ci"},{file:".travis.yml",type:"ci"}],ge=["node","python","go","rust","java"],qt={source:["src","lib","app","pages","components","core","api","server","client","pkg","cmd"],generated:["dist","build",".next","out","coverage","target",".cache","__pycache__",".turbo"],tests:["test","tests","__tests__","spec","e2e"],docs:["docs","doc","documentation"]},Pe=[".env",".env.*","keys/**","secrets/**","*.key","*.pem","*.p12","*.pfx","*.crt"],Mt=["node_modules/**",".git/**"],Vt={node:["package-lock.json","yarn.lock","pnpm-lock.yaml"],python:["Pipfile.lock","poetry.lock"],go:["go.sum"],rust:["Cargo.lock"],java:["gradle/wrapper/**"],docker:[],ci:[],generic:[]},Te={node:["package.json","tsconfig*.json","jest.config.*","vite.config.*","next.config.*","webpack.config.*",".eslintrc*",".eslint.config.*",".prettierrc*","babel.config.*"],python:["pyproject.toml","setup.py","setup.cfg","tox.ini","pytest.ini","mypy.ini",".flake8",".pylintrc","Pipfile"],go:["go.mod",".golangci.yml",".golangci.yaml"],rust:["Cargo.toml","rust-toolchain.toml","clippy.toml",".rustfmt.toml"],java:["pom.xml","build.gradle","build.gradle.kts","gradle.properties","settings.gradle","settings.gradle.kts"],docker:["Dockerfile","docker-compose.yml",".dockerignore"],ci:[".gitlab-ci.yml","Jenkinsfile",".travis.yml"],generic:["Makefile","CMakeLists.txt","meson.build"]},Bt=[".editorconfig",".nvmrc",".node-version",".python-version"],Yt=["config",".github",".gitlab",".circleci",".vscode"],Ut={node:"dependency and build config",python:"package and environment config",go:"module definition",rust:"crate manifest",java:"build definition",docker:"container config",ci:"pipeline definition",generic:"project config"},Wt={node:"package manager",python:"dependency resolver",go:"module checksums",rust:"dependency resolver",java:"Gradle wrapper"},Gt=["composer.json","Gemfile","mix.exs","pubspec.yaml","Package.swift","project.clj","build.sbt","stack.yaml","deno.json","deno.jsonc","Podfile"],Ht=["composer.lock","Gemfile.lock","mix.lock","pubspec.lock","Package.resolved"],Jt=[".csproj",".fsproj",".sln",".cabal"];function F(e){return ye.existsSync(e)}function Ce(e,t){return t.filter(o=>F(C.join(e,o))).map(o=>`${o}/**`)}function zt(e){let t=C.join(e,".gitignore");return F(t)?ye.readFileSync(t,"utf8").split(`
16
- `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")&&!o.startsWith("!")).map(o=>o.endsWith("/")?o+"**":o):[]}function U(e){return e.filter((t,o,n)=>t&&n.indexOf(t)===o)}function Xt(e){let t=new Set,o=[];for(let n of Kt){if(t.has(n.type))continue;let r=C.join(e,n.file||n.dir);F(r)&&(t.add(n.type),o.push(n.type))}return o.length>0?o:["generic"]}function Qt(e){return ge.find(t=>e.includes(t))??"generic"}function Zt(e){let t=Gt.filter(n=>F(C.join(e,n))),o=Ht.filter(n=>F(C.join(e,n)));try{let n=ye.readdirSync(e);for(let r of n)Jt.some(s=>r.endsWith(s))&&t.push(r)}catch{}return{manifests:t,lockfiles:o}}function eo(e,t){let o={};for(let[r,s]of Object.entries(qt))o[r]=Ce(e,s);o.secrets=Pe.filter(r=>{let s=r.split("/")[0].replace(/\*.*/,"");return s.includes("*")||F(C.join(e,s))});let n=U(t.flatMap(r=>Te[r]||Te.generic).concat(Bt));if(o.config=U([...n.filter(r=>!r.includes("*")&&!r.endsWith("/**")&&F(C.join(e,r))),...n.filter(r=>r.endsWith("/**")&&F(C.join(e,r.replace("/**","")))),...Ce(e,Yt)]),o.lockfiles=U(t.flatMap(r=>Vt[r]||[]).filter(r=>{let s=r.replace(/\*.*/,"").split("/")[0];return s.includes("*")||F(C.join(e,s))})),!t.some(r=>ge.includes(r))){let r=Zt(e);o.config=U([...o.config,...r.manifests]),o.lockfiles=U([...o.lockfiles,...r.lockfiles])}return o}function to(e,t,o){let n={};if(n.structure="Preserve the existing folder structure. Add new files within established directories. Do not create top-level directories, reorganize, or rename existing folders.",o.source.length>0&&(n.source=`Source code lives in ${o.source.join(", ")}. Make feature changes and bug fixes here only.`),n.secrets=`Never propose changes to credential or key files (${Pe.slice(0,4).join(", ")} \u2026). These are never task targets regardless of the instruction.`,o.generated.length>0&&(n.generated=`${o.generated.join(", ")} contain generated output. Modify the source files that produce them; never write to generated directories directly.`),o.config.length>0){let r=e.filter(c=>ge.includes(c)),s=r.length===1?Ut[r[0]]:"project configuration",i=o.config.slice(0,5).join(", "),a=o.config.length>5?" and related files":"";n.config=`Treat ${i}${a} as ${s} files. Do not modify them unless the task explicitly requires a configuration or dependency change.`}if(o.tests.length>0&&(n.tests=`Test files in ${o.tests.join(", ")} validate behavior. Update them only when the behavior they cover changes.`),o.lockfiles?.length>0){let r=Wt[t]||"tooling",s=o.lockfiles.slice(0,3).join(", ");n.lockfiles=`${s} are generated by the ${r}. Never edit them directly.`}if(t==="generic"){let r=o.config.filter(s=>!s.endsWith("/**"));r.length>0?n.unknown=`This project uses an unrecognized toolchain. Treat ${r.slice(0,3).join(", ")} as dependency/manifest files. Do not modify them unless the task explicitly requires a dependency change.`:n.unknown="This project uses an unrecognized toolchain. Do not assume standard source layouts, dependency files, or build conventions apply. Confirm any structural assumption before acting."}return e.includes("docker")&&(n.docker="Dockerfile and docker-compose.yml define the container environment. Treat them as infrastructure config \u2014 only modify when the task explicitly involves container or environment changes."),e.includes("ci")&&(n.ci="CI config files (.github/**, .gitlab-ci.yml, etc.) define the build and deployment pipeline. Do not modify them unless the task explicitly involves CI/CD changes."),n}function oo(e,t){let o=U([...e.source,...e.docs,...e.tests]),n=[...e.config],r=U([...e.secrets,...e.generated,...e.lockfiles||[],...Mt,...t.filter(s=>s.endsWith("/**")).slice(0,8)]);return{allow:o.length>0?o:["src/**"],approval:n.length>0?n:[],deny:r}}function Fe(e){let t=C.resolve(e||process.cwd()),o=Xt(t),n=Qt(o),r=eo(t,o),s=zt(t),i=to(o,n,r),a=oo(r,s);return{projectTypes:o,primaryType:n,surfaces:r,semantics:i,enforcement:a}}function je(e,t,o){let n=[],r=Array.isArray(e)?e.join(" + "):e;n.push(`Detected: ${r}`),n.push(""),n.push("Agent semantics:");for(let[,s]of Object.entries(t))n.push(` - ${s}`);return n.push(""),n.push("Enforcement:"),o.allow.length&&n.push(` allow: ${o.allow.join(", ")}`),o.approval.length&&n.push(` approval: ${o.approval.join(", ")}`),o.deny.length&&n.push(` deny: ${o.deny.slice(0,6).join(", ")}${o.deny.length>6?" \u2026":""}`),n.join(`
17
- `)}function ro(e){return process.stdin.isTTY?new Promise(t=>{let o=no.createInterface({input:process.stdin,output:process.stdout});o.question(e,n=>{o.close(),t(n.trim().toLowerCase())})}):Promise.resolve("y")}function so(e){return{...e,deny:[...new Set([...e.deny,...e.approval,"*.json","config/**"])],approval:[]}}function io(e){return{...e,approval:[]}}function ao(e){let t=new Date().toISOString(),o=new Date(Date.now()+4320*60*60*1e3).toISOString(),n="agent:gpt-v1-2026Q1",r="policy-signer-v1-2026Q1",s=v.join(e,".lbe");for(let g of["config","keys","data"])S.mkdirSync(v.join(s,g),{recursive:!0});let i={".lbe/data/nonce.db.json":JSON.stringify({entries:[]},null,2),".lbe/data/rate-limit.db.json":JSON.stringify({entries:[]},null,2),".lbe/data/policy.state.json":JSON.stringify({schemaVersion:"1",lastAccepted:null,updatedAt:null},null,2),".lbe/data/audit.log.jsonl":""};for(let[g,I]of Object.entries(i)){let b=v.join(e,g);S.existsSync(b)||S.writeFileSync(b,I)}let a=v.join(s,"keys"),c=v.join(a,"public.key"),l=v.join(a,"secret.key"),p,f;if(S.existsSync(c)&&S.existsSync(l))p=S.readFileSync(c,"utf8").trim(),f=S.readFileSync(l,"utf8").trim();else{let g=ne();p=g.publicKey,f=g.secretKey,S.writeFileSync(c,p),S.writeFileSync(l,f,{mode:384})}let m=v.join(s,"config/keys.json"),y=S.existsSync(m)?JSON.parse(S.readFileSync(m,"utf8")):{schemaVersion:"1",defaultKeyId:n,trustedKeys:{}};for(let g of[n,r])y.trustedKeys[g]||(y.trustedKeys[g]={publicKey:p,notBefore:t,expiresAt:o,validFrom:t,validUntil:o,deprecated:!1});y.defaultKeyId=n,S.writeFileSync(m,JSON.stringify(y,null,2));let h=v.join(s,"config/policy.default.json"),u;S.existsSync(h)?u=JSON.parse(S.readFileSync(h,"utf8")):(u={default:"DENY",version:"1.0.0",createdAt:t,security:{maxClockSkewSec:600,maxPolicyCreatedAtSkewSec:31536e3,defaultRateLimit:{windowSec:60,maxRequests:30}},requesters:{"agent:gpt":{allowAdapters:["noop","shell"],allowCommands:["RUN_SHELL"],rateLimit:{windowSec:60,maxRequests:30},filesystem:{roots:[e],denyPatterns:["**/.git/**","**/secrets/**","**/*.key"]},exec:{allowCmds:["ls","node","python","echo"],denyCmds:["rm","chmod","chown","curl","wget","su","sudo"]}}}},S.writeFileSync(h,JSON.stringify(u,null,2)));let d=De({policyObj:u,secretKeyB64:f,keyId:r});return d.ok&&S.writeFileSync(v.join(s,"config/policy.sig.json"),JSON.stringify(d.envelope,null,2)),{defaultKeyId:n,secretKeyB64:f,publicKeyB64:p}}function co(){return`# LBE Governance Contract
11
+ `;it(s);let i=B().exports.lbe_rate_check()!==0,a=at();if(i){let l=parseInt(a.match(/^EXCEEDED:(\d+)/)?.[1]??"1",10),c=a.replace(/^EXCEEDED:\d+\n/,"");return{ok:!1,retryAfterSec:l,updatedEntriesText:c}}return{ok:!0,retryAfterSec:0,updatedEntriesText:a.startsWith(`OK
12
+ `)?a.slice(3):a}}function dt(e,t=!1){let o=Do[e]??0,n=B().exports.lbe_classify_risk(o,t?1:0);return Lo[n]??"LOW"}var Ao,xe,ot,Oo,No,Ro,Lo,Do,se,ut=L(()=>{Ao=nt.dirname(_o(import.meta.url)),xe=nt.join(Ao,"lbe_engine.wasm"),ot={0:{allowed:!0,reason:null,message:"Policy check passed"},1:{allowed:!1,reason:"POLICY_NOT_CONFIGURED",message:"No policy configured"},2:{allowed:!1,reason:"REQUESTER_NOT_ALLOWED",message:"Requester not in policy"},3:{allowed:!1,reason:"COMMAND_NOT_ALLOWED",message:"Command not allowed for requester"},4:{allowed:!1,reason:"ADAPTER_NOT_ALLOWED",message:"Adapter not allowed"},5:{allowed:!1,reason:"NO_FILESYSTEM_ROOTS_DEFINED",message:"No filesystem roots defined for requester"},6:{allowed:!1,reason:"CWD_OUTSIDE_ALLOWED_ROOT",message:"Path not under allowed roots"},7:{allowed:!1,reason:"PATH_DENIED_BY_PATTERN",message:"Path matches deny pattern"},8:{allowed:!1,reason:"SHELL_CMD_DENIED",message:"Shell command not allowed"}},Oo={0:{valid:!0,error:null},1:{valid:!1,error:"Missing required field: id"},2:{valid:!1,error:"Missing required field: commandId"},3:{valid:!1,error:"Missing required field: requesterId"},4:{valid:!1,error:"Missing required field: sessionId"},5:{valid:!1,error:"Missing required field: timestamp"},6:{valid:!1,error:"Missing required field: nonce"},7:{valid:!1,error:"Missing required field: requires"},8:{valid:!1,error:"Missing required field: payload"},9:{valid:!1,error:"Missing required field: signature"},10:{valid:!1,error:"Field 'id' is invalid"},11:{valid:!1,error:"Field 'commandId' is invalid"},12:{valid:!1,error:"Field 'requesterId' is invalid"},13:{valid:!1,error:"Field 'sessionId' is invalid"},14:{valid:!1,error:"Field 'timestamp' is invalid"},15:{valid:!1,error:"Field 'nonce' is invalid"},16:{valid:!1,error:"Field 'requires' is invalid"},17:{valid:!1,error:"payload: missing required field: adapter"},18:{valid:!1,error:"payload: field 'adapter' is invalid"},19:{valid:!1,error:"signature: missing required field: alg"},20:{valid:!1,error:"signature: missing required field: keyId"},21:{valid:!1,error:"signature: missing required field: sig"},22:{valid:!1,error:"signature: field 'alg' must be ed25519"},23:{valid:!1,error:"signature: field 'sig' is invalid"},24:{valid:!1,error:"Field 'risk' is invalid"}},No={1:"KEY_ID_INVALID",2:"KEY_NOT_TRUSTED",3:"KEY_DEPRECATED",4:"KEY_REQUESTER_MISMATCH",5:"KEY_LIFECYCLE_INVALID",6:"KEY_NOT_YET_VALID",7:"KEY_EXPIRED"},Ro={0:"schema",1:"timestamp",2:"key",3:"signature",4:"rate_limit",5:"nonce",6:"policy",255:"ok"},Lo=["LOW","MEDIUM","HIGH","CRITICAL"],Do={ECHO:0,READ_FILE:1,WRITE_FILE:2,PATCH_FILE:3,DELETE_FILE:4,RUN_SHELL:5},se=null});import _e from"path";function Fo(e){let t=s=>e!=null&&Object.prototype.hasOwnProperty.call(e,s),o=s=>typeof s=="string",n=e?.payload,r=e?.signature;return{hasId:t("id"),idValid:o(e?.id)&&/^[A-Z_]+$/.test(e.id)&&e.id.length>=1&&e.id.length<=50,hasCommandId:t("commandId"),commandIdValid:o(e?.commandId)&&/^[a-f0-9-]+$/.test(e.commandId)&&e.commandId.length===36,hasRequesterId:t("requesterId"),requesterIdValid:o(e?.requesterId)&&e.requesterId.length>=3&&e.requesterId.length<=100,hasSessionId:t("sessionId"),sessionIdValid:o(e?.sessionId)&&e.sessionId.length>=3,hasTimestamp:t("timestamp"),timestampValid:typeof e?.timestamp=="number"&&e.timestamp>=1e9,hasNonce:t("nonce"),nonceValid:o(e?.nonce)&&e.nonce.length>=32&&e.nonce.length<=128,hasRequires:t("requires"),requiresValid:Array.isArray(e?.requires)&&e.requires.length>=1&&e.requires.every(o),hasPayload:t("payload")&&typeof n=="object"&&n!==null&&!Array.isArray(n),hasPayloadAdapter:n!=null&&Object.prototype.hasOwnProperty.call(n,"adapter"),payloadAdapterValid:o(n?.adapter),hasSignature:t("signature")&&typeof r=="object"&&r!==null&&!Array.isArray(r),hasSignatureAlg:r!=null&&Object.prototype.hasOwnProperty.call(r,"alg"),signatureAlgValid:r?.alg==="ed25519",hasSignatureKeyId:r!=null&&Object.prototype.hasOwnProperty.call(r,"keyId"),hasSignatureSig:r!=null&&Object.prototype.hasOwnProperty.call(r,"sig"),signatureSigValid:o(r?.sig)&&r.sig.length>=10,hasRisk:t("risk"),riskValid:["LOW","MEDIUM","HIGH","CRITICAL"].includes(e?.risk)}}function jo(e,t){let o=!!(e&&e.default==="DENY"&&e.requesters&&typeof e.requesters=="object"),n=e?.requesters?.[t.requesterId],r=t.id?.toLowerCase()??"",s=!!n?.allowCommands?.some(y=>y.toLowerCase()===r),i=!!n?.allowAdapters?.includes(t.payload?.adapter),a=!!t.payload?.cwd,l=!1,c=!1,p=!1;if(a){let y=n?.filesystem?.roots??[];if(l=y.length>0,l){let h=_e.resolve(t.payload.cwd);c=y.some(d=>{let g=_e.resolve(d);return h===g||h.startsWith(g+_e.sep)}),p=(n?.filesystem?.denyPatterns??[]).some(d=>new RegExp("^"+d.replace(/\./g,"\\.").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")+"$").test(h))}}let f=!1,m=!0;if(t.id==="RUN_SHELL"){f=!0;let y=n?.exec?.allowCmds??[],h=n?.exec?.denyCmds??[],u=t.payload?.cmd;h.includes(u)?m=!1:m=y.length===0||y.includes(u)}return{policyConfigured:o,requesterConfigured:!!n,commandAllowed:s,adapterAllowed:i,filesystemRequired:a,filesystemRootsDefined:l,filesystemOk:c,pathDenied:p,shellRequired:f,shellCommandOk:m}}function $o(e,t,o,n=new Date){if(!e||!t)return{keyIdFormatValid:!1,keyFound:!1,keyNotDeprecated:!1,keyRequesterMatches:!1,keyNotBeforeOk:!1,keyNotExpired:!1,keyLifecycleFieldsPresent:!1,publicKey:null};let s=/^[A-Za-z0-9:_-]{3,128}$/.test(t)&&t!=="default";if(!s)return{keyIdFormatValid:s,keyFound:!1,keyNotDeprecated:!1,keyRequesterMatches:!1,keyNotBeforeOk:!1,keyNotExpired:!1,keyLifecycleFieldsPresent:!1,publicKey:null};let i=e.trustedKeys?.[t],a=!!i;if(!a)return{keyIdFormatValid:s,keyFound:a,keyNotDeprecated:!1,keyRequesterMatches:!1,keyNotBeforeOk:!1,keyNotExpired:!1,keyLifecycleFieldsPresent:!1,publicKey:null};let l=!i.deprecated,c=!i.requesterId||i.requesterId===o,p=i.notBefore||i.validFrom,f=i.expiresAt||i.validUntil,m=typeof p=="string"&&typeof f=="string",y=!1,h=!1;if(m){let u=new Date(p),d=new Date(f);!isNaN(u.getTime())&&!isNaN(d.getTime())&&u<d&&(y=n>=u,h=n<d)}return{keyIdFormatValid:s,keyFound:a,keyNotDeprecated:l,keyRequesterMatches:c,keyNotBeforeOk:y,keyNotExpired:h,keyLifecycleFieldsPresent:m,publicKey:i.publicKey??null}}function ft(e){return(e?.entries??[]).map(t=>`${t.key}:${t.timestamp}`)}function pt(e){return e.split(`
13
+ `).filter(Boolean).map(t=>{let o=t.lastIndexOf(":");return{key:t.slice(0,o),timestamp:parseInt(t.slice(o+1),10)||0}})}function Ko(e){return(e?.entries??[]).map(t=>`${t.requesterId}:${t.timestamp}`)}function Mo(e){return e.split(`
14
+ `).filter(Boolean).map(t=>{let o=t.lastIndexOf(":");return{requesterId:t.slice(0,o),timestamp:parseInt(t.slice(o+1),10)||0}})}function mt({commandObj:e,pubKeyB64:t,keyStore:o,nonceDb:n,policy:r,rateLimiter:s,policyStatePath:i}){let a={valid:!1,commandId:e?.commandId,checks:{},errors:[]},l=Math.floor(Date.now()/1e3),c=new Date,p=Number.isFinite(r?.security?.maxClockSkewSec)?r.security.maxClockSkewSec:600;if(i&&r?.version!==void 0)try{let S=Ze({policyObj:r,statePath:i});if(a.checks.policyVersion=S.ok,!S.ok)return a.errors.push({type:"POLICY_VERSION_INVALID",message:S.message}),a}catch{a.checks.policyVersion=!0}else a.checks.policyVersion=!0;let f=Fo(e),m=e?.signature?.keyId,y=$o(o,m,e?.requesterId,c),h=!1,u=y.publicKey;if(!u&&t&&(u=t),u){let S={...e};delete S.signature,h=me({payloadObj:S,sigB64:e?.signature?.sig,pubKeyB64:u}).valid}let d=!0,g=0;if(h&&s&&typeof s.db<"u"){let S=r?.requesters?.[e.requesterId]?.rateLimit||{},A=r?.security?.defaultRateLimit||{},M=S.windowSec??A.windowSec??60,Ft=S.maxRequests??A.maxRequests??30,oe=lt({windowSec:M,maxRequests:Ft,nowSec:l,requesterId:e.requesterId,existingEntries:Ko(s.db)});d=oe.ok,g=oe.retryAfterSec,oe.ok&&(s.db.entries=Mo(oe.updatedEntriesText))}else if(h&&s&&typeof s.checkAndRecord=="function"){let S=r?.requesters?.[e.requesterId]?.rateLimit||{},A=r?.security?.defaultRateLimit||{},M=s.checkAndRecord({requesterId:e.requesterId,nowSec:l,windowSec:S.windowSec??A.windowSec??60,maxRequests:S.maxRequests??A.maxRequests??30});d=M.ok,g=M.retryAfterSec??0}let I=!0,b=`${e?.requesterId}|${e?.sessionId}|${e?.nonce}`,K=3600;if(h&&d&&n)if(typeof n.checkAndRecord=="function")if(n.db){let S=we({ttlSec:K,nowSec:l,newKey:b,existingEntries:ft(n.db)});I=S.ok,S.ok&&(n.db.entries=pt(S.updatedEntriesText))}else I=n.checkAndRecord({requesterId:e.requesterId,sessionId:e.sessionId,nonce:e.nonce}).ok;else{let S=we({ttlSec:K,nowSec:l,newKey:b,existingEntries:ft(n)});I=S.ok,S.ok&&(n.entries=pt(S.updatedEntriesText))}let O=jo(r,e??{}),_=ct({...f,cmdTimestamp:e?.timestamp??0,nowSec:l,maxClockSkewSec:p,...y,signatureValid:h,rateLimitOk:d,rateLimitRetryAfterSec:g,nonceOk:I,...O}),x=_.stage;if(a.checks.schema=x!==0,x>=1&&(a.checks.timestamp=x!==1),x>=2&&(a.checks.keyId=x!==2),x>=2&&(a.checks.signature=x!==2&&x!==3),x>=4&&(a.checks.rateLimit=x!==4),x>=5&&(a.checks.nonce=x!==5),(x>=6||_.ok)&&(a.checks.policy=x!==6),!_.ok){let S=_.stageLabel;if(S==="schema")a.errors.push({type:"SCHEMA_ERROR",message:_.schemaError||"Schema invalid"});else if(S==="timestamp")a.errors.push({type:"TIMESTAMP_SKEW_EXCEEDED",message:`Command timestamp skew ${_.skewSec}s exceeds allowed ${p}s`});else if(S==="key"){let A=_.keyReason||"KEY_ERROR",M={KEY_ID_INVALID:`Invalid keyId '${m}'`,KEY_NOT_TRUSTED:`Key '${m}' is not in trusted key store`,KEY_DEPRECATED:`Key '${m}' is deprecated`,KEY_REQUESTER_MISMATCH:`Key '${m}' is not authorized for requester '${e?.requesterId}'`,KEY_LIFECYCLE_INVALID:`Key '${m}' must define notBefore and expiresAt`,KEY_NOT_YET_VALID:`Key '${m}' is not yet valid`,KEY_EXPIRED:`Key '${m}' has expired`};a.errors.push({type:A,message:M[A]||A})}else S==="signature"?a.errors.push({type:"SIGNATURE_INVALID",message:u?"Signature verification failed":"No public key available"}):S==="rate_limit"?a.errors.push({type:"RATE_LIMIT_EXCEEDED",message:`Rate limit exceeded. Retry after ${_.retryAfterSec}s`}):S==="nonce"?a.errors.push({type:"REPLAY_NONCE",message:"Nonce has already been used"}):S==="policy"&&_.policyResult?a.errors.push({type:_.policyResult.reason,message:_.policyResult.message}):a.errors.push({type:"VALIDATION_FAILED",message:`Failed at stage: ${S}`});return a}return a.valid=!0,a.risk=dt(e.id,e.payload?.cmd==="rm"),a.message="Command validation successful",a}var yt=L(()=>{Z();et();ut()});async function gt(e){return{adapter:"noop",commandId:e.commandId||"unknown",command:e.id||"unknown",status:"completed",output:`[NOOP] Would execute: ${e.id||"unknown"} on adapter: ${e.payload?.adapter||"unknown"}`,exitCode:0,timestamp:new Date().toISOString()}}var ht=L(()=>{});import{spawnSync as qo}from"child_process";import Ae from"path";import Bo from"fs";function kt(e){try{return Bo.realpathSync(Ae.resolve(e))}catch{return Ae.resolve(e)}}function Vo(e){if(e===void 0)return{ok:!0,args:[]};if(!Array.isArray(e))return{ok:!1,error:"payload.args must be an array"};let t=[];for(let o of e){if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")return{ok:!1,error:"payload.args may only contain string, number, or boolean values"};t.push(String(o))}return{ok:!0,args:t}}async function St(e,t,o){let n=e.payload,r=Math.min(Math.max(Number(n.timeoutMs)||3e4,1),3e4),s=Math.min(Math.max(Number(n.maxOutputBytes)||1024*1024,1024),1024*1024);if(n.adapter!=="shell")return{adapter:"shell",commandId:e.commandId,status:"error",error:"Adapter mismatch",exitCode:1};let i=o?.exec?.allowCmds||[];if((o?.exec?.denyCmds||[]).includes(n.cmd))return{adapter:"shell",commandId:e.commandId,status:"blocked",error:`Command '${n.cmd}' is denied`,exitCode:2};if(i.length>0&&!i.includes(n.cmd))return{adapter:"shell",commandId:e.commandId,status:"blocked",error:`Command '${n.cmd}' not in allowlist`,exitCode:2};if(!(o?.filesystem?.roots||[]).some(f=>{let m=kt(f),y=kt(n.cwd);return y===m||y.startsWith(m+Ae.sep)}))return{adapter:"shell",commandId:e.commandId,status:"blocked",error:`CWD '${n.cwd}' not authorized`,exitCode:2};let p=Vo(n.args);if(!p.ok)return{adapter:"shell",commandId:e.commandId,status:"blocked",error:p.error,exitCode:2};try{let f=qo(n.cmd,p.args,{cwd:n.cwd,timeout:r,encoding:"utf8",maxBuffer:s,stdio:["pipe","pipe","pipe"],shell:!1});if(f.error)throw f.error;let m=`${f.stdout||""}${f.stderr||""}`,y=f.status??1;return y!==0?{adapter:"shell",commandId:e.commandId,command:n.cmd,status:"error",error:m.substring(0,s)||`Command exited with code ${y}`,exitCode:y,timestamp:new Date().toISOString()}:{adapter:"shell",commandId:e.commandId,command:n.cmd,status:"completed",output:m.substring(0,s),exitCode:0,timestamp:new Date().toISOString()}}catch(f){return{adapter:"shell",commandId:e.commandId,command:n.cmd,status:"error",error:f.message,exitCode:f.status||1,timestamp:new Date().toISOString()}}}var Et=L(()=>{});import V from"fs";import ae from"path";import Yo from"crypto";function It(e,t){let o=t||ae.resolve(".lbe/data/backups");V.existsSync(o)||V.mkdirSync(o,{recursive:!0});let n=ae.resolve(e),r=V.existsSync(n),s=null,i=null;r&&(s=V.readFileSync(n),i=Yo.createHash("sha256").update(s).digest("hex"));let a=ae.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_"),l=`${Date.now()}-${i?i.slice(0,8):"new"}-${a}`,c=r?ae.join(o,l):null;return r&&s!==null&&D(c,s),{originalPath:n,backupPath:c,existed:r,hash:i,createdAt:new Date().toISOString()}}function ce(e){if(!e)return{restored:!1,error:"No backup metadata"};let{originalPath:t,backupPath:o,existed:n}=e;if(!n)try{return V.existsSync(t)&&V.unlinkSync(t),{restored:!0,action:"deleted"}}catch(r){return{restored:!1,error:r.message}}if(!o||!V.existsSync(o))return{restored:!1,error:"Backup file not found at: "+o};try{let r=V.readFileSync(o);return D(t,r),{restored:!0,action:"restored"}}catch(r){return{restored:!1,error:r.message}}}var bt=L(()=>{z()});import H from"fs";import Y from"path";function Wo(e,t){return e?Y.isAbsolute(e)?Y.resolve(e):Y.resolve(t||process.cwd(),e):null}function Go(e,t){let o=vt(e);return t.some(n=>{let r=vt(n);return o===r||o.startsWith(r+Y.sep)})}function vt(e){let t=Y.resolve(e),o=[];for(;!H.existsSync(t);){let n=Y.dirname(t);if(n===t)break;o.unshift(Y.basename(t)),t=n}try{t=H.realpathSync(t)}catch{}return Y.join(t,...o)}function Ho(e,t){for(let o of t||[])if(new RegExp("^"+o.replace(/\./g,"\\.").replace(/\*\*/g,".*").replace(/\*/g,"[^/\\\\]*")+"$").test(e))return o;return null}function X(e,t,o,n=2){return{adapter:"file",commandId:e.commandId,status:"blocked",errorCode:t,error:o,exitCode:n}}function j(e,t,o,n=null,r=1){return{adapter:"file",commandId:e.commandId,status:"error",errorCode:t,error:o,backup:n?le(n):null,exitCode:r}}function le(e){return e?{path:e.backupPath,existed:e.existed,hash:e.hash,createdAt:e.createdAt}:null}async function xt(e,t,o){let n=e.payload,r=n.action,s=n.cwd||process.cwd(),i=Wo(n.target,s);if(!r)return X(e,"FILE_NO_ACTION","payload.action is required");if(!i&&r!=="noop")return X(e,"FILE_NO_TARGET","payload.target is required");let a=o?.filesystem?.roots||[];if(a.length===0)return X(e,"FILE_NO_ROOTS","No filesystem roots defined for requester");if(!Go(i,a))return X(e,"FILE_OUTSIDE_ROOT",`'${i}' is outside allowed roots`);let l=Ho(i,o?.filesystem?.denyPatterns);if(l)return X(e,"FILE_PATH_DENIED",`'${i}' matches deny pattern: ${l}`);switch(r){case"read":return Jo(e,i);case"write":return zo(e,i,n);case"patch":return Xo(e,i,n);case"delete":return Qo(e,i);default:return X(e,"FILE_UNKNOWN_ACTION",`Unknown action: '${r}'`)}}function Jo(e,t){if(!H.existsSync(t))return j(e,"FILE_NOT_FOUND",`Not found: ${t}`);try{let o=H.statSync(t);if(o.size>Uo)return j(e,"FILE_TOO_LARGE","File exceeds 10 MB read limit");let n=H.readFileSync(t,"utf8");return{adapter:"file",action:"read",commandId:e.commandId,status:"completed",target:t,output:n,bytesRead:o.size,exitCode:0}}catch(o){return j(e,"FILE_READ_ERROR",o.message)}}function zo(e,t,o){let n=o.content;if(n==null)return j(e,"FILE_MISSING_CONTENT","payload.content is required for write");let r=Oe(t);try{return D(t,n,{encoding:"utf8"}),{adapter:"file",action:"write",commandId:e.commandId,status:"completed",target:t,backup:le(r),output:`Wrote ${Buffer.byteLength(n,"utf8")} bytes to ${t}`,exitCode:0}}catch(s){return ce(r),j(e,"FILE_WRITE_ERROR",s.message,r)}}function Xo(e,t,o){let n=o.content;if(n==null)return j(e,"FILE_MISSING_CONTENT","payload.content is required for patch");let r=Oe(t);try{return D(t,n,{encoding:"utf8"}),{adapter:"file",action:"patch",commandId:e.commandId,status:"completed",target:t,backup:le(r),output:`Patched ${t} (${Buffer.byteLength(n,"utf8")} bytes)`,exitCode:0}}catch(s){return ce(r),j(e,"FILE_PATCH_ERROR",s.message,r)}}function Qo(e,t){if(!H.existsSync(t))return j(e,"FILE_NOT_FOUND",`Not found: ${t}`);let o=Oe(t);try{return H.unlinkSync(t),{adapter:"file",action:"delete",commandId:e.commandId,status:"completed",target:t,backup:le(o),output:`Deleted ${t}`,exitCode:0}}catch(n){return ce(o),j(e,"FILE_DELETE_ERROR",n.message,o)}}function Oe(e){try{return It(e)}catch{return null}}var Uo,wt=L(()=>{z();bt();Uo=10*1024*1024});function Zo(e){return _t[e]}async function At(e,t,o,n){let r=Zo(e);if(!r)return{adapter:e,commandId:t.commandId,status:"error",error:`Adapter '${e}' not found`,exitCode:1};try{return await r(t,o,n)}catch(s){return{adapter:e,commandId:t.commandId,status:"error",error:`Adapter execution failed: ${s.message}`,exitCode:9}}}var _t,Dr,Ot=L(()=>{ht();Et();wt();_t={noop:gt,shell:St,file:xt};Dr=Object.keys(_t)});var Dt={};$t(Dt,{createLocalExecutor:()=>sn});import Nt from"crypto";import J from"fs";import N from"path";function T(e,t,o=!1){return{ok:!1,decision:"deny",executed:!1,dryRun:!1,error:{code:e,message:t,recoverable:o}}}function en(e,t,o={}){let n=new Date,r=new Date(n.getTime()+365*24*60*60*1e3);return{version:1,default:"DENY",requesters:{[t]:{allowCommands:Object.values(Lt).map(s=>s.id),allowAdapters:["file","shell"],filesystem:{roots:[e],denyPatterns:[]},exec:{allowCmds:o.allowCommands||[],denyCmds:o.denyCommands||[]},rateLimit:{windowSec:60,maxRequests:o.maxRequests||60}}},security:{maxClockSkewSec:600,defaultRateLimit:{windowSec:60,maxRequests:60}},_keyWindow:{notBefore:n.toISOString(),expiresAt:r.toISOString()}}}function Rt(e){let t=N.resolve(e),o=[];for(;!J.existsSync(t);){let n=N.dirname(t);if(n===t)break;o.unshift(N.basename(t)),t=n}try{t=J.realpathSync(t)}catch{}return N.join(t,...o)}function Re(e,t){let o=Rt(e),n=Rt(t);return o===n||o.startsWith(n+N.sep)}function on(e,t){if(typeof e!="string")return null;for(let o of tn)if(o.test(e))return T("PAYLOAD_CONTENT_REJECTED",`Forbidden pattern in ${t}: ${o}`);return null}function nn(e,t,o={}){if(!t||typeof t!="object")return{error:T("REQUEST_INVALID","request must be an object")};let n=Lt[t.intent];if(!n)return{error:T("INTENT_UNSUPPORTED",`Unsupported intent '${t.intent}'`)};let r=typeof t.actor=="string"&&t.actor?t.actor:"agent:local",s=null;if(n.adapter==="file"){if(typeof t.target!="string"||!t.target)return{error:T("TARGET_REQUIRED","target is required for file intents")};if(s=N.resolve(e,t.target),!Re(s,e))return{error:T("PATH_OUTSIDE_ROOT","target is outside project root")};if(["write_file","patch_file"].includes(t.intent)&&typeof t.content!="string")return{error:T("CONTENT_REQUIRED","content is required for write and patch")};let a=on(t.content,"content");if(a)return{error:a}}let i=null;if(n.adapter==="shell"){if(i=t.command,!i||typeof i.cmd!="string"||!Array.isArray(i.args)||i.args.some(l=>typeof l!="string"))return{error:T("COMMAND_INVALID","command requires cmd and string args")};let a=N.resolve(e,i.cwd||".");if(!Re(a,e))return{error:T("CWD_OUTSIDE_ROOT","command cwd is outside project root")};if(!Array.isArray(o.allowCommands)||!o.allowCommands.includes(i.cmd))return{error:T("SHELL_NOT_ALLOWLISTED",`command '${i.cmd}' is not explicitly allowlisted`)};if(o.denyCommands?.includes(i.cmd))return{error:T("SHELL_DENIED",`command '${i.cmd}' is denied`)};i={...i,cwd:a,timeoutMs:Math.min(Math.max(i.timeoutMs||3e4,1),3e4),maxOutputBytes:Math.min(Math.max(i.maxOutputBytes||1024*1024,1024),1024*1024)}}return{actor:r,detail:n,target:s,command:i,request:t}}function rn(e,t,o){let{actor:n,detail:r,target:s,command:i,request:a}=e,l={id:r.id,risk:Ne.has(a.intent)?"MEDIUM":"LOW",commandId:Nt.randomUUID(),requesterId:n,sessionId:"local-host",timestamp:Math.floor(Date.now()/1e3),nonce:Nt.randomBytes(32).toString("hex"),requires:["policy","signature"],payload:{adapter:r.adapter,action:r.action,target:s,content:a.content,cmd:i?.cmd,args:i?.args,timeoutMs:i?.timeoutMs,maxOutputBytes:i?.maxOutputBytes,cwd:i?.cwd||(s?N.dirname(s):process.cwd())}},c=re({payloadObj:l,secretKeyB64:o});if(c.error)throw new Error(c.error);return{...l,signature:{alg:"ed25519",keyId:t,sig:c.signature}}}function sn(e={}){let t=N.resolve(e.rootDir||process.cwd()),o=e.keyId||"host:local-exec",n=e.keyPair||ne(),r=e.shell||{};function s(u,{recordNonce:d=!1}={}){let g=nn(t,u,r);if(g.error)return g;let I=G(t,e.mode||"enforce"),b=be(I.policy,t,{target:g.target,command:g.command?.cmd});if(I.policy.mode==="enforce"&&!b.allowed)return{error:T("LOCAL_POLICY_DENY",`Blocked by rule(s): ${b.winningRules.map(M=>M.id).join(", ")}`),local:I,localDecision:b,normalized:g};let O=en(t,g.actor,r),_={defaultKeyId:o,trustedKeys:{[o]:{publicKey:n.publicKey,notBefore:O._keyWindow.notBefore,expiresAt:O._keyWindow.expiresAt,deprecated:!1}}};delete O._keyWindow;let x=rn(g,o,n.secretKey),A=mt({commandObj:x,keyStore:_,nonceDb:d?{entries:[]}:{entries:[]},policy:O});return A.valid?{local:I,localDecision:b,normalized:g,proposal:x,policy:O,validation:A}:{error:T(A.errors[0]?.type||"VALIDATION_FAILED",A.errors[0]?.message||"Validation failed"),local:I,localDecision:b,normalized:g,proposal:x,policy:O,validation:A}}function i(u){let d=G(t,e.mode||"observe"),g=d.policy.mode,I=null,b=null;if(u.path)try{if(I=N.resolve(t,u.path),!Re(I,t))return{decision:"deny",deny:!0,matchedRules:["path:outside_root"],mode:g,enforced:g==="enforce",reason:"PATH_OUTSIDE_ROOT"}}catch{}u.cmd&&(b=u.cmd);let K=be(d.policy,t,{target:I,command:b}),O=!K.allowed;return{decision:O?"deny":"allow",deny:O,matchedRules:K.winningRules.map(_=>_.id),mode:g,enforced:g==="enforce"}}function a(u){let d=N.join(t,".lbe","events.jsonl"),g=N.dirname(d);J.existsSync(g)||J.mkdirSync(g,{recursive:!0});let I=JSON.stringify({ts:Math.floor(Date.now()/1e3),...u})+`
15
+ `,b=J.openSync(d,"a");try{J.writeSync(b,I)}finally{J.closeSync(b)}}async function l(u){let d=s(u);return d.error?{...d.error,dryRun:!0}:{ok:!0,decision:d.local.policy.mode==="observe"?"observe":"allow",executed:!1,dryRun:!0,matchedRules:d.localDecision.winningRules.map(g=>g.id),rollback:{available:Ne.has(d.normalized.request.intent),performed:!1}}}async function c(u){let d=s(u,{recordNonce:!0});if(d.error)return He(t,{action:u?.intent,actor:u?.actor||"agent:local",decision:"deny",error:d.error.error.code}),d.error;if(d.local.policy.mode==="observe")return ee(N.join(t,".lbe/audit.jsonl"),{kind:"local_execution",commandId:d.proposal.commandId,requesterId:d.normalized.actor,intent:d.normalized.request.intent,decision:"observe",status:"observed"}),{ok:!0,decision:"observe",executed:!1,dryRun:!1,matchedRules:d.localDecision.winningRules.map(O=>O.id),rollback:{available:!1,performed:!1}};let g=d.policy.requesters[d.normalized.actor],I=await At(d.normalized.detail.adapter,d.proposal,d.policy,g),b=I.status==="completed",K=ee(N.join(t,".lbe/audit.jsonl"),{kind:"local_execution",commandId:d.proposal.commandId,requesterId:d.normalized.actor,intent:d.normalized.request.intent,decision:b?"allow":"deny",status:I.status});return{ok:b,decision:b?"allow":"deny",executed:b,dryRun:!1,matchedRules:d.localDecision.winningRules.map(O=>O.id),auditId:K.hash,rollback:{available:Ne.has(d.normalized.request.intent),performed:!1,backupId:I.backup?.hash},...b?{}:{error:{code:I.errorCode||"EXECUTION_FAILED",message:I.error||"Execution failed",recoverable:!0}}}}return{rootDir:t,writeFile:(u,d)=>c({intent:"write_file",target:u,content:d}),readFile:u=>c({intent:"read_file",target:u}),patchFile:(u,d)=>c({intent:"patch_file",target:u,content:d}),deleteFile:u=>c({intent:"delete_file",target:u}),runShell:(u,d=[],g={})=>c({intent:"run_shell",command:{cmd:u,args:d,...g}}),validate:async u=>({...await l(u),dryRun:!1,executed:!1}),dryRun:l,execute:c,policy:{read:()=>G(t,e.mode||"enforce").policy,proposeRule:Ge,addRule:u=>We(t,u,e.mode||"enforce")},audit:{verify:()=>Ve(N.join(t,".lbe/audit.jsonl"))},evaluateSync:i,auditSync:a}}var Lt,Ne,tn,Tt=L(()=>{Z();yt();Ot();Se();ve();Lt={read_file:{id:"READ_FILE",adapter:"file",action:"read"},write_file:{id:"WRITE_FILE",adapter:"file",action:"write"},patch_file:{id:"PATCH_FILE",adapter:"file",action:"patch"},delete_file:{id:"DELETE_FILE",adapter:"file",action:"delete"},run_shell:{id:"RUN_SHELL",adapter:"shell",action:"run"}},Ne=new Set(["write_file","patch_file","delete_file"]);tn=[/\beval\s*\(/i,/\bFunction\s*\(/i,/\bexec\s*\(/i,/\brequire\s*\(/,/\bimport\s*\(/,/\bchild_process\b/,/\b__proto__\b/,/\bconstructor\s*\[/,/evalScript/i]});import E from"fs";import w from"path";import{spawn as de}from"child_process";import{fileURLToPath as an}from"url";Z();import k from"fs";import v from"path";import no from"readline";Z();import bn from"fs";import xn from"path";import gn from"fs";import kn from"path";function De({policyObj:e,secretKeyB64:t,keyId:o}){let n=re({payloadObj:e,secretKeyB64:t});return n.error?{ok:!1,reason:"POLICY_SIGNATURE_CREATE_FAILED",message:n.error,envelope:null}:{ok:!0,reason:null,message:"Policy signature created",envelope:{alg:"ed25519",keyId:o,sig:n.signature,createdAt:Math.floor(Date.now()/1e3)}}}import ye from"fs";import C from"path";var Kt=[{file:"package.json",type:"node"},{file:"pyproject.toml",type:"python"},{file:"requirements.txt",type:"python"},{file:"go.mod",type:"go"},{file:"Cargo.toml",type:"rust"},{file:"pom.xml",type:"java"},{file:"build.gradle",type:"java"},{file:"build.gradle.kts",type:"java"},{file:"Dockerfile",type:"docker"},{file:"docker-compose.yml",type:"docker"},{dir:".github/workflows",type:"ci"},{file:".gitlab-ci.yml",type:"ci"},{dir:".circleci",type:"ci"},{file:"Jenkinsfile",type:"ci"},{file:".travis.yml",type:"ci"}],ge=["node","python","go","rust","java"],Mt={source:["src","lib","app","pages","components","core","api","server","client","pkg","cmd"],generated:["dist","build",".next","out","coverage","target",".cache","__pycache__",".turbo"],tests:["test","tests","__tests__","spec","e2e"],docs:["docs","doc","documentation"]},Pe=[".env",".env.*","keys/**","secrets/**","*.key","*.pem","*.p12","*.pfx","*.crt"],qt=["node_modules/**",".git/**"],Bt={node:["package-lock.json","yarn.lock","pnpm-lock.yaml"],python:["Pipfile.lock","poetry.lock"],go:["go.sum"],rust:["Cargo.lock"],java:["gradle/wrapper/**"],docker:[],ci:[],generic:[]},Te={node:["package.json","tsconfig*.json","jest.config.*","vite.config.*","next.config.*","webpack.config.*",".eslintrc*",".eslint.config.*",".prettierrc*","babel.config.*"],python:["pyproject.toml","setup.py","setup.cfg","tox.ini","pytest.ini","mypy.ini",".flake8",".pylintrc","Pipfile"],go:["go.mod",".golangci.yml",".golangci.yaml"],rust:["Cargo.toml","rust-toolchain.toml","clippy.toml",".rustfmt.toml"],java:["pom.xml","build.gradle","build.gradle.kts","gradle.properties","settings.gradle","settings.gradle.kts"],docker:["Dockerfile","docker-compose.yml",".dockerignore"],ci:[".gitlab-ci.yml","Jenkinsfile",".travis.yml"],generic:["Makefile","CMakeLists.txt","meson.build"]},Vt=[".editorconfig",".nvmrc",".node-version",".python-version"],Yt=["config",".github",".gitlab",".circleci",".vscode"],Ut={node:"dependency and build config",python:"package and environment config",go:"module definition",rust:"crate manifest",java:"build definition",docker:"container config",ci:"pipeline definition",generic:"project config"},Wt={node:"package manager",python:"dependency resolver",go:"module checksums",rust:"dependency resolver",java:"Gradle wrapper"},Gt=["composer.json","Gemfile","mix.exs","pubspec.yaml","Package.swift","project.clj","build.sbt","stack.yaml","deno.json","deno.jsonc","Podfile"],Ht=["composer.lock","Gemfile.lock","mix.lock","pubspec.lock","Package.resolved"],Jt=[".csproj",".fsproj",".sln",".cabal"];function F(e){return ye.existsSync(e)}function Ce(e,t){return t.filter(o=>F(C.join(e,o))).map(o=>`${o}/**`)}function zt(e){let t=C.join(e,".gitignore");return F(t)?ye.readFileSync(t,"utf8").split(`
16
+ `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")&&!o.startsWith("!")).map(o=>o.endsWith("/")?o+"**":o):[]}function U(e){return e.filter((t,o,n)=>t&&n.indexOf(t)===o)}function Xt(e){let t=new Set,o=[];for(let n of Kt){if(t.has(n.type))continue;let r=C.join(e,n.file||n.dir);F(r)&&(t.add(n.type),o.push(n.type))}return o.length>0?o:["generic"]}function Qt(e){return ge.find(t=>e.includes(t))??"generic"}function Zt(e){let t=Gt.filter(n=>F(C.join(e,n))),o=Ht.filter(n=>F(C.join(e,n)));try{let n=ye.readdirSync(e);for(let r of n)Jt.some(s=>r.endsWith(s))&&t.push(r)}catch{}return{manifests:t,lockfiles:o}}function eo(e,t){let o={};for(let[r,s]of Object.entries(Mt))o[r]=Ce(e,s);o.secrets=Pe.filter(r=>{let s=r.split("/")[0].replace(/\*.*/,"");return s.includes("*")||F(C.join(e,s))});let n=U(t.flatMap(r=>Te[r]||Te.generic).concat(Vt));if(o.config=U([...n.filter(r=>!r.includes("*")&&!r.endsWith("/**")&&F(C.join(e,r))),...n.filter(r=>r.endsWith("/**")&&F(C.join(e,r.replace("/**","")))),...Ce(e,Yt)]),o.lockfiles=U(t.flatMap(r=>Bt[r]||[]).filter(r=>{let s=r.replace(/\*.*/,"").split("/")[0];return s.includes("*")||F(C.join(e,s))})),!t.some(r=>ge.includes(r))){let r=Zt(e);o.config=U([...o.config,...r.manifests]),o.lockfiles=U([...o.lockfiles,...r.lockfiles])}return o}function to(e,t,o){let n={};if(n.structure="Preserve the existing folder structure. Add new files within established directories. Do not create top-level directories, reorganize, or rename existing folders.",o.source.length>0&&(n.source=`Source code lives in ${o.source.join(", ")}. Make feature changes and bug fixes here only.`),n.secrets=`Never propose changes to credential or key files (${Pe.slice(0,4).join(", ")} \u2026). These are never task targets regardless of the instruction.`,o.generated.length>0&&(n.generated=`${o.generated.join(", ")} contain generated output. Modify the source files that produce them; never write to generated directories directly.`),o.config.length>0){let r=e.filter(l=>ge.includes(l)),s=r.length===1?Ut[r[0]]:"project configuration",i=o.config.slice(0,5).join(", "),a=o.config.length>5?" and related files":"";n.config=`Treat ${i}${a} as ${s} files. Do not modify them unless the task explicitly requires a configuration or dependency change.`}if(o.tests.length>0&&(n.tests=`Test files in ${o.tests.join(", ")} validate behavior. Update them only when the behavior they cover changes.`),o.lockfiles?.length>0){let r=Wt[t]||"tooling",s=o.lockfiles.slice(0,3).join(", ");n.lockfiles=`${s} are generated by the ${r}. Never edit them directly.`}if(t==="generic"){let r=o.config.filter(s=>!s.endsWith("/**"));r.length>0?n.unknown=`This project uses an unrecognized toolchain. Treat ${r.slice(0,3).join(", ")} as dependency/manifest files. Do not modify them unless the task explicitly requires a dependency change.`:n.unknown="This project uses an unrecognized toolchain. Do not assume standard source layouts, dependency files, or build conventions apply. Confirm any structural assumption before acting."}return e.includes("docker")&&(n.docker="Dockerfile and docker-compose.yml define the container environment. Treat them as infrastructure config \u2014 only modify when the task explicitly involves container or environment changes."),e.includes("ci")&&(n.ci="CI config files (.github/**, .gitlab-ci.yml, etc.) define the build and deployment pipeline. Do not modify them unless the task explicitly involves CI/CD changes."),n}function oo(e,t){let o=U([...e.source,...e.docs,...e.tests]),n=[...e.config],r=U([...e.secrets,...e.generated,...e.lockfiles||[],...qt,...t.filter(s=>s.endsWith("/**")).slice(0,8)]);return{allow:o.length>0?o:["src/**"],approval:n.length>0?n:[],deny:r}}function Fe(e){let t=C.resolve(e||process.cwd()),o=Xt(t),n=Qt(o),r=eo(t,o),s=zt(t),i=to(o,n,r),a=oo(r,s);return{projectTypes:o,primaryType:n,surfaces:r,semantics:i,enforcement:a}}function je(e,t,o){let n=[],r=Array.isArray(e)?e.join(" + "):e;n.push(`Detected: ${r}`),n.push(""),n.push("Agent semantics:");for(let[,s]of Object.entries(t))n.push(` - ${s}`);return n.push(""),n.push("Enforcement:"),o.allow.length&&n.push(` allow: ${o.allow.join(", ")}`),o.approval.length&&n.push(` approval: ${o.approval.join(", ")}`),o.deny.length&&n.push(` deny: ${o.deny.slice(0,6).join(", ")}${o.deny.length>6?" \u2026":""}`),n.join(`
17
+ `)}function ro(e){return process.stdin.isTTY?new Promise(t=>{let o=no.createInterface({input:process.stdin,output:process.stdout});o.question(e,n=>{o.close(),t(n.trim().toLowerCase())})}):Promise.resolve("y")}function so(e){return{...e,deny:[...new Set([...e.deny,...e.approval,"*.json","config/**"])],approval:[]}}function io(e){return{...e,approval:[]}}function ao(e){let t=new Date().toISOString(),o=new Date(Date.now()+4320*60*60*1e3).toISOString(),n="agent:gpt-v1-2026Q1",r="policy-signer-v1-2026Q1",s=v.join(e,".lbe");for(let g of["config","keys","data"])k.mkdirSync(v.join(s,g),{recursive:!0});let i={".lbe/data/nonce.db.json":JSON.stringify({entries:[]},null,2),".lbe/data/rate-limit.db.json":JSON.stringify({entries:[]},null,2),".lbe/data/policy.state.json":JSON.stringify({schemaVersion:"1",lastAccepted:null,updatedAt:null},null,2),".lbe/data/audit.log.jsonl":""};for(let[g,I]of Object.entries(i)){let b=v.join(e,g);k.existsSync(b)||k.writeFileSync(b,I)}let a=v.join(s,"keys"),l=v.join(a,"public.key"),c=v.join(a,"secret.key"),p,f;if(k.existsSync(l)&&k.existsSync(c))p=k.readFileSync(l,"utf8").trim(),f=k.readFileSync(c,"utf8").trim();else{let g=ne();p=g.publicKey,f=g.secretKey,k.writeFileSync(l,p),k.writeFileSync(c,f,{mode:384})}let m=v.join(s,"config/keys.json"),y=k.existsSync(m)?JSON.parse(k.readFileSync(m,"utf8")):{schemaVersion:"1",defaultKeyId:n,trustedKeys:{}};for(let g of[n,r])y.trustedKeys[g]||(y.trustedKeys[g]={publicKey:p,notBefore:t,expiresAt:o,validFrom:t,validUntil:o,deprecated:!1});y.defaultKeyId=n,k.writeFileSync(m,JSON.stringify(y,null,2));let h=v.join(s,"config/policy.default.json"),u;k.existsSync(h)?u=JSON.parse(k.readFileSync(h,"utf8")):(u={default:"DENY",version:"1.0.0",createdAt:t,security:{maxClockSkewSec:600,maxPolicyCreatedAtSkewSec:31536e3,defaultRateLimit:{windowSec:60,maxRequests:30}},requesters:{"agent:gpt":{allowAdapters:["noop","shell"],allowCommands:["RUN_SHELL"],rateLimit:{windowSec:60,maxRequests:30},filesystem:{roots:[e],denyPatterns:["**/.git/**","**/secrets/**","**/*.key"]},exec:{allowCmds:["ls","node","python","echo"],denyCmds:["rm","chmod","chown","curl","wget","su","sudo"]}}}},k.writeFileSync(h,JSON.stringify(u,null,2)));let d=De({policyObj:u,secretKeyB64:f,keyId:r});return d.ok&&k.writeFileSync(v.join(s,"config/policy.sig.json"),JSON.stringify(d.envelope,null,2)),{defaultKeyId:n,secretKeyB64:f,publicKeyB64:p}}function co(){return`# LBE Governance Contract
18
18
 
19
19
  This project has LetterBlack LBE (Local-first execution Governance) active.
20
20
 
@@ -61,28 +61,47 @@ const proposal = lbe.policy.proposeRule({
61
61
  - Policy: \`.lbe/policy.json\`
62
62
  - Audit: \`.lbe/audit.jsonl\`
63
63
  - Status: \`npx lbe-exec status\`
64
- `}function lo(e){let t=v.join(e,".lbe");S.mkdirSync(t,{recursive:!0}),S.writeFileSync(v.join(t,"AGENT_CONTRACT.md"),co())}function uo(e){let t=v.join(e,".lbe");S.mkdirSync(t,{recursive:!0});let o=[["lbe.policy.json",".lbe/policy.json"],["lbe.workspace.json",".lbe/workspace.json"]],n=[];for(let[s,i]of o){let a=v.join(e,s),c=v.join(e,i);S.existsSync(a)&&!S.existsSync(c)?(S.renameSync(a,c),n.push(s+" \u2192 "+i)):S.existsSync(a)&&(S.unlinkSync(a),n.push(s+" (removed \u2014 .lbe/ version exists)"))}let r=["CLAUDE.md",v.join(".github","copilot-instructions.md")];for(let s of r){let i=v.join(e,s);if(S.existsSync(i)){let a=S.readFileSync(i,"utf8");(a.includes("lbe-governance")||a.includes("LetterBlack LBE"))&&(S.unlinkSync(i),n.push(s+" (removed \u2014 LBE-generated file)"))}}return n}async function $e(e={}){let t=process.cwd(),o=e.yes||e.y||!process.stdin.isTTY,n=v.join(t,".lbe");S.mkdirSync(n,{recursive:!0});let r=v.join(n,"workspace.json");console.log(`
64
+ `}function lo(e){let t=v.join(e,".lbe");k.mkdirSync(t,{recursive:!0}),k.writeFileSync(v.join(t,"AGENT_CONTRACT.md"),co())}function uo(e){let t=v.join(e,".lbe");k.mkdirSync(t,{recursive:!0});let o=[["lbe.policy.json",".lbe/policy.json"],["lbe.workspace.json",".lbe/workspace.json"]],n=[];for(let[s,i]of o){let a=v.join(e,s),l=v.join(e,i);k.existsSync(a)&&!k.existsSync(l)?(k.renameSync(a,l),n.push(s+" \u2192 "+i)):k.existsSync(a)&&(k.unlinkSync(a),n.push(s+" (removed \u2014 .lbe/ version exists)"))}let r=["CLAUDE.md",v.join(".github","copilot-instructions.md")];for(let s of r){let i=v.join(e,s);if(k.existsSync(i)){let a=k.readFileSync(i,"utf8");(a.includes("lbe-governance")||a.includes("LetterBlack LBE"))&&(k.unlinkSync(i),n.push(s+" (removed \u2014 LBE-generated file)"))}}return n}async function $e(e={}){let t=process.cwd(),o=e.yes||e.y||!process.stdin.isTTY,n=v.join(t,".lbe");k.mkdirSync(n,{recursive:!0});let r=v.join(n,"workspace.json");console.log(`
65
65
  Scanning workspace...
66
- `);let{projectTypes:s,primaryType:i,semantics:a,enforcement:c}=Fe(t);console.log(je(s,a,c)),console.log("");let l=c;if(!o){let h=await ro("Accept? [Y = accept / s = strict / r = relaxed / n = cancel] ");if(h==="n")return console.log("Cancelled."),{success:!1};h==="s"&&(l=so(c)),h==="r"&&(l=io(c))}let p={lbe:!0,version:"0.4.0",state:"local",projectTypes:s,primaryType:i,semantics:a,enforcement:l};S.writeFileSync(r,JSON.stringify(p,null,2)),console.log("\u2713 Wrote .lbe/workspace.json"),ao(t);let f=v.join(n,"policy.json");S.existsSync(f)||S.writeFileSync(f,JSON.stringify({version:1,mode:"observe",workspace:t,rules:[]},null,2)+`
67
- `);let m=v.join(n,"audit.jsonl");S.existsSync(m)||S.writeFileSync(m,""),console.log("\u2713 Keys and policy ready (.lbe/)"),lo(t),console.log("\u2713 Agent contract written \u2192 .lbe/AGENT_CONTRACT.md");let y=uo(t);if(y.length){console.log(`
66
+ `);let{projectTypes:s,primaryType:i,semantics:a,enforcement:l}=Fe(t);console.log(je(s,a,l)),console.log("");let c=l;if(!o){let h=await ro("Accept? [Y = accept / s = strict / r = relaxed / n = cancel] ");if(h==="n")return console.log("Cancelled."),{success:!1};h==="s"&&(c=so(l)),h==="r"&&(c=io(l))}let p={lbe:!0,version:"0.4.0",state:"local",projectTypes:s,primaryType:i,semantics:a,enforcement:c};k.writeFileSync(r,JSON.stringify(p,null,2)),console.log("\u2713 Wrote .lbe/workspace.json"),ao(t);let f=v.join(n,"policy.json");k.existsSync(f)||k.writeFileSync(f,JSON.stringify({version:1,mode:"observe",workspace:t,rules:[]},null,2)+`
67
+ `);let m=v.join(n,"audit.jsonl");k.existsSync(m)||k.writeFileSync(m,""),console.log("\u2713 Keys and policy ready (.lbe/)"),lo(t),console.log("\u2713 Agent contract written \u2192 .lbe/AGENT_CONTRACT.md");let y=uo(t);if(y.length){console.log(`
68
68
  \u2713 Migrated legacy files:`);for(let h of y)console.log(" "+h)}return console.log(`
69
69
  Done. All LBE state is in .lbe/`),console.log(`Run npx lbe-exec status to verify.
70
- `),{success:!0,contract:p}}ve();async function Je(e,t={}){let o=G(t.root||process.cwd(),e);Ie(o.root,{...o.policy,mode:e}),console.log(JSON.stringify({mode:e,policy:o.policyPath},null,2))}var[,,Q,...Y]=process.argv,P=Object.fromEntries(Y.flatMap((e,t,o)=>e.startsWith("--")?[[e.slice(2),o[t+1]??!0]]:[])),Jr=Y.filter(e=>!e.startsWith("--")&&Y[Y.indexOf(e)-1]?.startsWith("--")===!1),Ct=A.dirname(an(import.meta.url));function cn(){let e=process.cwd(),t=E.existsSync(A.join(e,".lbe","policy.json"))?A.join(e,".lbe","policy.json"):A.join(e,"lbe.policy.json");return E.existsSync(t)?JSON.parse(E.readFileSync(t,"utf8")):null}function te(){let e=[A.resolve(Ct,"../hooks/register.cjs"),A.resolve(Ct,"../src/hooks/register.cjs")];return e.find(t=>E.existsSync(t))||e[0]}function ln(e){let t=/(?:^|\s)node\s+(\S+)/;return Object.entries(e||{}).filter(([o,n])=>o.includes(":lbe")||o.startsWith("lbe")?!1:t.test(n))}function Pt(e){let t=e.match(/(?:^|\s)node\s+(.+)/);return t?t[1].trim():null}function dn(e){let t=A.join(process.cwd(),"package.json");if(!E.existsSync(t))return[];let o=JSON.parse(E.readFileSync(t,"utf8")),n=o.scripts||{},r=[];if(e){let s=n[e];if(!s)return console.error(`No script named "${e}" found.`),[];let i=Pt(s);if(!i)return console.error(`Script "${e}" does not look like a node script.`),[];n[e]=`lbe-exec run-node --mode observe ${i}`,r.push(e)}else{let s=ln(n);for(let[i,a]of s){let c=Pt(a);if(!c)continue;let l=i+":lbe",p=i+":lbe:enforce";n[l]||(n[l]=`lbe-exec run-node --mode observe ${c}`,r.push(l)),n[p]||(n[p]=`lbe-exec run-node --mode enforce ${c}`,r.push(p))}}if(n["lbe:status"]||(n["lbe:status"]="lbe-exec status",r.push("lbe:status")),n["lbe:audit"]||(n["lbe:audit"]="lbe-exec audit",r.push("lbe:audit")),r.length){o.scripts=n,E.writeFileSync(t,JSON.stringify(o,null,2)+`
71
- `);for(let s of r)console.log(` added: ${s}`)}return r}switch(Q){case"run-node":{let e=P.mode||"observe";["observe","enforce"].includes(e)||(console.error("--mode must be observe or enforce"),process.exit(1));let t=Y.findIndex((s,i)=>!s.startsWith("--")&&(i===0||!Y[i-1].startsWith("--")));t===-1&&(console.error("Usage: lbe-exec run-node [--mode observe|enforce] <script> [...args]"),process.exit(1));let o=Y.slice(t),n=te();E.existsSync(n)||(console.error("Hook not found: "+n+`
70
+ `),{success:!0,contract:p}}ve();async function Je(e,t={}){let o=G(t.root||process.cwd(),e);Ie(o.root,{...o.policy,mode:e}),console.log(JSON.stringify({mode:e,policy:o.policyPath},null,2))}var[,,Q,...$]=process.argv,P=Object.fromEntries($.flatMap((e,t,o)=>e.startsWith("--")?[[e.slice(2),o[t+1]??!0]]:[])),Jr=$.filter(e=>!e.startsWith("--")&&$[$.indexOf(e)-1]?.startsWith("--")===!1),Ct=w.dirname(an(import.meta.url));function cn(){let e=process.cwd(),t=E.existsSync(w.join(e,".lbe","policy.json"))?w.join(e,".lbe","policy.json"):w.join(e,"lbe.policy.json");return E.existsSync(t)?JSON.parse(E.readFileSync(t,"utf8")):null}function te(){let e=[w.resolve(Ct,"../hooks/register.cjs"),w.resolve(Ct,"../src/hooks/register.cjs")];return e.find(t=>E.existsSync(t))||e[0]}function ln(e){let t=/(?:^|\s)node\s+(\S+)/;return Object.entries(e||{}).filter(([o,n])=>o.includes(":lbe")||o.startsWith("lbe")?!1:t.test(n))}function Pt(e){let t=e.match(/(?:^|\s)node\s+(.+)/);return t?t[1].trim():null}function dn(e){let t=w.join(process.cwd(),"package.json");if(!E.existsSync(t))return[];let o=JSON.parse(E.readFileSync(t,"utf8")),n=o.scripts||{},r=[];if(e){let s=n[e];if(!s)return console.error(`No script named "${e}" found.`),[];let i=Pt(s);if(!i)return console.error(`Script "${e}" does not look like a node script.`),[];n[e]=`lbe-exec run-node --mode observe ${i}`,r.push(e)}else{let s=ln(n);for(let[i,a]of s){let l=Pt(a);if(!l)continue;let c=i+":lbe",p=i+":lbe:enforce";n[c]||(n[c]=`lbe-exec run-node --mode observe ${l}`,r.push(c)),n[p]||(n[p]=`lbe-exec run-node --mode enforce ${l}`,r.push(p))}}if(n["lbe:status"]||(n["lbe:status"]="lbe-exec status",r.push("lbe:status")),n["lbe:audit"]||(n["lbe:audit"]="lbe-exec audit",r.push("lbe:audit")),r.length){o.scripts=n,E.writeFileSync(t,JSON.stringify(o,null,2)+`
71
+ `);for(let s of r)console.log(` added: ${s}`)}return r}switch(Q){case"run-node":{let e=P.mode||"observe";["observe","enforce"].includes(e)||(console.error("--mode must be observe or enforce"),process.exit(1));let t=$.findIndex((s,i)=>!s.startsWith("--")&&(i===0||!$[i-1].startsWith("--")));t===-1&&(console.error("Usage: lbe-exec run-node [--mode observe|enforce] <script> [...args]"),process.exit(1));let o=$.slice(t),n=te();E.existsSync(n)||(console.error("Hook not found: "+n+`
72
72
  Run: npm install @letterblack/lbe-exec`),process.exit(1)),de(process.execPath,["--require",n,...o],{stdio:"inherit",env:{...process.env,LBE_MODE:e,LBE_ROOT:process.cwd()}}).on("close",s=>process.exit(s??0));break}case"npm":{console.error('[lbe] Note: Use "lbe-exec run-node" for reliable hook preload.'),console.error(`[lbe] NODE_OPTIONS --require may not fire for all npm lifecycle hooks.
73
- `);let e=te();E.existsSync(e)||(console.error("Hook not found: "+e),process.exit(1));let t=process.env.NODE_OPTIONS||"",o=e.replace(/\\/g,"/"),n='--require "'+o+'"',r=t.includes(o)?t:(t+" "+n).trim(),s=Y.filter(a=>!a.startsWith("--mode")&&a!==P.mode);de("npm",s,{stdio:"inherit",shell:!0,env:{...process.env,NODE_OPTIONS:r,LBE_MODE:P.mode||"observe",LBE_ROOT:process.cwd()}}).on("close",a=>process.exit(a??0));break}case"status":{let e=process.cwd();console.log("\u2500\u2500 LBE Status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log("workspace: "+e);let t=te();console.log("hook file: "+t+(E.existsSync(t)?" (found)":" (MISSING)"));let o=process.env.LBE_ROOT||"";console.log("LBE_ROOT: "+(o||"(not set)"));let r=(process.env.NODE_OPTIONS||"").includes("register.cjs");console.log("NODE_OPTIONS contains hook: "+(r?"yes":"no"));let s=A.join(e,".lbe","events.jsonl"),i=E.existsSync(s);if(console.log("audit log: "+(i?s:"(none yet)")),i)try{let c=E.readFileSync(s,"utf8").split(`
74
- `).filter(l=>l.trim());if(c.length){let l=JSON.parse(c[c.length-1]),p=new Date((l.ts||0)*1e3).toISOString().replace("T"," ").slice(0,19),f=l.path||l.cmd||"?";console.log("last event: "+p+" "+l.action+" "+f+" \u2192 "+(l.decision||"?"))}else console.log("last event: (none)")}catch{console.log("last event: (unreadable)")}let a=A.join(e,".lbe","runtime","hook-status.json");if(E.existsSync(a)){let c;try{c=JSON.parse(E.readFileSync(a,"utf8"))}catch{}if(c){let l=!1;try{process.kill(c.pid,0),l=!0}catch{}if(console.log(`
75
- hook process: `+(l?"ACTIVE":"stale (process exited)")),console.log("hook pid: "+c.pid+(l?" (alive)":" (gone)")),console.log("hook mode: "+c.mode),console.log("hook started: "+c.started_at),c.patched){console.log(`
76
- Patched functions:`);for(let[p,f]of Object.entries(c.patched))console.log(" "+(f?"\u2713":"\u2013")+" "+p)}}}else console.log(`
77
- hook process: inactive \u2014 run: lbe-exec run-node ./agent.js`),console.log(" or: lbe-exec activate then lbe-exec shell");break}case"audit":{let e=A.join(process.cwd(),".lbe","events.jsonl");if(!E.existsSync(e)){console.log("No events log found. Run an agent with: npx lbe-exec run-node ./agent.js");break}let t=E.readFileSync(e,"utf8").split(`
73
+ `);let e=te();E.existsSync(e)||(console.error("Hook not found: "+e),process.exit(1));let t=process.env.NODE_OPTIONS||"",o=e.replace(/\\/g,"/"),n='--require "'+o+'"',r=t.includes(o)?t:(t+" "+n).trim(),s=$.filter(a=>!a.startsWith("--mode")&&a!==P.mode);de("npm",s,{stdio:"inherit",shell:!0,env:{...process.env,NODE_OPTIONS:r,LBE_MODE:P.mode||"observe",LBE_ROOT:process.cwd()}}).on("close",a=>process.exit(a??0));break}case"status":{let e=process.cwd();console.log("\u2500\u2500 LBE Status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log("workspace: "+e);let t=te();console.log("hook file: "+t+(E.existsSync(t)?" (found)":" (MISSING)"));let o=process.env.LBE_ROOT||"";console.log("LBE_ROOT: "+(o||"(not set)"));let r=(process.env.NODE_OPTIONS||"").includes("register.cjs");console.log("NODE_OPTIONS contains hook: "+(r?"yes":"no"));let s=w.join(e,".lbe","events.jsonl"),i=E.existsSync(s);if(console.log("audit log: "+(i?s:"(none yet)")),i)try{let l=E.readFileSync(s,"utf8").split(`
74
+ `).filter(c=>c.trim());if(l.length){let c=JSON.parse(l[l.length-1]),p=new Date((c.ts||0)*1e3).toISOString().replace("T"," ").slice(0,19),f=c.path||c.cmd||"?";console.log("last event: "+p+" "+c.action+" "+f+" \u2192 "+(c.decision||"?"))}else console.log("last event: (none)")}catch{console.log("last event: (unreadable)")}let a=w.join(e,".lbe","runtime","hook-status.json");if(E.existsSync(a)){let l;try{l=JSON.parse(E.readFileSync(a,"utf8"))}catch{}if(l){let c=!1;try{process.kill(l.pid,0),c=!0}catch{}if(console.log(`
75
+ hook process: `+(c?"ACTIVE":"stale (process exited)")),console.log("hook pid: "+l.pid+(c?" (alive)":" (gone)")),console.log("hook mode: "+l.mode),console.log("hook started: "+l.started_at),l.patched){console.log(`
76
+ Patched functions:`);for(let[p,f]of Object.entries(l.patched))console.log(" "+(f?"\u2713":"\u2013")+" "+p)}}}else console.log(`
77
+ hook process: inactive \u2014 run: lbe-exec run-node ./agent.js`),console.log(" or: lbe-exec activate then lbe-exec shell");break}case"audit":{let e=w.join(process.cwd(),".lbe","events.jsonl");if(!E.existsSync(e)){console.log("No events log found. Run an agent with: npx lbe-exec run-node ./agent.js");break}let t=E.readFileSync(e,"utf8").split(`
78
78
  `).filter(o=>o.trim());if(!t.length){console.log("No events recorded yet.");break}console.log("\u2500\u2500 LBE Event Log ("+t.length+" entries) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let o of t)try{let n=JSON.parse(o),r=new Date(n.ts*1e3).toISOString().replace("T"," ").slice(0,19),s=n.path||n.cmd||"?",i=n.enforced&&n.decision==="deny"?"BLOCKED":n.decision==="deny"?"WOULD-BLOCK":"allowed";console.log(`${r} [${n.mode}] ${n.action} ${s} \u2192 ${i}`)}catch{}break}case"init":$e(P).then(()=>{dn(P.wrap||null).length?(console.log(`
79
79
  \u2713 Added LBE script variants to package.json`),console.log(" Run your agent through LBE: npm run <name>:lbe")):(console.log(`
80
- No node agent scripts detected in package.json.`),console.log("Use: npx lbe-exec run-node [--mode observe|enforce] ./your-agent.js"))}).catch(e=>{console.error(e.message),process.exit(1)});break;case"activate":{let e=te();E.existsSync(e)||(console.error("Hook not found: "+e),console.error("Run: npm install @letterblack/lbe-exec"),process.exit(1));let t=P.mode||"observe",o=process.cwd(),n=A.join(o,".lbe");E.mkdirSync(n,{recursive:!0}),E.writeFileSync(A.join(n,"activation.json"),JSON.stringify({activated:!0,activatedAt:new Date().toISOString(),hookPath:e,mode:t,root:o},null,2)+`
80
+ No node agent scripts detected in package.json.`),console.log("Use: npx lbe-exec run-node [--mode observe|enforce] ./your-agent.js"))}).catch(e=>{console.error(e.message),process.exit(1)});break;case"activate":{let e=te();E.existsSync(e)||(console.error("Hook not found: "+e),console.error("Run: npm install @letterblack/lbe-exec"),process.exit(1));let t=P.mode||"observe",o=process.cwd(),n=w.join(o,".lbe");E.mkdirSync(n,{recursive:!0}),E.writeFileSync(w.join(n,"activation.json"),JSON.stringify({activated:!0,activatedAt:new Date().toISOString(),hookPath:e,mode:t,root:o},null,2)+`
81
81
  `),console.log("\u2500\u2500 LBE workspace activated \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log("workspace: "+o),console.log("hook: "+e),console.log("mode: "+t),console.log(`
82
82
  Next: open a governed shell session:`),console.log(" lbe-exec shell"),console.log(`
83
- Any Node.js agent run inside that shell is intercepted.`),console.log("Python, Go, native binaries, and PowerShell are NOT governed.");break}case"shell":{let e=A.join(process.cwd(),".lbe","activation.json"),t=null;if(E.existsSync(e))try{t=JSON.parse(E.readFileSync(e,"utf8"))}catch{}let o=t&&t.hookPath||te();E.existsSync(o)||(console.error("Hook not found. Run: lbe-exec activate"),process.exit(1));let n=P.mode||t&&t.mode||"observe",r=t&&t.root||process.cwd(),s=o.replace(/\\/g,"/"),i='--require "'+s+'"',a={...process.env,NODE_OPTIONS:i,LBE_ROOT:r,LBE_MODE:n};console.log("[lbe] Opening governed shell \u2014 mode: "+n),console.log("[lbe] NODE_OPTIONS set. Node.js agents are intercepted."),console.log("[lbe] Python / Go / native binaries are NOT governed."),console.log(`[lbe] Type "exit" to close.
84
- `);let c;if(process.platform==="win32"){let l=[`$env:NODE_OPTIONS='--require "${s}"'`,`$env:LBE_ROOT='${r}'`,`$env:LBE_MODE='${n}'`,`Write-Host '[lbe] Shell armed \u2014 mode: ${n}' -ForegroundColor Green`].join("; ");c=de("powershell.exe",["-NoExit","-Command",l],{stdio:"inherit",env:a})}else{let l=process.env.SHELL||"/bin/bash";c=de(l,[],{stdio:"inherit",env:a})}c.on("close",l=>{console.log(`
85
- [lbe] Governed shell closed.`),process.exit(l??0)});break}case"deactivate":{let e=process.cwd(),t=[A.join(e,".lbe","activation.json"),A.join(e,".lbe","runtime","hook-status.json")],o=0;for(let n of t)E.existsSync(n)&&(E.unlinkSync(n),o++);console.log(o?"\u2713 LBE deactivated \u2014 workspace activation files removed.":"Nothing to deactivate (workspace was not activated)."),console.log('Close any open "lbe-exec shell" sessions to fully disarm.');break}case"observe":case"enforce":Je(Q,P).catch(e=>{console.error(e.message),process.exit(1)});break;case"policy":{let e=cn();if(!e){console.log("No policy found. Run: npx lbe-exec init");break}if(!e.rules?.length){console.log("No rules defined.");break}for(let t of e.rules)console.log(`[${t.effect.toUpperCase()}] ${t.type}:${t.pattern} \u2014 ${t.from||""} (${t.id||"?"})`);break}case"execute":{Promise.resolve().then(()=>(Tt(),Dt)).then(async({createLocalExecutor:e})=>{let t=e({rootDir:process.cwd()}),o="";if(P.input)o=E.readFileSync(A.resolve(P.input),"utf8");else for await(let s of process.stdin)o+=s;let n=JSON.parse(o),r=await t.execute(n);console.log(JSON.stringify(r,null,2)),process.exit(r.ok?0:r.decision==="deny"?1:2)}).catch(e=>{console.error(e.message),process.exit(2)});break}default:console.log(`Usage: lbe-exec <command>
86
- `),console.log(" init Bootstrap governance \u2014 policy, keys, agent files"),console.log(" run-node Run a Node.js agent under LBE governance"),console.log(" [--mode observe|enforce] <script> [...args]"),console.log(" npm Wrap npm command with LBE hook (via NODE_OPTIONS)"),console.log(" [...npm-args]"),console.log(" status Show workspace, mode, hook state, patched functions"),console.log(" audit Show unified event log (.lbe/events.jsonl)"),console.log(" policy List active policy rules"),console.log(" activate Write workspace activation record (Node.js only)"),console.log(" [--mode observe|enforce]"),console.log(" shell Open a governed terminal (NODE_OPTIONS pre-set)"),console.log(" [--mode observe|enforce]"),console.log(" deactivate Remove workspace activation files"),console.log(" observe Switch to observer mode (log only, nothing blocked)"),console.log(" enforce Switch to enforcement mode (violations blocked)"),console.log(" execute Send a JSON request from stdin or --input file"),console.log(`
83
+ Any Node.js agent run inside that shell is intercepted.`),console.log("Python, Go, native binaries, and PowerShell are NOT governed.");break}case"shell":{let e=w.join(process.cwd(),".lbe","activation.json"),t=null;if(E.existsSync(e))try{t=JSON.parse(E.readFileSync(e,"utf8"))}catch{}let o=t&&t.hookPath||te();E.existsSync(o)||(console.error("Hook not found. Run: lbe-exec activate"),process.exit(1));let n=P.mode||t&&t.mode||"observe",r=t&&t.root||process.cwd(),s=o.replace(/\\/g,"/"),i='--require "'+s+'"',a={...process.env,NODE_OPTIONS:i,LBE_ROOT:r,LBE_MODE:n};console.log("[lbe] Opening governed shell \u2014 mode: "+n),console.log("[lbe] NODE_OPTIONS set. Node.js agents are intercepted."),console.log("[lbe] Python / Go / native binaries are NOT governed."),console.log(`[lbe] Type "exit" to close.
84
+ `);let l;if(process.platform==="win32"){let c=[`$env:NODE_OPTIONS='--require "${s}"'`,`$env:LBE_ROOT='${r}'`,`$env:LBE_MODE='${n}'`,`Write-Host '[lbe] Shell armed \u2014 mode: ${n}' -ForegroundColor Green`].join("; ");l=de("powershell.exe",["-NoExit","-Command",c],{stdio:"inherit",env:a})}else{let c=process.env.SHELL||"/bin/bash";l=de(c,[],{stdio:"inherit",env:a})}l.on("close",c=>{console.log(`
85
+ [lbe] Governed shell closed.`),process.exit(c??0)});break}case"deactivate":{let e=process.cwd(),t=[w.join(e,".lbe","activation.json"),w.join(e,".lbe","runtime","hook-status.json")],o=0;for(let n of t)E.existsSync(n)&&(E.unlinkSync(n),o++);console.log(o?"\u2713 LBE deactivated \u2014 workspace activation files removed.":"Nothing to deactivate (workspace was not activated)."),console.log('Close any open "lbe-exec shell" sessions to fully disarm.');break}case"observe":case"enforce":Je(Q,P).catch(e=>{console.error(e.message),process.exit(1)});break;case"policy":{let e=cn();if(!e){console.log("No policy found. Run: npx lbe-exec init");break}if(!e.rules?.length){console.log("No rules defined.");break}for(let t of e.rules)console.log(`[${t.effect.toUpperCase()}] ${t.type}:${t.pattern} \u2014 ${t.from||""} (${t.id||"?"})`);break}case"execute":{Promise.resolve().then(()=>(Tt(),Dt)).then(async({createLocalExecutor:e})=>{let t=e({rootDir:process.cwd()}),o="";if(P.input)o=E.readFileSync(w.resolve(P.input),"utf8");else for await(let s of process.stdin)o+=s;let n=JSON.parse(o),r=await t.execute(n);console.log(JSON.stringify(r,null,2)),process.exit(r.ok?0:r.decision==="deny"?1:2)}).catch(e=>{console.error(e.message),process.exit(2)});break}case"integrate":{let e=$[0],t=process.cwd(),n=["This workspace uses LBE execution governance.","Run Node agents through: npx lbe-exec run-node ./agent.js","Governance state lives in .lbe/ \u2014 do not create LBE files outside it.","Full contract: .lbe/AGENT_CONTRACT.md"].join(`
86
+ `),r={claude:{file:"CLAUDE.md",marker:"<!-- lbe-governance -->",content:`<!-- lbe-governance -->
87
+ ## LBE Governance
88
+
89
+ ${n}
90
+ <!-- /lbe-governance -->`},copilot:{file:".github/copilot-instructions.md",marker:"lbe-governance",content:`<!-- lbe-governance -->
91
+ ## LBE Governance
92
+
93
+ ${n}
94
+ <!-- /lbe-governance -->`},cursor:{file:".cursor/rules",marker:"lbe-governance",content:`# lbe-governance
95
+
96
+ ${n}`},gemini:{file:"GEMINI.md",marker:"lbe-governance",content:`<!-- lbe-governance -->
97
+ ## LBE Governance
98
+
99
+ ${n}
100
+ <!-- /lbe-governance -->`}},s=Object.keys(r).join(", ");if(!e||!r[e]){console.log("Usage: lbe-exec integrate <tool>"),console.log("Available: "+s);break}let{file:i,marker:a,content:l}=r[e],c=w.join(t,i);if(E.mkdirSync(w.dirname(c),{recursive:!0}),E.existsSync(c)){if(E.readFileSync(c,"utf8").includes(a)){console.log("Already integrated: "+i);break}E.appendFileSync(c,`
101
+
102
+ `+l+`
103
+ `),console.log("\u2713 Appended LBE section to "+i)}else E.writeFileSync(c,l+`
104
+ `),console.log("\u2713 Created "+i);console.log(" Agents reading that file will see LBE instructions.");break}default:console.log(`Usage: lbe-exec <command>
105
+ `),console.log(" init Bootstrap governance \u2014 policy, keys, agent files"),console.log(" run-node Run a Node.js agent under LBE governance"),console.log(" [--mode observe|enforce] <script> [...args]"),console.log(" npm Wrap npm command with LBE hook (via NODE_OPTIONS)"),console.log(" [...npm-args]"),console.log(" status Show workspace, mode, hook state, patched functions"),console.log(" audit Show unified event log (.lbe/events.jsonl)"),console.log(" policy List active policy rules"),console.log(" activate Write workspace activation record (Node.js only)"),console.log(" [--mode observe|enforce]"),console.log(" shell Open a governed terminal (NODE_OPTIONS pre-set)"),console.log(" [--mode observe|enforce]"),console.log(" deactivate Remove workspace activation files"),console.log(" integrate Create tool-specific instruction file (opt-in)"),console.log(" claude | copilot | cursor | gemini"),console.log(" observe Switch to observer mode (log only, nothing blocked)"),console.log(" enforce Switch to enforcement mode (violations blocked)"),console.log(" execute Send a JSON request from stdin or --input file"),console.log(`
87
106
  CLI: npx lbe-exec <command>`),Q&&Q!=="--help"&&Q!=="help"&&(console.error(`
88
107
  Unknown command: `+Q),process.exit(1))}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letterblack/lbe-exec",
3
- "version": "1.2.18",
3
+ "version": "1.2.20",
4
4
  "description": "Local host-signed execution layer for LetterBlack LBE.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -20,6 +20,7 @@
20
20
  "hooks/",
21
21
  "assets/",
22
22
  "README.md",
23
+ "TRUST.md",
23
24
  "types.d.ts",
24
25
  "LICENSE"
25
26
  ],