@akasecurity/cli 0.9.4 → 0.9.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/dist/cli.js +2394 -505
- package/extension/background.js +1 -0
- package/extension/content.js +1 -0
- package/extension/icons/icon128.png +0 -0
- package/extension/icons/icon16.png +0 -0
- package/extension/icons/icon48.png +0 -0
- package/extension/manifest.json +39 -0
- package/extension/popup.html +69 -0
- package/extension/popup.js +1 -0
- package/native-host/host.js +31139 -0
- package/native-host/scan-worker.js +18055 -0
- package/package.json +11 -7
- package/web-ui/package.json +14 -7
- package/web-ui/packages/dashboard-ui/package.json +2 -0
- package/web-ui/packages/detections/package.json +3 -2
- package/web-ui/packages/persistence/package.json +3 -2
- package/web-ui/packages/plugin-sdk/package.json +5 -2
- package/web-ui/packages/ui-kit/package.json +1 -0
- package/web-ui/rules/secrets/gcp-service-account.json +1 -1
- package/web-ui/web-ui/.next/BUILD_ID +1 -1
- package/web-ui/web-ui/.next/app-build-manifest.json +194 -56
- package/web-ui/web-ui/.next/app-path-routes-manifest.json +9 -9
- package/web-ui/web-ui/.next/build-manifest.json +8 -8
- package/web-ui/web-ui/.next/prerender-manifest.json +3 -3
- package/web-ui/web-ui/.next/required-server-files.json +5 -0
- package/web-ui/web-ui/.next/server/app/(app)/activity/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/activity/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/activity/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/data-shares/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/detections/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/detections/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/detections/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/exceptions/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/findings/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/findings/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/findings/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/inventory/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/policies/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/policies/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/policies/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/scan/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/scan/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/scan/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/security/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/security/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/security/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/settings/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/settings/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/settings/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/updates/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/updates/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/updates/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/vault/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/(app)/vault/page.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/(app)/vault/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/_not-found/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app/_not-found.html +1 -1
- package/web-ui/web-ui/.next/server/app/_not-found.rsc +2 -2
- package/web-ui/web-ui/.next/server/app/index.html +1 -1
- package/web-ui/web-ui/.next/server/app/index.rsc +2 -2
- package/web-ui/web-ui/.next/server/app/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/page_client-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/app-paths-manifest.json +9 -9
- package/web-ui/web-ui/.next/server/chunks/114.js +792 -0
- package/web-ui/web-ui/.next/server/chunks/160.js +785 -0
- package/web-ui/web-ui/.next/server/chunks/243.js +1 -1
- package/web-ui/web-ui/.next/server/chunks/333.js +1 -0
- package/web-ui/web-ui/.next/server/chunks/363.js +12 -0
- package/web-ui/web-ui/.next/server/chunks/413.js +1 -0
- package/web-ui/web-ui/.next/server/chunks/528.js +73 -0
- package/web-ui/web-ui/.next/server/chunks/557.js +5 -0
- package/web-ui/web-ui/.next/server/chunks/561.js +123 -0
- package/web-ui/web-ui/.next/server/functions-config-manifest.json +4 -4
- package/web-ui/web-ui/.next/server/middleware-build-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/middleware-manifest.json +5 -5
- package/web-ui/web-ui/.next/server/pages/404.html +1 -1
- package/web-ui/web-ui/.next/server/pages/500.html +1 -1
- package/web-ui/web-ui/.next/server/server-reference-manifest.js +1 -1
- package/web-ui/web-ui/.next/server/server-reference-manifest.json +1 -1
- package/web-ui/web-ui/.next/static/chunks/133-66e4c8e40b72a3e8.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/539-b35890d398017f99.js +62 -0
- package/web-ui/web-ui/.next/static/chunks/992-ba273ebe2ac236a5.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-1151de62cd9386c8.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-eaee9ff5ba1056e3.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-7fbcf876de9f09de.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/error-092d6780c93209d5.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-8f33eba279e45c1d.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/{page-1d468a1a0cf12aea.js → page-bf9c74a239afdab2.js} +1 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-e17e9d7c8547bc32.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-4bdf3d2ede57b3c7.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-88b768ca343a8524.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-a346cd78f5f28936.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-f79874ebd61fbf46.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-86e7e860ce98d0a4.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/security/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-557e1703a106d286.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-a1956abf86b48b8b.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-fe71f1fd0ab6cde6.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/loading-0e999b82265bac84.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-2473d9063bd5eb69.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/page-315a9068831a3ad5.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/{framework-3444de8758288822.js → framework-a566532c222ba944.js} +1 -1
- package/web-ui/web-ui/.next/static/chunks/{main-b13545f01f111855.js → main-f710385bb68f9de5.js} +1 -1
- package/web-ui/web-ui/.next/static/chunks/pages/{_app-7f0d920cc5af1c9f.js → _app-63f369037199ea68.js} +1 -1
- package/web-ui/web-ui/.next/static/chunks/pages/{_error-3d8b61361c4b2c6b.js → _error-41a11264bde7b852.js} +1 -1
- package/web-ui/web-ui/.next/static/css/2eca310301b96d98.css +2 -0
- package/web-ui/web-ui/.next/static/{cVKs25XbQsC1083sU5GOD → scT_YT84DnOMXJI2dA75N}/_buildManifest.js +1 -1
- package/web-ui/web-ui/dist/scan-worker.js +18055 -0
- package/web-ui/web-ui/package.json +4 -3
- package/web-ui/web-ui/server.js +1 -1
- package/web-ui/web-ui/.next/server/chunks/28.js +0 -1
- package/web-ui/web-ui/.next/server/chunks/330.js +0 -1
- package/web-ui/web-ui/.next/server/chunks/334.js +0 -2
- package/web-ui/web-ui/.next/server/chunks/514.js +0 -755
- package/web-ui/web-ui/.next/server/chunks/628.js +0 -84
- package/web-ui/web-ui/.next/server/chunks/817.js +0 -1
- package/web-ui/web-ui/.next/server/chunks/830.js +0 -750
- package/web-ui/web-ui/.next/server/chunks/949.js +0 -123
- package/web-ui/web-ui/.next/static/chunks/501-939e9e83b25a6293.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/84-8205054e8901dbde.js +0 -62
- package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-e3ce4be93d2f8ac5.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-8bb13b53c7bde504.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-07307e6d8ddb5cbf.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-aecbc7b6fbd143c2.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-863e759b7e26c759.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-7636a56ffa40d5c6.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-c80a692b9d05f321.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-01e6dceb36cb882f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-d98e303b17524dad.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-178c53b1f56b5e97.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-7f69b2579337c729.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-7019a1567cd9aadd.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-90ce0ad1b9403f48.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-7ef77f76ff07ea1f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/page-3fbfddda391d9939.js +0 -1
- package/web-ui/web-ui/.next/static/css/10425160b1a85ff4.css +0 -2
- /package/web-ui/web-ui/.next/static/{cVKs25XbQsC1083sU5GOD → scT_YT84DnOMXJI2dA75N}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
"use strict";exports.id=114,exports.ids=[114],exports.modules={4114:(a,b,c)=>{c.d(b,{WR:()=>as,qA:()=>at,Pi:()=>ct,o8:()=>bU,Qo:()=>bD,Ru:()=>cp,KS:()=>bQ,tI:()=>bO,_2:()=>bM,Dg:()=>bN,Wo:()=>bR,Rd:()=>bK,Ji:()=>bw,y9:()=>bJ,xR:()=>bT,v5:()=>bL,g5:()=>s});var d=c(77598),e=c(76760),f=c(79868),g=c(38172);function h(a){return(0,d.createHash)("sha256").update(a).digest("hex")}function i(a){return h((0,g.tTV)(["source_project",a]))}function j(a,b){return h((0,g.tTV)(["inspection_definition",a,b]))}var k=c(73024),l=c(75919);let m="aka.db";function n(a,b){if(!function(a){try{return(0,k.lstatSync)(a).isSymbolicLink()}catch{return!1}}(a))try{(0,k.chmodSync)(a,b)}catch{}}function o(a){(0,k.mkdirSync)(a,{recursive:!0,mode:448}),n(a,448)}function p(a){return[`${a}-wal`,`${a}-shm`,`${a}-journal`]}function q(a){n(a,384)}function r(a){for(let b of[a,...p(a)])n(b,384)}function s(a,b){let c=`${a}.${String(process.pid)}.tmp`;try{(0,k.rmSync)(c,{force:!0})}catch{}try{(0,k.writeFileSync)(c,b,{mode:384,flag:"wx"}),(0,k.renameSync)(c,a)}finally{try{(0,k.rmSync)(c,{force:!0})}catch{}}q(a)}function t(a){try{if((0,k.lstatSync)(a).isSymbolicLink())return{kind:"symlink"};return{kind:"gone"}}catch(a){if("ENOENT"===a.code)return{kind:"gone"};return{kind:"unknown",cause:a}}}class u extends Error{constructor(a,b){super(a,void 0===b?void 0:{cause:b}),this.code="key-unclaimable",this.name="KeyUnclaimableError"}}function v(a,b){let c,d=`${a}.${String(process.pid)}.${String(l.threadId)}.new`;try{(0,k.rmSync)(d,{force:!0})}catch{}try{(0,k.writeFileSync)(d,b,{mode:384,flag:"wx"}),c=function(a,b,c){try{return(0,k.linkSync)(a,b),!0}catch(b){let a=b.code;if("EEXIST"===a)return!1;if(!w.has(a??""))throw b}try{return(0,k.writeFileSync)(b,c,{mode:384,flag:"wx"}),!0}catch(a){if("EEXIST"===a.code)return!1;throw a}}(d,a,b)}finally{try{(0,k.rmSync)(d,{force:!0})}catch{}}return c&&q(a),c}let w=new Set(["EPERM","ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL"]);function x(a,b){return`${a}.${b}.${String(Date.now())}.${(0,d.randomUUID)().slice(0,8)}.bak`}function y(a){let b,c=(0,e.dirname)(a),d=`${(0,e.basename)(a)}.`;try{b=(0,k.readdirSync)(c)}catch{return}for(let a of b){if(!a.startsWith(d)||!a.endsWith(".bak.partial"))continue;let b=(0,e.join)(c,a);try{Date.now()-(0,k.statSync)(b).mtimeMs>3e5&&(0,k.rmSync)(b,{force:!0})}catch{}}}function z(a,b){let c=`${b}.partial`;try{(0,k.rmSync)(c,{force:!0}),a.prepare("VACUUM INTO ?").run(c),q(c),(0,k.renameSync)(c,b)}catch(a){try{(0,k.rmSync)(c,{force:!0})}catch{}throw a}}function A(a){return a.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function B(a){return Array.from({length:a},()=>"?").join(", ")}function C(a){return`%${A(a)}%`}function D(a){return`(${a.map(a=>`${a} LIKE ? ESCAPE '\\'`).join(" OR ")})`}let E=0;function F(a,b,c="DEFERRED"){if(a.isTransaction){let c=`aka_sp_${String(E+=1)}`;a.exec(`SAVEPOINT ${c}`);try{b(),a.exec(`RELEASE ${c}`)}catch(b){try{a.exec(`ROLLBACK TO ${c}`),a.exec(`RELEASE ${c}`)}catch{}throw b}return}a.exec("IMMEDIATE"===c?"BEGIN IMMEDIATE":"BEGIN");try{b(),a.exec("COMMIT")}catch(b){try{a.exec("ROLLBACK")}catch{}throw b}}function G(a,b,c="DEFERRED"){let d=a.isTransaction;try{return F(a,b,c),!0}catch(b){if(!a.isTransaction&&d)throw b;return!1}}function H(a){process.stderr.write(`[aka] ${a}
|
|
2
|
+
`)}function I(a,b,c){return void 0!==a.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ? LIMIT 1").get(b,c)}function J(a,b,c){let d=c?.includeGenerated?"table_xinfo":"table_info";return a.prepare(`PRAGMA ${d}(${b})`).all().map(a=>a.name)}function K(a,b){return void 0===b?a.all():Array.isArray(b)?a.all(...b):a.all(b)}function L(a,b){return void 0===b?a.get():Array.isArray(b)?a.get(...b):a.get(b)}function M(a){return 1===a||!0===a}function N(a){let b={};for(let[c,d]of Object.entries(a))b[c]=void 0===d?null:d;return b}function O(a,b,c){return L(a.prepare(b),c)?.n??0}function P(a,b,c){let d=new Map;for(let e of K(a.prepare(b),c))d.set(e.k,e.n);return d}function Q(a,b){let c=[];for(let d of a)try{c.push(b(d))}catch{}return c}function R(a){return"column"===a.kind?`column ${a.table}.${a.name}`:`table ${a.name}`}function S(a){return a.split(/-->\s*statement-breakpoint/).map(a=>a.trim()).filter(a=>a.length>0)}let T="0014_drop_legacy_events_findings",U=[{name:"input_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"},{name:"output_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"},{name:"cache_creation_input_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"},{name:"cache_read_input_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"},{name:"model",ddl:"ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"},{name:"provider",ddl:"ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"}];function V(a,b,c,d){let e=function(a,b){let c=a.prepare("SELECT last_rowid AS lastRowid FROM legacy_copy_watermark WHERE source = ?").get(b);return c?.lastRowid??0}(a,b),f=0;for(;f<1e3;){let g=c.all(e,200);if(0===g.length||(F(a,()=>{var c;d(g),e=g[g.length-1]?.rowid??e,c=e,a.prepare(`INSERT INTO legacy_copy_watermark (source, last_rowid) VALUES (?, ?)
|
|
3
|
+
ON CONFLICT(source) DO UPDATE SET last_rowid = excluded.last_rowid`).run(b,c)},"IMMEDIATE"),f+=g.length,g.length<200))return!0}return!1}function W(a,b){if(null==a)return b;try{return JSON.parse(a)}catch{return b}}function X(a){if(null!=a)try{let b=JSON.parse(a);if("object"==typeof b&&null!==b)return b}catch{}}function Y(a){return Buffer.from(JSON.stringify(a)).toString("base64url")}function Z(a){let b=X(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&"startedAtMs"in b&&"id"in b&&Number.isInteger(b.startedAtMs)&&"string"==typeof b.id?b:null}let $="max(started_at, coalesce(ended_at, started_at))";function _(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}let aa={session:"session",prompt:"prompt",response:"response",tool_call:"tool",hook:"hook",detection:"detection",share:"share",permission:"permission",commit:"commit",error:"error",active:"active"};function ab(a){if(!a)return[];let b=W(a,null);return Array.isArray(b)?b:[]}function ac(a){let b=g.TUN.safeParse(a);return b.success?b.data:"claudecode"}function ad(a,b,c){let d=Math.max(a.started_at,b.lastActivityMs),{status:e,endedAtMs:f}=function(a,b,c){if(a.status){let b=g.PhW.safeParse(a.status);if(b.success)return{status:b.data,endedAtMs:a.ended_at}}return null!==a.ended_at?{status:"completed",endedAtMs:a.ended_at}:b>=c-18e5?{status:"active",endedAtMs:null}:{status:"completed",endedAtMs:b}}(a,d,c);return{id:a.id,harness:ac(a.harness),title:a.title||a.project||a.repo||`Session ${a.id.slice(0,8)}`,project:a.project??"",repo:a.repo??"",branches:ab(a.branches),startedAt:(0,g.q11)(a.started_at),endedAt:null===f?null:(0,g.q11)(f),status:e,turns:b.turns,findings:b.findings,shares:b.shares}}function ae(a){let b=aa[a.event_type];if(!b)return null;let c=a.severity?g.U7X.safeParse(a.severity):null,d=a.link?g.Itg.safeParse(a.link):null;return{id:a.id,occurredAt:(0,g.q11)(a.started_at),kind:b,title:a.title??"",detail:a.detail??"",tool:a.tool,severity:c?.success?c.data:null,link:d?.success?d.data:null,targetId:a.target_id,internal:M(a.internal),flagged:M(a.flagged)}}let af=`
|
|
4
|
+
id,
|
|
5
|
+
event_type,
|
|
6
|
+
started_at,
|
|
7
|
+
coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
|
|
8
|
+
coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
|
|
9
|
+
coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
|
|
10
|
+
json_extract(attributes, '$.severity') AS severity,
|
|
11
|
+
json_extract(attributes, '$.link') AS link,
|
|
12
|
+
json_extract(attributes, '$.targetId') AS target_id,
|
|
13
|
+
json_extract(attributes, '$.internal') AS internal,
|
|
14
|
+
json_extract(attributes, '$.flagged') AS flagged`,ag="event_type = 'session'",ah=`EXISTS (
|
|
15
|
+
SELECT 1 FROM audit_events c
|
|
16
|
+
WHERE c.root_session_id = audit_events.id
|
|
17
|
+
AND c.event_type NOT IN ('hook', 'config_scan'))`;class ai{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}stats(a){let{startMs:b,endMs:c}=function a(b,c){let d;try{d=new Intl.DateTimeFormat("en-US",{timeZone:b,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(new Date(c))}catch{let d=_();return b===d?function(a){let b=864e5*Math.floor(a/864e5);return{startMs:b,endMs:b+864e5}}(c):a(d,c)}let e=Object.fromEntries(d.map(a=>[a.type,a.value])),f=Number(e.year),g=Number(e.month),h=Number(e.day),i=Number(e.hour),j=Date.UTC(f,g-1,h,i,Number(e.minute),Number(e.second))-c,k=Date.UTC(f,g-1,h,0,0,0)-j;return{startMs:k,endMs:k+864e5}}(a??_(),this.now()),d=O(this.db,`SELECT count(*) AS n FROM audit_events
|
|
18
|
+
WHERE ${ag} AND started_at >= ? AND started_at < ?
|
|
19
|
+
AND ${ah}`,[b,c]),e=this.now()-18e5,f=O(this.db,`SELECT count(*) AS n FROM audit_events s
|
|
20
|
+
WHERE s.event_type = 'session' AND s.ended_at IS NULL
|
|
21
|
+
AND max(
|
|
22
|
+
s.started_at,
|
|
23
|
+
coalesce(
|
|
24
|
+
(SELECT max(${$}) FROM audit_events e WHERE e.root_session_id = s.id),
|
|
25
|
+
s.started_at
|
|
26
|
+
)
|
|
27
|
+
) >= ?`,[e]),g=O(this.db,`SELECT count(*) AS n FROM audit_events
|
|
28
|
+
WHERE event_type = 'tool_call' AND started_at >= ? AND started_at < ?`,[b,c]);return Promise.resolve({sessionsToday:d,liveNow:f,toolCallsToday:g,findingsToday:O(this.db,`SELECT count(*) AS n FROM inspection_findings f
|
|
29
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
30
|
+
WHERE e.started_at >= ? AND e.started_at < ?`,[b,c]),egressToday:O(this.db,`SELECT count(DISTINCT json_extract(attributes, '$.destination')) AS n
|
|
31
|
+
FROM audit_events
|
|
32
|
+
WHERE event_type = 'share' AND started_at >= ? AND started_at < ?`,[b,c])})}listSessions(a){let b=a.cursor?Z(a.cursor):null,c=a.to?(0,g.I8t)(a.to):this.now(),d=a.from?(0,g.I8t)(a.from):void 0,e=[ag],f=[];if(a.harness&&a.harness.length>0&&(e.push(`coalesce(json_extract(attributes, '$.harness'), 'claudecode') IN (${B(a.harness.length)})`),f.push(...a.harness)),void 0!==d&&(e.push("started_at >= ?"),f.push(d)),e.push("started_at <= ?"),f.push(c),a.q){let b=C(a.q);e.push(`(content LIKE ? ESCAPE '\\'
|
|
33
|
+
OR json_extract(attributes, '$.project') LIKE ? ESCAPE '\\'
|
|
34
|
+
OR json_extract(attributes, '$.repo') LIKE ? ESCAPE '\\'
|
|
35
|
+
OR json_extract(attributes, '$.branches') LIKE ? ESCAPE '\\'
|
|
36
|
+
OR EXISTS (
|
|
37
|
+
SELECT 1 FROM audit_events d
|
|
38
|
+
WHERE d.root_session_id = audit_events.id
|
|
39
|
+
AND (d.content LIKE ? ESCAPE '\\'
|
|
40
|
+
OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`),f.push(b,b,b,b,b,b)}let h=O(this.db,`SELECT count(*) AS n FROM audit_events
|
|
41
|
+
WHERE ${[...e,`NOT ${ah}`].join(" AND ")}`,f);a.excludeEmpty&&e.push(ah),b&&(e.push("(started_at < ? OR (started_at = ? AND id < ?))"),f.push(b.startedAtMs,b.startedAtMs,b.id));let i=a.limit,j=K(this.db.prepare(`SELECT id,
|
|
42
|
+
json_extract(attributes, '$.harness') AS harness,
|
|
43
|
+
content AS title,
|
|
44
|
+
json_extract(attributes, '$.project') AS project,
|
|
45
|
+
json_extract(attributes, '$.repo') AS repo,
|
|
46
|
+
json_extract(attributes, '$.branches') AS branches,
|
|
47
|
+
json_extract(attributes, '$.status') AS status,
|
|
48
|
+
started_at,
|
|
49
|
+
ended_at
|
|
50
|
+
FROM audit_events
|
|
51
|
+
WHERE ${e.join(" AND ")}
|
|
52
|
+
ORDER BY started_at DESC, id DESC
|
|
53
|
+
LIMIT ?`),[...f,i+1]),k=j.length>i,l=k?j.slice(0,i):j,m=this.rollupsFor(l.map(a=>a.id)),n=this.now(),o=l.map(a=>ad(a,m.get(a.id)??{turns:0,findings:0,shares:0,lastActivityMs:0},n)),p=l[l.length-1];return Promise.resolve({items:o,nextCursor:k&&p?Y({startedAtMs:p.started_at,id:p.id}):null,emptyCount:h})}getSession(a){let b=L(this.db.prepare(`SELECT id,
|
|
54
|
+
json_extract(attributes, '$.harness') AS harness,
|
|
55
|
+
content AS title,
|
|
56
|
+
json_extract(attributes, '$.project') AS project,
|
|
57
|
+
json_extract(attributes, '$.repo') AS repo,
|
|
58
|
+
json_extract(attributes, '$.branches') AS branches,
|
|
59
|
+
json_extract(attributes, '$.status') AS status,
|
|
60
|
+
json_extract(attributes, '$.host') AS host,
|
|
61
|
+
json_extract(attributes, '$.cwd') AS cwd,
|
|
62
|
+
json_extract(attributes, '$.models') AS models,
|
|
63
|
+
json_extract(attributes, '$.version') AS version,
|
|
64
|
+
json_extract(attributes, '$.files') AS files,
|
|
65
|
+
started_at,
|
|
66
|
+
ended_at
|
|
67
|
+
FROM audit_events
|
|
68
|
+
WHERE id = ? AND event_type = 'session'
|
|
69
|
+
LIMIT 1`),[a]);if(!b)return Promise.resolve(null);let c=K(this.db.prepare(`SELECT ${af}
|
|
70
|
+
FROM audit_events
|
|
71
|
+
WHERE id = ? OR root_session_id = ?
|
|
72
|
+
ORDER BY started_at ASC, id ASC`),[a,a]).map(ae).filter(a=>null!==a),d=L(this.db.prepare(`SELECT
|
|
73
|
+
coalesce(sum(input_tokens), 0) AS input,
|
|
74
|
+
coalesce(sum(output_tokens), 0) AS output,
|
|
75
|
+
coalesce(sum(cache_creation_input_tokens), 0) AS cache_creation,
|
|
76
|
+
coalesce(sum(cache_read_input_tokens), 0) AS cache_read
|
|
77
|
+
FROM audit_events
|
|
78
|
+
WHERE root_session_id = ? AND event_type = 'llm_call'`),[a])??{input:0,output:0,cache_creation:0,cache_read:0},e=L(this.db.prepare(`SELECT model, provider FROM audit_events
|
|
79
|
+
WHERE root_session_id = ? AND event_type = 'llm_call'
|
|
80
|
+
ORDER BY started_at ASC, id ASC
|
|
81
|
+
LIMIT 1`),[a]),f=K(this.db.prepare(`SELECT coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
|
|
82
|
+
count(*) AS n
|
|
83
|
+
FROM audit_events
|
|
84
|
+
WHERE root_session_id = ? AND event_type = 'tool_call'
|
|
85
|
+
GROUP BY coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool'))`),[a]),g=K(this.db.prepare(`SELECT DISTINCT model FROM audit_events
|
|
86
|
+
WHERE root_session_id = ? AND event_type = 'llm_call' AND model IS NOT NULL AND model <> ''
|
|
87
|
+
ORDER BY model`),[a]).map(a=>a.model),h=O(this.db,`SELECT count(*) AS n FROM audit_events
|
|
88
|
+
WHERE root_session_id = ? AND event_type = 'commit'`,[a]),i=this.rollupsFor([a]).get(a)??{turns:0,findings:0,shares:0,lastActivityMs:0},j={sessionId:a,model:e?.model??"",provider:e?.provider??"",inputTokens:d.input,outputTokens:d.output,cacheCreation:d.cache_creation,cacheRead:d.cache_read,totalTokens:d.input+d.output+d.cache_creation+d.cache_read,estimatedCostUsd:null};return Promise.resolve({...ad(b,i,this.now()),host:b.host??"",cwd:b.cwd??"",models:g.length>0?g:ab(b.models),version:b.version??"",tokens:j,tools:Object.fromEntries(f.flatMap(a=>a.tool?[[a.tool,a.n]]:[])),files:ab(b.files),commits:h,events:c})}tokenReports(a){let b=this.readLlmCallLeaves(void 0===a?{}:{fromMs:a});return Promise.resolve((0,g.ryv)(b,g.q_t))}tokenReportForSession(a){return Promise.resolve((0,g.ryv)(this.readLlmCallLeaves({sessionId:a}),g.q_t)[0]??null)}harnessFacets(a){let b=K(this.db.prepare(`SELECT DISTINCT coalesce(json_extract(attributes, '$.harness'), 'claudecode') AS harness
|
|
89
|
+
FROM audit_events WHERE ${ag}${void 0===a?"":" AND started_at >= ?"}`),void 0===a?void 0:[a]),c=new Set;for(let a of b)c.add(ac(a.harness));return Promise.resolve([...c])}readLlmCallLeaves(a={}){let b=["event_type = 'llm_call'","attributes IS NOT NULL"],c=[];return void 0!==a.sessionId&&(b.push("root_session_id = ?"),c.push(a.sessionId)),void 0!==a.fromMs&&(b.push("started_at >= ?"),c.push(a.fromMs)),Q(K(this.db.prepare(`SELECT root_session_id AS sessionId, attributes
|
|
90
|
+
FROM audit_events
|
|
91
|
+
WHERE ${b.join(" AND ")}`),c).filter(a=>null!==a.sessionId),a=>({sessionId:a.sessionId,attributes:JSON.parse(a.attributes)}))}rollupsFor(a){let b=new Map(a.map(a=>[a,{turns:0,findings:0,shares:0,lastActivityMs:0}]));if(0===a.length)return b;let c=B(a.length);for(let d of K(this.db.prepare(`SELECT root_session_id AS id, max(${$}) AS m FROM audit_events
|
|
92
|
+
WHERE root_session_id IN (${c})
|
|
93
|
+
GROUP BY root_session_id`),a)){if(null===d.id)continue;let a=b.get(d.id);a&&null!==d.m&&(a.lastActivityMs=d.m)}for(let d of K(this.db.prepare(`SELECT root_session_id AS id, count(*) AS n FROM audit_events
|
|
94
|
+
WHERE root_session_id IN (${c}) AND event_type = 'prompt'
|
|
95
|
+
GROUP BY root_session_id`),a)){if(null===d.id)continue;let a=b.get(d.id);a&&(a.turns=d.n)}for(let d of K(this.db.prepare(`SELECT root_session_id AS id,
|
|
96
|
+
count(DISTINCT json_extract(attributes, '$.run_key')) AS n
|
|
97
|
+
FROM audit_events
|
|
98
|
+
WHERE root_session_id IN (${c}) AND event_type = 'llm_call'
|
|
99
|
+
AND json_extract(attributes, '$.run_key') IS NOT NULL
|
|
100
|
+
GROUP BY root_session_id`),a)){if(null===d.id)continue;let a=b.get(d.id);a&&(a.turns=Math.max(a.turns,d.n))}for(let d of K(this.db.prepare(`SELECT e.root_session_id AS id, count(*) AS n FROM inspection_findings f
|
|
101
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
102
|
+
WHERE e.root_session_id IN (${c})
|
|
103
|
+
GROUP BY e.root_session_id`),a)){if(null===d.id)continue;let a=b.get(d.id);a&&(a.findings=d.n)}for(let d of K(this.db.prepare(`SELECT root_session_id AS id,
|
|
104
|
+
count(DISTINCT json_extract(attributes, '$.destination')) AS n
|
|
105
|
+
FROM audit_events
|
|
106
|
+
WHERE root_session_id IN (${c}) AND event_type = 'share'
|
|
107
|
+
GROUP BY root_session_id`),a)){if(null===d.id)continue;let a=b.get(d.id);a&&(a.shares=d.n)}return b}}class aj{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO audit_events
|
|
108
|
+
(id, parent_id, root_session_id, event_type,
|
|
109
|
+
host_id, harness_id, source_project_id, started_at, ended_at,
|
|
110
|
+
severity, priority, content, content_hash, attributes)
|
|
111
|
+
VALUES
|
|
112
|
+
(:id, :parentId, :rootSessionId, :eventType,
|
|
113
|
+
:hostId, :harnessId, :sourceProjectId, :startedAt, :endedAt,
|
|
114
|
+
:severity, :priority, :content, :contentHash, :attributes)`),this.upsertLlmCallStmt=a.prepare(`INSERT INTO audit_events
|
|
115
|
+
(id, parent_id, root_session_id, event_type,
|
|
116
|
+
host_id, harness_id, source_project_id, started_at, ended_at,
|
|
117
|
+
severity, priority, content, content_hash, attributes)
|
|
118
|
+
VALUES
|
|
119
|
+
(:id, :parentId, :rootSessionId, :eventType,
|
|
120
|
+
:hostId, :harnessId, :sourceProjectId, :startedAt, :endedAt,
|
|
121
|
+
:severity, :priority, :content, :contentHash, :attributes)
|
|
122
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
123
|
+
attributes = excluded.attributes,
|
|
124
|
+
ended_at = excluded.ended_at
|
|
125
|
+
WHERE COALESCE(json_extract(excluded.attributes, '$.output_tokens'), 0)
|
|
126
|
+
> COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)`)}runInTransaction(a){F(this.db,a)}insertAuditEvent(a){let b=(0,g.V9M)(a);this.insertStmt.run(N({id:b.id,parentId:b.parentId,rootSessionId:b.rootSessionId,eventType:b.eventType,hostId:b.hostId,harnessId:b.harnessId,sourceProjectId:b.sourceProjectId,startedAt:b.startedAt,endedAt:b.endedAt,severity:b.severity,priority:b.priority,content:b.content,contentHash:b.contentHash,attributes:b.attributes}))}ensureSessionRoot(a,b){this.insertAuditEvent({id:a,eventType:"session",startedAt:b})}insertLlmCall(a){var b,c;let d=(0,g.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.messageId,h((0,g.tTV)(["audit_event_llm_call",b,c])));this.upsertLlmCallStmt.run(N({id:e,parentId:a.parentId,rootSessionId:a.rootSessionId,eventType:"llm_call",hostId:null,harnessId:null,sourceProjectId:null,startedAt:d,endedAt:null,severity:null,priority:null,content:null,contentHash:null,attributes:JSON.stringify(a.attributes)}))}insertToolCall(a){var b,c;let d=(0,g.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.toolUseId,h((0,g.tTV)(["audit_event_tool_call",b,c])));this.insertStmt.run(N({id:e,parentId:a.parentId,rootSessionId:a.rootSessionId,eventType:"tool_call",hostId:null,harnessId:null,sourceProjectId:null,startedAt:d,endedAt:null,severity:null,priority:null,content:null,contentHash:null,attributes:JSON.stringify(a.attributes)}))}findById(a){return L(this.db.prepare("SELECT * FROM audit_events WHERE id = :id"),{id:a})}sessionProvider(a){let b=this.findById(a);if(!b?.attributes)return;let c=X(b.attributes)?.provider;if("string"==typeof c)return c}llmCallLeaves(){return K(this.db.prepare(`SELECT root_session_id AS sessionId, attributes
|
|
127
|
+
FROM audit_events
|
|
128
|
+
WHERE event_type = 'llm_call' AND attributes IS NOT NULL`))}}class ak{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO classified_data (id, class, label, attributes)
|
|
129
|
+
VALUES (:id, :class, :label, :attributes)`)}upsert(a){var b;let c=(b=a.class,h((0,g.tTV)(["classified_data",b]))),d=(0,g.$BP)(a,c);return this.insertStmt.run(N({id:d.id,class:d.class,label:d.label,attributes:d.attributes})),c}}function al(a){return L(a.prepare(`SELECT id, started_at, attributes FROM audit_events
|
|
130
|
+
WHERE event_type = 'config_scan'
|
|
131
|
+
ORDER BY started_at DESC, id DESC LIMIT 1`))}class am{constructor(a){this.db=a}report(){let a=al(this.db);if(!a)return{scannedAt:null,skills:[],hooks:[],mcpServers:[],configFiles:[],topics:[]};let b=K(this.db.prepare(`SELECT id, object_type AS objectType, title, location, attributes FROM inventory
|
|
132
|
+
WHERE object_type IN ('skill', 'hook', 'mcp_server', 'config_file') AND last_seen >= :startedAt
|
|
133
|
+
ORDER BY object_type, title`),{startedAt:a.started_at}),c=K(this.db.prepare(`SELECT f.masked_match AS maskedMatch, d.rule_id AS ruleId, d.name AS name
|
|
134
|
+
FROM inspection_findings f
|
|
135
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
136
|
+
WHERE f.audit_event_id = :scanId`),{scanId:a.id}),d=[],e=[],f=[],g=[],h=this.trustOverrides();for(let a of b){let b=X(a.attributes);b&&("skill"===a.objectType?d.push(function(a,b){let c={id:a.id,name:a.title??"(unnamed)",source:an(b.source)??"unknown",scope:an(b.scope)??"unknown",status:"unknown"},d=an(b.description);void 0!==d&&(c.description=d);let e=an(b.version);void 0!==e&&(c.installedVersion=e);let f=an(b.updated_at);return void 0!==f&&(c.updatedAt=f),c}(a,b)):"hook"===a.objectType?e.push(function(a,b,c){let d=an(b.command)??"",e=c.filter(a=>a.maskedMatch===d),f={id:a.id,event:an(b.event)??"unknown",command:d,scope:an(b.scope)??"unknown",status:e.some(a=>"hook-external-egress"===a.ruleId)?"egress":e.some(a=>"hook-conflict"===a.ruleId)?"conflict":e.some(a=>"hook-unknown"===a.ruleId)?"unknown":"active",warnings:e.map(a=>a.name)},g=an(b.matcher);void 0!==g&&(f.matcher=g);let h=an(b.plugin_name);return void 0!==h&&(f.pluginName=h),f}(a,b,c)):"mcp_server"===a.objectType?f.push(function(a,b,c){let d={id:a.id,name:a.title??"(unnamed)",scope:an(b.scope)??"unknown",transport:an(b.transport)??"unknown",trust:c.get(a.id)??"unapproved"},e=an(b.command);void 0!==e&&(d.command=e);let f=an(b.url);if(void 0!==f&&(d.url=f),Array.isArray(b.env_keys)){let a=b.env_keys.filter(a=>"string"==typeof a);a.length>0&&(d.envKeys=a)}let g=an(b.plugin_name);void 0!==g&&(d.pluginName=g);let h=an(b.marketplace);void 0!==h&&(d.marketplace=h);let i=an(b.project);return void 0!==i&&(d.project=i),d}(a,b,h)):g.push(function(a,b){let c=an(b.scope)??"unknown",d={id:a.id,name:a.title??"(unnamed)",path:a.location??"",scope:c,kind:an(b.kind)??"Configuration file",untracked:"local"===c},e=an(b.detail);void 0!==e&&(d.detail=e),"number"==typeof b.entry_count&&(d.entryCount=b.entry_count);let f=an(b.updated_at);return void 0!==f&&(d.updatedAt=f),d}(a,b)))}return{scannedAt:new Date(a.started_at).toISOString(),skills:d,hooks:e,mcpServers:f,configFiles:g,topics:function(a,b,c,d,e){let f=[],g=a.filter(a=>"update_available"===a.status).length,h={topic:"skills",count:a.length};g>0&&(h.attention=`${String(g)} updates`),f.push(h);let i=b.filter(a=>"egress"===a.status).length,j=b.filter(a=>"conflict"===a.status).length,k=b.filter(a=>"unknown"===a.status).length,l=[];i>0&&l.push(`${String(i)} egress`),k>0&&l.push(`${String(k)} unknown`),j>0&&l.push(`${String(j)} conflict${j>1?"s":""}`);let m={topic:"hooks",count:b.length};l.length>0&&(m.attention=l.join(" \xb7 ")),f.push(m);let n=c.filter(a=>"unapproved"===a.trust).length,o={topic:"mcp",count:c.length};n>0&&(o.attention=`${String(n)} unapproved`),f.push(o);let p=d.filter(a=>a.untracked).length,q={topic:"config_files",count:d.length};p>0&&(q.attention=`${String(p)} untracked`),f.push(q);let r=function(a){let b=X(a)?.errors;return"number"==typeof b?b:0}(e),s={topic:"configuration",count:r};return r>0&&(s.attention=`${String(r)} sources failed to parse`),f.push(s),f}(d,e,f,g,a.attributes)}}trustOverrides(){let a=K(this.db.prepare("SELECT asset_id AS assetId, trust FROM mcp_trust_override")),b=new Map;for(let c of a)("known-good"===c.trust||"risky"===c.trust||"unapproved"===c.trust)&&b.set(c.assetId,c.trust);return b}}function an(a){return"string"==typeof a?a:void 0}function ao(a){let b=W(a,[]);if(!Array.isArray(b))return[];let c=[];for(let a of b)a&&"object"==typeof a&&c.push(a);return c}function ap(a,b){return a.version!==b.version||a.rulesJson!==b.rulesJson}class aq{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}listDetections(a){let b=K(this.db.prepare(`SELECT namespace, pack_id AS packId, version, name, enabled, policy_id AS policyId,
|
|
137
|
+
rules_json AS rulesJson
|
|
138
|
+
FROM installed_packs`)),c=this.availableByPack(),d=b.map(a=>{let b=c.get(`${a.namespace}/${a.packId}`);return{namespace:a.namespace,packId:a.packId,version:a.version,name:a.name,enabled:M(a.enabled),ruleCount:ao(a.rulesJson).length,policyId:a.policyId,...b&&ap(a,b)?{latestVersion:b.version}:{}}});return Promise.resolve((0,g.plk)(d,a))}availableByPack(){return new Map(K(this.db.prepare(`SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson
|
|
139
|
+
FROM available_packs`)).map(a=>[`${a.namespace}/${a.packId}`,a]))}getDetectionStats(){let a=K(this.db.prepare("SELECT enabled, rules_json AS rulesJson FROM installed_packs")),b=0,c=0,d=new Set;for(let e of a){M(e.enabled)&&(c+=1);let a=ao(e.rulesJson);for(let c of(b+=a.length,a))"string"==typeof c.id&&d.add(c.id)}return Promise.resolve({detections:a.length,rules:b,active:c,findingsLast30d:this.countFindingsLast30d([...d])})}getDetectionDetail(a){let b=(0,g.pnU)(a);if(!b)return Promise.resolve(null);let{namespace:c,packId:d}=b,e=L(this.db.prepare(`SELECT namespace, pack_id AS packId, version, name, enabled, policy_id AS policyId,
|
|
140
|
+
rules_json AS rulesJson, updated_at AS updatedAt
|
|
141
|
+
FROM installed_packs
|
|
142
|
+
WHERE namespace = ? AND pack_id = ?`),[c,d]);if(!e)return Promise.resolve(null);let f=ao(e.rulesJson),h=f.map(a=>a.id).filter(a=>"string"==typeof a),i=this.countFindingsLast30d(h),j=this.availableByPack().get(`${e.namespace}/${e.packId}`),k=j?ap(e,j)?{available:!0,latestVersion:j.version,latestRuleCount:ao(j.rulesJson).length}:{available:!1,latestVersion:j.version}:null;return Promise.resolve((0,g.a45)({namespace:e.namespace,packId:e.packId,version:e.version,name:e.name,enabled:M(e.enabled),rules:f,updatedAt:new Date(e.updatedAt),policyId:e.policyId},i,k))}countFindingsLast30d(a){if(0===a.length)return 0;let b=this.now()-2592e6,c=B(a.length);return O(this.db,`SELECT count(*) AS n
|
|
143
|
+
FROM inspection_findings f
|
|
144
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
145
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
146
|
+
WHERE e.started_at >= ?
|
|
147
|
+
AND e.event_type IN (${g.hfB})
|
|
148
|
+
AND d.rule_id IN (${c})`,[b,...a])}}class ar{constructor(a){this.db=a}contentHashes(){return Promise.resolve(new Set(K(this.db.prepare(`SELECT content_hash FROM audit_events
|
|
149
|
+
WHERE event_type IN (${g.hfB})`)).map(a=>a.content_hash)))}}let as=864e5;class at extends Error{constructor(a){super(`duplicate-active-exception: an active exception already exists for rule "${a}" and this value — revoke it before granting a new one`),this.code="duplicate-active-exception",this.name="DuplicateActiveExceptionError"}}class au extends Error{constructor(a){super(`ambiguous-exception-id: "${a}" matches more than one exception — add more characters`),this.code="ambiguous-exception-id",this.name="AmbiguousExceptionIdError"}}let av=`revoked_at IS NULL
|
|
150
|
+
AND (expires_at IS NULL OR expires_at > :now)
|
|
151
|
+
AND (max_uses IS NULL OR use_count < max_uses)`,aw=`capability = 'reveal_to_model'
|
|
152
|
+
AND conditions IS NULL
|
|
153
|
+
AND ${av}`;class ax{constructor(a,b=()=>Date.now()){this.db=a,this.now=b,this.consumeStmt=a.prepare(`UPDATE exceptions
|
|
154
|
+
SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
|
|
155
|
+
WHERE id = :id AND ${av}`),this.insertBlockedStmt=a.prepare(`INSERT OR REPLACE INTO blocked_detections (reference, rule_id, category, value_fingerprint, key_version, masked_value, session_id, repo, blocked_at)
|
|
156
|
+
VALUES (:reference, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue, :sessionId, :repo, :blockedAt)`),this.sweepBlockedStmt=a.prepare("DELETE FROM blocked_detections WHERE blocked_at <= :cutoff")}create(a){try{return Promise.resolve(this.createSync(a))}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}createSync(a){if(a.conditions?.provider!==void 0)throw Error("provider conditions are not supported yet — a grant with one would never apply");let b=(0,d.randomUUID)(),c=this.now();try{this.insertExceptionRow(b,a,c)}catch(d){if(!(d instanceof Error&&(2067===d.errcode||d.message.includes("UNIQUE constraint failed"))))throw d;F(this.db,()=>{if(1!==Number(this.db.prepare(`UPDATE exceptions
|
|
157
|
+
SET revoked_at = :now, revoked_by = :revokedBy,
|
|
158
|
+
revoke_reason = 'superseded by a new grant for the same value',
|
|
159
|
+
updated_at = :now
|
|
160
|
+
WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
|
|
161
|
+
AND key_version = :keyVersion AND revoked_at IS NULL
|
|
162
|
+
AND ((expires_at IS NOT NULL AND expires_at <= :now)
|
|
163
|
+
OR (max_uses IS NOT NULL AND use_count >= max_uses))`).run({now:c,revokedBy:a.createdBy,ruleId:a.ruleId,valueFingerprint:a.valueFingerprint,keyVersion:a.keyVersion}).changes))throw new at(a.ruleId);this.insertExceptionRow(b,a,c)},"IMMEDIATE")}let e=L(this.db.prepare("SELECT * FROM exceptions WHERE id = :id"),{id:b});if(void 0===e)throw Error("exception row not found immediately after insert");return ay(e)}insertExceptionRow(a,b,c){this.db.prepare(`INSERT INTO exceptions (
|
|
164
|
+
id, rule_id, category, value_fingerprint, key_version, masked_value,
|
|
165
|
+
capability, scope, expires_at, max_uses, use_count, last_used_at,
|
|
166
|
+
justification, conditions, created_by, created_via, created_at, updated_at
|
|
167
|
+
) VALUES (
|
|
168
|
+
:id, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue,
|
|
169
|
+
:capability, :scope, :expiresAt, :maxUses, 0, NULL, :justification,
|
|
170
|
+
:conditions, :createdBy, :createdVia, :now, :now
|
|
171
|
+
)`).run({id:a,ruleId:b.ruleId,category:b.category,valueFingerprint:b.valueFingerprint,keyVersion:b.keyVersion,maskedValue:b.maskedValue,capability:b.capability??"suppress",scope:b.scope,expiresAt:null===b.expiresAt?null:(0,g.I8t)(b.expiresAt),maxUses:b.maxUses,justification:b.justification,conditions:null===b.conditions?null:JSON.stringify(b.conditions),createdBy:b.createdBy,createdVia:b.createdVia,now:c})}list(a){let b=a?.includeTerminal?"":`WHERE ${av}`;return Promise.resolve(Q(K(this.db.prepare(`SELECT * FROM exceptions ${b} ORDER BY created_at DESC, rowid DESC`),a?.includeTerminal?{}:{now:this.now()}),ay))}getByIdPrefix(a){if(0===a.length)return Promise.resolve(void 0);let b=K(this.db.prepare(String.raw`SELECT * FROM exceptions WHERE id LIKE :pattern ESCAPE '\' LIMIT 2`),{pattern:`${A(a)}%`});if(b.length>1)return Promise.reject(new au(a));let c=b[0];if(!c)return Promise.resolve(void 0);try{return Promise.resolve(ay(c))}catch{return Promise.resolve(void 0)}}revoke(a,b,c){let d=this.now();return Promise.resolve(1===Number(this.db.prepare(`UPDATE exceptions
|
|
172
|
+
SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
|
|
173
|
+
WHERE id = :id AND revoked_at IS NULL`).run({id:a,revokedBy:b,reason:c??null,now:d}).changes))}consume(a,b=this.now()){return Promise.resolve(1===Number(this.consumeStmt.run({id:a,now:b}).changes))}activeBundleEntries(a,b=this.now()){return Promise.resolve(Q(K(this.db.prepare(`SELECT * FROM exceptions
|
|
174
|
+
WHERE key_version = :keyVersion AND ${av}
|
|
175
|
+
ORDER BY created_at DESC, rowid DESC`),{keyVersion:a,now:b}),a=>{let b=null===a.conditions?null:JSON.parse(a.conditions);return g.iRC.parse({id:a.id,ruleId:a.rule_id,valueFingerprint:a.value_fingerprint,keyVersion:a.key_version,capability:a.capability,expiresAt:null===a.expires_at?null:(0,g.q11)(a.expires_at),maxUses:a.max_uses,useCount:a.use_count,conditions:b})}))}recordBlocked(a){let b=this.now();return this.sweepBlockedStmt.run({cutoff:b-as}),this.insertBlockedStmt.run({reference:a.reference,ruleId:a.ruleId,category:a.category,valueFingerprint:a.valueFingerprint,keyVersion:a.keyVersion,maskedValue:a.maskedValue,sessionId:a.sessionId,repo:a.repo,blockedAt:b}),Promise.resolve()}recentBlocked(a=18e5){return Promise.resolve(K(this.db.prepare(`SELECT * FROM blocked_detections
|
|
176
|
+
WHERE blocked_at > :cutoff
|
|
177
|
+
ORDER BY blocked_at DESC, rowid DESC`),{cutoff:this.now()-a}).map(a=>({reference:a.reference,ruleId:a.rule_id,category:a.category,valueFingerprint:a.value_fingerprint,keyVersion:a.key_version,maskedValue:a.masked_value,sessionId:a.session_id,repo:a.repo,blockedAt:(0,g.q11)(a.blocked_at)})))}activeRevealGrant(a,b,c,d){try{let e=d??this.now(),f=L(this.db.prepare(`SELECT id FROM exceptions
|
|
178
|
+
WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
|
|
179
|
+
AND key_version = :keyVersion
|
|
180
|
+
AND ${aw}
|
|
181
|
+
LIMIT 1`),{ruleId:a,valueFingerprint:b,keyVersion:c,now:e});return Promise.resolve(f??null)}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}sweepTerminal(a,b=this.now()){return Promise.resolve(Number(this.db.prepare(`DELETE FROM exceptions
|
|
182
|
+
WHERE updated_at < :cutoff
|
|
183
|
+
AND (revoked_at IS NOT NULL
|
|
184
|
+
OR (expires_at IS NOT NULL AND expires_at <= :now)
|
|
185
|
+
OR (max_uses IS NOT NULL AND use_count >= max_uses))`).run({cutoff:b-a,now:b}).changes))}}function ay(a){let b=null===a.conditions?null:JSON.parse(a.conditions);return g.V8B.parse({id:a.id,ruleId:a.rule_id,category:a.category,valueFingerprint:a.value_fingerprint,keyVersion:a.key_version,maskedValue:a.masked_value,capability:a.capability,scope:a.scope,expiresAt:null===a.expires_at?null:(0,g.q11)(a.expires_at),maxUses:a.max_uses,useCount:a.use_count,lastUsedAt:null===a.last_used_at?null:(0,g.q11)(a.last_used_at),justification:a.justification,conditions:b,createdBy:a.created_by,createdVia:a.created_via,createdAt:(0,g.q11)(a.created_at),updatedAt:(0,g.q11)(a.updated_at),revokedAt:null===a.revoked_at?null:(0,g.q11)(a.revoked_at),revokedBy:a.revoked_by,revokeReason:a.revoke_reason})}function az(a){return`(
|
|
186
|
+
SELECT fr.status FROM finding_resolution fr
|
|
187
|
+
WHERE fr.finding_key = ${a}.finding_key
|
|
188
|
+
ORDER BY fr.created_at DESC, fr.rowid DESC
|
|
189
|
+
LIMIT 1
|
|
190
|
+
)`}let aA=`(
|
|
191
|
+
SELECT finding_key, status, method, resolved_at FROM (
|
|
192
|
+
SELECT fr.finding_key, fr.status, fr.method, fr.resolved_at,
|
|
193
|
+
ROW_NUMBER() OVER (
|
|
194
|
+
PARTITION BY fr.finding_key
|
|
195
|
+
ORDER BY fr.created_at DESC, fr.rowid DESC
|
|
196
|
+
) AS rn
|
|
197
|
+
FROM finding_resolution fr
|
|
198
|
+
) WHERE rn = 1
|
|
199
|
+
)`;function aB(a,b){return(0,g._6W)({severity:a.maxSeverity,latestDetectedAt:a.latestDetectedAt,id:""},{severity:b.maxSeverity,latestDetectedAt:b.latestDetectedAt,id:""})}function aC(a){return null===a||""===a?[]:a.split(",")}function aD(a){return(0,g.xog)({kind:a.kind,findingKey:a.finding_key,latestResolutionStatus:a.latest_status})}class aE{constructor(a){this.db=a}recentFindings(a){let b=a?.limit??50;return Promise.resolve(K(this.db.prepare(`SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
|
|
200
|
+
f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
|
|
201
|
+
json_extract(e.attributes, '$.source_tool') AS source_tool,
|
|
202
|
+
e.event_type AS kind
|
|
203
|
+
FROM inspection_findings f
|
|
204
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
205
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
206
|
+
WHERE e.event_type IN (${g.hfB})
|
|
207
|
+
ORDER BY e.started_at DESC, f.rowid DESC
|
|
208
|
+
LIMIT :limit`),{limit:b}).map(a=>({id:a.id,eventId:a.event_id,ruleId:a.rule_id,category:a.category,severity:a.severity,maskedMatch:a.masked_match,actionTaken:a.action_taken,confidence:a.confidence,occurredAt:(0,g.q11)(a.occurred_at),sourceTool:a.source_tool,kind:a.kind})))}sessionFindingsCount(a){return a?Promise.resolve(O(this.db,`SELECT count(*) AS n FROM inspection_findings f
|
|
209
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
210
|
+
WHERE e.root_session_id = :sessionId
|
|
211
|
+
AND e.event_type IN (${g.hfB})`,{sessionId:a})):Promise.resolve(0)}sessionFirings(a){return Object.fromEntries(P(this.db,`SELECT d.rule_id AS k, count(*) AS n
|
|
212
|
+
FROM inspection_findings f
|
|
213
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
214
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
215
|
+
WHERE e.root_session_id = :sessionId
|
|
216
|
+
AND e.event_type NOT IN (${g.hfB})
|
|
217
|
+
GROUP BY d.rule_id`,{sessionId:a}))}listGroupedFindings(a){let b=a.sessionId?" AND e.root_session_id = :sessionId":"",c=void 0===a.from?void 0:(0,g.I8t)(a.from),d=`WHERE e.event_type IN (${g.hfB})${b}${void 0===c?"":" AND e.started_at >= :fromMs"}`,e={...a.sessionId?{sessionId:a.sessionId}:{},...void 0===c?{}:{fromMs:c}},f=this.groupAggregates(void 0!==a.q&&""!==a.q,{predicate:d,params:e}),h=K(this.db.prepare(`SELECT id, rule_id, category, severity, masked_match, action_taken, confidence,
|
|
218
|
+
occurred_at, source_tool, repo, file, tool_name, event_id, session_id,
|
|
219
|
+
kind, finding_key, latest_status
|
|
220
|
+
FROM (
|
|
221
|
+
SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
|
|
222
|
+
d.severity AS severity, f.masked_match AS masked_match,
|
|
223
|
+
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
224
|
+
e.started_at AS occurred_at,
|
|
225
|
+
json_extract(e.attributes, '$.source_tool') AS source_tool,
|
|
226
|
+
json_extract(e.attributes, '$.repo') AS repo,
|
|
227
|
+
json_extract(e.attributes, '$.file_path') AS file,
|
|
228
|
+
json_extract(e.attributes, '$.tool_name') AS tool_name,
|
|
229
|
+
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
230
|
+
e.event_type AS kind, f.finding_key AS finding_key,
|
|
231
|
+
latest.status AS latest_status,
|
|
232
|
+
ROW_NUMBER() OVER (
|
|
233
|
+
PARTITION BY d.rule_id
|
|
234
|
+
ORDER BY e.started_at DESC, f.id DESC
|
|
235
|
+
) AS rn
|
|
236
|
+
FROM inspection_findings f
|
|
237
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
238
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
239
|
+
LEFT JOIN ${aA} latest
|
|
240
|
+
ON latest.finding_key = f.finding_key
|
|
241
|
+
${d}
|
|
242
|
+
)
|
|
243
|
+
WHERE rn <= :cap
|
|
244
|
+
ORDER BY occurred_at DESC, id DESC`),{cap:200,...e}).map(a=>({id:a.id,ruleId:a.rule_id,category:a.category,severity:a.severity,maskedMatch:a.masked_match,actionTaken:a.action_taken,confidence:a.confidence,occurredAt:(0,g.q11)(a.occurred_at),sourceTool:a.source_tool,repo:a.repo??"",file:a.file??"",...null===a.tool_name?{}:{toolName:a.tool_name},eventId:a.event_id,...null===a.session_id?{}:{sessionId:a.session_id},status:aD(a)})),i=(0,g.mAj)(h,{aggregates:f}),j={severity:a.severity,providers:a.provider,actions:a.action,statuses:a.status,subtype:a.subtype,q:a.q},k=(0,g.rG)(i,j),l=(0,g.A6E)((0,g.tXp)(i,j)),m=a.status??[],n={findings:l.reduce((a,b)=>{if(0===m.length)return a+b.instanceCount;let c=f.get(b.id);return a+(c?(0,g.Bfj)(c.statusInputs,m)??b.instanceCount:b.instanceCount)},0),groups:l.length},o=a.limit??g.goN,p=void 0===a.cursor?null:function(a){let b=X(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&"string"==typeof b.sev&&"string"==typeof b.t&&"string"==typeof b.id?{severity:b.sev,latestDetectedAt:b.t,id:b.id}:null}(a.cursor),q=null===p?0:function(a,b){let c=a.findIndex(a=>(0,g._6W)(a,b)>0);return -1===c?a.length:c}(l,p),r=l.slice(q,q+o),s=r.at(-1),t=q+o<l.length&&s?function(a){let b={sev:a.severity,t:a.latestDetectedAt,id:a.id};return Buffer.from(JSON.stringify(b)).toString("base64url")}(s):null,u=void 0===a.includeId||""===a.includeId?void 0:function(a,b,c){if(!b.some(a=>a.id===c||a.instances.some(a=>a.id===c)))return a.find(a=>a.id===c||a.instances.some(a=>a.id===c))}(l,r,a.includeId),v=m.length>0?new Set(m):null;return Promise.resolve({totals:n,facets:k,items:[...r,...u?[u]:[]].map(a=>v?{...a,instances:a.instances.filter(a=>void 0!==a.status&&v.has(a.status))}:a),nextCursor:t,...a.sessionId?{sessionFirings:this.sessionFirings(a.sessionId)}:{}})}listFindingInstances(a){let b,c={severity:a.severity,subtype:a.subtype,providers:a.provider,actions:a.action,statuses:a.status,tools:a.tool,repo:a.repo,file:a.file,q:a.q},d=a.limit??g.b2L,e=void 0===a.cursor?null:Z(a.cursor),f=(0,g.fj8)(c),h=[],i=0,j=!1;for(let e of this.scanFindingRows({sessionId:a.sessionId,from:a.from}))f.add(e),(0,g.am1)(e,c)&&(i+=1,h.length<d?(h.push((0,g.MgS)(e)),b=e):j=!0);let k=j&&b?Y({startedAtMs:(0,g.I8t)(b.occurredAt),id:b.id}):null;if(null!==e){let b=this.pageAfter(e,c,d,a);return Promise.resolve({totals:{findings:i},facets:f.facets(),items:b.items,nextCursor:b.nextCursor})}return Promise.resolve({totals:{findings:i},facets:f.facets(),items:h,nextCursor:k})}pageAfter(a,b,c,d){let e,f=[],h=!1;for(let i of this.scanFindingRows({sessionId:d.sessionId,from:d.from,after:a}))if((0,g.am1)(i,b))if(f.length<c)f.push((0,g.MgS)(i)),e=i;else{h=!0;break}return{items:f,nextCursor:h&&e?Y({startedAtMs:(0,g.I8t)(e.occurredAt),id:e.id}):null}}listFindingLocations(a){let b={severity:a.severity,subtype:a.subtype,providers:a.provider,actions:a.action,statuses:a.status,tools:a.tool,q:a.q},c=a.limit??100,d=new Map,e=0;for(let c of this.scanFindingRows({sessionId:a.sessionId,from:a.from})){if(!(0,g.am1)(c,b))continue;e+=1;let a=d.get(c.repo);void 0===a&&(a=new Map,d.set(c.repo,a));let f=a.get(c.file);void 0===f&&(f=(0,g.SSj)(),a.set(c.file,f)),(0,g._5V)(f,c)}let f=0,h=[...d.entries()].map(([a,b])=>{f+=b.size;let c=[...b.entries()].map(([a,b])=>({file:a,instanceCount:b.instanceCount,maxSeverity:b.maxSeverity,latestDetectedAt:b.latestDetectedAt,...void 0===(0,g.JB8)(b.statuses)?{}:{status:(0,g.JB8)(b.statuses)},ruleIds:[...b.ruleIds].slice(0,20)})).sort(aB),d=c.reduce((a,b)=>({instanceCount:a.instanceCount+b.instanceCount,maxSeverity:0>aB(b,a)?b.maxSeverity:a.maxSeverity,latestDetectedAt:b.latestDetectedAt>a.latestDetectedAt?b.latestDetectedAt:a.latestDetectedAt}),{instanceCount:0,maxSeverity:c[0]?.maxSeverity??"low",latestDetectedAt:""}),e=c.map(a=>a.status),h=(0,g.JB8)(e);return{repo:a,instanceCount:d.instanceCount,maxSeverity:d.maxSeverity,latestDetectedAt:d.latestDetectedAt,...void 0===h?{}:{status:h},files:c}});return h.sort(aB),Promise.resolve({totals:{findings:e,repos:h.length,files:f},items:h.slice(0,c),hasMore:h.length>c})}*scanFindingRows(a){let b=[`e.event_type IN (${g.hfB})`],c=[];void 0!==a.sessionId&&""!==a.sessionId&&(b.push("e.root_session_id = ?"),c.push(a.sessionId)),void 0!==a.from&&(b.push("e.started_at >= ?"),c.push((0,g.I8t)(a.from)));let d=`SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
|
|
245
|
+
d.severity AS severity, f.masked_match AS masked_match,
|
|
246
|
+
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
247
|
+
e.started_at AS occurred_at,
|
|
248
|
+
json_extract(e.attributes, '$.source_tool') AS source_tool,
|
|
249
|
+
json_extract(e.attributes, '$.repo') AS repo,
|
|
250
|
+
json_extract(e.attributes, '$.file_path') AS file,
|
|
251
|
+
json_extract(e.attributes, '$.tool_name') AS tool_name,
|
|
252
|
+
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
253
|
+
e.event_type AS kind, f.finding_key AS finding_key,
|
|
254
|
+
${az("f")} AS latest_status
|
|
255
|
+
FROM inspection_findings f
|
|
256
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
257
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
258
|
+
WHERE ${b.join(" AND ")}
|
|
259
|
+
AND (e.started_at < ? OR (e.started_at = ? AND f.id < ?))
|
|
260
|
+
ORDER BY e.started_at DESC, f.id DESC
|
|
261
|
+
LIMIT ?`,e=a.after??{startedAtMs:Number.MAX_SAFE_INTEGER,id:""};for(;;){let a=K(this.db.prepare(d),[...c,e.startedAtMs,e.startedAtMs,e.id,1e3]);for(let b of a)yield{id:b.id,ruleId:b.rule_id,category:b.category,severity:b.severity,maskedMatch:b.masked_match,actionTaken:b.action_taken,confidence:b.confidence,occurredAt:(0,g.q11)(b.occurred_at),sourceTool:b.source_tool,repo:b.repo??"",file:b.file??"",...null===b.tool_name?{}:{toolName:b.tool_name},eventId:b.event_id,...null===b.session_id?{}:{sessionId:b.session_id},status:aD(b)};if(a.length<1e3)return;let b=a[a.length-1];if(void 0===b)return;e={startedAtMs:b.occurred_at,id:b.id}}}groupAggregates(a,b){let c=a?`, group_concat(DISTINCT json_extract(e.attributes, '$.repo')) AS repos,
|
|
262
|
+
group_concat(DISTINCT json_extract(e.attributes, '$.file_path')) AS files,
|
|
263
|
+
group_concat(DISTINCT 'via ' || json_extract(e.attributes, '$.tool_name')) AS tool_names`:", NULL AS repos, NULL AS files, NULL AS tool_names";return new Map(this.db.prepare(`SELECT rule_id,
|
|
264
|
+
sum(tuple_count) AS instance_count,
|
|
265
|
+
max(latest_at) AS latest_at,
|
|
266
|
+
group_concat(source_tools) AS source_tools,
|
|
267
|
+
group_concat(actions_taken) AS actions_taken,
|
|
268
|
+
group_concat(status_tuple || '|' || tuple_count) AS status_inputs,
|
|
269
|
+
group_concat(repos) AS repos,
|
|
270
|
+
group_concat(files) AS files,
|
|
271
|
+
group_concat(tool_names) AS tool_names
|
|
272
|
+
FROM (
|
|
273
|
+
SELECT d.rule_id AS rule_id,
|
|
274
|
+
e.event_type || '|' ||
|
|
275
|
+
(CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '|' ||
|
|
276
|
+
coalesce(latest.status, '') AS status_tuple,
|
|
277
|
+
count(*) AS tuple_count,
|
|
278
|
+
max(e.started_at) AS latest_at,
|
|
279
|
+
group_concat(DISTINCT json_extract(e.attributes, '$.source_tool')) AS source_tools,
|
|
280
|
+
group_concat(DISTINCT f.action_taken) AS actions_taken
|
|
281
|
+
${c}
|
|
282
|
+
FROM inspection_findings f
|
|
283
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
284
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
285
|
+
LEFT JOIN ${aA} latest
|
|
286
|
+
ON latest.finding_key = f.finding_key
|
|
287
|
+
${b.predicate}
|
|
288
|
+
GROUP BY d.rule_id, status_tuple
|
|
289
|
+
)
|
|
290
|
+
GROUP BY rule_id`).all(b.params).map(b=>[b.rule_id,{instanceCount:b.instance_count,sourceTools:aC(b.source_tools),actionsTaken:aC(b.actions_taken),statusInputs:aC(b.status_inputs).map(a=>{let[b="",c="",d="",e=""]=a.split("|");return{kind:b,findingKey:""===c?null:c,latestResolutionStatus:""===d?null:d,count:Number(e)}}),latestDetectedAt:(0,g.q11)(b.latest_at),...a?{searchText:[b.repos??"",b.files??"",b.tool_names??""].filter(a=>""!==a).join(" ")}:{}}]))}healthSummary(){let a=O(this.db,`SELECT count(*) AS n FROM inspection_findings f
|
|
291
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
292
|
+
WHERE e.event_type IN (${g.hfB})`),b=Object.fromEntries(g.S8C.map(a=>[a,0]));for(let a of K(this.db.prepare(`SELECT f.action_taken AS action_taken, count(*) AS c
|
|
293
|
+
FROM inspection_findings f
|
|
294
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
295
|
+
WHERE e.event_type IN (${g.hfB})
|
|
296
|
+
GROUP BY f.action_taken`)))a.action_taken in b&&(b[a.action_taken]=a.c);let c={critical:0,high:0,medium:0,low:0};for(let a of K(this.db.prepare(`SELECT d.severity AS severity, count(*) AS c
|
|
297
|
+
FROM inspection_findings f
|
|
298
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
299
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
300
|
+
LEFT JOIN ${aA} latest
|
|
301
|
+
ON latest.finding_key = f.finding_key
|
|
302
|
+
WHERE e.event_type IN (${g.hfB})
|
|
303
|
+
AND (latest.status IS NULL OR latest.status != 'resolved')
|
|
304
|
+
GROUP BY d.severity`)))a.severity in c&&(c[a.severity]=a.c);let d=g.IgC,e=new Set(K(this.db.prepare(`SELECT DISTINCT json_extract(target, '$.category') AS category
|
|
305
|
+
FROM policies WHERE enabled = 1 AND json_extract(target, '$.category') IS NOT NULL`)).map(a=>a.category));return Promise.resolve({findings:a,byAction:b,bySeverity:c,coverage:0===d.length?0:d.filter(a=>e.has(a)).length/d.length})}activityByDay(a=7){let b=864e5*Math.floor(Date.now()/864e5)-(a-1)*864e5,c=K(this.db.prepare(`SELECT date(e.started_at / 1000, 'unixepoch') AS day, f.action_taken AS action, count(*) AS c
|
|
306
|
+
FROM inspection_findings f
|
|
307
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
308
|
+
WHERE e.started_at >= :since
|
|
309
|
+
AND e.event_type IN (${g.hfB})
|
|
310
|
+
GROUP BY day, f.action_taken`),{since:b}),d=new Map;for(let c=0;c<a;c++){let a=new Date(b+864e5*c).toISOString().slice(0,10);d.set(a,{day:a,total:0,redacted:0,warned:0,blocked:0})}for(let a of c){let b=d.get(a.day);b&&(b.total+=a.c,"redact"===a.action?b.redacted+=a.c:"warn"===a.action?b.warned+=a.c:"block"===a.action&&(b.blocked+=a.c))}return Promise.resolve([...d.values()].sort((a,b)=>a.day.localeCompare(b.day)))}}class aF{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
|
|
311
|
+
(id, rule_id, name, category, severity, definition, version)
|
|
312
|
+
VALUES
|
|
313
|
+
(:id, :ruleId, :name, :category, :severity, :definition, :version)`)}upsert(a){let b=j(a.ruleId,a.version),c=(0,g.JAl)(a,b);return this.insertStmt.run({id:c.id,ruleId:c.ruleId,name:c.name,category:c.category,severity:c.severity,definition:c.definition,version:c.version}),b}}class aG{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO inspection_findings
|
|
314
|
+
(id, audit_event_id, inspection_definition_id, classified_data_id,
|
|
315
|
+
span_start, span_end, masked_match, action_taken, confidence,
|
|
316
|
+
finding_key, first_detected_at)
|
|
317
|
+
VALUES
|
|
318
|
+
(:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
|
|
319
|
+
:spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
|
|
320
|
+
:findingKey,
|
|
321
|
+
COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
|
|
322
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
323
|
+
inspection_definition_id = excluded.inspection_definition_id
|
|
324
|
+
ON CONFLICT (finding_key) DO UPDATE SET
|
|
325
|
+
audit_event_id = excluded.audit_event_id,
|
|
326
|
+
inspection_definition_id = excluded.inspection_definition_id,
|
|
327
|
+
classified_data_id = excluded.classified_data_id,
|
|
328
|
+
span_start = excluded.span_start,
|
|
329
|
+
span_end = excluded.span_end,
|
|
330
|
+
masked_match = excluded.masked_match,
|
|
331
|
+
action_taken = excluded.action_taken,
|
|
332
|
+
confidence = excluded.confidence`),this.sessionDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
|
|
333
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
334
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
335
|
+
WHERE d.rule_id = :ruleId AND f.masked_match = :maskedMatch
|
|
336
|
+
AND e.root_session_id = :sessionId
|
|
337
|
+
AND e.event_type IN (${g.hfB})
|
|
338
|
+
LIMIT 1`),this.eventDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
|
|
339
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
340
|
+
WHERE f.audit_event_id = :auditEventId AND d.rule_id = :ruleId
|
|
341
|
+
AND f.masked_match = :maskedMatch
|
|
342
|
+
AND f.span_start = :spanStart AND f.span_end = :spanEnd
|
|
343
|
+
LIMIT 1`)}isSessionDuplicate(a,b,c){return void 0!==this.sessionDupStmt.get({ruleId:a,maskedMatch:b,sessionId:c})}isEventDuplicate(a,b,c,d,e){return void 0!==this.eventDupStmt.get({auditEventId:a,ruleId:b,maskedMatch:c,spanStart:d,spanEnd:e})}insertFinding(a){let b=(0,g.$3l)(a);this.insertStmt.run(N({id:b.id,auditEventId:b.auditEventId,inspectionDefinitionId:b.inspectionDefinitionId,classifiedDataId:b.classifiedDataId,spanStart:b.spanStart,spanEnd:b.spanEnd,maskedMatch:b.maskedMatch,actionTaken:b.actionTaken,confidence:b.confidence,findingKey:b.findingKey,firstDetectedAt:b.firstDetectedAt}))}}function aH(a){let b=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?$/.exec(a.trim());return b?{core:[Number(b[1]),Number(b[2]),Number(b[3])],pre:b[4]?b[4].split("."):[]}:null}let aI=g.Jr;function aJ(a){return a.map(a=>{var b;return`${a.namespace}/${a.packId}@${a.version}#${b=a.rulesJson,(0,d.createHash)("sha1").update(b).digest("hex")}`}).sort().join(",")}function aK(a){let b=/^(\d+)\.(\d+)\.(\d+)/.exec(a);return b?[Number(b[1]),Number(b[2]),Number(b[3])]:null}class aL{constructor(a){this.db=a,this.insertMissingStmt=a.prepare(`INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
|
|
344
|
+
VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
|
|
345
|
+
ON CONFLICT (namespace, pack_id) DO NOTHING`),this.upsertAvailableStmt=a.prepare(`INSERT INTO available_packs (id, namespace, pack_id, version, name, rules_json, recorded_by, updated_at)
|
|
346
|
+
VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, :recordedBy, :now)
|
|
347
|
+
ON CONFLICT (namespace, pack_id) DO UPDATE SET
|
|
348
|
+
version = excluded.version,
|
|
349
|
+
name = excluded.name,
|
|
350
|
+
rules_json = excluded.rules_json,
|
|
351
|
+
recorded_by = excluded.recorded_by,
|
|
352
|
+
updated_at = excluded.updated_at
|
|
353
|
+
WHERE available_packs.version <> excluded.version
|
|
354
|
+
OR available_packs.name <> excluded.name
|
|
355
|
+
OR available_packs.rules_json <> excluded.rules_json`),this.signatureStmt=a.prepare("SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs")}recordInventory(a,b){if(0!==a.length)try{let c=a.map(a=>({namespace:a.namespace,packId:a.packId,version:a.version,name:a.name,rulesJson:JSON.stringify(a.rules),ruleIds:new Set(a.rules.map(a=>a.id))}));if(this.storedSignature()===aJ(c))return;let e=Date.now();F(this.db,()=>{let a=this.mirrorState(),f=!1;for(let g of c){let c={id:(0,d.randomUUID)(),namespace:g.namespace,packId:g.packId,version:g.version,name:g.name,rulesJson:g.rulesJson,now:e},h=a.get(`${g.namespace}/${g.packId}`);void 0===h||!function(a,b){let c=aK(a.version);if(null===c)return!0;let d=aK(b.version);if(null===d)return!1;for(let a=0;a<3;a++){let b=c[a]??0,e=d[a]??0;if(b!==e)return b<e}for(let c of b.ruleIds)if(!a.ruleIds.has(c))return!0;return!1}(g,h)?this.upsertAvailableStmt.run({...c,id:(0,d.randomUUID)(),recordedBy:b?.recordedBy??null}):f=!0,this.insertMissingStmt.run(c)}f||this.pruneAvailable(c.map(a=>`${a.namespace}/${a.packId}`))},"IMMEDIATE")}catch{}}mirrorState(){return new Map(K(this.db.prepare("SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs")).map(a=>[`${a.namespace}/${a.packId}`,{version:a.version,ruleIds:function(a){let b=new Set,c=W(a,[]);if(!Array.isArray(c))return b;for(let a of c)if(a&&"object"==typeof a){let c=a.id;"string"==typeof c&&b.add(c)}return b}(a.rulesJson)}]))}pruneAvailable(a){let b=K(this.db.prepare("SELECT namespace, pack_id AS packId FROM available_packs")),c=new Set(a),d=this.db.prepare("DELETE FROM available_packs WHERE namespace = ? AND pack_id = ?");for(let a of b)c.has(`${a.namespace}/${a.packId}`)||d.run(a.namespace,a.packId)}applyUpdate(a,b){if(this.db.isTransaction)throw Error("applyUpdate must not be called inside an open transaction");let c=!1;return F(this.db,()=>{this.db.exec("UPDATE _pack_write_gate SET open = 1 WHERE id = 1");let d=this.db.prepare(`UPDATE installed_packs SET
|
|
356
|
+
version = (SELECT a.version FROM available_packs a
|
|
357
|
+
WHERE a.namespace = :namespace AND a.pack_id = :packId),
|
|
358
|
+
name = (SELECT a.name FROM available_packs a
|
|
359
|
+
WHERE a.namespace = :namespace AND a.pack_id = :packId),
|
|
360
|
+
rules_json = (SELECT a.rules_json FROM available_packs a
|
|
361
|
+
WHERE a.namespace = :namespace AND a.pack_id = :packId),
|
|
362
|
+
updated_at = :now
|
|
363
|
+
WHERE namespace = :namespace AND pack_id = :packId
|
|
364
|
+
AND EXISTS (SELECT 1 FROM available_packs a
|
|
365
|
+
WHERE a.namespace = :namespace AND a.pack_id = :packId)`).run({namespace:a,packId:b,now:Date.now()});this.db.exec("UPDATE _pack_write_gate SET open = 0 WHERE id = 1"),c=Number(d.changes)>0},"IMMEDIATE"),c}installedRuleset(){let a=K(this.db.prepare("SELECT enabled, policy_id AS policyId, rules_json AS rulesJson, version FROM installed_packs")),b={installedPacks:a.length,enabledPacks:0,rules:[],invalidRules:0,ruleActions:new Map,ruleVersions:new Map};for(let c of a){let a;if(!M(c.enabled))continue;b.enabledPacks+=1;let d=(0,g.DhA)(c.policyId);try{a=JSON.parse(c.rulesJson)}catch{b.invalidRules+=1;continue}if(!Array.isArray(a)){b.invalidRules+=1;continue}for(let e of a){let a=g.jON.safeParse(e);a.success?(b.rules.push(a.data),b.ruleActions.set(a.data.id,d),b.ruleVersions.set(a.data.id,c.version)):b.invalidRules+=1}}return b}newestRecordedBinary(){let a=K(this.db.prepare("SELECT DISTINCT recorded_by AS recordedBy FROM available_packs WHERE recorded_by IS NOT NULL")),b=null;for(let c of a){let a=c.recordedBy.lastIndexOf("@");if(a<=0||a===c.recordedBy.length-1)continue;let d=c.recordedBy.slice(0,a),e=c.recordedBy.slice(a+1);null!==aH(e)&&(null===b||function(a,b){let c=aH(a),d=aH(b);if(!c||!d)return 0;for(let a=0;a<3;a++){let b=c.core[a]??0,e=d.core[a]??0;if(b!==e)return b<e?-1:1}return function(a,b){if(0===a.length&&0===b.length)return 0;if(0===a.length)return 1;if(0===b.length)return -1;let c=Math.min(a.length,b.length);for(let d=0;d<c;d++){let c=a[d]??"",e=b[d]??"";if(c===e)continue;let f=/^\d+$/.test(c),g=/^\d+$/.test(e);if(f&&!g)return -1;if(!f&&g)return 1;if(f&&g)return Number(c)<Number(e)?-1:1;return c<e?-1:1}return a.length===b.length?0:a.length<b.length?-1:1}(c.pre,d.pre)}(e,b.version)>0)&&(b={binary:d,version:e})}return b}counts(){return Promise.resolve(L(this.db.prepare(`SELECT count(*) AS packs,
|
|
366
|
+
coalesce(sum(json_array_length(rules_json)), 0) AS rules,
|
|
367
|
+
coalesce(sum(enabled), 0) AS enabled
|
|
368
|
+
FROM installed_packs`))??{packs:0,rules:0,enabled:0})}countsByPolicyId(){return P(this.db,`SELECT coalesce(policy_id, '${aI}') AS k, count(*) AS n
|
|
369
|
+
FROM installed_packs
|
|
370
|
+
GROUP BY k`)}listByPolicyId(a){return K(this.db.prepare(`SELECT namespace, pack_id AS packId, name, enabled, rules_json AS rulesJson
|
|
371
|
+
FROM installed_packs
|
|
372
|
+
WHERE coalesce(policy_id, '${aI}') = ?
|
|
373
|
+
ORDER BY name ASC`),[a]).map(a=>({id:`${a.namespace}/${a.packId}`,name:a.name,ruleCount:ao(a.rulesJson).length,enabled:M(a.enabled)}))}setPolicy(a,b,c){if(null!==c&&!g.HUb.safeParse(c).success)throw Error(`Unknown policy '${c}'. Must be one of: ${g.V0H.join(", ")}.`);return Number(this.db.prepare(`UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
|
|
374
|
+
WHERE namespace = :namespace AND pack_id = :packId`).run({policyId:c,now:Date.now(),namespace:a,packId:b}).changes)>0}setEnabled(a,b,c){return Number(this.db.prepare(`UPDATE installed_packs SET enabled = :enabled, updated_at = :now
|
|
375
|
+
WHERE namespace = :namespace AND pack_id = :packId`).run({enabled:+!!c,now:Date.now(),namespace:a,packId:b}).changes)>0}storedSignature(){return aJ(K(this.signatureStmt))}}class aM{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO inventory
|
|
376
|
+
(id, object_type, location, title, host_id, attributes, first_seen, last_seen)
|
|
377
|
+
VALUES
|
|
378
|
+
(:id, :objectType, :location, :title, :hostId, :attributes, :firstSeen, :lastSeen)
|
|
379
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
380
|
+
location = excluded.location,
|
|
381
|
+
title = excluded.title,
|
|
382
|
+
host_id = excluded.host_id,
|
|
383
|
+
attributes = excluded.attributes,
|
|
384
|
+
last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){var c,d;let e=(c=a.objectType,d=a.identityKey,h((0,g.tTV)(["inventory",c,d]))),f=(0,g.gzP)(a,e,b);return this.upsertStmt.run(N({id:f.id,objectType:f.objectType,location:f.location,title:f.title,hostId:f.hostId,attributes:f.attributes,firstSeen:f.firstSeen,lastSeen:f.lastSeen})),e}findById(a){return L(this.db.prepare("SELECT * FROM inventory WHERE id = :id"),{id:a})}distinctTitles(a){return K(this.db.prepare(`SELECT DISTINCT title FROM inventory
|
|
385
|
+
WHERE object_type = :objectType AND title IS NOT NULL
|
|
386
|
+
ORDER BY title`),{objectType:a}).map(a=>a.title)}osVersions(){return K(this.db.prepare(`SELECT DISTINCT os_version AS value FROM inventory
|
|
387
|
+
WHERE object_type = 'host' AND os_version IS NOT NULL
|
|
388
|
+
ORDER BY value`)).map(a=>a.value)}}let aN=["config","skill","mcp","hook"],aO=new Set(g.SHn.options),aP="(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))",aQ={claudecode:"Claude Code",cursor:"Cursor",codex:"Codex",antigravity:"Antigravity"},aR={accessCounts:{open:0,approved:0,blocked:0,total:0},findingsCount:0};function aS(a,b){if(a.provider&&aO.has(a.provider))return a.provider;let c=(b.title??"").toLowerCase().replace(/[\s-]/g,"");return c.includes("claudecode")||"claude"===c?"claudecode":c.includes("cursor")?"cursor":c.includes("codex")?"codex":c.includes("antigravity")?"antigravity":null}function aT(a){return a.some(a=>{let b=W(a.attributes,{});return"sample"!==b.provenance&&"claudecode"===aS(b,a)})}function aU(a){let b={id:a.id,type:a.assetType,name:a.name,sub:a.sub??"",flags:W(a.flagsJson,[])};return"mcp"===a.assetType&&a.effectiveTrust&&(b.trust=a.effectiveTrust),b}function aV(a){let b="update_available"===a.status?["update"]:[],c={source:a.source,scope:a.scope};return void 0!==a.installedVersion&&(c.installedVersion=a.installedVersion),void 0!==a.latestVersion&&(c.latestVersion=a.latestVersion),void 0!==a.updatedAt&&(c.updatedAt=a.updatedAt),{id:a.id,assetType:"skill",name:a.name,sub:`Skill \xb7 ${a.source}`,description:a.description??null,flagsJson:JSON.stringify(b),metaJson:JSON.stringify(c),trust:null,toolsJson:null,effectiveTrust:null}}function aW(a){let b="egress"===a.status?["risk"]:"conflict"===a.status?["conflict"]:"unknown"===a.status?["unknown"]:[],c={event:a.event,command:a.command,scope:a.scope,status:a.status};return void 0!==a.matcher&&(c.matcher=a.matcher),void 0!==a.pluginName&&(c.pluginName=a.pluginName),a.warnings.length>0&&(c.warnings=a.warnings),{id:a.id,assetType:"hook",name:aZ(a.command.trim(),64),sub:a.matcher?`Hook \xb7 ${a.event} \xb7 ${a.matcher}`:`Hook \xb7 ${a.event}`,description:a.warnings.length>0?a.warnings.join(" \xb7 "):null,flagsJson:JSON.stringify(b),metaJson:JSON.stringify(c),trust:null,toolsJson:null,effectiveTrust:null}}function aX(a){let b={scope:a.scope,transport:a.transport};return void 0!==a.command&&(b.command=a.command),void 0!==a.url&&(b.url=a.url),void 0!==a.envKeys&&(b.envKeys=a.envKeys),void 0!==a.pluginName&&(b.pluginName=a.pluginName),void 0!==a.marketplace&&(b.marketplace=a.marketplace),void 0!==a.project&&(b.project=a.project),{id:a.id,assetType:"mcp",name:a.name,sub:`MCP server \xb7 ${a.transport} \xb7 ${aZ(function(a){if(void 0!==a.url)try{return new URL(a.url).host}catch{return a.url}return a.command??a.name}(a),48)}`,description:null,flagsJson:"[]",metaJson:JSON.stringify(b),trust:"unapproved",toolsJson:null,effectiveTrust:a.trust}}function aY(a){let b=a.untracked?["untracked"]:[],c={kind:a.kind,scope:a.scope,path:a.path};return void 0!==a.detail&&(c.detail=a.detail),void 0!==a.entryCount&&(c.entryCount=a.entryCount),void 0!==a.updatedAt&&(c.updatedAt=a.updatedAt),{id:a.id,assetType:"config",name:a.name,sub:a.kind,description:a.detail??null,flagsJson:JSON.stringify(b),metaJson:JSON.stringify(c),trust:null,toolsJson:null,effectiveTrust:null}}function aZ(a,b){return a.length>b?`${a.slice(0,b-1)}…`:a}function a$(a,b,c){let d=W(a.attributes,{});return{id:a.id,name:a.name??"",repo:a.url??"",visibility:d.visibility??"private",language:d.language??"",policyDefault:d.policyDefault??"approved",updatedAt:new Date(a.lastSeen).toISOString(),accessCounts:b,findingsCount:c}}function a_(a){return{path:a.path,name:a.name,origin:a.origin,access:a.effectiveAccess,isCustom:null!==a.overrideAccess&&a.overrideAccess!==a.defaultAccess,findings:a.findingsCount,blockedAt:null!==a.blockedAtMs?new Date(a.blockedAtMs).toISOString():null,note:a.note}}class a0{constructor(a){this.db=a}getInventoryStats(){let a=P(this.db,"SELECT asset_type AS k, count(*) AS n FROM inventory_asset GROUP BY asset_type"),b={project:0,skill:a.get("skill")??0,mcp:a.get("mcp")??0,hook:a.get("hook")??0,config:a.get("config")??0};b.project=O(this.db,`SELECT count(*) AS n FROM source_project WHERE ${aP}`);let c=P(this.db,`SELECT coalesce(o.trust, a.trust) AS k, count(*) AS n
|
|
389
|
+
FROM inventory_asset a
|
|
390
|
+
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
391
|
+
WHERE a.asset_type = 'mcp' AND coalesce(o.trust, a.trust) IS NOT NULL
|
|
392
|
+
GROUP BY coalesce(o.trust, a.trust)`),d={"known-good":c.get("known-good")??0,risky:c.get("risky")??0,unapproved:c.get("unapproved")??0},e=O(this.db,`SELECT count(*) AS n FROM inventory
|
|
393
|
+
WHERE object_type = 'harness'
|
|
394
|
+
AND (last_seen >= :liveSince OR json_extract(attributes, '$.provenance') = 'sample')`,{liveSince:Date.now()-2592e6}),f=O(this.db,"SELECT count(*) AS n FROM inventory_asset WHERE flags_json <> '[]'"),g=O(this.db,"SELECT count(DISTINCT project_id) AS n FROM project_file WHERE findings_count > 0"),h=this.configAssetRows();for(let a of h)b[a.assetType]+=1,"mcp"===a.assetType&&a.effectiveTrust&&(d[a.effectiveTrust]+=1);return Promise.resolve({attention:f+g+h.filter(a=>"[]"!==a.flagsJson).length,byType:b,harnesses:e,mcpTrust:d})}listHarnesses(a){let b=this.fetchHarnessRows();if(0===b.length)return Promise.resolve({items:[]});let c=new Map;for(let a of b){let b=aS(W(a.attributes,{}),a);if(!b)continue;let d=c.get(b);d?d.push(a):c.set(b,[a])}let d=this.assetsByHarness(b.map(a=>a.id),a),e=[...new Set(b.flatMap(a=>W(a.attributes,{}).projectIds??[]))],f=this.fetchProjectsByIds(e),g=this.projectAggregates(e),h=this.configAssetRows(a,aT(b)),i=[];for(let[b,e]of c){let c=e.flatMap(a=>d.get(a.id)??[]),j=e.some(a=>"sample"!==W(a.attributes,{}).provenance)&&"claudecode"===b&&h.length>0?[...c,...h].sort((a,b)=>a.name.localeCompare(b.name)):c;if(a&&0===j.length)continue;let k=e[0];if(!k)continue;let l=W(k.attributes,{}),m=[...new Set(e.flatMap(a=>W(a.attributes,{}).projectIds??[]))].map(a=>f.get(a)).filter(a=>void 0!==a).map(a=>{let b=g.get(a.id)??aR;return a$(a,b.accessCounts,b.findingsCount)}),n=e.reduce((a,b)=>a+(W(b.attributes,{}).sessions??0),0),o=j.reduce((a,b)=>a+W(b.flagsJson,[]).length,0),p=new Map;for(let a of j){let b=p.get(a.assetType);b?b.push(aU(a)):p.set(a.assetType,[aU(a)])}let q=aN.filter(a=>p.has(a)).map(a=>({type:a,assets:p.get(a)??[]}));i.push({id:b,label:l.label??aQ[b],kind:l.kind??l.provider??b,version:l.harness_version??k.harnessVersion??"",sessions:n,assetCount:j.length,flagCount:o,projects:m,categories:q})}return Promise.resolve({items:i})}listAssets(a){let b=this.fetchAssets(a.type,a.q);if(0===b.length)return Promise.resolve({groups:[]});let c=new Map;for(let a of b){let b=c.get(a.assetType);b?b.push(a):c.set(a.assetType,[a])}let d=[...c.entries()].map(([a,b])=>{let c=new Map;for(let a of b)for(let b of W(a.flagsJson,[]))c.set(b,(c.get(b)??0)+1);let d={type:a,total:b.length,flagRollup:Object.fromEntries(c),items:b.map(aU)};if("mcp"===a){let a=new Map;for(let c of b)c.effectiveTrust&&a.set(c.effectiveTrust,(a.get(c.effectiveTrust)??0)+1);d.trustRollup=Object.fromEntries(a)}return d});return d.sort((a,b)=>aN.indexOf(a.type)-aN.indexOf(b.type)),Promise.resolve({groups:d})}getAsset(a){let b=this.fetchAssetById(a);return Promise.resolve(b?function(a){let b={id:a.id,type:a.assetType,name:a.name,sub:a.sub??"",flags:W(a.flagsJson,[]),description:a.description??null,trust:"mcp"===a.assetType?a.effectiveTrust??null:null,meta:W(a.metaJson,{}),finding:null};if("mcp"===a.assetType&&null!==a.toolsJson){let c=W(a.toolsJson,[]);b.tools="unapproved"===a.effectiveTrust?c.map(a=>({...a,risk:a.risk??"Tool access blocked: MCP server trust is unapproved."})):c}return b}(b):null)}listProjects(a){let b=this.fetchProjects(a),c=this.projectAggregates(b.map(a=>a.id));return Promise.resolve({items:b.map(a=>{let b=c.get(a.id)??aR;return a$(a,b.accessCounts,b.findingsCount)})})}getProjectTree(a,b){let c=this.fetchProjectById(a);if(!c)return Promise.resolve(null);let d=W(c.attributes,{}),e={id:c.id,repo:c.url??"",visibility:d.visibility??"private"},f=b.path??"";if("blocked"===b.filter){let b=this.fetchProjectFilesBlocked(a);return b.sort((a,b)=>(b.blockedAtMs??0)-(a.blockedAtMs??0)),Promise.resolve({project:e,path:f,files:b.map(a_)})}if(void 0!==b.q&&""!==b.q)return Promise.resolve({project:e,path:f,files:this.fetchProjectFilesSearch(a,b.q).map(a_)});let g=this.fetchProjectFilesUnder(a,f),h=""===f?"":`${f}/`,i=[],j=new Map;for(let a of g){let b=h.length>0?a.path.slice(h.length):a.path,c=b.indexOf("/");if(-1===c)i.push(a);else{let d=b.slice(0,c),e=j.get(d)??[];e.push(a),j.set(d,e)}}let k=[...j.entries()].sort(([a],[b])=>a.localeCompare(b)).map(([a,b])=>({name:a,path:h.length>0?`${f}/${a}`:a,accessCounts:function(a){let b={open:0,approved:0,blocked:0,total:0};for(let c of a)b.total++,b[c.effectiveAccess]++;return b}(b)}));return Promise.resolve({project:e,path:f,folders:k,files:i.map(a_)})}getProjectFile(a,b){let c=this.fetchProjectById(a);if(!c)return Promise.resolve(null);let d=this.fetchProjectFile(a,b);if(!d)return Promise.resolve(null);let e=W(c.attributes,{});return Promise.resolve({...a_(d),project:{repo:c.url??"",visibility:e.visibility??"private",language:e.language??"",policyDefault:e.policyDefault??"approved",updatedAt:new Date(c.lastSeen).toISOString()},findingsRefs:[]})}setFileAccess(a,b,c){let e=this.fetchProjectFile(a,b);return!!e&&(c===e.defaultAccess?this.db.prepare("DELETE FROM file_access_override WHERE project_id = ? AND path = ?").run(a,b):this.db.prepare(`INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
|
|
395
|
+
VALUES (:id, :projectId, :path, :access, :now, :now)
|
|
396
|
+
ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`).run({id:(0,d.randomUUID)(),projectId:a,path:b,access:c,now:Date.now()}),!0)}setMcpTrust(a,b){let c=this.fetchAssetById(a);return c?"mcp"!==c.assetType?"not_mcp":(b===c.trust?this.db.prepare("DELETE FROM mcp_trust_override WHERE asset_id = ?").run(a):this.db.prepare(`INSERT INTO mcp_trust_override (id, asset_id, trust, created_at, updated_at)
|
|
397
|
+
VALUES (:id, :assetId, :trust, :now, :now)
|
|
398
|
+
ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`).run({id:(0,d.randomUUID)(),assetId:a,trust:b,now:Date.now()}),this.configRowsCache=void 0,"ok"):"not_found"}fetchHarnessRows(){return K(this.db.prepare(`SELECT id, title, attributes, harness_version AS harnessVersion
|
|
399
|
+
FROM inventory
|
|
400
|
+
WHERE object_type = 'harness'
|
|
401
|
+
AND (last_seen >= :liveSince OR json_extract(attributes, '$.provenance') = 'sample')`),{liveSince:Date.now()-2592e6})}assetsByHarness(a,b){let c=new Map;if(0===a.length)return c;let d=[...a],e=`ha.harness_id IN (${B(a.length)})`;if(b){let a=C(b);e+=` AND ${D(["a.name","a.sub"])}`,d.push(a,a)}for(let a of K(this.db.prepare(`SELECT ha.harness_id AS harnessInvId, a.id, a.asset_type AS assetType, a.name, a.sub,
|
|
402
|
+
a.description, a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
|
|
403
|
+
a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
|
|
404
|
+
FROM harness_asset ha
|
|
405
|
+
JOIN inventory_asset a ON a.id = ha.asset_id
|
|
406
|
+
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
407
|
+
WHERE ${e}
|
|
408
|
+
ORDER BY a.name ASC`),d)){let b=a.harnessInvId,[d]=this.mapAssetRows([a]);if(!d)continue;let e=c.get(b);e?e.push(d):c.set(b,[d])}return c}fetchAssets(a,b){let c=[],d=[];if(a&&a.length>0&&(c.push(`a.asset_type IN (${B(a.length)})`),d.push(...a)),b){let a=C(b);c.push(D(["a.name","a.sub"])),d.push(a,a)}let e=c.length?`WHERE ${c.join(" AND ")}`:"",f=this.mapAssetRows(K(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
|
|
409
|
+
a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
|
|
410
|
+
a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
|
|
411
|
+
FROM inventory_asset a
|
|
412
|
+
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
413
|
+
${e}
|
|
414
|
+
ORDER BY a.name ASC`),d)),g=this.configAssetRows(b).filter(b=>!a||0===a.length||a.includes(b.assetType));return g.length>0?[...f,...g].sort((a,b)=>a.name.localeCompare(b.name)):f}fetchAssetById(a){return this.mapAssetRows(K(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
|
|
415
|
+
a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
|
|
416
|
+
a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
|
|
417
|
+
FROM inventory_asset a
|
|
418
|
+
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
419
|
+
WHERE a.id = ?`),[a]))[0]??this.configAssetRows().find(b=>b.id===a)??null}mapAssetRows(a){return a.map(a=>({id:a.id,assetType:a.assetType,name:a.name,sub:a.sub??null,description:a.description??null,flagsJson:a.flagsJson??"[]",metaJson:a.metaJson??"{}",trust:a.trust??null,toolsJson:a.toolsJson??null,effectiveTrust:a.effectiveTrust??null}))}configAssetRows(a,b){let c=this.liveConfigAssetRows(b);if(!a)return c;let d=a.toLowerCase();return c.filter(a=>a.name.toLowerCase().includes(d)||(a.sub??"").toLowerCase().includes(d))}liveConfigAssetRows(a){if(!(a??aT(this.fetchHarnessRows())))return[];let b=this.latestConfigScanId();if(null===b)return[];if(this.configRowsCache?.scanId===b)return this.configRowsCache.rows;let c=new am(this.db).report(),d=[...c.skills.map(aV),...c.hooks.map(aW),...c.mcpServers.map(aX),...c.configFiles.map(aY)].sort((a,b)=>a.name.localeCompare(b.name));return this.configRowsCache={scanId:b,rows:d},d}latestConfigScanId(){return al(this.db)?.id??null}fetchProjects(a){let b=`SELECT id, url, name, attributes, last_seen AS lastSeen FROM source_project
|
|
420
|
+
WHERE ${aP}`,c=[];if(a){let d=C(a);b+=` AND ${D(["name","url"])}`,c.push(d,d)}return b+=" ORDER BY name ASC",K(this.db.prepare(b),c)}fetchProjectById(a){return L(this.db.prepare("SELECT id, url, name, attributes, last_seen AS lastSeen FROM source_project WHERE id = ?"),[a])??null}fetchProjectsByIds(a){let b=new Map;if(0===a.length)return b;for(let c of K(this.db.prepare(`SELECT id, url, name, attributes, last_seen AS lastSeen
|
|
421
|
+
FROM source_project WHERE id IN (${B(a.length)})`),a))b.set(c.id,c);return b}projectAggregates(a){let b=new Map;if(0===a.length)return b;for(let c of K(this.db.prepare(`SELECT f.project_id AS projectId,
|
|
422
|
+
coalesce(o.access, f.default_access) AS eff,
|
|
423
|
+
count(*) AS n,
|
|
424
|
+
coalesce(sum(f.findings_count), 0) AS findings
|
|
425
|
+
FROM project_file f
|
|
426
|
+
LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
|
|
427
|
+
WHERE f.project_id IN (${B(a.length)})
|
|
428
|
+
GROUP BY f.project_id, eff`),a)){let a=b.get(c.projectId);a||(a={accessCounts:{open:0,approved:0,blocked:0,total:0},findingsCount:0},b.set(c.projectId,a)),a.accessCounts.total+=c.n,a.accessCounts[c.eff]+=c.n,a.findingsCount+=c.findings}return b}fileSelect(a){return`SELECT f.path, f.name, f.origin, f.default_access AS defaultAccess,
|
|
429
|
+
f.findings_count AS findingsCount, f.blocked_at AS blockedAtMs, f.note,
|
|
430
|
+
coalesce(o.access, f.default_access) AS effectiveAccess,
|
|
431
|
+
o.access AS overrideAccess
|
|
432
|
+
FROM project_file f
|
|
433
|
+
LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
|
|
434
|
+
WHERE ${a}`}mapFileRows(a){return a.map(a=>({path:a.path,name:a.name,origin:a.origin,defaultAccess:a.defaultAccess,findingsCount:a.findingsCount??0,blockedAtMs:a.blockedAtMs??null,note:a.note??null,effectiveAccess:a.effectiveAccess,overrideAccess:a.overrideAccess??null}))}fetchProjectFilesUnder(a,b){return""===b?this.mapFileRows(K(this.db.prepare(this.fileSelect("f.project_id = ? ORDER BY f.path ASC")),[a])):this.mapFileRows(K(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path LIKE ? ESCAPE '\\' ORDER BY f.path ASC")),[a,`${A(b)}/%`]))}fetchProjectFilesSearch(a,b){let c=C(b);return this.mapFileRows(K(this.db.prepare(this.fileSelect("f.project_id = ? AND (f.path LIKE ? ESCAPE '\\' OR f.name LIKE ? ESCAPE '\\') ORDER BY f.path ASC")),[a,c,c]))}fetchProjectFilesBlocked(a){return this.mapFileRows(K(this.db.prepare(this.fileSelect("f.project_id = ? AND coalesce(o.access, f.default_access) = 'blocked' AND f.blocked_at IS NOT NULL")),[a]))}fetchProjectFile(a,b){return this.mapFileRows(K(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path = ?")),[a,b]))[0]??null}}class a1{constructor(a){this.db=a}readPolicies(){return Promise.resolve(Q(K(this.db.prepare("SELECT * FROM policies")),a=>{let b=JSON.parse(a.target),c=a.custom_keywords?JSON.parse(a.custom_keywords):void 0;return g.PEm.parse({id:a.id,scope:a.scope,target:b,action:a.action,enabled:M(a.enabled),customKeywords:c})}))}seedDefaults(){if(O(this.db,"SELECT count(*) AS n FROM policies")>0)return;let a=this.db.prepare(`INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
|
|
435
|
+
VALUES (:id, 'global', :target, :action, 1, :now, :now)`);G(this.db,()=>{for(let[b,c]of Object.entries(g.unw))a.run({id:(0,d.randomUUID)(),target:JSON.stringify({category:b}),action:c,now:Date.now()})})}upsertCategoryAction(a,b){let c=Date.now();this.db.prepare(`INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
|
|
436
|
+
VALUES (:id, 'global', :target, :action, 1, :now, :now)
|
|
437
|
+
ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`).run({id:(0,d.randomUUID)(),target:JSON.stringify({category:a}),action:b,now:c})}capCategoryActions(){return Number(this.db.prepare(`UPDATE policies SET action='warn', updated_at=:now
|
|
438
|
+
WHERE scope='global' AND action IN ('block','redact')
|
|
439
|
+
AND json_extract(target,'$.category') IS NOT NULL`).run({now:Date.now()}).changes)}getCategoryAction(a){let b=this.db.prepare("SELECT action FROM policies WHERE scope='global' AND json_extract(target,'$.category') = :category").get({category:a});return b?.action}}class a2{constructor(a){this.packs=a}getPolicyList(a){if("custom"===a)return Promise.resolve({items:[]});let b=this.packs.countsByPolicyId();return Promise.resolve({items:g.RRF.map(a=>({id:a,kind:"builtin",name:g.ZpU[a].name,enabled:!0,usedByCount:b.get(a)??0}))})}getPolicyStats(){let a=this.packs.countsByPolicyId(),b=g.V0H.reduce((b,c)=>b+(a.get(c)??0),0),c=g.V0H.length;return Promise.resolve({policies:c,builtin:c,custom:0,detectionsGoverned:b})}getPolicyDetail(a){let b=g.V0H.find(b=>b===a);if(void 0===b)return Promise.resolve(null);let c=g.ZpU[b];return Promise.resolve({specVersion:1,id:a,kind:"builtin",name:c.name,enabled:!0,description:c.description,usedBy:this.packs.listByPolicyId(a)})}}class a3{constructor(a){this.db=a,this.maxStampStmt=a.prepare("SELECT coalesce(max(updated_at), 0) AS maxStamp FROM project_file WHERE project_id = :projectId"),this.upsertStmt=a.prepare(`INSERT INTO project_file
|
|
440
|
+
(id, project_id, path, name, origin, default_access, findings_count, blocked_at, note, created_at, updated_at)
|
|
441
|
+
VALUES
|
|
442
|
+
(:id, :projectId, :path, :name, :origin, :defaultAccess, 0, NULL, NULL, :now, :now)
|
|
443
|
+
ON CONFLICT (project_id, path) DO UPDATE SET
|
|
444
|
+
name = excluded.name,
|
|
445
|
+
origin = excluded.origin,
|
|
446
|
+
default_access = excluded.default_access,
|
|
447
|
+
updated_at = excluded.updated_at`),this.pruneStmt=a.prepare("DELETE FROM project_file WHERE project_id = :projectId AND updated_at < :now")}replaceForProject(a,b,c){let e=Math.max(c,(L(this.maxStampStmt,{projectId:a})?.maxStamp??0)+1);for(let c of b.files)this.upsertStmt.run({id:(0,d.randomUUID)(),projectId:a,path:c.path,name:c.name,origin:c.origin,defaultAccess:c.defaultAccess,now:e});b.truncated||this.pruneStmt.run({projectId:a,now:e})}}class a4{constructor(a,b=()=>Date.now()){this.db=a,this.now=b,this.insertStmt=a.prepare(`INSERT INTO finding_resolution (id, finding_key, status, method, resolved_at, evidence, created_at)
|
|
448
|
+
VALUES (:id, :findingKey, :status, :method, :resolvedAt, :evidence, :createdAt)`),this.latestStmt=a.prepare(`SELECT status, method, resolved_at, evidence
|
|
449
|
+
FROM finding_resolution
|
|
450
|
+
WHERE finding_key = :findingKey
|
|
451
|
+
ORDER BY created_at DESC, rowid DESC
|
|
452
|
+
LIMIT 1`),this.openAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
|
|
453
|
+
FROM inspection_findings f
|
|
454
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
455
|
+
WHERE e.event_type = 'code_change'
|
|
456
|
+
AND json_extract(e.attributes, '$.file_path') = :path
|
|
457
|
+
AND f.finding_key IS NOT NULL
|
|
458
|
+
AND ${az("f")} IS NOT 'resolved'`),this.resolvedAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
|
|
459
|
+
FROM inspection_findings f
|
|
460
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
461
|
+
WHERE e.event_type = 'code_change'
|
|
462
|
+
AND json_extract(e.attributes, '$.file_path') = :path
|
|
463
|
+
AND f.finding_key IS NOT NULL
|
|
464
|
+
AND ${az("f")} = 'resolved'`)}insertResolution(a){this.insertStmt.run({id:(0,d.randomUUID)(),findingKey:a.findingKey,status:g.GCf.parse(a.status),method:g.cqq.parse(a.method),resolvedAt:a.resolvedAt,evidence:a.evidence,createdAt:this.now()})}latestByKey(a){let b=L(this.latestStmt,{findingKey:a});if(b)return{status:b.status,method:b.method,resolvedAt:b.resolved_at,evidence:b.evidence??""}}openAtRestKeysForPath(a){return K(this.openAtRestStmt,{path:a}).map(a=>a.finding_key)}resolvedAtRestKeysForPath(a){return K(this.resolvedAtRestStmt,{path:a}).map(a=>a.finding_key)}}class a5{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO rule_probe_cache (rule_key, verdict, worst_probe_ms, checked_at)
|
|
465
|
+
VALUES (:ruleKey, :verdict, :worstProbeMs, :checkedAt)
|
|
466
|
+
ON CONFLICT (rule_key) DO UPDATE SET
|
|
467
|
+
verdict = excluded.verdict,
|
|
468
|
+
worst_probe_ms = excluded.worst_probe_ms,
|
|
469
|
+
checked_at = excluded.checked_at`),this.readStmt=a.prepare("SELECT verdict, worst_probe_ms AS worstProbeMs FROM rule_probe_cache WHERE rule_key = :ruleKey"),this.countQuarantinedStmt=a.prepare("SELECT COUNT(*) AS n FROM rule_probe_cache WHERE verdict = 'quarantined'"),this.clearQuarantinedStmt=a.prepare("DELETE FROM rule_probe_cache WHERE verdict = 'quarantined'")}getVerdict(a){return L(this.readStmt,{ruleKey:a})}countQuarantined(){return L(this.countQuarantinedStmt,{})?.n??0}clearQuarantined(){let a=this.countQuarantined();return{refused:!G(this.db,()=>{this.clearQuarantinedStmt.run()}),cleared:a-this.countQuarantined()}}setVerdict(a,b,c){G(this.db,()=>{this.upsertStmt.run({ruleKey:a,verdict:b,worstProbeMs:c,checkedAt:Date.now()})})}}class a6{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
|
|
470
|
+
VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
|
|
471
|
+
ON CONFLICT (path) DO UPDATE SET
|
|
472
|
+
mtime = excluded.mtime,
|
|
473
|
+
content_hash = excluded.content_hash,
|
|
474
|
+
ruleset_hash = excluded.ruleset_hash,
|
|
475
|
+
scanned_at = excluded.scanned_at`),this.readStmt=a.prepare(`SELECT path, mtime, content_hash AS contentHash
|
|
476
|
+
FROM scan_ledger WHERE ruleset_hash = :rulesetHash`)}entriesForRuleset(a){return new Map(K(this.readStmt,{rulesetHash:a}).map(a=>[a.path,{mtime:a.mtime,contentHash:a.contentHash}]))}upsertEntries(a){if(0===a.length)return;let b=Date.now();G(this.db,()=>{for(let c of a)this.upsertStmt.run({path:c.path,mtime:c.mtime,contentHash:c.contentHash,rulesetHash:c.rulesetHash,scannedAt:b})})}}function a7(a,b){return void 0===a?b:Math.min(Math.max(1,Math.trunc(a)),g.u8Q)}let a8=`(v.occurrence_count > 1
|
|
477
|
+
OR (SELECT count(*) FROM secret_vault_sighting s WHERE s.pointer_id = v.pointer_id) > 1)`,a9=`v.pointer_id, v.category, v.rule_id, v.masked_match, v.provider,
|
|
478
|
+
v.occurrence_count, v.first_seen, v.last_seen`,ba=`
|
|
479
|
+
pointer_id AS pointerId,
|
|
480
|
+
value_fingerprint AS valueFingerprint,
|
|
481
|
+
fingerprint_key_version AS fingerprintKeyVersion,
|
|
482
|
+
key_version AS keyVersion,
|
|
483
|
+
format_version AS formatVersion,
|
|
484
|
+
category,
|
|
485
|
+
rule_id AS ruleId,
|
|
486
|
+
masked_match AS maskedMatch,
|
|
487
|
+
provider,
|
|
488
|
+
ciphertext,
|
|
489
|
+
nonce,
|
|
490
|
+
auth_tag AS authTag,
|
|
491
|
+
occurrence_count AS occurrenceCount,
|
|
492
|
+
first_seen AS firstSeen,
|
|
493
|
+
last_seen AS lastSeen`;function bb(a){let{provider:b,...c}=a;return null===b?c:{...c,provider:b}}class bc{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO secret_vault (
|
|
494
|
+
pointer_id, value_fingerprint, fingerprint_key_version, key_version,
|
|
495
|
+
format_version, category, rule_id, masked_match, provider,
|
|
496
|
+
ciphertext, nonce, auth_tag,
|
|
497
|
+
occurrence_count, first_seen, last_seen
|
|
498
|
+
) VALUES (
|
|
499
|
+
:pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
|
|
500
|
+
:formatVersion, :category, :ruleId, :maskedMatch, :provider,
|
|
501
|
+
:ciphertext, :nonce, :authTag,
|
|
502
|
+
1, :now, :now
|
|
503
|
+
)`),this.bumpStmt=a.prepare(`UPDATE secret_vault
|
|
504
|
+
SET occurrence_count = occurrence_count + 1, last_seen = :now
|
|
505
|
+
WHERE value_fingerprint = :valueFingerprint`),this.byPointerStmt=a.prepare(`SELECT ${ba} FROM secret_vault WHERE pointer_id = :pointerId`),this.byFingerprintStmt=a.prepare(`SELECT ${ba} FROM secret_vault WHERE value_fingerprint = :valueFingerprint`),this.listStmt=a.prepare(`SELECT ${ba} FROM secret_vault ORDER BY first_seen`),this.replaceCiphertextStmt=a.prepare(`UPDATE secret_vault
|
|
506
|
+
SET key_version = :keyVersion, ciphertext = :ciphertext, nonce = :nonce, auth_tag = :authTag
|
|
507
|
+
WHERE pointer_id = :pointerId`),this.refreshFingerprintStmt=a.prepare(`UPDATE secret_vault
|
|
508
|
+
SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
|
|
509
|
+
WHERE pointer_id = :pointerId`),this.derefStmt=a.prepare(`INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
|
|
510
|
+
VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`)}upsert(a,b){let c=!1;F(this.db,()=>{if(void 0===L(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint})){this.insertStmt.run(N({pointerId:a.pointerId,valueFingerprint:a.valueFingerprint,fingerprintKeyVersion:a.fingerprintKeyVersion,keyVersion:a.keyVersion,formatVersion:a.formatVersion??g.viY,category:a.category,ruleId:a.ruleId,maskedMatch:a.maskedMatch,provider:a.provider,ciphertext:a.ciphertext,nonce:a.nonce,authTag:a.authTag,now:b})),c=!0;return}this.bumpStmt.run({valueFingerprint:a.valueFingerprint,now:b})},"IMMEDIATE");let d=L(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint});if(void 0===d)throw Error("vault: row vanished immediately after write");return{row:bb(d),minted:c}}byPointerId(a){let b=L(this.byPointerStmt,{pointerId:a});return void 0===b?null:bb(b)}byValueFingerprint(a){let b=L(this.byFingerprintStmt,{valueFingerprint:a});return void 0===b?null:bb(b)}recordDeref(a){this.derefStmt.run(N({id:a.id,pointerId:a.pointerId,at:a.at,target:a.target,reason:a.reason,outcome:a.outcome,grantId:a.grantId,pointerCount:a.pointerCount??1}))}listAll(){return K(this.listStmt).map(bb)}replaceCiphertext(a,b){this.replaceCiphertextStmt.run({pointerId:a,...b})}refreshFingerprint(a,b){this.refreshFingerprintStmt.run({pointerId:a,...b})}purgeAll(){let a=0;return F(this.db,()=>{a=this.countEntries(),this.db.exec("DELETE FROM secret_vault")},"IMMEDIATE"),a}recordSighting(a,b){this.db.prepare(`INSERT INTO secret_vault_sighting (id, pointer_id, location, kind, first_seen, last_seen)
|
|
511
|
+
VALUES (:id, :pointerId, :location, :kind, :now, :now)
|
|
512
|
+
ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`).run({id:(0,d.randomUUID)(),pointerId:a.pointerId,location:a.location,kind:a.kind,now:b})}sightingsFor(a){let b=new Map(a.map(a=>[a,[]]));if(0===a.length)return b;for(let c of K(this.db.prepare(`SELECT pointer_id, location, kind, first_seen, last_seen
|
|
513
|
+
FROM secret_vault_sighting
|
|
514
|
+
WHERE pointer_id IN (${B(a.length)})
|
|
515
|
+
ORDER BY last_seen DESC`),a))b.get(c.pointer_id)?.push({location:c.location,kind:c.kind,firstSeen:new Date(c.first_seen).toISOString(),lastSeen:new Date(c.last_seen).toISOString()});return b}toInventoryEntries(a){let b=this.sightingsFor(a.map(a=>a.pointer_id));return a.map(a=>({pointerId:a.pointer_id,category:a.category,...null===a.provider?{}:{provider:a.provider},maskedMatch:a.masked_match,occurrences:a.occurrence_count,firstSeen:new Date(a.first_seen).toISOString(),lastSeen:new Date(a.last_seen).toISOString(),revealGrantId:a.grant_id,sightings:b.get(a.pointer_id)??[]}))}listInventory(a={},b=Date.now()){let c=a7(a.limit,g.mBk),d=void 0===a.cursor?null:Z(a.cursor),e=null===d?"":"WHERE (v.last_seen < :cursorLastSeen OR (v.last_seen = :cursorLastSeen AND v.pointer_id < :cursorPointerId))",f=K(this.db.prepare(`SELECT ${a9},
|
|
516
|
+
(SELECT e.id FROM exceptions e
|
|
517
|
+
WHERE e.rule_id = v.rule_id
|
|
518
|
+
AND e.value_fingerprint = v.value_fingerprint
|
|
519
|
+
AND e.key_version = v.fingerprint_key_version
|
|
520
|
+
AND ${aw}
|
|
521
|
+
LIMIT 1) AS grant_id
|
|
522
|
+
FROM secret_vault v
|
|
523
|
+
${e}
|
|
524
|
+
ORDER BY v.last_seen DESC, v.pointer_id DESC
|
|
525
|
+
LIMIT :limit`),N({now:b,limit:c+1,...null===d?{}:{cursorLastSeen:d.startedAtMs,cursorPointerId:d.id}})),h=f.length>c,i=h?f.slice(0,c):f,j=i[i.length-1];return{totals:{values:this.countEntries()},items:this.toInventoryEntries(i),nextCursor:h&&j?Y({startedAtMs:j.last_seen,id:j.pointer_id}):null}}listReuse(a={},b=Date.now()){var c;let d=a7(a.limit,g.mBk),e=void 0===a.cursor?null:function(a){let b=X(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&Number.isInteger(b.occurrences)&&"string"==typeof b.pointerId?{occurrences:b.occurrences,pointerId:b.pointerId}:null}(a.cursor),f=null===e?"":`AND (v.occurrence_count < :cursorOccurrences
|
|
526
|
+
OR (v.occurrence_count = :cursorOccurrences AND v.pointer_id < :cursorPointerId))`,h=K(this.db.prepare(`SELECT ${a9},
|
|
527
|
+
(SELECT e.id FROM exceptions e
|
|
528
|
+
WHERE e.rule_id = v.rule_id
|
|
529
|
+
AND e.value_fingerprint = v.value_fingerprint
|
|
530
|
+
AND e.key_version = v.fingerprint_key_version
|
|
531
|
+
AND ${aw}
|
|
532
|
+
LIMIT 1) AS grant_id
|
|
533
|
+
FROM secret_vault v
|
|
534
|
+
WHERE ${a8} ${f}
|
|
535
|
+
ORDER BY v.occurrence_count DESC, v.pointer_id DESC
|
|
536
|
+
LIMIT :limit`),N({now:b,limit:d+1,...null===e?{}:{cursorOccurrences:e.occurrences,cursorPointerId:e.pointerId}})),i=h.length>d,j=i?h.slice(0,d):h,k=j[j.length-1];return{totals:{reused:this.countReused()},items:this.toInventoryEntries(j),nextCursor:i&&k?(c={occurrences:k.occurrence_count,pointerId:k.pointer_id},Buffer.from(JSON.stringify(c)).toString("base64url")):null}}listDerefs(a={}){let b=a7(a.limit,g.hdu),c=void 0===a.cursor?null:Z(a.cursor),d=[];!0!==a.includeBatched&&d.push("reason NOT IN ('display', 'view-render')"),null!==c&&d.push("(at < :cursorAt OR (at = :cursorAt AND id < :cursorId))");let e=0===d.length?"":`WHERE ${d.join(" AND ")}`,f=K(this.db.prepare(`SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
|
|
537
|
+
FROM secret_vault_deref ${e}
|
|
538
|
+
ORDER BY at DESC, id DESC LIMIT :limit`),N({limit:b+1,...null===c?{}:{cursorAt:c.startedAtMs,cursorId:c.id}})),h=f.length>b,i=h?f.slice(0,b):f,j=i[i.length-1],k=!0===a.includeBatched?0:O(this.db,"SELECT count(*) AS n FROM secret_vault_deref WHERE reason IN ('display', 'view-render')");return{items:i.map(a=>({id:a.id,pointerId:a.pointer_id,at:new Date(a.at).toISOString(),target:a.target,reason:a.reason,outcome:a.outcome,...null===a.grant_id?{}:{grantId:a.grant_id},pointerCount:a.pointer_count})),nextCursor:h&&j?Y({startedAtMs:j.at,id:j.id}):null,hiddenBatched:k}}countEntries(){return O(this.db,"SELECT COUNT(*) AS n FROM secret_vault")}countReused(){return O(this.db,`SELECT COUNT(*) AS n FROM secret_vault v WHERE ${a8}`)}}let bd=["critical","high","medium","low"],be={block:"blocked",redact:"redacted",warn:"warned"},bf=["blocked","redacted","warned"],bg=[{provider:"claudecode",coverage:100,supported:!0},{provider:"cursor",coverage:0,supported:!1},{provider:"codex",coverage:80,supported:!0},{provider:"antigravity",coverage:60,supported:!0},{provider:"claudeai",coverage:0,supported:!1},{provider:"chatgpt",coverage:0,supported:!1},{provider:"copilot",coverage:0,supported:!1},{provider:"api",coverage:0,supported:!1}],bh={"7d":"day","30d":"day","3m":"week","6m":"week"};function bi(a){return 864e5*Math.floor(a/864e5)}function bj(a){return new Date(a).toISOString().slice(0,10)}class bk{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}severitySummary(){let a=new Map(K(this.db.prepare(`SELECT d.severity AS severity,
|
|
539
|
+
COUNT(*) AS count,
|
|
540
|
+
SUM(CASE
|
|
541
|
+
WHEN e.event_type != 'code_change' THEN 1
|
|
542
|
+
WHEN f.finding_key IS NULL THEN 0
|
|
543
|
+
WHEN latest.status = 'resolved' THEN 1
|
|
544
|
+
ELSE 0
|
|
545
|
+
END) AS caught,
|
|
546
|
+
SUM(CASE
|
|
547
|
+
WHEN e.event_type = 'code_change'
|
|
548
|
+
AND f.finding_key IS NOT NULL
|
|
549
|
+
AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
|
|
550
|
+
ELSE 0
|
|
551
|
+
END) AS open_at_rest
|
|
552
|
+
FROM inspection_findings f
|
|
553
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
554
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
555
|
+
LEFT JOIN ${aA} latest
|
|
556
|
+
ON latest.finding_key = f.finding_key
|
|
557
|
+
WHERE e.event_type IN (${g.hfB})
|
|
558
|
+
GROUP BY d.severity`)).map(a=>[a.severity,a])),b=bd.map(b=>({severity:b,count:a.get(b)?.count??0,caught:a.get(b)?.caught??0,openAtRest:a.get(b)?.open_at_rest??0}));return Promise.resolve({total:b.reduce((a,b)=>a+b.count,0),needsRemediation:b.reduce((a,b)=>a+b.openAtRest,0),bySeverity:b})}scanCoverage(a){return Promise.resolve({range:a,providers:bg.map(a=>({...a}))})}enforcementActions(a){let b=864e5*g.eI7[a],c=this.now(),d=c-b,e=this.findingsInRange(c-2*b,c),f={blocked:0,redacted:0,warned:0},h={blocked:0,redacted:0,warned:0};for(let a of e){let b=be[a.actionTaken];b&&(a.occurredAt>=d?f[b]++:h[b]++)}let i=bf.map(a=>({kind:a,count:f[a],delta:f[a]-h[a]}));return Promise.resolve({range:a,total:i.reduce((a,b)=>a+b.count,0),actions:i})}findingsTimeseries(a){let b=bh[a],c=("day"===b?1:7)*864e5,d=g.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),h=bi(f)-(d-1)*864e5,i=this.findingsInRange(h,f),j=Array.from({length:e},(a,b)=>({timestamp:bj(h+b*c),critical:0,high:0,medium:0}));for(let a of i){let b=j[Math.floor((a.occurredAt-h)/c)];if(b){var k;("critical"===(k=a.severity)||"high"===k||"medium"===k)&&b[a.severity]++}}return Promise.resolve({range:a,granularity:b,points:j})}mttrTrend(a){let b=bh[a],c=("day"===b?1:7)*864e5,d=g.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),h=bi(f)-(d-1)*864e5,i=K(this.db.prepare(`SELECT COALESCE(f.first_detected_at, e.started_at) AS first_detected_at, d.severity AS severity,
|
|
559
|
+
latest.status AS latest_status,
|
|
560
|
+
latest.method AS latest_method,
|
|
561
|
+
latest.resolved_at AS latest_resolved_at
|
|
562
|
+
FROM inspection_findings f
|
|
563
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
564
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
565
|
+
LEFT JOIN ${aA} latest
|
|
566
|
+
ON latest.finding_key = f.finding_key
|
|
567
|
+
WHERE f.finding_key IS NOT NULL
|
|
568
|
+
AND e.event_type IN (${g.hfB})
|
|
569
|
+
AND EXISTS (
|
|
570
|
+
SELECT 1 FROM finding_resolution fr
|
|
571
|
+
WHERE fr.finding_key = f.finding_key
|
|
572
|
+
AND fr.resolved_at >= :windowStart
|
|
573
|
+
)`),{windowStart:h}),j=new Map,k=new Map;for(let a of i){if("resolved"!==a.latest_status||"fixed-at-source"!==a.latest_method||null==a.latest_resolved_at||a.latest_resolved_at<h||a.latest_resolved_at>=f)continue;let b=Math.floor((a.latest_resolved_at-h)/c);if(b<0||b>=e)continue;let d=`${String(b)}:${a.severity}`,g=Math.max(0,a.latest_resolved_at-a.first_detected_at);j.set(d,(j.get(d)??0)+g),k.set(d,(k.get(d)??0)+1)}return Promise.resolve({range:a,granularity:b,points:Array.from({length:e},(a,b)=>{let d={};for(let a of bd){let c=`${String(b)}:${a}`,e=k.get(c)??0;d[a]=e>0?(j.get(c)??0)/e:null}return{timestamp:bj(h+b*c),bySeverity:d}})})}topSources(a,b={}){let c=b.limit??5;if("user"===b.kind)return Promise.resolve({range:a,items:[]});let d=this.now(),e=d-864e5*g.eI7[a];return Promise.resolve({range:a,items:K(this.db.prepare(`SELECT json_extract(e.attributes, '$.repo') AS repo, count(*) AS c
|
|
574
|
+
FROM inspection_findings f
|
|
575
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
576
|
+
WHERE e.started_at >= :from AND e.started_at < :to
|
|
577
|
+
AND e.event_type IN (${g.hfB})
|
|
578
|
+
AND json_extract(e.attributes, '$.repo') IS NOT NULL
|
|
579
|
+
AND json_extract(e.attributes, '$.repo') != ''
|
|
580
|
+
GROUP BY repo
|
|
581
|
+
ORDER BY c DESC, repo
|
|
582
|
+
LIMIT :limit`),{from:e,to:d,limit:c}).map(a=>({id:`repo_${a.repo}`,name:a.repo,kind:"repo",findingsCount:a.c}))})}recentlyResolved(a=20){return Promise.resolve({items:K(this.db.prepare(`SELECT f.finding_key AS finding_key,
|
|
583
|
+
d.rule_id AS rule_id,
|
|
584
|
+
d.severity AS severity,
|
|
585
|
+
json_extract(e.attributes, '$.file_path') AS path,
|
|
586
|
+
COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
|
|
587
|
+
latest.resolved_at AS latest_resolved_at
|
|
588
|
+
FROM inspection_findings f
|
|
589
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
590
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
591
|
+
LEFT JOIN ${aA} latest
|
|
592
|
+
ON latest.finding_key = f.finding_key
|
|
593
|
+
WHERE e.event_type = 'code_change'
|
|
594
|
+
AND f.finding_key IS NOT NULL
|
|
595
|
+
AND latest.status = 'resolved'
|
|
596
|
+
AND latest.method = 'fixed-at-source'
|
|
597
|
+
AND latest.resolved_at IS NOT NULL
|
|
598
|
+
ORDER BY latest_resolved_at DESC
|
|
599
|
+
LIMIT :limit`),{limit:a}).map(a=>({findingKey:a.finding_key,ruleId:a.rule_id,severity:a.severity,path:a.path??"",resolvedAt:new Date(a.latest_resolved_at).toISOString(),detectedAt:new Date(a.first_detected_at).toISOString()}))})}findingsInRange(a,b){return K(this.db.prepare(`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
|
|
600
|
+
FROM inspection_findings f
|
|
601
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
602
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
603
|
+
WHERE e.started_at >= :from AND e.started_at < :to
|
|
604
|
+
AND e.event_type IN (${g.hfB})
|
|
605
|
+
ORDER BY e.started_at`),{from:a,to:b}).map(a=>({occurredAt:a.occurred_at,severity:a.severity,actionTaken:a.action_taken}))}}let bl=["provider","internal","external","ip"],bm="('http', 'ws')",bn=`LEFT JOIN egress_decision_override oh ON oh.host = d.host
|
|
606
|
+
LEFT JOIN egress_decision_override ol ON ol.destination_id = d.id AND ol.host IS NULL`;function bo(a){return{id:a.id,method:a.method,transport:a.transport,url:a.url,template:a.template,dataClass:a.dataClass,lastSeen:new Date(a.lastSeenMs).toISOString(),callSiteCount:a.callSiteCount}}function bp(a,b){let c=b.map(a=>a.transport),d=b.map(a=>a.dataClass),e=b.reduce((a,b)=>a+b.callSiteCount,0),f=b.length>0?Math.max(...b.map(a=>a.lastSeenMs)):a.lastSeenMs;return{id:a.id,kind:a.kind,name:a.name,host:a.host,category:a.category,trust:a.trust,status:(0,g.Gw9)(a.trust,a.overrideDecision),isCustom:(0,g.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(f).toISOString(),endpointCount:b.length,callSiteCount:e,transports:(0,g.by7)(c),dataClasses:(0,g.hzO)(d),review:(0,g.Fnc)(a.trust,c),network:"provider"===a.kind?null:W(a.networkJson,null),endpoints:b.map(bo)}}class bq{constructor(a){this.db=a}stats(){let a=O(this.db,"SELECT count(*) AS n FROM share_destination"),b=O(this.db,"SELECT count(*) AS n FROM share_endpoint"),c=O(this.db,"SELECT count(*) AS n FROM share_call_site"),d=O(this.db,`SELECT count(DISTINCT destination_id) AS n FROM share_endpoint
|
|
607
|
+
WHERE transport IN ${bm}`),e=O(this.db,`SELECT count(DISTINCT d.id) AS n
|
|
608
|
+
FROM share_destination d
|
|
609
|
+
LEFT JOIN share_endpoint e ON e.destination_id = d.id
|
|
610
|
+
AND e.transport IN ${bm}
|
|
611
|
+
WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`),f=P(this.db,"SELECT kind AS k, count(*) AS n FROM share_destination GROUP BY kind"),g={provider:f.get("provider")??0,internal:f.get("internal")??0,external:f.get("external")??0,ip:f.get("ip")??0},h=P(this.db,"SELECT trust AS k, count(*) AS n FROM share_destination GROUP BY trust");return Promise.resolve({destinations:a,endpoints:b,callSites:c,needsReview:e,insecure:d,byKind:g,byTrust:{recognized:h.get("recognized")??0,internal:h.get("internal")??0,unverified:h.get("unverified")??0,ip:h.get("ip")??0}})}listDestinations(a){let b=void 0===a.q||""===a.q?void 0:a.q,c=this.fetchDestinations(b,a.kind),d=this.groupEndpoints(c.map(a=>a.id)),e=c.map(a=>bp(a,d.get(a.id)??[])),f=new Map;for(let a of e){let b=f.get(a.kind);b?b.push(a):f.set(a.kind,[a])}return Promise.resolve({groups:bl.filter(a=>f.has(a)).map(a=>{let b=f.get(a)??[];return{kind:a,total:b.length,items:b}})})}needsReview(){let a=this.fetchDestinations(void 0,void 0,!0),b=this.groupEndpoints(a.map(a=>a.id));return Promise.resolve({items:a.map(a=>({dest:a,endpoints:b.get(a.id)??[]})).map(({dest:a,endpoints:b})=>({summary:bp(a,b),endpoints:b})).filter(({summary:a})=>a.review.needsReview).map(({summary:a,endpoints:b})=>({id:a.id,kind:a.kind,name:a.name,host:a.host,trust:a.trust,status:a.status,review:a.review,topDataClass:(0,g.C05)(b.map(a=>a.dataClass)),callSiteCount:a.callSiteCount,lastSeen:a.lastSeen})).sort((a,b)=>{let c=(0,g.WSs)(a.review.reasons)-(0,g.WSs)(b.review.reasons);return 0!==c?c:b.lastSeen.localeCompare(a.lastSeen)})})}getDestination(a){let b=this.fetchDestinationById(a);if(!b)return Promise.resolve(null);let c=this.fetchEndpoints([b.id]),d=this.fetchCallSites(c.map(a=>a.id));return Promise.resolve(function(a,b,c){let d=b.map(a=>a.transport),e=b.length>0?Math.max(...b.map(a=>a.lastSeenMs)):a.lastSeenMs,f=new Map;for(let a of c.slice(0,200)){let b={id:a.id,project:a.project,file:a.file,line:a.line,snippet:a.snippet,dynamic:a.dynamic,vendored:a.vendored,projectId:a.projectId},c=f.get(a.endpointId);c?c.push(b):f.set(a.endpointId,[b])}return{id:a.id,kind:a.kind,name:a.name,host:a.host,category:a.category,trust:a.trust,status:(0,g.Gw9)(a.trust,a.overrideDecision),isCustom:(0,g.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(e).toISOString(),transports:(0,g.by7)(d),dataClasses:(0,g.hzO)(b.map(a=>a.dataClass)),review:(0,g.Fnc)(a.trust,d),network:"provider"===a.kind?null:W(a.networkJson,null),note:a.note,endpoints:b.map(a=>({...bo(a),sites:f.get(a.id)??[]}))}}(b,c,d))}setEgressDecision(a,b){let c=!1;return F(this.db,()=>{let e=this.db.prepare("SELECT host FROM share_destination WHERE id = ?").get(a);void 0!==e&&(c=!0,this.db.prepare(`DELETE FROM egress_decision_override
|
|
612
|
+
WHERE host = :host OR (destination_id = :destinationId AND host IS NULL)`).run({host:e.host,destinationId:a}),null!==b&&this.db.prepare(`INSERT INTO egress_decision_override
|
|
613
|
+
(id, destination_id, host, decision, created_at, updated_at)
|
|
614
|
+
VALUES (:id, :destinationId, :host, :decision, :now, :now)`).run({id:(0,d.randomUUID)(),destinationId:a,host:e.host,decision:b,now:Date.now()}))},"IMMEDIATE"),c}recordProjectEgress(a){let{hits:b,droppedFiles:c,truncated:d}=function(a,b){if(a.length<=5e3)return{hits:[...a],droppedFiles:[],truncated:!1};if("walk"===b)return{hits:a.slice(0,5e3),droppedFiles:[],truncated:!0};let c=new Map;for(let b of a){let a=c.get(b.site.file);void 0===a?c.set(b.site.file,[b]):a.push(b)}let d=[],e=[];for(let[a,b]of c)d.length+b.length>5e3?e.push(a):d.push(...b);return{hits:d,droppedFiles:e,truncated:!0}}(a.hits,a.reconcile.mode),e=function(a,b){if("walk"===a.mode||0===b.length)return a;let c=new Set(b);return{mode:"ledger",scannedFiles:a.scannedFiles.filter(a=>!c.has(a)),deletedFiles:a.deletedFiles.filter(a=>!c.has(a))}}(a.reconcile,c),f=Date.now(),g={destinations:0,endpoints:0,callSites:0,truncated:d,droppedFiles:c};return F(this.db,()=>{let h=a.projectId??this.knownProjectId(a.projectKey);this.reconcileCallSites(a.projectKey,e),this.upsertHits(a,b,h,f),this.confirmLastSeen(a.projectKey,f),this.pruneOrphans(),g={...this.projectTotals(a.projectKey),truncated:d,droppedFiles:c}},"IMMEDIATE"),g}reconcileCallSites(a,b){if("walk"===b.mode){let c=b.walkedPrefix.replace(/\/+$/,"");this.db.prepare(`DELETE FROM share_call_site
|
|
615
|
+
WHERE project_key = :key
|
|
616
|
+
AND (:prefix = '' OR file = :prefix OR file LIKE :subtree ESCAPE '\\')
|
|
617
|
+
AND file NOT LIKE '.%'
|
|
618
|
+
AND file NOT LIKE '%/.%'`).run({key:a,prefix:c,subtree:`${A(c)}/%`});return}let c=[...new Set([...b.scannedFiles,...b.deletedFiles])];for(let b=0;b<c.length;b+=500){let d=c.slice(b,b+500);this.db.prepare(`DELETE FROM share_call_site
|
|
619
|
+
WHERE project_key = ? AND file IN (${B(d.length)})`).run(a,...d)}}upsertHits(a,b,c,e){if(0===b.length)return;let f=this.db.prepare(`INSERT INTO share_destination
|
|
620
|
+
(id, kind, name, host, category, trust, network_json, last_seen, provenance,
|
|
621
|
+
created_at, updated_at)
|
|
622
|
+
VALUES (:id, :kind, :name, :host, :category, :trust, :networkJson, :now, 'scan', :now, :now)
|
|
623
|
+
ON CONFLICT (host) DO UPDATE SET
|
|
624
|
+
kind = excluded.kind,
|
|
625
|
+
name = excluded.name,
|
|
626
|
+
category = excluded.category,
|
|
627
|
+
trust = excluded.trust,
|
|
628
|
+
network_json = excluded.network_json,
|
|
629
|
+
last_seen = excluded.last_seen,
|
|
630
|
+
updated_at = excluded.updated_at`),g=this.db.prepare("SELECT id FROM share_destination WHERE host = ?"),h=this.db.prepare(`INSERT INTO share_endpoint
|
|
631
|
+
(id, destination_id, method, transport, url, template, data_class, last_seen,
|
|
632
|
+
created_at, updated_at)
|
|
633
|
+
VALUES (:id, :destinationId, :method, :transport, :url, :template, :dataClass, :now,
|
|
634
|
+
:now, :now)
|
|
635
|
+
ON CONFLICT (destination_id, method, url) DO UPDATE SET
|
|
636
|
+
transport = excluded.transport,
|
|
637
|
+
template = excluded.template,
|
|
638
|
+
data_class = excluded.data_class,
|
|
639
|
+
last_seen = excluded.last_seen,
|
|
640
|
+
updated_at = excluded.updated_at`),i=this.db.prepare("SELECT id FROM share_endpoint WHERE destination_id = ? AND method = ? AND url = ?"),j=this.db.prepare(`INSERT INTO share_call_site
|
|
641
|
+
(id, endpoint_id, project, project_key, file, line, snippet, dynamic, vendored,
|
|
642
|
+
project_id, created_at, updated_at)
|
|
643
|
+
VALUES (:id, :endpointId, :project, :projectKey, :file, :line, :snippet, :dynamic,
|
|
644
|
+
:vendored, :projectId, :now, :now)
|
|
645
|
+
ON CONFLICT (endpoint_id, project_key, file, line) DO UPDATE SET
|
|
646
|
+
snippet = excluded.snippet,
|
|
647
|
+
dynamic = excluded.dynamic,
|
|
648
|
+
vendored = excluded.vendored,
|
|
649
|
+
project = excluded.project,
|
|
650
|
+
project_id = COALESCE(excluded.project_id, share_call_site.project_id),
|
|
651
|
+
updated_at = excluded.updated_at`),k=new Map,l=new Map;for(let m of b){let b=k.get(m.host);void 0===b&&(f.run({id:(0,d.randomUUID)(),kind:m.kind,name:m.name,host:m.host,category:m.category,trust:m.trust,networkJson:null===m.network?null:JSON.stringify(m.network),now:e}),b=L(g,[m.host])?.id??"",k.set(m.host,b));let n=`${b}\0${m.method}\0${m.url}`,o=l.get(n);void 0===o&&(h.run({id:(0,d.randomUUID)(),destinationId:b,method:m.method,transport:m.transport,url:m.url,template:+!!m.template,dataClass:m.dataClass,now:e}),o=L(i,[b,m.method,m.url])?.id??"",l.set(n,o)),j.run({id:(0,d.randomUUID)(),endpointId:o,project:a.project,projectKey:a.projectKey,file:m.site.file,line:m.site.line,snippet:m.site.snippet,dynamic:+!!m.site.dynamic,vendored:+!!m.site.vendored,projectId:c,now:e})}}knownProjectId(a){return L(this.db.prepare(`SELECT project_id AS projectId FROM share_call_site
|
|
652
|
+
WHERE project_key = ? AND project_id IS NOT NULL LIMIT 1`),[a])?.projectId??null}confirmLastSeen(a,b){this.db.prepare(`UPDATE share_endpoint SET last_seen = :now, updated_at = :now
|
|
653
|
+
WHERE id IN (SELECT DISTINCT endpoint_id FROM share_call_site WHERE project_key = :key)`).run({now:b,key:a}),this.db.prepare(`UPDATE share_destination SET last_seen = :now, updated_at = :now
|
|
654
|
+
WHERE id IN (SELECT DISTINCT e.destination_id
|
|
655
|
+
FROM share_endpoint e
|
|
656
|
+
JOIN share_call_site c ON c.endpoint_id = e.id
|
|
657
|
+
WHERE c.project_key = :key)`).run({now:b,key:a})}pruneOrphans(){this.db.exec(`DELETE FROM share_endpoint
|
|
658
|
+
WHERE NOT EXISTS (SELECT 1 FROM share_call_site c WHERE c.endpoint_id = share_endpoint.id)`),this.db.exec(`DELETE FROM egress_decision_override
|
|
659
|
+
WHERE host IS NULL
|
|
660
|
+
AND destination_id IN (
|
|
661
|
+
SELECT d.id FROM share_destination d
|
|
662
|
+
WHERE NOT EXISTS (SELECT 1 FROM share_endpoint e WHERE e.destination_id = d.id))`),this.db.exec(`DELETE FROM share_destination
|
|
663
|
+
WHERE NOT EXISTS (
|
|
664
|
+
SELECT 1 FROM share_endpoint e WHERE e.destination_id = share_destination.id)`)}projectTotals(a){return{destinations:O(this.db,`SELECT count(DISTINCT e.destination_id) AS n
|
|
665
|
+
FROM share_endpoint e
|
|
666
|
+
JOIN share_call_site c ON c.endpoint_id = e.id
|
|
667
|
+
WHERE c.project_key = ?`,[a]),endpoints:O(this.db,"SELECT count(DISTINCT endpoint_id) AS n FROM share_call_site WHERE project_key = ?",[a]),callSites:O(this.db,"SELECT count(*) AS n FROM share_call_site WHERE project_key = ?",[a])}}mapDestRow(a){return{id:a.id,kind:a.kind,name:a.name,host:a.host,category:a.category,trust:a.trust,note:a.note,networkJson:a.networkJson,lastSeenMs:a.lastSeenMs,overrideDecision:a.overrideDecision??null}}fetchDestinations(a,b,c=!1){let d,e=`d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
|
|
668
|
+
d.network_json AS networkJson, d.last_seen AS lastSeenMs,
|
|
669
|
+
d.created_at AS createdAt,
|
|
670
|
+
COALESCE(oh.decision, ol.decision) AS overrideDecision`,f=[],g=[];if(b&&b.length>0&&(f.push(`d.kind IN (${B(b.length)})`),g.push(...b)),c&&f.push(`(d.trust IN ('unverified', 'ip')
|
|
671
|
+
OR EXISTS (SELECT 1 FROM share_endpoint re
|
|
672
|
+
WHERE re.destination_id = d.id
|
|
673
|
+
AND re.transport IN ${bm}))`),a){let b=C(a);f.push(`(d.name LIKE ? ESCAPE '\\' OR d.category LIKE ? ESCAPE '\\' OR e.url LIKE ? ESCAPE '\\'
|
|
674
|
+
OR c.project LIKE ? ESCAPE '\\' OR c.file LIKE ? ESCAPE '\\')`),g.push(b,b,b,b,b),d=`SELECT DISTINCT ${e}
|
|
675
|
+
FROM share_destination d
|
|
676
|
+
${bn}
|
|
677
|
+
LEFT JOIN share_endpoint e ON e.destination_id = d.id
|
|
678
|
+
LEFT JOIN share_call_site c ON c.endpoint_id = e.id
|
|
679
|
+
${f.length?`WHERE ${f.join(" AND ")}`:""}
|
|
680
|
+
ORDER BY d.created_at ASC, d.id ASC`}else d=`SELECT ${e}
|
|
681
|
+
FROM share_destination d
|
|
682
|
+
${bn}
|
|
683
|
+
${f.length?`WHERE ${f.join(" AND ")}`:""}
|
|
684
|
+
ORDER BY d.created_at ASC, d.id ASC`;return K(this.db.prepare(d),g).map(a=>this.mapDestRow(a))}fetchDestinationById(a){let b=L(this.db.prepare(`SELECT d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
|
|
685
|
+
d.network_json AS networkJson, d.last_seen AS lastSeenMs,
|
|
686
|
+
COALESCE(oh.decision, ol.decision) AS overrideDecision
|
|
687
|
+
FROM share_destination d
|
|
688
|
+
${bn}
|
|
689
|
+
WHERE d.id = ?`),[a]);return b?this.mapDestRow(b):null}fetchEndpoints(a){return 0===a.length?[]:K(this.db.prepare(`SELECT e.id, e.destination_id AS destinationId, e.method, e.transport, e.url,
|
|
690
|
+
e.template, e.data_class AS dataClass, e.last_seen AS lastSeenMs,
|
|
691
|
+
count(c.id) AS callSiteCount
|
|
692
|
+
FROM share_endpoint e
|
|
693
|
+
LEFT JOIN share_call_site c ON c.endpoint_id = e.id
|
|
694
|
+
WHERE e.destination_id IN (${B(a.length)})
|
|
695
|
+
GROUP BY e.id
|
|
696
|
+
ORDER BY e.created_at ASC, e.id ASC`),a).map(a=>({id:a.id,destinationId:a.destinationId,method:a.method,transport:a.transport,url:a.url,template:1===a.template,dataClass:a.dataClass,lastSeenMs:a.lastSeenMs,callSiteCount:a.callSiteCount}))}groupEndpoints(a){let b=new Map;for(let c of this.fetchEndpoints(a)){let a=b.get(c.destinationId);a?a.push(c):b.set(c.destinationId,[c])}return b}fetchCallSites(a){return 0===a.length?[]:K(this.db.prepare(`SELECT id, endpoint_id AS endpointId, project, file, line, snippet, dynamic, vendored,
|
|
697
|
+
project_id AS projectId
|
|
698
|
+
FROM share_call_site
|
|
699
|
+
WHERE endpoint_id IN (${B(a.length)})
|
|
700
|
+
ORDER BY created_at ASC, id ASC`),a).map(a=>({id:a.id,endpointId:a.endpointId,project:a.project,file:a.file,line:a.line,snippet:a.snippet,dynamic:1===a.dynamic,vendored:1===a.vendored,projectId:a.projectId}))}}class br{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO source_project
|
|
701
|
+
(id, url, name, attributes, first_seen, last_seen)
|
|
702
|
+
VALUES
|
|
703
|
+
(:id, :url, :name, :attributes, :firstSeen, :lastSeen)
|
|
704
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
705
|
+
url = excluded.url,
|
|
706
|
+
name = excluded.name,
|
|
707
|
+
attributes = excluded.attributes,
|
|
708
|
+
last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){let c=i(a.url),d=(0,g.QCA)(a,c,b);return this.upsertStmt.run(N({id:d.id,url:d.url,name:d.name,attributes:d.attributes,firstSeen:d.firstSeen,lastSeen:d.lastSeen})),c}findById(a){return L(this.db.prepare("SELECT * FROM source_project WHERE id = :id"),{id:a})}distinctNames(){return K(this.db.prepare(`SELECT DISTINCT name FROM source_project
|
|
709
|
+
WHERE name IS NOT NULL
|
|
710
|
+
ORDER BY name`)).map(a=>a.name)}}let bs=Symbol("aka.persistence.unsafeTestOnlyRawHandle");function bt(a,b){return b?{...a,hostId:b}:a}function bu(a){try{a.close()}catch{}}function bv(a){let b=new f.DatabaseSync(a);try{b.exec("PRAGMA journal_mode = WAL"),b.exec("PRAGMA busy_timeout = 2000"),b.exec("PRAGMA foreign_keys = ON")}catch(a){throw bu(b),a}return b}function bw(a){o(a);let{db:b,events:c,findings:f,policies:l,installedPacks:n,scanLedger:q,secretVault:s,exceptions:t,resolutions:u,ruleProbeCache:v,security:w,detections:B,shares:C,policyCatalog:D,inventory:E,inventoryAssets:K,projectFiles:L,activity:M,sourceProject:O,auditEvents:P,classifiedData:Q,inspectionDefinitions:W,inspectionFindings:X,configInventory:Y}=function(a){let b=bv(a);try{var c;if(c=b,I(c,"table","tenants")||J(c,"events").includes("tenant_id")){let c=function(a,b){let c;y(b);let d=x(b,"legacy"),e=!1;try{z(a,d),e=!0}catch(a){c=a}finally{a.close()}if(!e){H(`Could not snapshot the incompatible ${m} (${String(c)}); moving the store aside with its sidecars instead.`);let a=[];(0,k.renameSync)(b,d),a.push([d,b]);try{for(let c of p(b)){let e=`${d}${c.slice(b.length)}`;try{(0,k.renameSync)(c,e),a.push([e,c])}catch{(0,k.rmSync)(c,{force:!0})}}}catch(b){for(let[b,c]of a.reverse())try{(0,k.renameSync)(b,c)}catch{}throw b}return r(d),d}try{for(let a of((0,k.rmSync)(b,{force:!0}),p(b)))(0,k.rmSync)(a,{force:!0})}catch(a){if((0,k.existsSync)(b))try{(0,k.rmSync)(d,{force:!0})}catch{}throw a}return d}(b,a);b=bv(a),H(`Detected an older, incompatible (tenant-bearing) ${m}; backed it up to ${c} and created a fresh store.`)}!function(a,b){var c,d,e;let f=a.prepare("PRAGMA user_version").get().user_version;a.exec("CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)");let h=new Set(a.prepare("SELECT tag FROM migration_ledger").all().map(a=>a.tag)),k=0===h.size&&f>0,l=a.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)");for(let[b,c]of g.lFU.entries()){if(h.has(c.tag)||c.tag===T)continue;let d=function(a){let b=[];for(let c of a.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?`([^`]+)`/g))void 0===c[1]||c[1].startsWith("__new_")||b.push({kind:"table",name:c[1]});for(let c of a.matchAll(/ALTER TABLE `([^`]+)` ADD (?:COLUMN )?`([^`]+)`/g))void 0!==c[1]&&void 0!==c[2]&&b.push({kind:"column",table:c[1],name:c[2]});return b}(c.sql),e=d.filter(b=>"column"===b.kind?J(a,b.table,{includeGenerated:!0}).includes(b.name):I(a,"table",b.name));if(e.length>0&&e.length<d.length){let a=d.filter(a=>!e.includes(a)),b=`sqlite migration ${c.tag} has no ledger row, but the store already has ${e.map(R).join(", ")} while missing ${a.map(R).join(", ")} — the schema diverged from the migration history; refusing to replay or skip.`;throw H(b),Error(`[aka] ${b}`)}let g=d.length>0?e.length===d.length:k&&b<f,i=/PRAGMA foreign_keys\s*=\s*OFF/i.test(c.sql),j=S(c.sql);i&&a.exec("PRAGMA foreign_keys = OFF");try{F(a,()=>{for(let b of j){let c=function(a){let b=a.replace(/^(?:\s*--[^\n]*\n?)+/,"").trimStart();return/^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(b)?.[1]}(b);if(void 0===c){if(g)continue}else if(I(a,"index",c))continue;a.exec(b)}if(i&&!g){let b=a.prepare("PRAGMA foreign_key_check").all();if(b.length>0)throw Error(`[aka] sqlite migration ${c.tag} left ${String(b.length)} foreign-key violation(s); rolling back.`)}l.run(c.tag,Date.now())},"IMMEDIATE")}finally{i&&a.exec("PRAGMA foreign_keys = ON")}}f<g.lFU.length&&a.exec(`PRAGMA user_version = ${String(g.lFU.length)}`),c=a,d="audit_events",I(c,"table",d)&&(J(c,d).includes("synced_at")||c.exec(`ALTER TABLE ${d} ADD COLUMN synced_at integer`)),a.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
|
|
711
|
+
path TEXT PRIMARY KEY,
|
|
712
|
+
mtime TEXT NOT NULL,
|
|
713
|
+
content_hash TEXT NOT NULL,
|
|
714
|
+
ruleset_hash TEXT NOT NULL,
|
|
715
|
+
scanned_at INTEGER NOT NULL
|
|
716
|
+
)`),a.exec(`CREATE TABLE IF NOT EXISTS blocked_detections (
|
|
717
|
+
reference TEXT PRIMARY KEY,
|
|
718
|
+
rule_id TEXT NOT NULL,
|
|
719
|
+
category TEXT NOT NULL,
|
|
720
|
+
value_fingerprint TEXT NOT NULL,
|
|
721
|
+
key_version INTEGER NOT NULL,
|
|
722
|
+
masked_value TEXT NOT NULL,
|
|
723
|
+
session_id TEXT,
|
|
724
|
+
repo TEXT,
|
|
725
|
+
blocked_at INTEGER NOT NULL
|
|
726
|
+
)`),a.exec(`CREATE TABLE IF NOT EXISTS rule_probe_cache (
|
|
727
|
+
rule_key TEXT PRIMARY KEY,
|
|
728
|
+
verdict TEXT NOT NULL,
|
|
729
|
+
worst_probe_ms REAL NOT NULL,
|
|
730
|
+
checked_at INTEGER NOT NULL
|
|
731
|
+
)`),(e=a).exec(`CREATE TABLE IF NOT EXISTS \`_pack_write_gate\` (
|
|
732
|
+
\`id\` integer PRIMARY KEY NOT NULL,
|
|
733
|
+
\`open\` integer DEFAULT 0 NOT NULL,
|
|
734
|
+
CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)
|
|
735
|
+
)`),e.exec("INSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0)"),I(e,"table","installed_packs")&&e.exec(`CREATE TRIGGER IF NOT EXISTS trg_installed_packs_write_gate
|
|
736
|
+
BEFORE UPDATE OF version, name, rules_json ON installed_packs
|
|
737
|
+
WHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1
|
|
738
|
+
BEGIN SELECT RAISE(IGNORE); END`),function(a){if(!I(a,"table","audit_events"))return;let b=new Set(J(a,"audit_events",{includeGenerated:!0}));for(let c of U)b.has(c.name)||a.exec(c.ddl)}(a),function(a){try{let b=a.prepare(`SELECT id, url, name, attributes, first_seen AS firstSeen, last_seen AS lastSeen
|
|
739
|
+
FROM source_project
|
|
740
|
+
WHERE url IS NOT NULL AND id NOT LIKE 'sample:%'
|
|
741
|
+
ORDER BY last_seen DESC, id`).all().map(a=>({row:a,canonicalId:i(a.url)})).filter(({row:a,canonicalId:b})=>a.id!==b);if(0===b.length)return;let c=a.prepare(`INSERT INTO source_project (id, url, name, attributes, first_seen, last_seen)
|
|
742
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
743
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
744
|
+
first_seen = min(first_seen, excluded.first_seen),
|
|
745
|
+
last_seen = max(last_seen, excluded.last_seen)`),d=a.prepare("UPDATE audit_events SET source_project_id = ? WHERE source_project_id = ?"),e=a.prepare("UPDATE share_call_site SET project_id = ? WHERE project_id = ?"),f=["project_file","file_access_override"].map(b=>({dropCollisions:a.prepare(`DELETE FROM ${b} WHERE project_id = ?
|
|
746
|
+
AND path IN (SELECT path FROM ${b} WHERE project_id = ?)`),repoint:a.prepare(`UPDATE ${b} SET project_id = ? WHERE project_id = ?`)})),g=a.prepare("DELETE FROM source_project WHERE id = ?");F(a,()=>{for(let{row:a,canonicalId:h}of b){for(let{dropCollisions:b,repoint:e}of(c.run(h,a.url,a.name,a.attributes,a.firstSeen,a.lastSeen),d.run(h,a.id),f))b.run(a.id,h),e.run(h,a.id);e.run(h,a.id),g.run(a.id)}},"IMMEDIATE")}catch(a){H(`source_project id reconcile failed: ${String(a)}`)}}(a),!h.has(T)&&function(a){try{if(!function(a){let b=a.prepare(`SELECT rowid AS rowid, id, source_tool AS sourceTool, kind, occurred_at AS occurredAt,
|
|
747
|
+
content_hash AS contentHash, content, metadata
|
|
748
|
+
FROM events WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO audit_events
|
|
749
|
+
(id, parent_id, root_session_id, event_type, started_at, content, content_hash, attributes)
|
|
750
|
+
VALUES (:id, :parentId, :rootSessionId, :eventType, :startedAt, :content, :contentHash, :attributes)`),d=a.prepare("INSERT OR IGNORE INTO audit_events (id, event_type, started_at) VALUES (?, 'session', ?)");return V(a,"events",b,a=>{for(let e of a){var b;let a=function(a){if(null!==a)try{return JSON.parse(a)}catch{return}}(e.metadata),f=a?.sessionId??null;null!==f&&d.run(f,e.occurredAt),c.run(N({id:e.id,parentId:f,rootSessionId:f,eventType:e.kind,startedAt:e.occurredAt,content:e.content,contentHash:e.contentHash,attributes:(b={...e,metadata:a},JSON.stringify((0,g.$w9)({id:b.id,sourceTool:b.sourceTool,kind:b.kind,occurredAt:new Date(b.occurredAt).toISOString(),contentHash:b.contentHash,content:b.content,metadata:b.metadata})))}))}})}(a))return!1;let b=a.prepare(`SELECT rowid AS rowid, id, event_id AS eventId, rule_id AS ruleId, category, severity,
|
|
751
|
+
span_start AS spanStart, span_end AS spanEnd, masked_match AS maskedMatch,
|
|
752
|
+
action_taken AS actionTaken, confidence, finding_key AS findingKey,
|
|
753
|
+
first_detected_at AS firstDetectedAt
|
|
754
|
+
FROM findings WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
|
|
755
|
+
(id, rule_id, name, category, severity, definition, version)
|
|
756
|
+
VALUES (:id, :ruleId, :name, :category, :severity, :definition, :version)`),d=a.prepare(`INSERT INTO inspection_findings
|
|
757
|
+
(id, audit_event_id, inspection_definition_id, classified_data_id,
|
|
758
|
+
span_start, span_end, masked_match, action_taken, confidence,
|
|
759
|
+
finding_key, first_detected_at)
|
|
760
|
+
VALUES
|
|
761
|
+
(:id, :auditEventId, :inspectionDefinitionId, NULL,
|
|
762
|
+
:spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
|
|
763
|
+
:findingKey, :firstDetectedAt)
|
|
764
|
+
ON CONFLICT(id) DO NOTHING
|
|
765
|
+
ON CONFLICT (finding_key) DO UPDATE SET
|
|
766
|
+
first_detected_at = CASE
|
|
767
|
+
WHEN first_detected_at IS NULL THEN excluded.first_detected_at
|
|
768
|
+
WHEN excluded.first_detected_at IS NULL THEN first_detected_at
|
|
769
|
+
ELSE min(first_detected_at, excluded.first_detected_at)
|
|
770
|
+
END`);return V(a,"findings",b,a=>{let b=new Map;for(let e of a){let a=JSON.stringify([e.ruleId,e.category,e.severity]),f=b.get(a);if(void 0===f){let d=`unmigrated/${e.category}/${e.severity}`;f=j(e.ruleId,d),c.run(N({id:f,ruleId:e.ruleId,name:e.ruleId,category:e.category,severity:e.severity,definition:"",version:d})),b.set(a,f)}d.run(N({id:e.id,auditEventId:e.eventId,inspectionDefinitionId:f,spanStart:e.spanStart,spanEnd:e.spanEnd,maskedMatch:e.maskedMatch,actionTaken:e.actionTaken,confidence:e.confidence,findingKey:e.findingKey,firstDetectedAt:e.firstDetectedAt}))}})}catch(a){return H(`legacy history backfill failed: ${String(a)}`),!1}}(a)&&function(a,b){let c=g.lFU.find(a=>a.tag===T);if(c){if(b)try{var d=a,e=b;y(e);let c=x(e,"pre-drop");z(d,c)}catch(a){H(`legacy events/findings backup failed; deferring the drop: ${String(a)}`);return}try{F(a,()=>{if(!a.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(c.tag)){for(let b of S(c.sql))a.exec(b);a.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(c.tag,Date.now())}},"IMMEDIATE")}catch(a){H(`legacy events/findings drop failed; deferring: ${String(a)}`)}}}(a,b)}(b,a),r(a);let d=new a1(b),e=new aL(b),f={events:new ar(b),findings:new aE(b),policies:d,installedPacks:e,scanLedger:new a6(b),secretVault:new bc(b),exceptions:new ax(b),resolutions:new a4(b),ruleProbeCache:new a5(b),security:new bk(b),detections:new aq(b),shares:new bq(b),policyCatalog:new a2(e),inventory:new aM(b),inventoryAssets:new a0(b),projectFiles:new a3(b),activity:new ai(b),sourceProject:new br(b),auditEvents:new aj(b),classifiedData:new ak(b),inspectionDefinitions:new aF(b),inspectionFindings:new aG(b),configInventory:new am(b)};return d.seedDefaults(),{db:b,...f}}catch(a){throw bu(b),a}}((0,e.join)(a,m));return{events:c,findings:f,policies:l,installedPacks:n,scanLedger:q,secretVault:s,exceptions:t,resolutions:u,ruleProbeCache:v,security:w,detections:B,shares:C,policyCatalog:D,inventory:E,inventoryAssets:K,activity:M,sourceProject:O,auditEvents:P,classifiedData:Q,inspectionDefinitions:W,inspectionFindings:X,recordCapture:function(a,c){G(b,()=>{let b=a.metadata?.sessionId;b&&P.ensureSessionRoot(b,a.occurredAt);let d=function(a,b,c=null){return h((0,g.tTV)(["capture",a??"no_session",b,c??"no_path"]))}(b??null,a.contentHash,a.metadata?.filePath??null);P.insertAuditEvent({id:d,eventType:a.kind,startedAt:a.occurredAt,parentId:b,rootSessionId:b,content:a.content,contentHash:a.contentHash,attributes:(0,g.$w9)(a)});let e=new Map;for(let a of c){if(b&&X.isSessionDuplicate(a.ruleId,a.maskedMatch,b)||X.isEventDuplicate(d,a.ruleId,a.maskedMatch,a.span.start,a.span.end))continue;let c=`${a.ruleId}@${(0,g.qmP)(a)}`,f=e.get(c);f||(f=W.upsert((0,g.jTf)(a)),e.set(c,f)),X.insertFinding({id:a.id,auditEventId:d,inspectionDefinitionId:f,span:a.span,maskedMatch:a.maskedMatch,actionTaken:a.actionTaken,confidence:a.confidence,findingKey:a.findingKey??void 0})}})},ensureInventory:function(a){let c={};return G(b,()=>{let b=Date.now();a.host&&(c.hostId=E.upsert(a.host,b)),a.harness&&(c.harnessId=E.upsert(bt(a.harness,c.hostId),b)),c.accountId=E.upsert(bt({objectType:"user",identityKey:"local",attributes:{source:"local"}},c.hostId),b),a.project&&(c.sourceProjectId=O.upsert(a.project,b))})?c:{}},recordConfigScan:function(a){G(b,()=>{let b=(0,g.I8t)(a.scanEvent.startedAt);for(let c of a.items)E.upsert(c,b);P.insertAuditEvent(a.scanEvent);let c=new Map;for(let b of a.definitions??[])c.set(`${b.ruleId}@${b.version}`,W.upsert(b));for(let b of a.findings??[]){let e=c.get(`${b.ruleId}@${b.version}`);e&&X.insertFinding({id:(0,d.randomUUID)(),auditEventId:a.scanEvent.id,inspectionDefinitionId:e,span:b.span,maskedMatch:b.maskedMatch,actionTaken:b.actionTaken,confidence:b.confidence})}})},recordProjectFiles:function(a,c){0!==c.files.length&&G(b,()=>{L.replaceForProject(a,c,Date.now())})},reconcileWorktreeProjects:function(a,c,d){try{let f=c.split(e.sep).join("/"),g=d.split(e.sep).join("/"),h=d===c?"":"url IN (:worktreePosix, :worktreeWin) OR ",i=b.prepare(`SELECT id FROM source_project
|
|
771
|
+
WHERE id <> :canonicalId
|
|
772
|
+
AND (${h}url LIKE :pattern ESCAPE '\\' OR url LIKE :patternWin ESCAPE '\\')`).all({canonicalId:a,...d===c?{}:{worktreePosix:g,worktreeWin:g.split("/").join("\\")},pattern:`${A(f)}/.claude/worktrees/%`,patternWin:`${A(f.split("/").join("\\"))}\\\\.claude\\\\worktrees\\\\%`});if(0===i.length)return;F(b,()=>{for(let{id:c}of i)b.prepare("UPDATE audit_events SET source_project_id = :canonicalId WHERE source_project_id = :id").run({canonicalId:a,id:c}),b.prepare("UPDATE OR IGNORE file_access_override SET project_id = :canonicalId WHERE project_id = :id").run({canonicalId:a,id:c}),b.prepare("DELETE FROM file_access_override WHERE project_id = :id").run({id:c}),b.prepare("DELETE FROM project_file WHERE project_id = :id").run({id:c}),b.prepare("DELETE FROM source_project WHERE id = :id").run({id:c})})}catch{}},configInventoryReport:()=>Y.report(),facets:function(){return{hosts:E.distinctTitles("host"),harnesses:E.distinctTitles("harness"),osVersions:E.osVersions(),projects:O.distinctNames()}},purgeSampleData:()=>{!function(a){try{if(!a.prepare(`SELECT (
|
|
773
|
+
EXISTS(SELECT 1 FROM share_destination WHERE provenance = 'sample')
|
|
774
|
+
OR EXISTS(SELECT 1 FROM audit_events WHERE id LIKE 'sample:activity:%')
|
|
775
|
+
OR EXISTS(SELECT 1 FROM inventory_asset WHERE provenance = 'sample')
|
|
776
|
+
) AS n`).get().n)return;F(a,()=>{a.exec(`DELETE FROM share_call_site WHERE endpoint_id IN (
|
|
777
|
+
SELECT e.id FROM share_endpoint e
|
|
778
|
+
JOIN share_destination d ON d.id = e.destination_id
|
|
779
|
+
WHERE d.provenance = 'sample')`),a.exec(`DELETE FROM egress_decision_override WHERE destination_id IN (
|
|
780
|
+
SELECT id FROM share_destination WHERE provenance = 'sample')`),a.exec(`DELETE FROM share_endpoint WHERE destination_id IN (
|
|
781
|
+
SELECT id FROM share_destination WHERE provenance = 'sample')`),a.exec("DELETE FROM share_destination WHERE provenance = 'sample'"),a.exec(`DELETE FROM harness_asset WHERE asset_id IN (SELECT id FROM inventory_asset WHERE provenance = 'sample')
|
|
782
|
+
OR harness_id IN (SELECT id FROM inventory WHERE object_type = 'harness' AND json_extract(attributes, '$.provenance') = 'sample')`),a.exec("DELETE FROM mcp_trust_override WHERE asset_id IN (SELECT id FROM inventory_asset WHERE provenance = 'sample')"),a.exec("DELETE FROM file_access_override WHERE project_id IN (SELECT id FROM source_project WHERE json_extract(attributes, '$.provenance') = 'sample')"),a.exec("DELETE FROM project_file WHERE project_id IN (SELECT id FROM source_project WHERE json_extract(attributes, '$.provenance') = 'sample')"),a.exec("DELETE FROM inventory_asset WHERE provenance = 'sample'"),a.exec("DELETE FROM source_project WHERE json_extract(attributes, '$.provenance') = 'sample'"),a.exec("DELETE FROM inventory WHERE object_type = 'harness' AND json_extract(attributes, '$.provenance') = 'sample'"),a.exec("DELETE FROM inspection_findings WHERE id LIKE 'sample:activity:%'"),a.exec("DELETE FROM inspection_definitions WHERE id LIKE 'sample:activity:%'"),a.exec("DELETE FROM audit_events WHERE root_session_id LIKE 'sample:activity:%'"),a.exec("DELETE FROM audit_events WHERE id LIKE 'sample:activity:%'"),a.exec(`CREATE TABLE IF NOT EXISTS app_meta (
|
|
783
|
+
key TEXT PRIMARY KEY,
|
|
784
|
+
value TEXT NOT NULL
|
|
785
|
+
)`),a.exec("DELETE FROM app_meta WHERE key LIKE 'sample_seeded:%'")})}catch{}}(b)},transaction:async function a(a){b.exec("BEGIN");try{let c=await a();return b.exec("COMMIT"),c}catch(a){try{b.exec("ROLLBACK")}catch{}throw a}},close:()=>{b.close()},[bs]:b}}var bx=c(48161);let by=new Set(["EEXIST","EACCES","EPERM","EBUSY"]),bz=new Int32Array(new SharedArrayBuffer(4));class bA extends Error{constructor(a,b,c,d,e){super(`cannot lock ${b} for writing: ${c}`+(void 0===d?"":` (held by pid ${String(d)})`),e),this.name="FileLockError",this.reason=a,this.file=b,this.holderPid=d}}function bB(a){let b;try{b=(0,k.readFileSync)(a,"utf8")}catch{return null}try{let{pid:a,token:c,at:d,host:e}=JSON.parse(b);if("number"!=typeof a||"string"!=typeof c||"number"!=typeof d)return null;return{pid:a,token:c,at:d,host:"string"==typeof e?e:""}}catch{return null}}function bC(a,b){let c,e=(0,d.randomUUID)();try{c=(0,k.openSync)(a,"wx",384)}catch(e){let c=e.code??"";if("EEXIST"===c||by.has(c)&&((0,k.existsSync)(a)||function(a){let b=`${a}.probe-${(0,d.randomUUID)()}`;try{return(0,k.closeSync)((0,k.openSync)(b,"wx",384)),!0}catch{return!1}finally{try{(0,k.rmSync)(b,{force:!0})}catch{}}}(a)))return null;throw new bA("unavailable",b,e instanceof Error?e.message:String(e),void 0,{cause:e})}let f={pid:process.pid,token:e,at:Date.now(),host:(0,bx.hostname)()};try{(0,k.writeFileSync)(c,`${JSON.stringify(f)}
|
|
786
|
+
`)}catch{try{(0,k.closeSync)(c)}catch{}return(0,k.rmSync)(a,{force:!0}),null}try{(0,k.closeSync)(c)}catch{}return e}function bD(a){let b=a.filePath.replaceAll("\\","/");return(0,d.createHash)("sha256").update(`${a.ruleId}\0${b}\0${a.valueFingerprint}`).digest("hex")}function bE(a){return(0,e.join)(a,"exception.key")}let bF={exceptions:"key_version",blocked_detections:"key_version",secret_vault:"fingerprint_key_version"};class bG extends Error{constructor(a){super(`cannot read the stored fingerprint key versions: ${a instanceof Error?a.message:String(a)}`,{cause:a}),this.code="floor-unreadable",this.name="FloorUnreadableError"}}function bH(a){let b,c=(0,e.join)(a,m);if(!(0,k.existsSync)(c))return 0;try{(b=new f.DatabaseSync(c,{readOnly:!0})).exec(`PRAGMA busy_timeout = ${String(250)}`);let a=0;for(let[c,d]of Object.entries(bF))try{let e=L(b.prepare(`SELECT MAX(${d}) AS v FROM ${c}`));a=Math.max(a,e?.v??0)}catch(a){if(1!==a.errcode)throw new bG(a)}return a}catch(a){throw a instanceof bG?a:new bG(a)}finally{b?.close()}}function bI(a){return JSON.stringify({version:a.version,material:a.material.toString("base64")})}function bJ(a){let b;try{b=(0,k.readFileSync)(bE(a),"utf8")}catch(a){if("ENOENT"===a.code)return null;throw a instanceof Error?a:Error(String(a))}let c=JSON.parse(b);if("object"!=typeof c||null===c)throw Error("exception key file is corrupt: not a JSON object");let{version:d,material:e}=c;if("number"!=typeof d||!Number.isInteger(d)||d<1)throw Error("exception key file is corrupt: bad version");if("string"!=typeof e)throw Error("exception key file is corrupt: bad material");let f=Buffer.from(e,"base64");if(32!==f.length)throw Error("exception key file is corrupt: bad material length");return{version:d,material:f}}function bK(a){let b=bJ(a);return b?(q(bE(a)),b):function(a,b){o(a);let c=bE(a);if(v(c,`${bI(b)}
|
|
787
|
+
`))return b;let d=bJ(a);if(d)return q(c),d;let e=t(c);throw new u(function(a,b){switch(b){case"symlink":return`exception key file is a symlink (${a}); remove it so a key can be created`;case"gone":return"exception key file was removed while it was being created";case"unknown":return`exception key file (${a}) is occupied but cannot be inspected; check the permissions on its directory`}}(c,e.kind),e.cause)}(a,{version:bH(a)+1,material:(0,d.randomBytes)(32)})}function bL(a){var b;let c=bJ(a);return b={version:Math.max(c?.version??0,bH(a))+1,material:(0,d.randomBytes)(32)},o(a),s(bE(a),`${bI(b)}
|
|
788
|
+
`),b}function bM(a,b){return(0,d.createHmac)("sha256",a.material).update(b,"utf8").digest("hex")}function bN(a,b){var c;return(0,g.qEQ)(b,null===(c=a)?{status:"absent"}:{status:"present",version:c.version})}function bO(){return(0,e.join)((0,bx.homedir)(),".aka")}function bP(a=bO()){return(0,e.join)(a,"settings")}function bQ(a=bO()){return(0,e.join)(a,"data")}function bR(a=bO()){return(0,e.join)(a,"keys")}c(51455);let bS="settings.json";function bT(a=bO()){let b=function(a){let b;try{b=(0,k.readFileSync)(a,"utf8")}catch{return null}return X(b)??null}((0,e.join)(bP(a),bS));if(!b)return(0,g.i1j)();try{return g.hd_.parse(b)}catch{return(0,g.i1j)()}}function bU(a,b=bO()){let c=bP(b);o(c);let d=(0,e.join)(c,bS);return function(a,b,c={}){let d=c.timeoutMs??5e3,e=c.staleMs??2e3,f=`${a}.lock`,g=Date.now()+d,h=bC(f,a);for(;null===h;){if(function(a,b){let c,d=`${a}.break`;try{c=(0,k.openSync)(d,"wx",384)}catch{return function(a){try{Date.now()-(0,k.statSync)(a).mtimeMs>=1e4&&(0,k.rmSync)(a,{force:!0})}catch{}}(d),!1}try{(0,k.closeSync)(c)}catch{}try{if(!(0,k.existsSync)(a)||!function(a,b,c){var d;if(!a)try{return Date.now()-(0,k.statSync)(b).mtimeMs>=c}catch{return!1}return!(Date.now()-a.at<c)&&(!(a.host===(0,bx.hostname)()&&function(a){if(!Number.isInteger(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"ESRCH"!==a.code}}(a.pid))||Date.now()-a.at>=(d=c,Math.max(30*d,6e4)))}(bB(a),a,b))return!1;return(0,k.rmSync)(a,{force:!0}),!0}catch{return!1}finally{try{(0,k.rmSync)(d,{force:!0})}catch{}}}(f,e)){h=bC(f,a);continue}if(Date.now()>=g)throw new bA("timeout",a,`still held after ${String(d)}ms`,bB(f)?.pid);Atomics.wait(bz,0,0,5),h=bC(f,a)}try{var i;let c=b();if(i=c,"object"==typeof i&&null!==i&&"function"==typeof i.then)throw c.then(()=>void 0,()=>void 0),TypeError(`withFileLock(${a}) was given an async body; the lock is released as soon as it returns, so the awaited work would run unguarded. Pass a synchronous function.`);return c}finally{!function(a,b){try{if(bB(a)?.token!==b)return;(0,k.rmSync)(a,{force:!0})}catch{}}(f,h)}}(d,()=>{let c=bT(b),e="function"==typeof a?a(c):a,f=g.hd_.parse({...c,...e,onboardedAt:e.onboardedAt??c.onboardedAt??new Date().toISOString()});return s(d,`${JSON.stringify(f,null,2)}
|
|
789
|
+
`),f})}let bV="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function bW(a){let b="",c=0,d=0;for(let e of a)for(c=c<<8|e,d+=8;d>=5;)b+=bV.charAt(c>>>d-5&31),d-=5;return d>0&&(b+=bV.charAt(c<<5-d&31)),b}function bX(a){let b=[],c=0,d=0;for(let e of a){let a=bV.indexOf(e);if(a<0)throw Error("base32: character outside the alphabet");c=c<<5|a,(d+=5)>=8&&(b.push(c>>>d-8&255),d-=8)}return Buffer.from(b)}function bY(a){if(!Number.isInteger(a)||a<1||a>0xffffffff)throw Error("vault: key version out of range");let b=[],c=a;for(;c>0;)b.unshift(255&c),c=Math.floor(c/256);return bW(Uint8Array.from(b))}function bZ(a){let b=b=>Buffer.from((0,d.hkdfSync)("sha256",a,"aka:vault:v1",b,32));return{enc:b("aka:vault:enc:v1"),sign:b("aka:vault:sign:v1")}}function b$(a,b,c,d=g.viY){if(16!==b.length)throw Error("vault: pointer id must be 16 bytes");let e=Buffer.alloc(6);return e.writeUInt16BE(d,0),e.writeUInt32BE(a,2),Buffer.concat([e,Buffer.from(b),Buffer.from(c,"utf8")])}function b_(a,b,c,e){let f=(0,d.createCipheriv)("aes-256-gcm",a,e);return f.setAAD(c),{ciphertext:Buffer.concat([f.update(b,"utf8"),f.final()]),nonce:e,authTag:f.getAuthTag()}}function b0(a,b,c){try{let e=(0,d.createDecipheriv)("aes-256-gcm",a,b.nonce);return e.setAAD(c),e.setAuthTag(b.authTag),Buffer.concat([e.update(b.ciphertext),e.final()]).toString("utf8")}catch{return null}}function b1(a,b,c,e){return(0,d.createHmac)("sha256",a).update(b$(b,c,e,g.viY)).digest().subarray(0,10)}function b2(a,b,c,e,f){if(10!==f.length)return!1;let g=b1(a,b,c,e);return(0,d.timingSafeEqual)(g,Buffer.from(f))}var b3=c(31421);let b4={symlink:"the path is a symlink; remove it so a keyring can be created",gone:"the path was occupied but holds no keyring (removed while it was being created)",unknown:"the path is occupied but cannot be inspected; check the permissions on its directory"};class b5 extends Error{constructor(a){super(`vault: key epoch ${String(a)} is not present in the keyring`),this.name="VaultKeyEpochMissingError",this.version=a}}let b6="vault.key",b7="aka-vault",b8="keyring";function b9(a){let b=JSON.parse(a);if("object"!=typeof b||null===b)throw Error("vault key file is corrupt: not a JSON object");let{current:c,keys:d}=b;if("number"!=typeof c||!Number.isInteger(c)||c<1)throw Error("vault key file is corrupt: bad current version");if("object"!=typeof d||null===d||Array.isArray(d))throw Error("vault key file is corrupt: bad keys map");let e=new Map;for(let[a,b]of Object.entries(d)){let c=Number(a);if(!Number.isInteger(c)||c<1)throw Error("vault key file is corrupt: bad key version");if("string"!=typeof b)throw Error("vault key file is corrupt: bad key material");let d=Buffer.from(b,"base64");if(32!==d.length)throw Error("vault key file is corrupt: bad key material length");e.set(c,d)}if(!e.has(c))throw Error("vault key file is corrupt: current version has no material");return{current:c,keys:e}}function ca(a){let b={};for(let c of[...a.keys.keys()].sort((a,b)=>a-b)){let d=a.keys.get(c);d&&(b[String(c)]=d.toString("base64"))}return JSON.stringify({current:a.current,keys:b})}function cb(){return{current:1,keys:new Map([[1,(0,d.randomBytes)(32)]])}}function cc(a){let b=Math.max(...a.keys.keys())+1,c=new Map(a.keys);return c.set(b,(0,d.randomBytes)(32)),{current:b,keys:c}}function cd(a){let b=a.keys.get(a.current);if(!b)throw new b5(a.current);return{material:b,version:a.current}}function ce(a,b){let c=a.keys.get(b);if(!c)throw new b5(b);return{material:c,version:b}}function cf(a){try{return Promise.resolve(a())}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}function cg(a){return a instanceof Error?a:Error(String(a))}let ch="owner",ci="vault: a key rotation is already in progress";function cj(a,b){try{(0,k.mkdirSync)(a)}catch(a){if("EEXIST"===a.code)return!1;throw cg(a)}try{return(0,k.writeFileSync)((0,e.join)(a,ch),`${b}
|
|
790
|
+
`,{mode:384}),!0}catch(b){throw(0,k.rmSync)(a,{recursive:!0,force:!0}),cg(b)}}function ck(a,b){o(a);let c=function(a){let b,c=(0,e.join)(a,`${b6}.lock`),f=(0,d.randomBytes)(16).toString("hex");if(cj(c,f))return{lock:c,owner:f};try{b=(0,k.statSync)(c)}catch{throw Error(ci)}if(Date.now()-b.mtimeMs<6e4)throw Error(ci);let g=`${c}.stale.${f}`;try{let a=(0,k.statSync)(c);if(a.ino!==b.ino||a.mtimeMs!==b.mtimeMs)throw Error(ci);(0,k.renameSync)(c,g)}catch(a){if(a instanceof Error&&a.message===ci)throw a;throw Error(ci,{cause:a})}if((0,k.rmSync)(g,{recursive:!0,force:!0}),!cj(c,f))throw Error(ci);return{lock:c,owner:f}}(a);try{return b()}finally{!function(a){try{if((0,k.readFileSync)((0,e.join)(a.lock,ch),"utf8").trim()!==a.owner)return}catch{return}(0,k.rmSync)(a.lock,{recursive:!0,force:!0})}(c)}}class cl{#a;constructor(a){this.#a=a}get filePath(){return(0,e.join)(this.#a,b6)}loadOrCreate(){return cf(()=>{let a=this.#b();return a?(cm(this.filePath),cd(a)):cd(this.#c())})}rotate(){return cf(()=>ck(this.#a,()=>{let a=this.#b();return a?cd(this.#d(cc(a))):cd(this.#c())}))}materialFor(a){return cf(()=>{let b=this.#b();if(!b)throw new b5(a);return ce(b,a)})}#b(){let a;try{a=(0,k.readFileSync)(this.filePath,"utf8")}catch(a){if("ENOENT"===a.code)return null;throw a instanceof Error?a:Error(String(a))}return b9(a)}#c(){o(this.#a);let a=cb();if(v(this.filePath,`${ca(a)}
|
|
791
|
+
`))return a;let b=this.#b();if(!b){let a=t(this.filePath);throw new u(`vault: cannot create a key file at ${this.filePath} — ${b4[a.kind]}`,a.cause)}return cm(this.filePath),b}#d(a){o(this.#a);let b=this.filePath,c=`${b}.tmp`;return(0,k.writeFileSync)(c,`${ca(a)}
|
|
792
|
+
`,{mode:384}),(0,k.renameSync)(c,b),cm(b),a}}function cm(a){try{(0,k.chmodSync)(a,384)}catch{}}let cn=a=>(0,b3.execFileSync)("/usr/bin/security",a,{encoding:"utf8",stdio:["ignore","pipe","ignore"]});class co{#a;#e;constructor(a,b=cn){if(b===cn&&"darwin"!==process.platform)throw Error(`keychain custody is not available on this platform (${process.platform}); use file custody`);this.#a=a,this.#e=b}get keysDir(){return this.#a}loadOrCreate(){return cf(()=>{let a=this.#b();return a?cd(a):cd(this.#f(cb()))})}rotate(){return cf(()=>ck(this.#a,()=>{let a=this.#b();return a?cd(this.#g(cc(a))):cd(this.#f(cb()))}))}materialFor(a){return cf(()=>{let b=this.#b();if(!b)throw new b5(a);return ce(b,a)})}#b(){let a;try{a=this.#e(["find-generic-password","-s",b7,"-a",b8,"-w"])}catch(a){if(44===a.status)return null;throw Error(`vault: keychain read failed (${a instanceof Error?a.message:String(a)}); refusing to treat the failure as an absent keyring`,{cause:a})}let b=a.trim();return 0===b.length?null:b9(b)}#f(a){let b=["add-generic-password","-s",b7,"-a",b8,"-w",ca(a)];try{this.#e(b)}catch(b){let a=this.#b();if(a)return a;throw cg(b)}return a}#g(a){return this.#e(["add-generic-password","-U","-s",b7,"-a",b8,"-w",ca(a)]),a}}function cp(a,b){return"keychain"===a?new co(b):new cl(b)}let cq=Symbol("aka.vault.consentAbsent"),cr=Symbol("aka.vault.unavailable");function cs(a){if(!g.XZo.test(a))return null;let b=a.slice(6,-2),c=b.indexOf(":");if(c<0)return null;let d=b.slice(0,c),[e,f,h]=b.slice(c+1).split(".");if(void 0===e||void 0===f||void 0===h)return null;try{let a=function(a){let b=bX(a);if(0===b.length||b.length>4)throw Error("vault: bad key version encoding");let c=0;for(let a of b)c=256*c+a;if(c<1)throw Error("vault: bad key version");return c}(e),b=bX(f),c=bX(h);if(bY(a)!==e||bW(b)!==f||bW(c)!==h)return null;return{category:d,keyVersion:a,pointerId:b,tag:c}}catch{return null}}class ct{#h;#i;#j;#k;#l;constructor(a){this.#h=a.repo,this.#i=a.keys,this.#j=a.isConsented,this.#k=a.verifyGrant,this.#l=a.now??(()=>Date.now())}async tokenize(a,b,c){if(!this.#j())return cq;let e=c(),f=bM(e,a),h=this.#h.byValueFingerprint(f),i=this.#l();if(h)return this.#h.upsert({...h,provider:h.provider??void 0},i),await this.#m(h.keyVersion,h.pointerId,h.category);let{material:j,version:k}=await this.#i.loadOrCreate(),l=bZ(j),m=(0,d.randomBytes)(16),n=b$(k,m,b.category,g.viY),o=b_(l.enc,a,n,(0,d.randomBytes)(12)),{row:p}=this.#h.upsert({pointerId:bW(m),valueFingerprint:f,fingerprintKeyVersion:e.version,keyVersion:k,formatVersion:g.viY,category:b.category,ruleId:b.ruleId,maskedMatch:b.maskedMatch,provider:b.provider,ciphertext:o.ciphertext.toString("base64"),nonce:o.nonce.toString("base64"),authTag:o.authTag.toString("base64")},i);return await this.#m(p.keyVersion,p.pointerId,p.category)}async detokenize(a,b){let c,d,e=cs(a);if(!e)return cr;try{let a=await this.#i.materialFor(e.keyVersion);c=bZ(a.material).sign}catch{return cr}if(!b2(c,e.keyVersion,e.pointerId,e.category,e.tag))return cr;let f=bW(e.pointerId),g=this.#h.byPointerId(f);if(!g)return this.#n(f,b,"unavailable"),cr;if(g.category!==e.category)return cr;if("model"===b.target){let a,c=b.grantId,d=this.#k;if(void 0===d||void 0===c||""===c)return this.#n(f,b,"refused"),cr;try{a=await d(c,{ruleId:g.ruleId,valueFingerprint:g.valueFingerprint,fingerprintKeyVersion:g.fingerprintKeyVersion})}catch{a=!1}if(!a)return this.#n(f,b,"refused"),cr}try{let a=await this.#i.materialFor(g.keyVersion);d=b0(bZ(a.material).enc,{ciphertext:Buffer.from(g.ciphertext,"base64"),nonce:Buffer.from(g.nonce,"base64"),authTag:Buffer.from(g.authTag,"base64")},b$(g.keyVersion,e.pointerId,g.category,g.formatVersion))}catch{d=null}return null===d?(this.#n(f,b,"unavailable"),cr):(this.#n(f,b,"revealed"),d)}async revealEntry(a,b){let c=this.#h.byPointerId(a);if(!c)return this.#n(a,{target:"human",reason:b.reason},"unavailable"),cr;let d=await this.#o(c);return null===d?(this.#n(a,{target:"human",reason:b.reason},"unavailable"),cr):(this.#n(a,{target:"human",reason:b.reason},"revealed"),d)}async describePointer(a){let b=await this.#p(a);return b?{category:b.category,...void 0===b.provider?{}:{provider:b.provider},maskedMatch:b.maskedMatch,occurrences:b.occurrenceCount,firstSeen:new Date(b.firstSeen).toISOString(),lastSeen:new Date(b.lastSeen).toISOString()}:null}async resolvePointerIdentity(a){let b=await this.#p(a);return b?{ruleId:b.ruleId,valueFingerprint:b.valueFingerprint,fingerprintKeyVersion:b.fingerprintKeyVersion}:null}async rotateVaultKey(){let a=await this.#i.rotate(),b=bZ(a.material).enc,c=0;for(let e of this.#h.listAll()){let f;if(e.keyVersion===a.version)continue;let g=bX(e.pointerId);try{let a=await this.#i.materialFor(e.keyVersion);f=b0(bZ(a.material).enc,{ciphertext:Buffer.from(e.ciphertext,"base64"),nonce:Buffer.from(e.nonce,"base64"),authTag:Buffer.from(e.authTag,"base64")},b$(e.keyVersion,g,e.category,e.formatVersion))}catch{f=null}if(null===f)continue;let h=b_(b,f,b$(a.version,g,e.category,e.formatVersion),(0,d.randomBytes)(12));this.#h.replaceCiphertext(e.pointerId,{keyVersion:a.version,ciphertext:h.ciphertext.toString("base64"),nonce:h.nonce.toString("base64"),authTag:h.authTag.toString("base64")}),c+=1}return{version:a.version,reEncrypted:c}}async refreshFingerprints(a){let b=0;for(let c of this.#h.listAll())try{let d=await this.#o(c);if(null===d)continue;this.#h.refreshFingerprint(c.pointerId,{valueFingerprint:bM(a,d),fingerprintKeyVersion:a.version}),b+=1}catch{continue}return b}purgeVault(){let a=this.#h.purgeAll();return this.#h.recordDeref({id:(0,d.randomUUID)(),pointerId:"*",at:this.#l(),target:"human",reason:"purge",outcome:"unavailable",pointerCount:Math.max(a,1)}),a}async #m(a,b,c){var d;let e=bX(b),f=bZ((await this.#i.materialFor(a)).material).sign;return d=b1(f,a,e,c),`[[aka:${c}:${bY(a)}.${bW(e)}.${bW(d)}]]`}async #o(a){try{let b=await this.#i.materialFor(a.keyVersion);return b0(bZ(b.material).enc,{ciphertext:Buffer.from(a.ciphertext,"base64"),nonce:Buffer.from(a.nonce,"base64"),authTag:Buffer.from(a.authTag,"base64")},b$(a.keyVersion,bX(a.pointerId),a.category,a.formatVersion))}catch{return null}}async #p(a){let b=cs(a);if(!b)return null;try{let a=await this.#i.materialFor(b.keyVersion),c=bZ(a.material).sign;if(!b2(c,b.keyVersion,b.pointerId,b.category,b.tag))return null}catch{return null}let c=this.#h.byPointerId(bW(b.pointerId));return c?.category!==b.category?null:c}#n(a,b,c){this.#h.recordDeref({id:(0,d.randomUUID)(),pointerId:a,at:this.#l(),target:b.target,reason:b.reason,outcome:c,...void 0===b.grantId?{}:{grantId:b.grantId},pointerCount:(0,g.kqf)(b.reason)?b.pointerCount??1:1})}}},38172:(a,b,c)=>{c.d(b,{S8C:()=>y,hxQ:()=>av,Itg:()=>aj,Nh0:()=>b_,QcD:()=>b$,RRF:()=>ba,ZpU:()=>bd,HUb:()=>a9,hfB:()=>ap,unw:()=>bc,b2L:()=>Q,goN:()=>N,Jr:()=>be,hdu:()=>cL,mBk:()=>cK,gbA:()=>v,V8B:()=>aQ,IgC:()=>a5,aIg:()=>bJ,iRC:()=>aR,GCf:()=>E,agn:()=>b0,TUN:()=>U,SHn:()=>aB,rov:()=>cY,V0H:()=>a8,mzG:()=>R,v5Q:()=>O,OVs:()=>cP,LsM:()=>cN,bm0:()=>cO,u8Q:()=>cM,kxf:()=>cV,viY:()=>cv,XZo:()=>cy,jUf:()=>cA,PEm:()=>a3,eI7:()=>dc,cqq:()=>F,eYL:()=>b1,JJC:()=>b2,jON:()=>a_,lFU:()=>d,PhW:()=>ah,uQz:()=>cX,BIx:()=>ax,DzG:()=>cS,NFD:()=>cR,hd_:()=>c$,_5V:()=>ct,tXp:()=>cg,plk:()=>bD,mAj:()=>ca,Fnc:()=>dV,ryv:()=>r,tTV:()=>ag,qmP:()=>c7,_6W:()=>ci,rG:()=>ck,Bfj:()=>cf,fj8:()=>cp,q_t:()=>p,i1j:()=>c_,xog:()=>b9,hzO:()=>dX,by7:()=>dW,Gw9:()=>dT,q11:()=>h,U7X:()=>w,JB8:()=>b8,kqf:()=>cF,y_0:()=>dU,qEQ:()=>aS,hds:()=>cU,I8t:()=>g,am1:()=>cm,SSj:()=>cs,K7s:()=>b3,jwX:()=>cz,DhA:()=>bf,WSs:()=>d$,a45:()=>bB,N6N:()=>f,A6E:()=>cj,pnU:()=>bC,V9M:()=>c2,$w9:()=>c6,jTf:()=>c8,$BP:()=>c3,JAl:()=>c4,$3l:()=>c5,MgS:()=>cq,gzP:()=>c0,QCA:()=>c1,C05:()=>dY});let d=[{tag:"0000_acoustic_felicia_hardy",sql:"CREATE TABLE `audit_events` (\n `id` text PRIMARY KEY NOT NULL,\n `parent_id` text,\n `root_session_id` text,\n `event_type` text NOT NULL,\n `host_id` text,\n `harness_id` text,\n `source_project_id` text,\n `started_at` integer NOT NULL,\n `ended_at` integer,\n `severity` text,\n `priority` text,\n `content` text,\n `content_hash` text,\n `attributes` text,\n FOREIGN KEY (`parent_id`) REFERENCES `audit_events`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`root_session_id`) REFERENCES `audit_events`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`host_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`harness_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`source_project_id`) REFERENCES `source_project`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_parent` ON `audit_events` (`parent_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_session` ON `audit_events` (`root_session_id`,`started_at`);--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_harness_t` ON `audit_events` (`harness_id`,`started_at`);--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_project_t` ON `audit_events` (`source_project_id`,`started_at`);--\x3e statement-breakpoint\nCREATE TABLE `classified_data` (\n `id` text PRIMARY KEY NOT NULL,\n `class` text NOT NULL,\n `label` text,\n `attributes` text\n);\n--\x3e statement-breakpoint\nCREATE TABLE `events` (\n `id` text PRIMARY KEY NOT NULL,\n `source_tool` text NOT NULL,\n `kind` text NOT NULL,\n `occurred_at` integer NOT NULL,\n `content_hash` text NOT NULL,\n `content` text NOT NULL,\n `metadata` text\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_events_occurred` ON `events` (`occurred_at`);--\x3e statement-breakpoint\nCREATE TABLE `findings` (\n `id` text PRIMARY KEY NOT NULL,\n `event_id` text NOT NULL,\n `rule_id` text NOT NULL,\n `category` text NOT NULL,\n `severity` text NOT NULL,\n `span_start` integer NOT NULL,\n `span_end` integer NOT NULL,\n `masked_match` text NOT NULL,\n `action_taken` text NOT NULL,\n `confidence` real NOT NULL,\n FOREIGN KEY (`event_id`) REFERENCES `events`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_findings_event` ON `findings` (`event_id`);--\x3e statement-breakpoint\nCREATE TABLE `inspection_definitions` (\n `id` text PRIMARY KEY NOT NULL,\n `rule_id` text NOT NULL,\n `name` text NOT NULL,\n `category` text NOT NULL,\n `severity` text NOT NULL,\n `definition` text NOT NULL,\n `version` text NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE TABLE `inspection_findings` (\n `id` text PRIMARY KEY NOT NULL,\n `audit_event_id` text NOT NULL,\n `inspection_definition_id` text NOT NULL,\n `classified_data_id` text,\n `span_start` integer NOT NULL,\n `span_end` integer NOT NULL,\n `masked_match` text NOT NULL,\n `action_taken` text NOT NULL,\n `confidence` real NOT NULL,\n FOREIGN KEY (`audit_event_id`) REFERENCES `audit_events`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`inspection_definition_id`) REFERENCES `inspection_definitions`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`classified_data_id`) REFERENCES `classified_data`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event` ON `inspection_findings` (`audit_event_id`);--\x3e statement-breakpoint\nCREATE TABLE `installed_packs` (\n `id` text PRIMARY KEY NOT NULL,\n `namespace` text NOT NULL,\n `pack_id` text NOT NULL,\n `version` text NOT NULL,\n `name` text NOT NULL,\n `rules_json` text NOT NULL,\n `enabled` integer DEFAULT true NOT NULL,\n `policy_id` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_installed_packs_pack` ON `installed_packs` (`namespace`,`pack_id`);--\x3e statement-breakpoint\nCREATE TABLE `inventory` (\n `id` text PRIMARY KEY NOT NULL,\n `object_type` text NOT NULL,\n `location` text,\n `title` text,\n `host_id` text,\n `attributes` text NOT NULL,\n `os_version` text GENERATED ALWAYS AS (json_extract(attributes, '$.os_version')) VIRTUAL,\n `harness_version` text GENERATED ALWAYS AS (json_extract(attributes, '$.harness_version')) VIRTUAL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL,\n FOREIGN KEY (`host_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_type` ON `inventory` (`object_type`);--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_type_osver` ON `inventory` (`object_type`,`os_version`);--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_type_harnessver` ON `inventory` (`object_type`,`harness_version`);--\x3e statement-breakpoint\nCREATE TABLE `policies` (\n `id` text PRIMARY KEY NOT NULL,\n `scope` text DEFAULT 'global' NOT NULL,\n `target` text NOT NULL,\n `action` text NOT NULL,\n `enabled` integer DEFAULT true NOT NULL,\n `custom_keywords` text,\n `name` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_policies_scope_target` ON `policies` (`scope`,`target`);--\x3e statement-breakpoint\nCREATE TABLE `source_project` (\n `id` text PRIMARY KEY NOT NULL,\n `url` text,\n `name` text,\n `attributes` text NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n"},{tag:"0001_adorable_marten_broadcloak",sql:"ALTER TABLE `audit_events` ADD `input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `output_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `cache_creation_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `cache_read_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `model` text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `provider` text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL;--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_session_type` ON `audit_events` (`root_session_id`,`started_at`) WHERE event_type = 'llm_call';"},{tag:"0002_groovy_big_bertha",sql:"CREATE TABLE `exceptions` (\n `id` text PRIMARY KEY NOT NULL,\n `rule_id` text NOT NULL,\n `category` text NOT NULL,\n `value_fingerprint` text NOT NULL,\n `key_version` integer NOT NULL,\n `masked_value` text NOT NULL,\n `scope` text NOT NULL,\n `expires_at` integer,\n `max_uses` integer,\n `use_count` integer DEFAULT 0 NOT NULL,\n `last_used_at` integer,\n `justification` text NOT NULL,\n `conditions` text,\n `created_by` text NOT NULL,\n `created_via` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n `revoked_at` integer,\n `revoked_by` text,\n `revoke_reason` text\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_exceptions_active` ON `exceptions` (`rule_id`,`value_fingerprint`,`key_version`) WHERE revoked_at IS NULL;"},{tag:"0003_rich_sage",sql:"CREATE TABLE `egress_decision_override` (\n `id` text PRIMARY KEY NOT NULL,\n `destination_id` text NOT NULL,\n `decision` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`destination_id`) REFERENCES `share_destination`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override` ON `egress_decision_override` (`destination_id`);--\x3e statement-breakpoint\nCREATE TABLE `file_access_override` (\n `id` text PRIMARY KEY NOT NULL,\n `project_id` text NOT NULL,\n `path` text NOT NULL,\n `access` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`project_id`) REFERENCES `source_project`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_file_access_override_project` ON `file_access_override` (`project_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_file_access_override` ON `file_access_override` (`project_id`,`path`);--\x3e statement-breakpoint\nCREATE TABLE `harness_asset` (\n `id` text PRIMARY KEY NOT NULL,\n `harness_id` text NOT NULL,\n `asset_id` text NOT NULL,\n `created_at` integer NOT NULL,\n FOREIGN KEY (`harness_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`asset_id`) REFERENCES `inventory_asset`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_harness_asset_harness` ON `harness_asset` (`harness_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_harness_asset` ON `harness_asset` (`harness_id`,`asset_id`);--\x3e statement-breakpoint\nCREATE TABLE `inventory_asset` (\n `id` text PRIMARY KEY NOT NULL,\n `asset_type` text NOT NULL,\n `name` text NOT NULL,\n `sub` text,\n `description` text,\n `flags_json` text DEFAULT '[]' NOT NULL,\n `meta_json` text DEFAULT '{}' NOT NULL,\n `trust` text,\n `tools_json` text,\n `provenance` text DEFAULT 'scan' NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_asset_type` ON `inventory_asset` (`asset_type`);--\x3e statement-breakpoint\nCREATE TABLE `mcp_trust_override` (\n `id` text PRIMARY KEY NOT NULL,\n `asset_id` text NOT NULL,\n `trust` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`asset_id`) REFERENCES `inventory_asset`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_mcp_trust_override` ON `mcp_trust_override` (`asset_id`);--\x3e statement-breakpoint\nCREATE TABLE `project_file` (\n `id` text PRIMARY KEY NOT NULL,\n `project_id` text NOT NULL,\n `path` text NOT NULL,\n `name` text NOT NULL,\n `origin` text NOT NULL,\n `default_access` text NOT NULL,\n `findings_count` integer DEFAULT 0 NOT NULL,\n `blocked_at` integer,\n `note` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`project_id`) REFERENCES `source_project`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_project_file_project` ON `project_file` (`project_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_project_file` ON `project_file` (`project_id`,`path`);--\x3e statement-breakpoint\nCREATE TABLE `share_call_site` (\n `id` text PRIMARY KEY NOT NULL,\n `endpoint_id` text NOT NULL,\n `project` text NOT NULL,\n `file` text NOT NULL,\n `line` integer NOT NULL,\n `snippet` text NOT NULL,\n `dynamic` integer DEFAULT false NOT NULL,\n `vendored` integer DEFAULT false NOT NULL,\n `project_id` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`endpoint_id`) REFERENCES `share_endpoint`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_share_call_site_endpoint` ON `share_call_site` (`endpoint_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_call_site` ON `share_call_site` (`endpoint_id`,`project`,`file`,`line`);--\x3e statement-breakpoint\nCREATE TABLE `share_destination` (\n `id` text PRIMARY KEY NOT NULL,\n `kind` text NOT NULL,\n `name` text NOT NULL,\n `host` text NOT NULL,\n `category` text NOT NULL,\n `trust` text NOT NULL,\n `note` text,\n `network_json` text,\n `last_seen` integer NOT NULL,\n `provenance` text DEFAULT 'scan' NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_share_destination_kind` ON `share_destination` (`kind`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_destination_host` ON `share_destination` (`host`);--\x3e statement-breakpoint\nCREATE TABLE `share_endpoint` (\n `id` text PRIMARY KEY NOT NULL,\n `destination_id` text NOT NULL,\n `method` text NOT NULL,\n `transport` text NOT NULL,\n `url` text NOT NULL,\n `template` integer DEFAULT false NOT NULL,\n `data_class` text NOT NULL,\n `last_seen` integer NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`destination_id`) REFERENCES `share_destination`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_share_endpoint_dest` ON `share_endpoint` (`destination_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_endpoint` ON `share_endpoint` (`destination_id`,`method`,`url`);"},{tag:"0004_glorious_mindworm",sql:"CREATE TABLE `available_packs` (\n `id` text PRIMARY KEY NOT NULL,\n `namespace` text NOT NULL,\n `pack_id` text NOT NULL,\n `version` text NOT NULL,\n `name` text NOT NULL,\n `rules_json` text NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_available_packs_pack` ON `available_packs` (`namespace`,`pack_id`);"},{tag:"0005_fast_vindicator",sql:'PRAGMA foreign_keys=OFF;--\x3e statement-breakpoint\nCREATE TABLE `__new_mcp_trust_override` (\n `id` text PRIMARY KEY NOT NULL,\n `asset_id` text NOT NULL,\n `trust` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nINSERT INTO `__new_mcp_trust_override`("id", "asset_id", "trust", "created_at", "updated_at") SELECT "id", "asset_id", "trust", "created_at", "updated_at" FROM `mcp_trust_override`;--\x3e statement-breakpoint\nDROP TABLE `mcp_trust_override`;--\x3e statement-breakpoint\nALTER TABLE `__new_mcp_trust_override` RENAME TO `mcp_trust_override`;--\x3e statement-breakpoint\nPRAGMA foreign_keys=ON;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_mcp_trust_override` ON `mcp_trust_override` (`asset_id`);'},{tag:"0006_magenta_flatman",sql:'CREATE TABLE `_pack_write_gate` (\n `id` integer PRIMARY KEY NOT NULL,\n `open` integer DEFAULT 0 NOT NULL,\n CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)\n);\n--\x3e statement-breakpoint\nALTER TABLE `available_packs` ADD `recorded_by` text;--\x3e statement-breakpoint\nINSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0);\n--\x3e statement-breakpoint\nCREATE TRIGGER trg_installed_packs_write_gate\nBEFORE UPDATE OF version, name, rules_json ON installed_packs\nWHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1\nBEGIN SELECT RAISE(IGNORE); END;'},{tag:"0007_thick_stick",sql:"CREATE TABLE `finding_resolution` (\n `id` text PRIMARY KEY NOT NULL,\n `finding_key` text NOT NULL,\n `status` text NOT NULL,\n `method` text NOT NULL,\n `resolved_at` integer NOT NULL,\n `evidence` text,\n `created_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_finding_resolution_key` ON `finding_resolution` (`finding_key`);--\x3e statement-breakpoint\nALTER TABLE `findings` ADD `finding_key` text;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_findings_key` ON `findings` (`finding_key`);"},{tag:"0008_freezing_selene",sql:"ALTER TABLE `findings` ADD `first_detected_at` integer;--\x3e statement-breakpoint\nUPDATE `findings` SET `first_detected_at` = (SELECT `occurred_at` FROM `events` WHERE `events`.`id` = `findings`.`event_id`) WHERE `first_detected_at` IS NULL;"},{tag:"0009_findings_path_expression_index",sql:"-- Custom migration: partial expression index for the resolver's per-path reads.\n--\n-- openAtRestKeysForPath / resolvedAtRestKeysForPath (and the scanner's tier-3\n-- open-key probe) filter at-rest events by\n-- e.kind = 'code_change' AND json_extract(e.metadata, '$.filePath') = :path\n-- once per changed/deleted file on every scan — previously a full events scan\n-- per file. json_extract is deterministic, so SQLite allows it in an index;\n-- the WHERE kind = 'code_change' keeps the index to exactly the rows those\n-- queries can match (in-flight events are never path-addressed).\nCREATE INDEX `idx_events_code_change_path` ON `events` (json_extract(`metadata`, '$.filePath')) WHERE `kind` = 'code_change';\n"},{tag:"0010_events_session_expression_index",sql:"-- Custom migration: partial expression index for session-scoped finding reads.\n--\n-- sessionFindingsCount, the session-scoped listGroupedFindings paths, and the\n-- insert-time session dedup all filter live-capture events by\n-- json_extract(e.metadata, '$.sessionId') = :sessionId\n-- — previously a full findings-join scan with a JSON parse per row. The\n-- IS NOT NULL predicate keeps the index to session-stamped events only (an\n-- equality probe implies non-null, so SQLite still uses it).\nCREATE INDEX `idx_events_session_id` ON `events` (json_extract(`metadata`, '$.sessionId')) WHERE json_extract(`metadata`, '$.sessionId') IS NOT NULL;\n"},{tag:"0011_egress_writer",sql:'-- Stable per-project reconcile key for egress call sites, plus a host-keyed\n-- egress decision override that survives destination pruning.\n--\n-- DROP INDEX IF EXISTS, not a bare DROP: the applier replays a pending\n-- migration\'s non-index statements verbatim, so a store that lost\n-- uq_share_call_site out of band would throw here — and on the plugin hook path\n-- that throw is swallowed fail-open, silently stopping capture.\n--\n-- Existing rows carry the old key\'s discriminator into project_key\n-- (\'legacy:\' || project), so the new unique index is a re-encoding of the old\n-- one and cannot collide on rows the old one allowed. Leaving them on the\n-- column default would collapse two projects\' identical file/line hits onto\n-- one key and abort the whole migration. Writer keys are \'git:\'/\'path:\'-\n-- prefixed, so a backfilled row never collides with a captured one either.\n--\n-- egress_decision_override.destination_id becomes nullable with ON DELETE SET\n-- NULL, which SQLite can only do by rebuilding the table. `host` is ADDed\n-- before the rebuild so the copy has a column to read and so the migration\n-- still presents two probeable columns to the applier\'s evidence check.\nALTER TABLE `share_call_site` ADD `project_key` text DEFAULT \'\' NOT NULL;--\x3e statement-breakpoint\nUPDATE `share_call_site` SET `project_key` = \'legacy:\' || `project`;--\x3e statement-breakpoint\nDROP INDEX IF EXISTS `uq_share_call_site`;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_call_site` ON `share_call_site` (`endpoint_id`,`project_key`,`file`,`line`);--\x3e statement-breakpoint\nCREATE INDEX `idx_share_call_site_project` ON `share_call_site` (`project_key`,`endpoint_id`);--\x3e statement-breakpoint\nALTER TABLE `egress_decision_override` ADD `host` text;--\x3e statement-breakpoint\nPRAGMA foreign_keys=OFF;--\x3e statement-breakpoint\nCREATE TABLE `__new_egress_decision_override` (\n `id` text PRIMARY KEY NOT NULL,\n `destination_id` text,\n `host` text,\n `decision` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`destination_id`) REFERENCES `share_destination`(`id`) ON UPDATE no action ON DELETE set null\n);\n--\x3e statement-breakpoint\nINSERT INTO `__new_egress_decision_override`("id", "destination_id", "host", "decision", "created_at", "updated_at") SELECT "id", "destination_id", "host", "decision", "created_at", "updated_at" FROM `egress_decision_override`;--\x3e statement-breakpoint\nDROP TABLE `egress_decision_override`;--\x3e statement-breakpoint\nALTER TABLE `__new_egress_decision_override` RENAME TO `egress_decision_override`;--\x3e statement-breakpoint\nPRAGMA foreign_keys=ON;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override` ON `egress_decision_override` (`destination_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override_host` ON `egress_decision_override` (`host`) WHERE `host` IS NOT NULL;\n'},{tag:"0012_handy_the_captain",sql:"ALTER TABLE `inspection_findings` ADD `finding_key` text;--\x3e statement-breakpoint\nALTER TABLE `inspection_findings` ADD `first_detected_at` integer;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_inspection_findings_key` ON `inspection_findings` (`finding_key`);"},{tag:"0013_legacy_history_backfill_support",sql:"-- Legacy-to-generalized backfill support: the schema the resumable\n-- events/findings -> audit_events/inspection_findings copy needs (the row\n-- copy itself runs as a batched post-migration installer, not here — see\n-- @akasecurity/persistence's migrations.ts), plus the audit_events read-path\n-- indexes replacing the ones the legacy events table carried (0009/0010).\n\n-- Tracks how far the batched, resumable copy has advanced through each legacy\n-- table, by rowid, so a copy interrupted mid-run resumes instead of\n-- restarting, and a completed copy is a cheap no-op on every later open.\nCREATE TABLE `legacy_copy_watermark` (\n `source` text PRIMARY KEY NOT NULL,\n `last_rowid` integer DEFAULT 0 NOT NULL\n);\n--\x3e statement-breakpoint\n-- Serves the time-range read family that scans a single event_type across a\n-- start/end window (e.g. the Activity timeline) without a full-table scan.\nCREATE INDEX `idx_audit_type_t` ON `audit_events` (`event_type`,`started_at`);\n--\x3e statement-breakpoint\n-- Partial expression index mirroring `idx_events_code_change_path` (0009) for\n-- the generalized audit_events/attributes pair: file-path reads filter\n-- `event_type = 'code_change' AND json_extract(attributes, '$.file_path') = :path`.\nCREATE INDEX `idx_audit_code_change_path` ON `audit_events` (json_extract(`attributes`, '$.file_path')) WHERE `event_type` = 'code_change';\n--\x3e statement-breakpoint\n-- Synthesizes a stub session root (event_type = 'session', no attributes) for\n-- every legacy `events.metadata.sessionId` that has no audit_events row yet.\n-- audit_events.root_session_id is a self-FK, enforced with foreign-key\n-- checking on, and INSERT OR IGNORE does not suppress a foreign-key violation\n-- (only UNIQUE/PK/NOT NULL/CHECK) — so this must run before the events copy\n-- resolves root_session_id, or every session-scoped row's insert fails.\n-- started_at takes the earliest legacy occurred_at recorded under that\n-- session, so the stub root's own timeline position is never later than\n-- anything it will end up parenting.\nINSERT INTO audit_events (id, event_type, root_session_id, started_at)\nSELECT\n json_extract(metadata, '$.sessionId'),\n 'session',\n NULL,\n min(occurred_at)\nFROM events\nWHERE json_valid(metadata)\n AND json_extract(metadata, '$.sessionId') IS NOT NULL\n AND json_extract(metadata, '$.sessionId') NOT IN (SELECT id FROM audit_events)\nGROUP BY json_extract(metadata, '$.sessionId');\n"},{tag:"0014_drop_legacy_events_findings",sql:"-- Custom migration: drops the frozen legacy `events`/`findings` tables\n-- (superseded by audit_events/inspection_definitions/inspection_findings) and\n-- replaces them with read-only views of the same name.\n--\n-- persistence's migrations.ts applies this migration ONLY once the batched\n-- history backfill (see runLegacyHistoryBackfill) has fully drained both\n-- tables, and only after copying the live file aside — see\n-- backupBeforeLegacyDrop in packages/persistence/src/migrations.ts. A store\n-- still mid-copy keeps its real tables and this migration stays pending.\n--\n-- The views exist for skew: the `aka` CLI and the Claude Code plugin update\n-- independently against one shared store, so an older, already-installed\n-- binary can open a store a newer binary already dropped these tables on.\n-- Every already-shipped repository constructor prepares its SQL eagerly at\n-- open time, so a bare \"table not found\" would fail the WHOLE open, not just\n-- a findings-specific read — these views keep `prepare()` succeeding so an\n-- old binary's unrelated features keep working; its own reads stay truthful,\n-- and its rare (already fail-open) writes fail at run time instead.\n--\n-- The 0009/0010 expression indexes existed only over the legacy `events`\n-- table; DROP TABLE below would remove them implicitly, but they are\n-- dropped explicitly first so the intent reads clearly. IF EXISTS so a store\n-- that reached here with an index missing out of band (an adopted-tag store\n-- whose physical index was never built) does not throw a deterministic \"no\n-- such index\" out of the fail-open drop path.\nDROP INDEX IF EXISTS `idx_events_code_change_path`;\n--\x3e statement-breakpoint\nDROP INDEX IF EXISTS `idx_events_session_id`;\n--\x3e statement-breakpoint\n-- `findings.event_id` references `events.id` — drop the child first.\nDROP TABLE `findings`;\n--\x3e statement-breakpoint\nDROP TABLE `events`;\n--\x3e statement-breakpoint\n-- Legacy `events` shape, projected from audit_events: `kind`/`occurred_at`/\n-- `source_tool` become real columns again (source_tool round-trips through\n-- the attributes bag, the only place a capture-typed audit row keeps it);\n-- `metadata` is reconstructed as the old camelCase JSON object from the new\n-- snake_case attributes bag, with `root_session_id` folded back in as\n-- `sessionId` (the one legacy metadata key that became a column, never an\n-- attribute, on the new table). Constrained to the four capture kinds so\n-- structural rows (session/run/tool_call/llm_call/source_lookup/config_scan)\n-- never leak into a legacy reader's result set — the old `events` table\n-- never held them either.\nCREATE VIEW `events` AS\nSELECT\n id,\n json_extract(attributes, '$.source_tool') AS source_tool,\n event_type AS kind,\n started_at AS occurred_at,\n content_hash,\n content,\n -- Plugin-local bookkeeping column that `ensureSyncedAtColumn` adds to the\n -- real `events` table at open time. A pre-cutover binary runs that probe on\n -- EVERY open; without this projection its `columnNames('events')` check\n -- misses `synced_at` and issues `ALTER TABLE events ADD COLUMN` against this\n -- view, which SQLite rejects (\"Cannot add a column to a view\") — a hard,\n -- non-fail-open crash of the whole open, the exact skew failure these views\n -- exist to prevent. Projecting it (always NULL; no reader consumes it)\n -- short-circuits that ALTER.\n NULL AS synced_at,\n json_object(\n 'sessionId', root_session_id,\n 'repo', json_extract(attributes, '$.repo'),\n 'filePath', json_extract(attributes, '$.file_path'),\n 'toolName', json_extract(attributes, '$.tool_name'),\n 'gitignored', json_extract(attributes, '$.gitignored'),\n 'wholeFile', json_extract(attributes, '$.whole_file'),\n 'model', json_extract(attributes, '$.model'),\n 'turnIndex', json_extract(attributes, '$.turn_index'),\n 'correlationId', json_extract(attributes, '$.correlation_id'),\n 'traceId', json_extract(attributes, '$.trace_id'),\n 'exceptionIds', json_extract(attributes, '$.exception_ids')\n ) AS metadata\nFROM audit_events\nWHERE event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--\x3e statement-breakpoint\n-- A plain single-row INSERT (the old writer's shape — no ON CONFLICT) is\n-- accepted by prepare() against a view once an INSTEAD OF INSERT trigger\n-- exists, so it fails at run time instead of at open — landing in the same\n-- fail-open path the caller already wraps its write in.\nCREATE TRIGGER `trg_events_ro`\nINSTEAD OF INSERT ON `events`\nBEGIN SELECT RAISE(ABORT, 'events is read-only; write to audit_events instead'); END;\n--\x3e statement-breakpoint\n-- Legacy `findings` shape: rule_id/category/severity come from the joined\n-- inspection_definitions row (the legacy table inlined them per-row; the\n-- generalized schema normalizes them out into the shared definition). A view\n-- has no rowid of its own, so the underlying table's rowid is re-exposed\n-- explicitly under that name — a legacy reader ordering by `f.rowid` would\n-- otherwise fail to resolve the column at all. Joined to audit_events for the\n-- same four-capture-kind constraint as the events view above (a finding\n-- attached to a tool_call/config_scan row never existed in the legacy table\n-- either — see the persistence findings repository's identical predicate).\nCREATE VIEW `findings` AS\nSELECT\n f.id AS id,\n f.rowid AS rowid,\n f.audit_event_id AS event_id,\n d.rule_id AS rule_id,\n d.category AS category,\n d.severity AS severity,\n f.span_start AS span_start,\n f.span_end AS span_end,\n f.masked_match AS masked_match,\n f.action_taken AS action_taken,\n f.confidence AS confidence,\n f.finding_key AS finding_key,\n f.first_detected_at AS first_detected_at\nFROM inspection_findings f\nJOIN audit_events e ON e.id = f.audit_event_id\nJOIN inspection_definitions d ON d.id = f.inspection_definition_id\nWHERE e.event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--\x3e statement-breakpoint\n-- Defense in depth only: SQLite refuses to plan ANY upsert against a view\n-- (\"cannot UPSERT a view\") no matter what trigger exists, so this can never\n-- rescue the real legacy writer, which always used\n-- `ON CONFLICT (finding_key) DO UPDATE` — that statement still fails at\n-- prepare() on an old binary, same as it would with no trigger at all. This\n-- only covers a plain-INSERT shape, should one ever exist.\nCREATE TRIGGER `trg_findings_ro`\nINSTEAD OF INSERT ON `findings`\nBEGIN SELECT RAISE(ABORT, 'findings is read-only; write to inspection_findings instead'); END;\n"},{tag:"0015_busy_vengeance",sql:"CREATE TABLE `secret_vault` (\n `pointer_id` text PRIMARY KEY NOT NULL,\n `value_fingerprint` text NOT NULL,\n `fingerprint_key_version` integer NOT NULL,\n `key_version` integer NOT NULL,\n `category` text NOT NULL,\n `rule_id` text NOT NULL,\n `masked_match` text NOT NULL,\n `provider` text,\n `ciphertext` text NOT NULL,\n `nonce` text NOT NULL,\n `auth_tag` text NOT NULL,\n `occurrence_count` integer DEFAULT 1 NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_value` ON `secret_vault` (`value_fingerprint`);--\x3e statement-breakpoint\nCREATE TABLE `secret_vault_deref` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `at` integer NOT NULL,\n `target` text NOT NULL,\n `reason` text NOT NULL,\n `outcome` text NOT NULL,\n `grant_id` text,\n `pointer_count` integer DEFAULT 1 NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_pointer` ON `secret_vault_deref` (`pointer_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_reason_at` ON `secret_vault_deref` (`reason`,`at`);"},{tag:"0016_breezy_zodiak",sql:"ALTER TABLE `exceptions` ADD `capability` text DEFAULT 'suppress' NOT NULL;"},{tag:"0017_rainy_kat_farrell",sql:"CREATE TABLE `secret_vault_sighting` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `location` text NOT NULL,\n `kind` text NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_sighting` ON `secret_vault_sighting` (`pointer_id`,`location`);"},{tag:"0018_serious_tana_nile",sql:"ALTER TABLE `secret_vault` ADD `format_version` integer DEFAULT 2 NOT NULL;"},{tag:"0019_audit_started_at_index",sql:"CREATE INDEX `idx_audit_started_at` ON `audit_events` (`started_at`);"},{tag:"0020_secret_vault_pagination_indexes",sql:"CREATE INDEX `idx_secret_vault_last_seen` ON `secret_vault` (`last_seen`,`pointer_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_reuse` ON `secret_vault` (`occurrence_count`,`pointer_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_at` ON `secret_vault_deref` (`at`,`id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_signal` ON `secret_vault_deref` (`at`,`id`) WHERE `reason` NOT IN ('display', 'view-render');"}],e=/^(\d+)([mh])$/;function f(a,b=Date.now()){let c=a.trim().toLowerCase();return"once"===c?{scope:"once",expiresAt:new Date(b+18e5).toISOString(),maxUses:1}:"permanent"===c?{scope:"permanent",expiresAt:null,maxUses:null}:{scope:"temporary",expiresAt:new Date(b+function(a){let b=e.exec(a.trim()),c=b?Number(b[1]):0;if(!b||c<=0)throw Error(`invalid duration '${a}' — use <n>m or <n>h (e.g. 30m, 1h, 24h)`);let d=c*("h"===b[2]?36e5:6e4);if(d>864e5)throw Error(`duration '${a}' exceeds the 24h maximum for --for — use --permanent (revocable any time) for an open-ended grant`);return d}(c)).toISOString(),maxUses:null}}function g(a){return new Date(a).getTime()}function h(a){return new Date(a).toISOString()}function i(a,b){return{input:a,output:b,cacheWrite5m:1.25*a,cacheWrite1h:2*a,cacheRead:.1*a,webSearch:.01}}let j={input:0,output:0,cacheWrite5m:0,cacheWrite1h:0,cacheRead:0,webSearch:0},k={"claude-fable-5":i(10,50),"claude-opus-4-8":i(5,25),"claude-opus-4-7":i(5,25),"claude-opus-4-6":i(5,25),"claude-opus-4-5":i(5,25),"claude-sonnet-5":i(3,15),"claude-sonnet-4-6":i(3,15),"claude-sonnet-4-5":i(3,15),"claude-haiku-4-5":i(1,5)},l={...Object.fromEntries(Object.entries(k).map(([a,b])=>[`anthropic/${a}`,b])),"ollama/*":j,"local/*":j},m={standard:1,batch:.5,priority:1.5},n=Object.keys(k);function o(a){let b=a.replace(/^(us|eu|apac|global)\./,"").replace(/^anthropic[./]/,"").replace(/@[\w-]+$/,"").replace(/-v\d+:\d+$/,"").replace(/:\d+$/,"").replace(/-\d{8}$/,"");for(let a of n)if(b===a)return a;return b}let p={normalizeModelId(a,b){let c=a.trim().toLowerCase();if("ollama"===c||"local"===c)return{provider:c,model:"*"};if("anthropic"===c||"bedrock"===c||"vertex"===c)return{provider:c,model:o(b)};let d=/^anthropic\/(.+)$/.exec(b);return d?.[1]!==void 0?{provider:c,model:o(d[1])}:{provider:c,model:b}},costFor({provider:a,model:b,usage:c}){var d;let e=this.normalizeModelId(a,b),f=l[`${e.provider}/${e.model}`];return void 0===f?null:((c.inputTokens??0)*f.input+(c.outputTokens??0)*f.output+(c.cacheWrite1hTokens??0)*f.cacheWrite1h+(c.cacheWrite5mTokens??0)*f.cacheWrite5m+(c.cacheReadTokens??0)*f.cacheRead)/1e6*(void 0===(d=c.serviceTier)?1:m[d]??1)+(c.webSearchRequests??0)*f.webSearch}};new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1});let q=a=>a??0;function r(a,b){let c=new Map;for(let{sessionId:d,attributes:e}of a){let a=e.provider??"unknown",f=e.model??"unknown",g=`${a} ${f}`,h=c.get(d);void 0===h&&(h=new Map,c.set(d,h));let i=h.get(g);void 0===i&&(i={provider:a,model:f,input:0,output:0,cacheCreation:0,cacheRead:0,costUsd:0,priced:!1},h.set(g,i)),i.input+=q(e.input_tokens),i.output+=q(e.output_tokens),i.cacheCreation+=q(e.cache_creation_input_tokens),i.cacheRead+=q(e.cache_read_input_tokens);let j=b.costFor({provider:a,model:f,usage:function(a){let b={inputTokens:q(a.input_tokens),outputTokens:q(a.output_tokens),cacheWrite1hTokens:q(a.ephemeral_1h_input_tokens),cacheWrite5mTokens:q(a.ephemeral_5m_input_tokens),cacheReadTokens:q(a.cache_read_input_tokens),webSearchRequests:q(a.web_search_requests)};return void 0!==a.service_tier&&(b.serviceTier=a.service_tier),b}(e)});null!==j&&(i.costUsd+=j,i.priced=!0)}let d=[];for(let[a,b]of c){let c=[],e=0,f=0,g=!1,h=!1;for(let d of b.values()){let b=d.input+d.output+d.cacheCreation+d.cacheRead;e+=b;let i=d.priced?d.costUsd:null;null===i?h=!0:(g=!0,f+=i),c.push({sessionId:a,model:d.model,provider:d.provider,inputTokens:d.input,outputTokens:d.output,cacheCreation:d.cacheCreation,cacheRead:d.cacheRead,totalTokens:b,estimatedCostUsd:i})}c.sort((a,b)=>b.totalTokens-a.totalTokens),d.push({sessionId:a,rollups:c,totalTokens:e,estimatedCostUsd:g?f:null,costIsPartial:h})}return d.sort((a,b)=>b.totalTokens-a.totalTokens),d}var s=c(14901),t=c(54206),u=c(8004);let v=s.k5(["pii","financial","secret","phi","code_context","code_flaw","custom","config"]).meta({id:"DetectionCategory"}),w=s.k5(["critical","high","medium","low"]).meta({id:"Severity"}),x=s.k5(["warn","redact","block","allow","log"]).meta({id:"ActionTaken"}),y=x.options,z=s.Ik({start:s.ai().int().nonnegative(),end:s.ai().int().nonnegative()}).meta({id:"Span"}),A=s.Ik({id:s.Os(),eventId:s.Os(),ruleId:s.Yj(),category:v,severity:w,span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1)}).meta({id:"Finding"});A.meta({id:"DetectedFinding"});let B=s.k5(["blocked","redacted","warned","allowed","quarantined","monitored"]).meta({id:"FindingAction"}),C=s.k5(["claudecode","claudedesktop","cursor","copilot","chatgpt","claudeai","codex","antigravity","api"]).meta({id:"FindingProvider"}),D=s.k5(["secret","pii","source_code","external_share","mcp_server","customer_data","financial","phi","custom"]).meta({id:"FindingCategory"});s.k5(["in-flight","at-rest"]).meta({id:"FindingOrigin"});let E=s.k5(["open","handled","resolved","dismissed"]).meta({id:"FindingStatus"}),F=s.k5(["enforced-in-flight","fixed-at-source","exception","acknowledged","false-positive","redetected"]).meta({id:"ResolutionMethod"}),G=s.Ik({maskedValue:s.Yj(),contextPrefix:s.Yj()}).meta({id:"FindingMatch"}),H=s.Ik({id:s.Yj(),name:s.Yj().nullable()}).meta({id:"FindingDetectionRef"}),I=s.Ik({id:s.Yj(),name:s.Yj()}).meta({id:"FindingPolicyRef"}),J=s.Ik({id:s.Yj(),provider:C,repo:s.Yj(),file:s.Yj(),toolName:s.Yj().optional(),action:B,detectedAt:t.w$(),confidence:s.ai().min(0).max(1),status:E.optional(),eventId:s.Yj().optional(),sessionId:s.Yj().optional()}).meta({id:"FindingInstance"}),K=s.Ik({id:s.Yj(),category:D,subtype:s.Yj(),severity:w,match:G,detection:H,policy:I,instanceCount:s.ai().int().nonnegative(),providers:s.YO(C),aggregateAction:B.nullable(),latestDetectedAt:t.w$(),instances:s.YO(J),status:E.optional()}).meta({id:"FindingGroup"});s.Ik({findings:s.ai().int().nonnegative(),groups:s.ai().int().nonnegative(),bySeverity:s.Ik({critical:s.ai().int().nonnegative(),high:s.ai().int().nonnegative(),medium:s.ai().int().nonnegative(),low:s.ai().int().nonnegative()})}).meta({id:"FindingStats"});let L=s.Ik({value:s.Yj(),count:s.ai().int().nonnegative()}).meta({id:"FindingFacetItem"}),M=s.Ik({severity:s.YO(L),subtype:s.YO(L),provider:s.YO(L),action:s.YO(L),status:s.YO(L),tool:s.YO(L).optional()}).meta({id:"FindingFacets"}),N=50,O=s.Ik({severity:s.YO(w).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(C).optional(),action:s.YO(B).optional(),status:s.YO(E).optional(),q:s.Yj().optional(),sessionId:s.Yj().optional(),from:t.w$().optional(),includeId:s.Yj().optional(),groupBy:s.eu("type").optional(),limit:u.ai().int().min(1).max(100).optional(),cursor:s.Yj().optional()});s.Ik({totals:s.Ik({findings:s.ai().int().nonnegative(),groups:s.ai().int().nonnegative()}),facets:M,items:s.YO(K),nextCursor:s.Yj().nullable(),sessionFirings:s.g1(s.Yj(),s.ai().int().nonnegative()).optional()}).meta({id:"ListGroupedFindingsResponse"}),s.Ik({action:B.exclude(["quarantined"]),instanceId:s.Yj().optional()}).meta({id:"ApplyFindingActionRequest"}),K.meta({id:"ApplyFindingActionResponse"}),s.Ik({severity:s.YO(w).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(C).optional(),action:s.YO(B).optional(),q:s.Yj().optional(),format:s.k5(["csv","json"]).optional()});let P=J.extend({groupId:s.Yj(),category:D,subtype:s.Yj(),severity:w,match:G,detection:H,policy:I}).meta({id:"FindingInstanceDetail"}),Q=50,R=s.Ik({severity:s.YO(w).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(C).optional(),action:s.YO(B).optional(),status:s.YO(E).optional(),tool:s.YO(s.Yj()).optional(),repo:s.Yj().optional(),file:s.Yj().optional(),q:s.Yj().optional(),sessionId:s.Yj().optional(),from:t.w$().optional(),limit:u.ai().int().min(1).max(200).optional(),cursor:s.Yj().optional()});s.Ik({totals:s.Ik({findings:s.ai().int().nonnegative()}),facets:M,items:s.YO(P),nextCursor:s.Yj().nullable()}).meta({id:"ListFindingInstancesResponse"});let S=s.Ik({file:s.Yj(),instanceCount:s.ai().int().nonnegative(),maxSeverity:w,latestDetectedAt:t.w$(),status:E.optional(),ruleIds:s.YO(s.Yj())}).meta({id:"FindingLocationFile"}),T=s.Ik({repo:s.Yj(),instanceCount:s.ai().int().nonnegative(),maxSeverity:w,latestDetectedAt:t.w$(),status:E.optional(),files:s.YO(S)}).meta({id:"FindingLocationRepo"});s.Ik({severity:s.YO(w).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(C).optional(),action:s.YO(B).optional(),status:s.YO(E).optional(),tool:s.YO(s.Yj()).optional(),q:s.Yj().optional(),sessionId:s.Yj().optional(),from:t.w$().optional(),limit:u.ai().int().min(1).max(500).optional()}),s.Ik({totals:s.Ik({findings:s.ai().int().nonnegative(),repos:s.ai().int().nonnegative(),files:s.ai().int().nonnegative()}),items:s.YO(T),hasMore:s.zM()}).meta({id:"ListFindingLocationsResponse"});let U=s.k5(["claudecode","cursor","copilot","codex","antigravity","windsurf","claudedesktop","chatgpt","claudeai","api"]).meta({id:"Harness"}),V={"claude-code":"claudecode","claude-desktop":"claudedesktop","github-copilot":"copilot",cursor:"cursor",chatgpt:"chatgpt",codex:"codex",antigravity:"antigravity","claude-ai":"claudeai"},W=s.k5(["host","harness","user","skill","hook","mcp_server","config_file"]).meta({id:"InventoryObjectType"}),X=s.k5(["session","run","tool_call","llm_call","source_lookup","prompt","response","code_change","tool_use","config_scan"]).meta({id:"AuditEventType"}),Y=s.g1(s.Yj(),s.L5());s.Ik({host_name:s.Yj().optional(),os:s.Yj().optional(),os_version:s.Yj().optional(),arch:s.Yj().optional()}).catchall(s.L5()),s.Ik({harness_version:s.Yj().optional(),interface:s.Yj().optional()}).catchall(s.L5()),s.Ik({display_name:s.Yj().optional(),email:s.Yj().optional()}).catchall(s.L5()),s.Ik({source:s.Yj().optional(),version:s.Yj().optional(),description:s.Yj().optional(),updated_at:s.Yj().optional(),scope:s.Yj().optional(),plugin_name:s.Yj().optional()}).catchall(s.L5()),s.Ik({event:s.Yj().optional(),matcher:s.Yj().optional(),command:s.Yj().optional(),scope:s.Yj().optional(),plugin_name:s.Yj().optional(),timeout:s.ai().optional()}).catchall(s.L5()),s.Ik({scope:s.Yj().optional(),transport:s.Yj().optional(),command:s.Yj().optional(),url:s.Yj().optional(),env_keys:s.YO(s.Yj()).optional(),plugin_name:s.Yj().optional(),marketplace:s.Yj().optional(),project:s.Yj().optional()}).catchall(s.L5()),s.Ik({kind:s.Yj().optional(),detail:s.Yj().optional(),scope:s.Yj().optional(),updated_at:s.Yj().optional(),entry_count:s.ai().optional()}).catchall(s.L5());let Z=s.Ik({model:s.Yj().optional(),provider:s.Yj().optional(),input_tokens:s.ai().int().nonnegative().optional(),output_tokens:s.ai().int().nonnegative().optional(),cache_creation_input_tokens:s.ai().int().nonnegative().optional(),cache_read_input_tokens:s.ai().int().nonnegative().optional(),ephemeral_1h_input_tokens:s.ai().int().nonnegative().optional(),ephemeral_5m_input_tokens:s.ai().int().nonnegative().optional(),web_search_requests:s.ai().int().nonnegative().optional(),web_fetch_requests:s.ai().int().nonnegative().optional(),service_tier:s.Yj().optional(),stop_reason:s.Yj().optional(),message_id:s.Yj().optional(),uuid:s.Yj().optional(),parent_uuid:s.Yj().optional(),run_key:s.Yj().optional()}).catchall(s.L5());s.Ik({sessionId:s.Yj().min(1),messageId:s.Yj().min(1),parentId:s.Yj().min(1),rootSessionId:s.Yj().min(1),startedAt:t.w$(),attributes:Z});let $=s.Ik({tool_name:s.Yj().optional(),tool_use_id:s.Yj().optional(),target:s.Yj().optional(),is_error:s.zM().optional(),input_size:s.ai().int().nonnegative().optional(),output_size:s.ai().int().nonnegative().optional(),uuid:s.Yj().optional(),parent_uuid:s.Yj().optional(),run_key:s.Yj().optional()}).catchall(s.L5());s.Ik({source_tool:s.Yj().optional(),file_path:s.Yj().optional(),repo:s.Yj().optional(),tool_name:s.Yj().optional(),gitignored:s.zM().optional(),whole_file:s.zM().optional(),correlation_id:s.uR().optional(),trace_id:s.Yj().regex(/^[0-9a-f]{32}$/).optional(),exception_ids:s.YO(s.Os()).optional()}).catchall(s.L5());let _=s.Ik({ruleId:s.Yj().min(1),ruleName:s.Yj(),ruleVersion:s.Yj().min(1),category:v,severity:w,span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1)});s.Ik({sessionId:s.Yj().min(1),toolUseId:s.Yj().min(1),parentId:s.Yj().min(1),rootSessionId:s.Yj().min(1),startedAt:t.w$(),attributes:$,inspections:s.YO(_).default([])});let aa=s.Ik({objectType:W,identityKey:s.Yj().min(1),location:s.Yj().optional(),title:s.Yj().optional(),hostId:s.Yj().optional(),attributes:Y.default({})}).meta({id:"InventoryInput"}),ab=s.Ik({url:s.Yj().min(1),name:s.Yj().optional(),attributes:Y.default({})}).meta({id:"SourceProjectInput"}),ac=s.Ik({id:s.Yj().min(1),eventType:X,startedAt:t.w$(),endedAt:t.w$().optional(),parentId:s.Yj().optional(),rootSessionId:s.Yj().optional(),hostId:s.Yj().optional(),harnessId:s.Yj().optional(),sourceProjectId:s.Yj().optional(),severity:w.optional(),priority:s.Yj().optional(),content:s.Yj().optional(),contentHash:s.Yj().optional(),attributes:Y.optional()}).meta({id:"AuditEventInput"});s.Ik({class:s.Yj().min(1),label:s.Yj().optional(),attributes:Y.optional()});let ad=s.Ik({ruleId:s.Yj().min(1),version:s.Yj().min(1),name:s.Yj(),category:v,severity:w,definition:s.Yj()});s.Ik({id:s.Yj().min(1),auditEventId:s.Yj().min(1),inspectionDefinitionId:s.Yj().min(1),classifiedDataId:s.Yj().optional(),span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1),findingKey:s.Yj().optional(),firstDetectedAt:t.w$().optional()}),s.Ik({host:aa.optional(),harness:aa.optional(),project:ab.optional()}).meta({id:"InventoryContext"}),s.Ik({hostId:s.Yj().optional(),harnessId:s.Yj().optional(),accountId:s.Yj().optional(),sourceProjectId:s.Yj().optional()}).meta({id:"ResolvedInventory"}),s.Ik({hosts:s.YO(s.Yj()),harnesses:s.YO(s.Yj()),osVersions:s.YO(s.Yj()),projects:s.YO(s.Yj())}).meta({id:"InventoryFacets"});let ae=s.Ik({sessionId:s.Yj(),model:s.Yj(),provider:s.Yj(),inputTokens:s.ai().int().nonnegative(),outputTokens:s.ai().int().nonnegative(),cacheCreation:s.ai().int().nonnegative(),cacheRead:s.ai().int().nonnegative(),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai().nullable()}).meta({id:"TokenRollup"});s.Ik({sessionId:s.Yj(),rollups:s.YO(ae),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai().nullable(),costIsPartial:s.zM()});let af=s.Ik({provider:s.Yj(),model:s.Yj(),inputTokens:s.ai().int().nonnegative(),outputTokens:s.ai().int().nonnegative(),cacheTokens:s.ai().int().nonnegative(),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai().nullable()});function ag(a){return JSON.stringify(a)}s.Ik({models:s.YO(af),sessionCount:s.ai().int().nonnegative(),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai(),costIsPartial:s.zM()});let ah=s.k5(["active","completed","interrupted","error"]),ai=s.k5(["session","prompt","response","tool","hook","detection","share","permission","commit","error","active"]),aj=s.k5(["detections","shares","inventory"]),ak=s.Ik({id:s.Yj(),occurredAt:t.w$(),kind:ai,title:s.Yj(),detail:s.Yj(),tool:s.Yj().nullable(),severity:w.nullable(),link:aj.nullable(),targetId:s.Yj().nullable(),internal:s.zM(),flagged:s.zM()}).meta({id:"ActivityAuditEvent"}),al=s.Ik({id:s.Yj(),harness:U,title:s.Yj(),project:s.Yj(),repo:s.Yj(),branches:s.YO(s.Yj()),startedAt:t.w$(),endedAt:t.w$().nullable(),status:ah,turns:s.ai().int().nonnegative(),findings:s.ai().int().nonnegative(),shares:s.ai().int().nonnegative()}).meta({id:"ActivitySessionSummary"});al.extend({host:s.Yj(),cwd:s.Yj(),models:s.YO(s.Yj()),version:s.Yj(),tokens:ae,tools:s.g1(s.Yj(),s.ai().int().nonnegative()),files:s.YO(s.Yj()),commits:s.ai().int().nonnegative(),events:s.YO(ak)}).meta({id:"ActivitySession"}),s.Ik({tz:s.Yj().optional()});let am=s.Ik({sessionsToday:s.ai().int().nonnegative(),liveNow:s.ai().int().nonnegative(),toolCallsToday:s.ai().int().nonnegative(),findingsToday:s.ai().int().nonnegative(),egressToday:s.ai().int().nonnegative()}).meta({id:"GetActivityStatsResponse"});s.Ik({q:s.Yj().optional(),harness:s.YO(U).optional(),from:s.KC([t.p6(),t.w$()]).optional(),to:s.KC([t.p6(),t.w$()]).optional(),excludeEmpty:s.uE().optional(),limit:u.ai().int().min(1).max(100).default(50),cursor:s.Yj().optional()});let an=s.Ik({items:s.YO(al),nextCursor:s.Yj().nullable(),emptyCount:s.ai().int().nonnegative()}).meta({id:"ListActivitySessionsResponse"});s.Ik({limit:u.ai().int().min(1).max(500).default(100),cursor:s.Yj().optional(),order:s.k5(["asc","desc"]).default("asc")}),s.Ik({items:s.YO(ak),nextCursor:s.Yj().nullable()}).meta({id:"ListSessionEventsResponse"}),s.Ik({format:s.k5(["ndjson","json"]).default("ndjson")}),s.Ik({format:s.k5(["csv","json"]).default("csv"),q:s.Yj().optional(),harness:s.YO(U).optional(),from:s.KC([t.p6(),t.w$()]).optional(),to:s.KC([t.p6(),t.w$()]).optional()}),s.Ik({stats:am,sessions:an}).meta({id:"ActivityOverviewResponse"});let ao=s.k5(["prompt","response","code_change","tool_use"]).meta({id:"EventKind"}),ap=ao.options.map(a=>`'${a}'`).join(","),aq=s.k5(["claude-code","claude-desktop","cursor","chatgpt","claude-ai","github-copilot","codex","antigravity","cli","unknown"]).meta({id:"SourceTool"}),ar=s.Ik({sessionId:s.Yj().optional(),repo:s.Yj().optional(),filePath:s.Yj().optional(),toolName:s.Yj().optional(),gitignored:s.zM().optional(),wholeFile:s.zM().optional(),model:s.Yj().optional(),turnIndex:s.ai().int().nonnegative().optional(),correlationId:s.uR().optional(),traceId:s.Yj().regex(/^[0-9a-f]{32}$/).optional(),exceptionIds:s.YO(s.Os()).optional()}).meta({id:"EventMetadata"}),as=s.Ik({id:s.Os(),sourceTool:aq,kind:ao,occurredAt:t.w$(),contentHash:s.Yj(),content:s.Yj(),metadata:ar.optional()}).meta({id:"Event"}),at=as.meta({id:"IngestEvent"});s.Ik({events:s.YO(at).min(1).max(100),dedupe:s.eu("content-hash").optional()}).meta({id:"IngestBatch"});let au=s.k5(["project","skill","mcp","hook","config"]).meta({id:"AssetType"}),av=s.k5(["open","approved","blocked"]).meta({id:"AccessLevel"}),aw=s.k5(["source","public-dep","vendored","config","data","docs","generated"]).meta({id:"Origin"}),ax=s.k5(["known-good","risky","unapproved"]).meta({id:"TrustLevel"}),ay=s.k5(["update","stale","conflict","unknown","change","untracked","risk","findings"]).meta({id:"Flag"}),az=s.k5(["public","private"]).meta({id:"Visibility"}),aA=s.k5(["block","redact","warn"]).meta({id:"HarnessEventKind"}),aB=s.k5(["claudecode","cursor","codex","antigravity"]).meta({id:"HarnessId"}),aC=s.Ik({open:s.ai().int().nonnegative(),approved:s.ai().int().nonnegative(),blocked:s.ai().int().nonnegative(),total:s.ai().int().nonnegative()}).meta({id:"AccessCounts"}),aD=s.Ik({id:s.Yj(),type:au,name:s.Yj(),sub:s.Yj(),flags:s.YO(ay),trust:ax.optional()}).meta({id:"AssetSummary"}),aE=s.Ik({id:s.Yj(),name:s.Yj(),repo:s.Yj(),visibility:az,language:s.Yj(),policyDefault:av,updatedAt:t.w$(),accessCounts:aC,findingsCount:s.ai().int().nonnegative()}).meta({id:"ProjectSummary"}),aF=s.Ik({type:au,assets:s.YO(aD)}),aG=s.Ik({id:aB,label:s.Yj(),kind:s.Yj(),version:s.Yj(),sessions:s.ai().int().nonnegative(),assetCount:s.ai().int().nonnegative(),flagCount:s.ai().int().nonnegative(),projects:s.YO(aE),categories:s.YO(aF)}).meta({id:"HarnessSummary"});s.Ik({items:s.YO(aG)}).meta({id:"ListHarnessesResponse"});let aH=s.Ik({type:au,total:s.ai().int().nonnegative(),trustRollup:s.Ik({"known-good":s.ai().int().nonnegative(),risky:s.ai().int().nonnegative(),unapproved:s.ai().int().nonnegative()}).partial().strict().optional(),flagRollup:s.Ik({update:s.ai().int().nonnegative(),stale:s.ai().int().nonnegative(),conflict:s.ai().int().nonnegative(),unknown:s.ai().int().nonnegative(),change:s.ai().int().nonnegative(),untracked:s.ai().int().nonnegative(),risk:s.ai().int().nonnegative(),findings:s.ai().int().nonnegative()}).partial().strict(),items:s.YO(aD)}).meta({id:"AssetGroup"});s.Ik({groups:s.YO(aH)}).meta({id:"ListAssetsResponse"});let aI=s.Ik({name:s.Yj(),signature:s.Yj(),description:s.Yj(),write:s.zM(),risk:s.Yj().nullable()}).meta({id:"McpTool"}),aJ=s.Ik({id:s.Yj(),title:s.Yj(),note:s.Yj()});aD.extend({description:s.Yj().nullable(),trust:ax.nullable(),meta:s.g1(s.Yj(),s.L5()),finding:aJ.nullable(),tools:s.YO(aI).optional()}).meta({id:"AssetDetail"}),s.Ik({items:s.YO(aE)}).meta({id:"ListProjectsResponse"}),s.Ik({attention:s.ai().int().nonnegative(),byType:s.Ik({project:s.ai().int().nonnegative(),skill:s.ai().int().nonnegative(),mcp:s.ai().int().nonnegative(),hook:s.ai().int().nonnegative(),config:s.ai().int().nonnegative()}),harnesses:s.ai().int().nonnegative(),mcpTrust:s.Ik({"known-good":s.ai().int().nonnegative(),risky:s.ai().int().nonnegative(),unapproved:s.ai().int().nonnegative()})}).meta({id:"InventoryStats"});let aK=s.Ik({path:s.Yj(),name:s.Yj(),origin:aw,access:av,isCustom:s.zM(),findings:s.ai().int().nonnegative(),blockedAt:t.w$().nullable().optional(),note:s.Yj().nullable().optional()}).meta({id:"FileSummary"}),aL=s.Ik({name:s.Yj(),path:s.Yj(),accessCounts:aC}).meta({id:"FolderSummary"});s.Ik({project:s.Ik({id:s.Yj(),repo:s.Yj(),visibility:az}),path:s.Yj(),folders:s.YO(aL).optional(),files:s.YO(aK)}).meta({id:"ProjectTreeResponse"}),aK.extend({project:s.Ik({repo:s.Yj(),visibility:az,language:s.Yj(),policyDefault:av,updatedAt:t.w$()}),findingsRefs:s.YO(s.Ik({id:s.Yj(),title:s.Yj()}))}).meta({id:"FileDetail"}),s.Ik({path:s.Yj(),access:av}).meta({id:"SetFileAccessBody"}),s.Ik({file:aK,accessCounts:aC}).meta({id:"SetFileAccessResponse"}),s.Ik({trust:ax}).meta({id:"SetMcpTrustBody"});let aM=s.Ik({kind:aA,title:s.Yj(),detail:s.Yj(),occurredAt:t.w$(),findingId:s.Yj().nullable().optional()}).meta({id:"HarnessEventItem"});s.Ik({counts:s.Ik({block:s.ai().int().nonnegative(),redact:s.ai().int().nonnegative(),warn:s.ai().int().nonnegative()}),items:s.YO(aM)}).meta({id:"HarnessEventsResponse"}),s.Ik({jobId:s.Yj(),startedAt:t.w$()}).meta({id:"RescanResponse"}),s.Ik({repo:s.Yj()}).meta({id:"ConnectProjectBody"}),s.Ik({type:s.YO(au).optional(),q:s.Yj().optional()}),s.Ik({path:s.Yj().optional(),q:s.Yj().optional(),filter:s.k5(["blocked"]).optional()}),s.Ik({path:s.Yj()}),s.Ik({limit:u.ai().int().min(1).max(50).default(7)});let aN=s.k5(["once","temporary","permanent"]),aO=s.Ik({repo:s.Yj().optional(),sourceTool:s.Yj().optional(),provider:s.Yj().optional()}).strict(),aP=s.k5(["suppress","reveal_to_model"]),aQ=s.Ik({id:s.Os(),ruleId:s.Yj(),category:v,valueFingerprint:s.Yj().regex(/^[0-9a-f]{64}$/),keyVersion:s.ai().int().positive(),maskedValue:s.Yj(),capability:aP.default("suppress"),scope:aN,expiresAt:t.w$().nullable(),maxUses:s.ai().int().positive().nullable(),useCount:s.ai().int().nonnegative(),lastUsedAt:t.w$().nullable(),justification:s.Yj().min(1),conditions:aO.nullable(),createdBy:s.Yj(),createdVia:s.k5(["cli-approve","cli-add","web-approve","web-add","api","setup-triage"]),createdAt:t.w$(),updatedAt:t.w$(),revokedAt:t.w$().nullable(),revokedBy:s.Yj().nullable(),revokeReason:s.Yj().nullable()}),aR=aQ.pick({id:!0,ruleId:!0,valueFingerprint:!0,keyVersion:!0,capability:!0,expiresAt:!0,maxUses:!0,useCount:!0,conditions:!0});function aS(a,b){return"present"===b.status&&b.version===a}aQ.omit({valueFingerprint:!0}),s.k5(["keyword","regex","validator"]).meta({id:"MatcherType"}),s.k5(["safe","quarantined"]).meta({id:"RuleProbeVerdict"});let aT=s.Ik({type:s.eu("keyword"),keywords:s.YO(s.Yj().min(1)).min(1),caseSensitive:s.zM().default(!1)}),aU=s.Ik({type:s.eu("regex"),pattern:s.Yj().min(1).max(2e3),flags:s.Yj().default("gi"),captureGroup:s.ai().int().nonnegative().optional()}).refine(a=>(function(a,b){try{return new RegExp(a,b),!0}catch{return!1}})(a.pattern,a.flags),{message:"pattern/flags do not form a valid JavaScript regular expression",path:["pattern"]}).refine(a=>void 0!==a.captureGroup||!function(a,b){try{let c=new RegExp(a,b.replace(/[gy]/g,""));return c.exec("")?.[0].length===0}catch{return!1}}(a.pattern,a.flags),{message:'a whole-match regex that can match the empty string (e.g. "\\d*", "a?", "(?:)") can hang the matcher — scope the quantifier to a captureGroup, or require at least one character',path:["pattern"]}),aV=s.Ik({type:s.eu("validator"),name:s.k5(["luhn","entropy","ssn-checksum"]),config:s.g1(s.Yj(),s.L5()).optional()}),aW=s.gM("type",[aT,aU,aV]).meta({id:"Matcher"}),aX=s.Ik({extensions:s.YO(s.Yj().regex(/^\.[A-Za-z0-9]+$/)).min(1)}).meta({id:"AppliesTo"}),aY=s.KC([s.Yj(),s.Ik({name:s.Yj(),config:s.g1(s.Yj(),s.L5()).optional()})]).meta({id:"PostValidatorRef"}),aZ=s.Ik({categories:s.YO(v).min(1).optional(),ruleIds:s.YO(s.Yj().min(1)).min(1).optional(),labels:s.YO(s.Yj().min(1)).min(1).optional(),windowChars:s.ai().int().positive().default(160),confidenceBoost:s.ai().min(0).max(.3).optional()}).refine(a=>(a.categories?.length??0)+(a.ruleIds?.length??0)+(a.labels?.length??0)>0,{message:"requiresNearby needs at least one of categories, ruleIds, or labels"}).meta({id:"RequiresNearby"}),a$=s.Ik({label:s.Yj(),text:s.Yj().max(5e4),shouldMatch:s.zM(),filePath:s.Yj().optional(),expectedSpans:s.YO(s.Ik({start:s.ai(),end:s.ai()})).optional()}).meta({id:"RuleFixture"}),a_=s.Ik({specVersion:s.eu(1),id:s.Yj().regex(/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/),name:s.Yj(),category:v,severity:w,matcher:aW,appliesTo:aX.optional(),postValidators:s.YO(aY).optional(),requiresNearby:aZ.optional(),examples:s.YO(s.Yj()).optional()}).meta({id:"Rule"}),a0=s.Ik({name:s.Yj(),email:s.Rp().optional(),url:s.OZ().optional()}).meta({id:"Author"});s.Ik({specVersion:s.eu(1),id:s.Yj(),name:s.Yj(),version:s.Yj(),rules:s.YO(s.Yj()),description:s.Yj().optional(),author:a0.optional(),license:s.Yj().optional(),sourceUrl:s.OZ().optional()}).meta({id:"PackManifest"});let a1=s.k5(["global","repo","user"]).meta({id:"PolicyScope"}),a2=s.KC([s.Ik({ruleId:s.Yj()}),s.Ik({category:v})]).meta({id:"PolicyTarget"}),a3=s.Ik({id:s.Os(),scope:a1,target:a2,action:x,enabled:s.zM().default(!0),customKeywords:s.YO(s.Yj()).optional(),name:s.Yj().optional()}).meta({id:"Policy"});s.Ik({version:s.Yj(),policies:s.YO(a3),rules:s.YO(a_).optional(),rulesComplete:s.zM().optional(),exceptions:s.YO(aR).optional(),ruleVersions:s.g1(s.Yj(),s.Yj()).optional(),customKeywords:s.YO(s.Yj()),fetchedAt:t.w$()}).meta({id:"PolicyBundle"});let a4=["config"],a5=v.options.filter(a=>!a4.includes(a)),a6={secret:"critical",financial:"critical",code_flaw:"critical",pii:"high",phi:"high",custom:"high",code_context:"low",config:"low"},a7=s.k5(["builtin","custom"]).meta({id:"PolicyKind"}),a8=["monitor","warn","redact","block"],a9=s.k5(a8).meta({id:"BuiltinPolicyId"}),ba=a8,bb={monitor:{name:"Monitor",action:"log",description:"Log every match for audit. The request is allowed through untouched."},warn:{name:"Warn",action:"warn",description:"Allow the request, but warn the user inline before it is sent."},redact:{name:"Redact",action:"redact",description:"Automatically strip the matched value from the request, then continue."},block:{name:"Block",action:"block",description:"Refuse the request entirely whenever any rule in this detection matches."}},bc=Object.fromEntries(v.options.map(a=>[a,bb[function(a){if(a4.includes(a))return"monitor";let b=a6[a];return"critical"===b||"high"===b?"warn":"monitor"}(a)].action])),bd=Object.fromEntries(a8.map(a=>[a,{id:a,...bb[a]}])),be="monitor";function bf(a){let b=a9.safeParse(a??be);return bd[b.success?b.data:be].action}let bg=s.Ik({id:s.Yj(),name:s.Yj(),ruleCount:s.ai().int().nonnegative(),enabled:s.zM()}).meta({id:"UsedByItem"}),bh=s.Ik({id:s.Yj(),kind:a7,name:s.Yj(),enabled:s.zM(),usedByCount:s.ai().int().nonnegative()}).meta({id:"PolicyListItem"});s.Ik({specVersion:s.eu(1),id:s.Yj(),kind:a7,name:s.Yj(),enabled:s.zM(),description:s.Yj(),usedBy:s.YO(bg)}).meta({id:"PolicyDetail"}),s.Ik({policies:s.ai().int().nonnegative(),builtin:s.ai().int().nonnegative(),custom:s.ai().int().nonnegative(),detectionsGoverned:s.ai().int().nonnegative()}).meta({id:"PolicyStatsResponse"}),s.Ik({cursor:s.Yj().optional(),limit:u.ai().int().min(1).max(200).default(50),sourceTool:s.Yj().optional(),kind:s.Yj().optional(),from:t.w$().optional(),to:t.w$().optional()}),s.Ik({items:s.YO(as),nextCursor:s.Yj().nullable()}).meta({id:"ListEventsResponse"}),s.Ik({accepted:s.ai().int().nonnegative(),duplicates:s.ai().int().nonnegative()}).meta({id:"IngestResponse"}),s.Ik({cursor:s.Yj().optional(),limit:u.ai().int().min(1).max(200).default(50),severity:s.Yj().optional(),category:s.Yj().optional(),eventId:s.Os().optional()}),s.Ik({items:s.YO(A),nextCursor:s.Yj().nullable()}).meta({id:"ListFindingsResponse"}),s.Ik({items:s.YO(bh)}).meta({id:"ListPoliciesResponse"}),a3.omit({id:!0}).meta({id:"CreatePolicyRequest"}),a3.partial().required({id:!0}).meta({id:"UpdatePolicyRequest"}),s.Ik({accepted:s.zM()}).meta({id:"RecordAuditEventResponse"}),s.Ik({error:s.Ik({code:s.Yj(),message:s.Yj(),details:s.L5().optional()})}).meta({id:"ErrorResponse"});let bi=s.k5(["user","project","local","plugin"]),bj=s.Ik({name:s.Yj().min(1),source:s.Yj().min(1),scope:bi,pluginName:s.Yj().optional(),version:s.Yj().optional(),description:s.Yj().optional(),updatedAt:t.w$().optional(),location:s.Yj().optional()}),bk=s.Ik({event:s.Yj().min(1),matcher:s.Yj().optional(),command:s.Yj().min(1),timeout:s.ai().optional(),scope:bi,pluginName:s.Yj().optional(),location:s.Yj().optional()}),bl=s.Ik({name:s.Yj().min(1),scope:bi,pluginName:s.Yj().optional(),marketplace:s.Yj().optional(),project:s.Yj().optional(),transport:s.Yj().min(1),command:s.Yj().optional(),url:s.Yj().optional(),envKeys:s.YO(s.Yj()).optional(),location:s.Yj().optional()}),bm=s.Ik({name:s.Yj().min(1),path:s.Yj().min(1),scope:bi,kind:s.Yj().min(1),detail:s.Yj().optional(),entryCount:s.ai().optional(),updatedAt:t.w$().optional()});s.Ik({scannedAt:t.w$(),skills:s.YO(bj),hooks:s.YO(bk),mcpServers:s.YO(bl),configFiles:s.YO(bm),errors:s.YO(s.Ik({source:s.Yj(),reason:s.Yj()}))});let bn=s.Ik({ruleId:s.Yj().min(1),version:s.Yj().min(1),span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1)});s.Ik({items:s.YO(aa),scanEvent:ac,definitions:s.YO(ad).optional(),findings:s.YO(bn).optional()});let bo=s.Yj().regex(/^[a-z][a-z0-9-]*$/),bp=s.Yj().regex(/^[a-z][a-z0-9-]*$/),bq=s.Yj().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/),br=s.k5(["labs","user","org"]),bs=s.k5(["library"]).meta({id:"OriginEnum"}),bt=s.k5(["all","library","custom","customized","updates"]),bu=s.k5(["new","imported","update"]).meta({id:"LibraryStateEnum"}),bv=s.Ik({all:s.ai().int().nonnegative(),library:s.ai().int().nonnegative(),custom:s.ai().int().nonnegative(),customized:s.ai().int().nonnegative(),updates:s.ai().int().nonnegative()}).meta({id:"DetectionCounts"}),bw=s.Ik({id:s.Yj(),name:s.Yj(),version:bq,enabled:s.zM(),origin:bs,publisher:bo.optional(),publisherKind:br.optional(),ruleCount:s.ai().int().nonnegative(),namespace:bo,packId:bp,policyId:s.Yj().optional(),latestVersion:bq.optional()}).meta({id:"DetectionListItem"});s.Ik({counts:bv,items:s.YO(bw)}).meta({id:"ListDetectionsResponse"}),s.Ik({filter:bt.optional().default("all"),q:s.Yj().optional()}),s.Ik({detections:s.ai().int().nonnegative(),rules:s.ai().int().nonnegative(),active:s.ai().int().nonnegative(),findingsLast30d:s.ai().int().nonnegative()}).meta({id:"DetectionStats"});let bx=s.Ik({id:s.Yj(),name:s.Yj(),category:v,severity:w,matcher:aW}).meta({id:"DetectionRule"}),by=s.Ik({available:s.zM(),latestVersion:bq,latestRuleCount:s.ai().int().nonnegative().optional()}).nullable().meta({id:"DetectionUpdate"});s.Ik({id:s.Yj(),name:s.Yj(),version:bq,enabled:s.zM(),origin:bs,publisher:bo.optional(),publisherKind:br.optional(),ruleCount:s.ai().int().nonnegative(),namespace:bo,packId:bp,description:s.Yj().optional(),editedAt:t.w$(),findingsLast30d:s.ai().int().nonnegative(),latestVersion:bq.nullable().optional(),update:by,rules:s.YO(bx),modified:s.zM(),policyId:s.Yj().optional()}).meta({id:"DetectionDetail"});let bz=s.Ik({id:s.Yj(),name:s.Yj(),publisher:bo,publisherKind:br.optional(),category:v.optional(),version:bq,ruleCount:s.ai().int().nonnegative(),description:s.Yj().optional(),updatedAt:t.w$(),state:bu,importedAs:s.Yj().nullable()}).meta({id:"LibraryItem"});function bA(a){return{id:`${a.namespace}/${a.packId}`,name:a.name,version:a.version,enabled:a.enabled,origin:"library",namespace:a.namespace,packId:a.packId,ruleCount:a.ruleCount,...null!=a.policyId?{policyId:a.policyId}:{},...null!=a.latestVersion?{latestVersion:a.latestVersion}:{}}}function bB(a,b,c){let d=a.rules.flatMap(a=>{let b=aW.safeParse(a.matcher);return b.success?[{id:a.id,name:a.name,category:a.category,severity:a.severity,matcher:b.data}]:[]});return{id:`${a.namespace}/${a.packId}`,name:a.name,version:a.version,enabled:a.enabled,origin:"library",namespace:a.namespace,packId:a.packId,ruleCount:a.rules.length,editedAt:a.updatedAt.toISOString(),findingsLast30d:b,latestVersion:c?c.latestVersion:null,update:c,rules:d,modified:!1,...null!=a.policyId?{policyId:a.policyId}:{}}}function bC(a){let b=a.indexOf("/");return b<1||b===a.length-1?null:{namespace:a.slice(0,b),packId:a.slice(b+1)}}function bD(a,b){let c=a.filter(a=>null!=a.latestVersion),d={all:a.length,library:a.length,custom:0,customized:0,updates:c.length},e=b.filter,f="custom"===e||"customized"===e?[]:"updates"===e?[...c]:[...a];if(b.q){let a=b.q.toLowerCase();f=f.filter(b=>b.name.toLowerCase().includes(a)||b.packId.toLowerCase().includes(a)||b.namespace.toLowerCase().includes(a))}return f.sort((a,b)=>a.enabled!==b.enabled?a.enabled?-1:1:a.name.localeCompare(b.name)),{counts:d,items:f.map(bA)}}s.Ik({categories:s.YO(v),items:s.YO(bz)}).meta({id:"ListLibraryResponse"}),s.Ik({libraryId:s.Yj().refine(a=>/^[^/]+\/[^/]+$/.test(a),{message:"libraryId must be in namespace/packId format"})}).meta({id:"ImportDetectionRequest"});let bE=s.k5(["provider","internal","external","ip"]).meta({id:"DestinationKind"}),bF=s.k5(["https","http","sftp","grpc","smtp","ws","wss"]).meta({id:"Transport"}),bG=s.k5(["secrets","pii","customer","source","telemetry","logs","metrics","none"]).meta({id:"DataClass"}),bH=bG.options,bI=s.k5(["recognized","internal","unverified","ip"]).meta({id:"ShareTrustLevel"}),bJ=s.k5(["allow","block"]).meta({id:"EgressDecision"}),bK=s.k5(["allowed","blocked","review"]).meta({id:"EgressStatus"}),bL=s.k5(["raw_ip","unverified_domain","plaintext_transport"]).meta({id:"ReviewReason"}),bM=s.k5(["GET","POST","PUT","DELETE","SDK","REF"]).meta({id:"HttpMethod"}),bN=s.Ik({needsReview:s.zM(),reasons:s.YO(bL)}).meta({id:"ReviewInfo"}),bO=s.Ik({port:s.ai().int().nullable(),geo:s.Yj().nullable(),ptr:s.Yj().nullable()}).meta({id:"DestinationNetwork"}),bP=s.Ik({id:s.Yj(),method:bM,transport:bF,url:s.Yj(),template:s.zM(),dataClass:bG,lastSeen:t.w$(),callSiteCount:s.ai().int().nonnegative()}).meta({id:"EndpointSummary"}),bQ=s.Ik({id:s.Yj(),project:s.Yj(),file:s.Yj(),line:s.ai().int().nonnegative(),snippet:s.Yj(),dynamic:s.zM(),vendored:s.zM(),projectId:s.Yj().nullable()}).meta({id:"CallSite"}),bR=bP.extend({sites:s.YO(bQ)}).meta({id:"EndpointWithSites"}),bS=s.Ik({id:s.Yj(),kind:bE,name:s.Yj(),host:s.Yj(),category:s.Yj(),trust:bI,status:bK,isCustom:s.zM(),lastSeen:t.w$(),endpointCount:s.ai().int().nonnegative(),callSiteCount:s.ai().int().nonnegative(),transports:s.YO(bF),dataClasses:s.YO(bG),review:bN,network:bO.nullable(),endpoints:s.YO(bP)}).meta({id:"ShareDestinationSummary"});bS.omit({endpointCount:!0,callSiteCount:!0,endpoints:!0}).extend({note:s.Yj().nullable(),endpoints:s.YO(bR)}).meta({id:"ShareDestinationDetail"});let bT=s.Ik({id:s.Yj(),kind:bE,name:s.Yj(),host:s.Yj(),trust:bI,status:bK,review:bN,topDataClass:bG,callSiteCount:s.ai().int().nonnegative(),lastSeen:t.w$()}).meta({id:"ReviewDestination"}),bU=s.Ik({kind:bE,total:s.ai().int().nonnegative(),items:s.YO(bS)}).meta({id:"ShareDestinationGroup"});s.Ik({groups:s.YO(bU)}).meta({id:"ListShareDestinationsResponse"}),s.Ik({items:s.YO(bT)}).meta({id:"NeedsReviewResponse"}),s.Ik({destinations:s.ai().int().nonnegative(),endpoints:s.ai().int().nonnegative(),callSites:s.ai().int().nonnegative(),needsReview:s.ai().int().nonnegative(),insecure:s.ai().int().nonnegative(),byKind:s.Ik({provider:s.ai().int().nonnegative(),internal:s.ai().int().nonnegative(),external:s.ai().int().nonnegative(),ip:s.ai().int().nonnegative()}),byTrust:s.Ik({recognized:s.ai().int().nonnegative(),internal:s.ai().int().nonnegative(),unverified:s.ai().int().nonnegative(),ip:s.ai().int().nonnegative()})}).meta({id:"SharesStats"}),s.Ik({decision:bJ.nullable()}).meta({id:"SetEgressDecisionBody"}),s.Ik({destination:bS}).meta({id:"SetEgressDecisionResponse"}),s.Ik({q:s.Yj().optional(),kind:s.YO(bE).optional(),groupBy:s.k5(["destination"]).default("destination"),review:s.uE().default(!1)}),s.Ik({format:s.k5(["csv","json"]).default("csv"),q:s.Yj().optional(),kind:s.YO(bE).optional()});let bV=s.k5(["npm","pypi","go","maven","rubygems","cargo","composer","nuget"]).meta({id:"EgressEcosystem"});s.Ik({id:s.Yj(),name:s.Yj(),category:s.Yj(),hostSuffixes:s.YO(s.Yj()).min(1),apiBase:s.Yj(),defaultDataClasses:s.YO(bG).min(1),sdks:s.jg(bV,s.YO(s.Yj()))}).meta({id:"ProviderRegistryEntry"});let bW=s.Ik({file:s.Yj(),line:s.ai().int().positive(),snippet:s.Yj(),dynamic:s.zM(),vendored:s.zM()}).meta({id:"EgressCallSiteHit"}),bX=s.Ik({host:s.Yj(),kind:bE,name:s.Yj(),category:s.Yj(),trust:bI,network:bO.nullable(),method:bM,transport:bF,url:s.Yj(),template:s.zM(),dataClass:bG,site:bW}).meta({id:"ResolvedEgressHit"}),bY=s.gM("mode",[s.Ik({mode:s.eu("walk"),walkedPrefix:s.Yj()}),s.Ik({mode:s.eu("ledger"),scannedFiles:s.YO(s.Yj()),deletedFiles:s.YO(s.Yj())})]).meta({id:"EgressReconcile"});s.Ik({projectKey:s.Yj().min(1),project:s.Yj(),projectId:s.Yj().nullable(),reconcile:bY,hits:s.YO(bX)}).meta({id:"RecordProjectEgressInput"}),s.Ik({destinations:s.ai().int().nonnegative(),endpoints:s.ai().int().nonnegative(),callSites:s.ai().int().nonnegative(),truncated:s.zM(),droppedFiles:s.YO(s.Yj()).default([])}).meta({id:"EgressWriteSummary"});let bZ=s.Yj().optional(),b$=s.Ik({reference:s.Yj(),scope:s.Yj(),reason:s.Yj(),confirmation:bZ}),b_=s.Ik({ruleId:s.Yj(),value:s.Yj(),scope:s.Yj(),reason:s.Yj(),confirmation:bZ}),b0=s.Ik({pointer:s.Yj(),scope:s.Yj(),justification:s.Yj(),confirmation:bZ}),b1=s.Ik({id:s.Yj(),reason:s.Yj()}),b2=s.Ik({confirmation:s.Yj()});function b3(a,b){let c=a.safeParse(b);if(c.success)return{ok:!0,data:c.data};for(let a of c.error.issues){let[b]=a.path;if("string"==typeof b)return{ok:!1,field:b,wrongType:"invalid_type"===a.code}}return{ok:!1,field:null,wrongType:!1}}function b4(a){return({log:"monitored",block:"blocked",redact:"redacted",warn:"warned",allow:"allowed"})[a]??"allowed"}function b5(a){return"code_context"===a?"source_code":a}function b6(a){return V[a]??"api"}let b7=["open","handled","dismissed","resolved"];function b8(a){let b=new Set(a.filter(a=>void 0!==a));if(0!==b.size){for(let a of b7)if(b.has(a))return a}}function b9(a){return"code_change"!==a.kind?"handled":null===a.findingKey?"open":"resolved"===a.latestResolutionStatus?"resolved":"dismissed"===a.latestResolutionStatus?"dismissed":"open"}function ca(a,b={}){let c=b.overrides,d=b.packNames,e=b.aggregates,f=new Map;for(let b of a){let a=f.get(b.ruleId);a?a.push(b):f.set(b.ruleId,[b])}let g=[];for(let[a,b]of f){let f=b.map(a=>{let b=c?.get(a.id)??a.actionTaken;return{id:a.id,provider:b6(a.sourceTool),repo:a.repo,file:a.file,...void 0===a.toolName?{}:{toolName:a.toolName},...void 0===a.eventId?{}:{eventId:a.eventId},...void 0===a.sessionId?{}:{sessionId:a.sessionId},action:b4(b),detectedAt:a.occurredAt,confidence:a.confidence,status:a.status}}),h=e?.get(a),i=h?.latestDetectedAt??b.reduce((a,b)=>b.occurredAt>a?b.occurredAt:a,b[0]?.occurredAt??new Date(0).toISOString()),j=new Set,k=(h?[...new Set(h.sourceTools.map(b6))].sort():f.map(a=>a.provider)).filter(a=>!j.has(a)&&(j.add(a),!0)),l=new Set(h?h.actionsTaken.map(b4):f.map(a=>a.action)),m=1===l.size?[...l][0]??null:null,n=b[0]?.severity??"low",o={id:a,name:d?.get(a)??null},p=b5(b[0]?.category??"custom"),q={id:`category:${p}`,name:p},r={maskedValue:b[0]?.maskedMatch??"",contextPrefix:""},s=b8(h?h.statusInputs.map(b9):f.map(a=>a.status)),t={id:a,category:p,subtype:a,severity:n,match:r,detection:o,policy:q,instanceCount:h?.instanceCount??f.length,providers:k,aggregateAction:m,latestDetectedAt:i,instances:f,status:s};h&&(cd.set(t,[...l]),void 0!==h.searchText&&cb.set(t,cc(t,h.searchText))),g.push(t)}return g}let cb=new WeakMap;function cc(a,b){return[a.subtype,a.category,a.match.maskedValue,a.policy.name,a.id,...a.instances.map(a=>a.repo),...a.instances.map(a=>a.file),...a.instances.map(a=>a.toolName?`via ${a.toolName}`:""),...a.instances.map(a=>a.id),...void 0===b?[]:[b]].join(" ").toLowerCase()}let cd=new WeakMap;function ce(a){let b=cd.get(a);if(void 0!==b)return b;let c=[...new Set(a.instances.map(a=>a.action))];return cd.set(a,c),c}function cf(a,b){let c=new Set(b),d=0;for(let b of a){if(void 0===b.count)return null;c.has(b9(b))&&(d+=b.count)}return d}function cg(a,b){let c=a;if(b.severity&&b.severity.length>0){let a=new Set(b.severity);c=c.filter(b=>a.has(b.severity))}if(b.providers&&b.providers.length>0){let a=new Set(b.providers);c=c.filter(b=>b.providers.some(b=>a.has(b)))}if(b.actions&&b.actions.length>0){let a=new Set(b.actions);c=c.filter(b=>ce(b).some(b=>a.has(b)))}if(b.subtype&&b.subtype.length>0){let a=new Set(b.subtype);c=c.filter(b=>a.has(b.subtype))}if(b.statuses&&b.statuses.length>0){let a=new Set(b.statuses);c=c.filter(b=>void 0!==b.status&&a.has(b.status))}if(b.q){let a=b.q.toLowerCase();c=c.filter(b=>(function(a){let b=cb.get(a);if(void 0!==b)return b;let c=cc(a);return cb.set(a,c),c})(b).includes(a))}return c}let ch={critical:0,high:1,medium:2,low:3};function ci(a,b){let c=(ch[a.severity]??-1)-(ch[b.severity]??-1);if(0!==c)return c;let d=b.latestDetectedAt.localeCompare(a.latestDetectedAt);return 0!==d?d:a.id.localeCompare(b.id)}function cj(a){return[...a].sort(ci)}function ck(a,b){let c=cg(a,{providers:b.providers,actions:b.actions,statuses:b.statuses,q:b.q,subtype:b.subtype}),d=new Map;for(let a of c)d.set(a.severity,(d.get(a.severity)??0)+1);let e=cg(a,{actions:b.actions,statuses:b.statuses,q:b.q,subtype:b.subtype,severity:b.severity}),f=new Map;for(let a of e)for(let b of a.providers)f.set(b,(f.get(b)??0)+1);let g=cg(a,{providers:b.providers,statuses:b.statuses,q:b.q,subtype:b.subtype,severity:b.severity}),h=new Map;for(let a of g)for(let b of ce(a))h.set(b,(h.get(b)??0)+1);let i=cg(a,{providers:b.providers,actions:b.actions,statuses:b.statuses,q:b.q,severity:b.severity}),j=new Map;for(let a of i)j.set(a.subtype,(j.get(a.subtype)??0)+1);let k=cg(a,{providers:b.providers,actions:b.actions,q:b.q,subtype:b.subtype,severity:b.severity}),l=new Map;for(let a of k)void 0!==a.status&&l.set(a.status,(l.get(a.status)??0)+1);let m=a=>[...a.entries()].map(([a,b])=>({value:a,count:b}));return{severity:m(d),provider:m(f),action:m(h),subtype:m(j),status:m(l)}}let cl=["severity","subtype","providers","actions","statuses","tools","repo","file","q"];function cm(a,b,c){for(let d of cl)if(d!==c&&!function(a,b,c){switch(c){case"severity":return!b.severity?.length||b.severity.includes(a.severity);case"subtype":return!b.subtype?.length||b.subtype.includes(a.ruleId);case"providers":return!b.providers?.length||b.providers.includes(b6(a.sourceTool));case"actions":return!b.actions?.length||b.actions.includes(b4(a.actionTaken));case"statuses":return!b.statuses?.length||void 0!==a.status&&b.statuses.includes(a.status);case"tools":return!b.tools?.length||void 0!==a.toolName&&b.tools.includes(a.toolName);case"repo":return void 0===b.repo||""===b.repo||a.repo===b.repo;case"file":return void 0===b.file||""===b.file||a.file===b.file;case"q":return!b.q||[a.ruleId,a.category,a.maskedMatch,a.repo,a.file,a.toolName?`via ${a.toolName}`:"",a.id].join(" ").toLowerCase().includes(b.q.toLowerCase())}}(a,b,d))return!1;return!0}function cn(a){return[...a.entries()].map(([a,b])=>({value:a,count:b})).sort((a,b)=>b.count-a.count||a.value.localeCompare(b.value))}function co(a,b){a.set(b,(a.get(b)??0)+1)}function cp(a){let b=new Map,c=new Map,d=new Map,e=new Map,f=new Map,g=new Map;return{add(h){cm(h,a,"severity")&&co(b,h.severity),cm(h,a,"subtype")&&co(c,h.ruleId),cm(h,a,"providers")&&co(d,b6(h.sourceTool)),cm(h,a,"actions")&&co(e,b4(h.actionTaken)),void 0!==h.status&&cm(h,a,"statuses")&&co(f,h.status),void 0!==h.toolName&&cm(h,a,"tools")&&co(g,h.toolName)},facets:()=>({severity:cn(b),subtype:cn(c),provider:cn(d),action:cn(e),status:cn(f),tool:cn(g)})}}function cq(a){let b=b5(a.category);return{id:a.id,provider:b6(a.sourceTool),repo:a.repo,file:a.file,...void 0===a.toolName?{}:{toolName:a.toolName},eventId:a.eventId,...void 0===a.sessionId?{}:{sessionId:a.sessionId},action:b4(a.actionTaken),detectedAt:a.occurredAt,confidence:a.confidence,...void 0===a.status?{}:{status:a.status},groupId:a.ruleId,category:b,subtype:a.ruleId,severity:a.severity,match:{maskedValue:a.maskedMatch,contextPrefix:""},detection:{id:a.ruleId,name:null},policy:{id:`category:${b}`,name:b}}}let cr={critical:0,high:1,medium:2,low:3};function cs(){return{instanceCount:0,maxSeverityRank:Number.MAX_SAFE_INTEGER,maxSeverity:"low",latestDetectedAt:"",statuses:[],ruleIds:new Set}}function ct(a,b){a.instanceCount+=1;let c=cr[b.severity]??Number.MAX_SAFE_INTEGER-1;c<a.maxSeverityRank&&(a.maxSeverityRank=c,a.maxSeverity=b.severity),b.occurredAt>a.latestDetectedAt&&(a.latestDetectedAt=b.occurredAt),a.statuses.push(b.status),a.ruleIds.add(b.ruleId)}let cu=s.Ik({id:s.Os(),namespace:bo,packId:bp,version:bq,name:s.Yj(),enabled:s.zM().default(!0),policyId:s.Yj().optional()}).meta({id:"InstalledPack"});s.Ik({namespace:bo,packId:bp,version:bq}).meta({id:"InstallPackRequest"}),s.Ik({items:s.YO(cu)}).meta({id:"ListInstalledPacksResponse"}),s.Ik({enabled:s.zM().optional(),policyId:s.Yj().nullable().optional()}).refine(a=>Object.keys(a).some(b=>void 0!==a[b]),{message:"At least one field must be provided"}).meta({id:"PatchInstalledPackRequest"});let cv=2,cw=v.options.join("|"),cx=RegExp(`\\[\\[aka:(?:${cw}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`),cy=RegExp(`^${cx.source}$`);function cz(){return RegExp(cx.source,"g")}let cA=s.Yj().regex(cy);s.Ik({category:v,keyVersion:s.ai().int().positive(),pointerId:s.Yj(),tag:s.Yj()}),s.Ik({pointerId:s.Yj(),valueFingerprint:s.Yj().regex(/^[0-9a-f]{64}$/),fingerprintKeyVersion:s.ai().int().positive(),keyVersion:s.ai().int().positive(),category:v,ruleId:s.Yj(),maskedMatch:s.Yj(),provider:s.Yj().optional(),ciphertext:s.Yj(),nonce:s.Yj(),authTag:s.Yj(),occurrenceCount:s.ai().int().nonnegative(),firstSeen:s.Yj(),lastSeen:s.Yj()}),s.Ik({category:v,provider:s.Yj().optional(),maskedMatch:s.Yj(),occurrences:s.ai().int().nonnegative(),firstSeen:s.Yj(),lastSeen:s.Yj()}),s.Ik({ruleId:s.Yj(),valueFingerprint:s.Yj().regex(/^[0-9a-f]{64}$/),fingerprintKeyVersion:s.ai().int().positive()});let cB=s.k5(["human","model"]),cC=s.k5(["display","explicit-reveal","view-render","model-input","remediation","purge"]),cD=s.k5(["revealed","refused","unavailable"]),cE=["display","view-render"];function cF(a){return cE.includes(a)}let cG=s.Ik({id:s.Os(),pointerId:s.Yj(),at:s.Yj(),target:cB,reason:cC,outcome:cD,grantId:s.Yj().optional(),pointerCount:s.ai().int().positive().default(1)}),cH=s.k5(["prompt","tool-input","tool-output","file","transcript"]),cI=s.Ik({location:s.Yj(),kind:cH,firstSeen:s.Yj(),lastSeen:s.Yj()}),cJ=s.Ik({pointerId:s.Yj(),category:v,provider:s.Yj().optional(),maskedMatch:s.Yj(),occurrences:s.ai().int().nonnegative(),firstSeen:s.Yj(),lastSeen:s.Yj(),revealGrantId:s.Yj().nullable(),sightings:s.YO(cI)}),cK=50,cL=50,cM=200,cN=s.Ik({limit:u.ai().int().min(1).max(cM).optional(),cursor:s.Yj().optional()});s.Ik({totals:s.Ik({values:s.ai().int().nonnegative()}),items:s.YO(cJ),nextCursor:s.Yj().nullable()});let cO=s.Ik({limit:u.ai().int().min(1).max(cM).optional(),cursor:s.Yj().optional()});s.Ik({totals:s.Ik({reused:s.ai().int().nonnegative()}),items:s.YO(cJ),nextCursor:s.Yj().nullable()});let cP=s.Ik({includeBatched:s.zM().optional(),limit:u.ai().int().min(1).max(cM).optional(),cursor:s.Yj().optional()});s.Ik({items:s.YO(cG),nextCursor:s.Yj().nullable(),hiddenBatched:s.ai().int().nonnegative()});let cQ=s.Yj(),cR=s.k5(["masked","full","off"]),cS=1,cT=s.Ik({acknowledgedAt:t.w$(),version:s.ai().int().positive()});function cU(a){return a?.version===cS}let cV=1,cW=s.k5(["standalone"]),cX=s.k5(["redact","warn"]),cY=s.k5(["full","session-only"]),cZ=s.Ik({acknowledgedAt:t.w$(),payloadVersion:s.ai().int().positive()}),c$=s.Ik({specVersion:s.ai().int().positive().default(5),runMode:s.vk(a=>"attached"===a?"standalone":a,cW.default("standalone")),policy:cX.default("redact"),historicalAccess:cY.default("session-only"),dataSharesInPlace:s.zM().default(!0),vaultConsent:cT.optional(),vaultKeyCustody:cQ.default("file"),vaultInlineReveal:cR.default("masked"),onboardedAt:t.w$().optional(),modelJudgeConsent:cZ.optional()});function c_(){return c$.parse({})}function c0(a,b,c){return{id:b,objectType:a.objectType,location:a.location??null,title:a.title??null,hostId:a.hostId??null,attributes:JSON.stringify(a.attributes),firstSeen:c,lastSeen:c}}function c1(a,b,c){return{id:b,url:a.url,name:a.name??null,attributes:JSON.stringify(a.attributes),firstSeen:c,lastSeen:c}}function c2(a){return{id:a.id,parentId:a.parentId??null,rootSessionId:a.rootSessionId??null,eventType:a.eventType,hostId:a.hostId??null,harnessId:a.harnessId??null,sourceProjectId:a.sourceProjectId??null,startedAt:g(a.startedAt),endedAt:a.endedAt?g(a.endedAt):null,severity:a.severity??null,priority:a.priority??null,content:a.content??null,contentHash:a.contentHash??null,attributes:a.attributes?JSON.stringify(a.attributes):null}}function c3(a,b){return{id:b,class:a.class,label:a.label??null,attributes:a.attributes?JSON.stringify(a.attributes):null}}function c4(a,b){return{id:b,ruleId:a.ruleId,name:a.name,category:a.category,severity:a.severity,definition:a.definition,version:a.version}}function c5(a){return{id:a.id,auditEventId:a.auditEventId,inspectionDefinitionId:a.inspectionDefinitionId,classifiedDataId:a.classifiedDataId??null,spanStart:a.span.start,spanEnd:a.span.end,maskedMatch:a.maskedMatch,actionTaken:a.actionTaken,confidence:a.confidence,findingKey:a.findingKey??null,firstDetectedAt:a.firstDetectedAt?g(a.firstDetectedAt):null}}function c6(a){let b=a.metadata;return{source_tool:a.sourceTool,...b?.repo!==void 0?{repo:b.repo}:{},...b?.filePath!==void 0?{file_path:b.filePath}:{},...b?.toolName!==void 0?{tool_name:b.toolName}:{},...b?.gitignored!==void 0?{gitignored:b.gitignored}:{},...b?.wholeFile!==void 0?{whole_file:b.wholeFile}:{},...b?.correlationId!==void 0?{correlation_id:b.correlationId}:{},...b?.traceId!==void 0?{trace_id:b.traceId}:{},...b?.exceptionIds!==void 0?{exception_ids:b.exceptionIds}:{},...b?.model!==void 0?{model:b.model}:{},...b?.turnIndex!==void 0?{turn_index:b.turnIndex}:{}}}function c7(a){return`capture/${a.category}/${a.severity}`}function c8(a){return{ruleId:a.ruleId,version:c7(a),name:a.ruleId,category:a.category,severity:a.severity,definition:JSON.stringify({ruleId:a.ruleId})}}let c9=s.Ik({path:s.Yj().min(1),name:s.Yj().min(1),origin:aw,defaultAccess:av});s.Ik({files:s.YO(c9),truncated:s.zM(),scannedAt:s.Yj()});let da=["7d","30d","3m","6m"],db=s.k5(da).meta({id:"TimeRange"}),dc={"7d":7,"30d":30,"3m":90,"6m":180};db.catch("7d");let dd=s.k5(["still-valid","unknown","invalid"]),de=s.Ik({filePath:s.Yj(),span:z.optional()}).strict(),df=s.Ik({provider:s.Yj(),maskedToken:s.Yj(),where:de,state:dd,observedAt:t.w$().optional()}).strict();s.Ik({provider:s.Yj(),maskedToken:s.Yj(),consolePath:s.Yj(),occurrenceSpread:s.ai().int().positive()}).strict();let dg=s.k5(["redact-rotation-checklist","redact-only","set-secret-redact","leave"]),dh=s.k5(["first-run","pre-push","secret-scan"]);s.Ik({entrySource:dh}).strict();let di=s.Ik({id:dg,label:s.Yj()}),dj=s.Ik({kind:s.eu("decision"),entrySource:dh,secretCount:s.ai().int().positive(),prompt:s.Yj(),options:s.PV([di.extend({id:s.eu("redact-rotation-checklist")}),di.extend({id:s.eu("redact-only")}),di.extend({id:s.eu("set-secret-redact")}),di.extend({id:s.eu("leave")})])}),dk=s.Ik({kind:s.eu("no-decision")});s.gM("kind",[dj,dk]),s.Ik({rules:s.YO(a_).min(1).max(100),text:s.Yj().max(5e4).optional(),fixtures:s.YO(a$).max(200).optional()}).refine(a=>void 0!==a.text||(a.fixtures?.length??0)>0,{message:"Provide `text`, `fixtures`, or both — there must be something to test"}).meta({id:"TestRulesRequest"});let dl=s.Ik({ruleId:s.Yj(),category:v,severity:w,span:z,confidence:s.ai().min(0).max(1),match:s.Yj()}).meta({id:"RuleTestMatch"}),dm=s.Ik({label:s.Yj(),shouldMatch:s.zM(),didMatch:s.zM(),passed:s.zM(),matches:s.YO(dl)}).meta({id:"FixtureResult"});s.Ik({adhoc:s.Ik({matches:s.YO(dl)}).optional(),fixtures:s.YO(dm),summary:s.Ik({total:s.ai().int().nonnegative(),passed:s.ai().int().nonnegative(),failed:s.ai().int().nonnegative()}),unsupportedRuleIds:s.YO(s.Yj())}).meta({id:"TestRulesResponse"});let dn=s.Ik({severity:w,count:s.ai().int().nonnegative(),caught:s.ai().int().nonnegative().optional(),openAtRest:s.ai().int().nonnegative().optional()}).meta({id:"SeveritySummaryItem"});s.Ik({total:s.ai().int().nonnegative(),needsRemediation:s.ai().int().nonnegative().optional(),bySeverity:s.YO(dn)}).meta({id:"SeveritySummaryResponse"}),s.Ik({range:s.k5(da).default("7d")});let dp=s.k5(["blocked","redacted","warned"]).meta({id:"EnforcementActionKind"}),dq=s.Ik({kind:dp,count:s.ai().int().nonnegative(),delta:s.ai().int()}).meta({id:"EnforcementAction"});s.Ik({range:db,total:s.ai().int().nonnegative(),actions:s.YO(dq)}).meta({id:"EnforcementActionsResponse"});let dr=s.k5(["day","week"]).meta({id:"TimeseriesGranularity"}),ds=s.Ik({timestamp:t.p6(),critical:s.ai().int().nonnegative(),high:s.ai().int().nonnegative(),medium:s.ai().int().nonnegative()}).meta({id:"FindingsTimeseriesPoint"});s.Ik({range:db,granularity:dr,points:s.YO(ds)}).meta({id:"FindingsTimeseriesResponse"});let dt=s.Ik({timestamp:t.p6(),bySeverity:s.Ik({critical:s.ai().nonnegative().nullable(),high:s.ai().nonnegative().nullable(),medium:s.ai().nonnegative().nullable(),low:s.ai().nonnegative().nullable()})}).meta({id:"MttrTrendPoint"});s.Ik({range:db,granularity:dr,points:s.YO(dt)}).meta({id:"MttrTrendResponse"});let du=s.Ik({findingKey:s.Yj(),ruleId:s.Yj(),severity:w,path:s.Yj(),resolvedAt:t.w$(),detectedAt:t.w$()}).meta({id:"ResolvedFeedItem"});s.Ik({items:s.YO(du)}).meta({id:"RecentlyResolvedResponse"});let dv=["repo","user"],dw=s.k5(dv).meta({id:"SourceKind"}),dx=s.Ik({id:s.Yj(),name:s.Yj(),kind:dw,findingsCount:s.ai().int().nonnegative()}).meta({id:"TopSource"});s.Ik({range:db,items:s.YO(dx)}).meta({id:"TopSourcesResponse"}),s.Ik({range:s.k5(da).default("7d"),limit:u.ai().int().min(1).max(50).default(5),kind:s.k5(dv).optional()});let dy=s.k5(["claudecode","cursor","codex","antigravity","claudeai","chatgpt","copilot","api"]).meta({id:"Provider"}),dz=s.Ik({provider:dy,coverage:s.ai().int().min(0).max(100),supported:s.zM()}).meta({id:"ScanCoverageProvider"});s.Ik({range:db,providers:s.YO(dz)}).meta({id:"ScanCoverageResponse"});let dA=s.k5(["repo","user","team","policy","share","rule"]).meta({id:"SubjectType"}),dB=s.Ik({type:dA,id:s.Yj(),label:s.Yj()}).meta({id:"RecommendationSubject"}),dC=s.k5(["apply","navigate"]).meta({id:"RecommendationActionMode"}),dD=s.Ik({mode:dC,type:s.Yj(),label:s.Yj(),href:s.Yj().optional(),policyId:s.Yj().optional(),teamId:s.Yj().optional()}).meta({id:"RecommendationAction"}),dE=s.Ik({id:s.Yj(),category:s.Yj(),severity:w,title:s.Yj(),description:s.Yj(),subjects:s.YO(dB),action:dD}).meta({id:"RecommendedAction"});s.Ik({items:s.YO(dE)}).meta({id:"RecommendedActionsResponse"}),s.Ik({limit:u.ai().int().min(1).max(20).default(3)});let dF=s.Ik({type:s.Yj(),policyId:s.Yj().optional(),teamId:s.Yj().optional()}).meta({id:"AppliedAction"});s.Ik({id:s.Yj(),status:s.eu("applied"),appliedAction:dF}).meta({id:"ApplyRecommendedActionResponse"}),s.Ik({id:s.Yj(),status:s.eu("dismissed")}).meta({id:"DismissRecommendedActionResponse"}),s.Ik({id:s.Yj()}),s.Ik({ruleId:s.Yj(),category:v,severity:w,maskedMatch:s.Yj(),rawMatch:s.Yj(),context:s.Yj(),filePath:s.Yj().optional(),confidence:s.ai().min(0).max(1),id:s.Yj().optional(),valueFingerprint:s.Yj().optional(),keyVersion:s.ai().int().nonnegative().optional()});let dG=s.Ik({category:v,action:a9,reasoning:s.Yj(),genuineCount:s.ai().int().nonnegative(),fpCount:s.ai().int().nonnegative(),fpIds:s.YO(s.Yj())});s.Ik({perCategory:s.YO(dG),notes:s.Yj()});let dH=s.Ik({total:s.ai().int().nonnegative(),important:s.ai().int().nonnegative(),routine:s.ai().int().nonnegative()}).refine(a=>a.total===a.important+a.routine,{message:"total must equal important + routine",path:["total"]}),dI=s.Ik({ruleId:s.Yj(),category:v,valueFingerprint:s.Yj(),keyVersion:s.ai().int().nonnegative()}),dJ=s.Ik({pattern:s.Yj(),count:s.ai().int().nonnegative(),values:s.YO(dI).min(1)}),dK=s.Ik({category:v,count:s.ai().int().nonnegative(),egress:s.zM()}),dL=s.Ik({counts:dH,routineCategories:s.YO(v),surfacedCategories:s.YO(v),findingKinds:s.YO(dK),posture:s.g1(v,a9),maskedFindings:s.YO(df).optional(),falsePositivePatterns:s.YO(dJ).optional()}),dM=dG.pick({category:!0,genuineCount:!0,fpCount:!0}).extend({egress:s.zM()});s.Ik({categories:s.YO(dM),posture:s.g1(v,a9)}),s.Ik({frame:dL,copy:s.Yj()}),s.k5(["scan","floor"]);let dN=s.Ik({id:s.k5(["enter-remediation","open-dashboard","not-now"]),label:s.Yj()}),dO=s.PV([dN.extend({id:s.eu("open-dashboard")}),dN.extend({id:s.eu("not-now")})]),dP=s.PV([dN.extend({id:s.eu("enter-remediation")}),dN.extend({id:s.eu("open-dashboard")}),dN.extend({id:s.eu("not-now")})]);s.Ik({worthALook:s.ai().int().nonnegative(),liveKeys:s.ai().int().nonnegative().optional(),options:s.KC([dO,dP])}).refine(a=>a.options.some(a=>"enter-remediation"===a.id)===(a.liveKeys??0)>0,{message:"the chain-entry option is present exactly when liveKeys > 0",path:["options"]}).refine(a=>(a.liveKeys??0)<=a.worthALook,{message:"liveKeys is a subset of worthALook and cannot exceed it",path:["liveKeys"]});let dQ=new Set(["recognized","internal"]);function dR(a){return dQ.has(a)?"allowed":"review"}function dS(a){return"block"===a?"blocked":"allowed"}function dT(a,b){return null===b?dR(a):dS(b)}function dU(a,b){return null!==b&&dS(b)!==dR(a)}function dV(a,b){let c=function(a,b){let c=[];return"ip"===a&&c.push("raw_ip"),"unverified"===a&&c.push("unverified_domain"),(b.includes("http")||b.includes("ws"))&&c.push("plaintext_transport"),c}(a,b);return{needsReview:c.length>0,reasons:c}}function dW(a){return Array.from(new Set(a))}function dX(a){let b=new Set(a);return bH.filter(a=>b.has(a))}function dY(a){return dX(a)[0]??"none"}let dZ={raw_ip:0,unverified_domain:1,plaintext_transport:2};function d$(a){return 0===a.length?1/0:Math.min(...a.map(a=>dZ[a]))}}};
|