@akasecurity/cli 0.9.8 → 0.9.10
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/dist/cli.js +12237 -3792
- package/extension/manifest.json +1 -1
- package/native-host/host.js +12439 -5407
- package/native-host/scan-worker.js +8186 -2742
- package/native-host/sync.js +12742 -7049
- package/package.json +8 -8
- package/web-ui/package.json +5 -4
- package/web-ui/packages/dashboard-ui/package.json +7 -5
- package/web-ui/packages/detections/package.json +2 -2
- package/web-ui/packages/local-ops/package.json +2 -2
- package/web-ui/packages/persistence/package.json +2 -2
- package/web-ui/packages/plugin-sdk/package.json +3 -3
- package/web-ui/packages/schema/package.json +5 -4
- package/web-ui/packages/ui-kit/package.json +2 -2
- package/web-ui/web-ui/.next/BUILD_ID +1 -1
- package/web-ui/web-ui/.next/app-build-manifest.json +256 -256
- package/web-ui/web-ui/.next/app-path-routes-manifest.json +8 -8
- package/web-ui/web-ui/.next/build-manifest.json +14 -14
- package/web-ui/web-ui/.next/prerender-manifest.json +10 -10
- package/web-ui/web-ui/.next/required-server-files.json +3 -2
- 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 +3 -3
- 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.js.nft.json +1 -1
- 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 +10 -10
- package/web-ui/web-ui/.next/server/app/icon.svg/route.js +1 -1
- package/web-ui/web-ui/.next/server/app/icon.svg/route.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/app/index.html +1 -1
- package/web-ui/web-ui/.next/server/app/index.rsc +10 -10
- package/web-ui/web-ui/.next/server/app/page.js +2 -2
- package/web-ui/web-ui/.next/server/app/page.js.nft.json +1 -1
- 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 +8 -8
- package/web-ui/web-ui/.next/server/chunks/19.js +22 -0
- package/web-ui/web-ui/.next/server/chunks/389.js +903 -0
- package/web-ui/web-ui/.next/server/chunks/475.js +1 -0
- package/web-ui/web-ui/.next/server/chunks/585.js +12 -0
- package/web-ui/web-ui/.next/server/chunks/589.js +99 -0
- package/web-ui/web-ui/.next/server/chunks/667.js +894 -0
- package/web-ui/web-ui/.next/server/chunks/67.js +6 -0
- package/web-ui/web-ui/.next/server/chunks/7.js +1 -0
- package/web-ui/web-ui/.next/server/chunks/743.js +11 -0
- package/web-ui/web-ui/.next/server/chunks/851.js +1 -0
- package/web-ui/web-ui/.next/server/chunks/935.js +61 -0
- package/web-ui/web-ui/.next/server/chunks/{271.js → 950.js} +3 -3
- package/web-ui/web-ui/.next/server/functions-config-manifest.json +5 -5
- 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/middleware.js +2 -2
- 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/pages/_app.js +1 -1
- package/web-ui/web-ui/.next/server/pages/_app.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/pages/_document.js +1 -1
- package/web-ui/web-ui/.next/server/pages/_document.js.nft.json +1 -1
- package/web-ui/web-ui/.next/server/pages/_error.js +9 -9
- package/web-ui/web-ui/.next/server/pages/_error.js.nft.json +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/288-2743815300ed0872.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/399-6887e92996f64590.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/526-026c69b926a17dbb.js +50 -0
- package/web-ui/web-ui/.next/static/chunks/52b9c8c1-87132a73d61bdb69.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/563-a96f29a2819589cb.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/907-207847c57011ba44.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-e4f94a75c631ce86.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-d70fcc5612f380b7.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-e1823ce15bb6277d.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/error-14165283b00c8626.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-0fcffe4b9dff201f.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-c95079a2acd284fd.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-4b9f034bd078f5d3.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-b97fc083884ef341.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-e96e7e947ed5f279.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-83072d434c6b6b0e.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-b90748d139a546c9.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-7a46abe149271870.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/security/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-f4a1ee202d6e60a4.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-2ec6d863f1a31792.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-b388003fb0d3efd1.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/loading-5ae897a85d4509ca.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-6bda74d234a1376a.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/_not-found/page-a0f1d816312dcb9c.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/layout-d6718b04dff0ca9c.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/app/page-9f976e619a11c1dd.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/{framework-ad79db97790c5c58.js → framework-78529e4152d251a3.js} +1 -1
- package/web-ui/web-ui/.next/static/chunks/main-aef82d1ebf75b725.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/main-app-ecdeb13a427413ee.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/pages/_app-cb7c9f431bf725f7.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/pages/_error-fae7cf4a2cfcee1b.js +1 -0
- package/web-ui/web-ui/.next/static/chunks/{webpack-1b293f289da20845.js → webpack-f10501a57c4d919d.js} +1 -1
- package/web-ui/web-ui/.next/static/css/81a7ed955b02c959.css +2 -0
- package/web-ui/web-ui/.next/static/{zjNAa9qOfKutYwuhfySp_ → k7tk0MLkPITbi_x6JL01X}/_buildManifest.js +1 -1
- package/web-ui/web-ui/dist/scan-worker.js +8186 -2742
- package/web-ui/web-ui/package.json +7 -5
- package/web-ui/web-ui/server.js +1 -1
- package/web-ui/web-ui/.next/server/chunks/214.js +0 -73
- package/web-ui/web-ui/.next/server/chunks/258.js +0 -1
- package/web-ui/web-ui/.next/server/chunks/261.js +0 -22
- package/web-ui/web-ui/.next/server/chunks/314.js +0 -783
- package/web-ui/web-ui/.next/server/chunks/326.js +0 -12
- package/web-ui/web-ui/.next/server/chunks/523.js +0 -1
- package/web-ui/web-ui/.next/server/chunks/68.js +0 -123
- package/web-ui/web-ui/.next/server/chunks/803.js +0 -6
- package/web-ui/web-ui/.next/server/chunks/844.js +0 -791
- package/web-ui/web-ui/.next/server/chunks/853.js +0 -11
- package/web-ui/web-ui/.next/server/chunks/967.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/180-0ab5475b6174d4b3.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/202-12a474de79b2ad1c.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/392-0af97129ba2175ca.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/39f60ebf-2d09993ae96ffb2f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/622-0520747def5cc37b.js +0 -62
- package/web-ui/web-ui/.next/static/chunks/699-f5e42f0ed71707d9.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-ee3b9956abc7cf1b.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-9997c04ce4d4a451.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-5c9b3e6f6d832127.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/error-b23da3100319d95d.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-5f56a9fa25e7af46.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-38dcdc2eb2e47f53.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-94d735bc414c9b5c.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-073d0b64e942914f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-71344cf66ee67b51.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-bf74f5338553e0b3.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-5bdaaab9140bb24a.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-24429599495731bf.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/security/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-d9a6be4fb74dd62b.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-f633645e1112fcb9.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-429f377f34456a96.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/loading-6dba555198465a8f.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-21c59276737a8b9e.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/_not-found/page-70d570cb7ebebf40.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/layout-0c542f2984281272.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/app/page-3fecd9ee711fb63b.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/main-62317e1f0973aad9.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/main-app-54d1703ac3de3a4b.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/pages/_app-58f8bdc469e1bada.js +0 -1
- package/web-ui/web-ui/.next/static/chunks/pages/_error-bfbac2b89a182714.js +0 -1
- package/web-ui/web-ui/.next/static/css/3be78f90024fcfd7.css +0 -2
- /package/web-ui/web-ui/.next/static/{zjNAa9qOfKutYwuhfySp_ → k7tk0MLkPITbi_x6JL01X}/_ssgManifest.js +0 -0
|
@@ -1,791 +0,0 @@
|
|
|
1
|
-
"use strict";exports.id=844,exports.ids=[844],exports.modules={48844:(a,b,c)=>{c.d(b,{WR:()=>aA,qA:()=>aB,qk:()=>b5,Pi:()=>cJ,o8:()=>b6,Qo:()=>bN,Ru:()=>cF,KS:()=>b$,tI:()=>bY,_2:()=>bW,Dg:()=>bX,Wo:()=>b_,Rd:()=>bU,Ji:()=>bG,y9:()=>bT,xR:()=>b3,v5:()=>bV,g5:()=>q});var d=c(73024),e=c(76760),f=c(85002),g=c(75919);let h="aka.db";function i(a,b){if(!function(a){try{return(0,d.lstatSync)(a).isSymbolicLink()}catch{return!1}}(a))try{(0,d.chmodSync)(a,b)}catch{}}function j(a){i(a,448)}function k(a,b=!1){(0,d.mkdirSync)(a,{recursive:b,mode:448})}function l(a){k(a,!0),j(a)}function m(a){return[`${a}-wal`,`${a}-shm`,`${a}-journal`]}function n(a){i(a,384)}function o(a){for(let b of[a,...m(a)])i(b,384)}function p(a,b){(0,d.writeFileSync)(a,b,{mode:384,flag:"wx"})}function q(a,b){let c=`${a}.${String(process.pid)}.tmp`;try{(0,d.rmSync)(c,{force:!0})}catch{}try{p(c,b),(0,d.renameSync)(c,a)}finally{try{(0,d.rmSync)(c,{force:!0})}catch{}}n(a)}function r(a){try{if((0,d.lstatSync)(a).isSymbolicLink())return{kind:"symlink"};return{kind:"gone"}}catch(a){if("ENOENT"===a.code)return{kind:"gone"};return{kind:"unknown",cause:a}}}class s extends Error{constructor(a,b){super(a,void 0===b?void 0:{cause:b}),this.code="key-unclaimable",this.name="KeyUnclaimableError"}}function t(a,b){let c,e=`${a}.${String(process.pid)}.${String(g.threadId)}.new`;try{(0,d.rmSync)(e,{force:!0})}catch{}try{p(e,b),c=function(a,b,c){try{return(0,d.linkSync)(a,b),!0}catch(b){let a=b.code;if("EEXIST"===a)return!1;if(!u.has(a??""))throw b}try{return p(b,c),!0}catch(a){if("EEXIST"===a.code)return!1;throw a}}(e,a,b)}finally{try{(0,d.rmSync)(e,{force:!0})}catch{}}return c&&n(a),c}let u=new Set(["EPERM","ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL"]);var v=c(77598),w=c(79868);function x(a){return(0,v.createHash)("sha256").update(a).digest("hex")}function y(a){return x((0,f.tTV)(["source_project",a]))}function z(a,b){return x((0,f.tTV)(["inspection_definition",a,b]))}function A(a,b){return`${a}.${b}.${String(Date.now())}.${(0,v.randomUUID)().slice(0,8)}.bak`}let B=".partial",C=`.bak${B}`,D="copy";function E(a){let b,c=(0,e.dirname)(a),f=`${(0,e.basename)(a)}.`;try{b=(0,d.readdirSync)(c)}catch{return}for(let a of b){if(!a.startsWith(f)||!a.endsWith(C))continue;let b=(0,e.join)(c,a);try{let a=function(a){for(let b of[(0,e.join)(a,D),a])try{return Date.now()-(0,d.statSync)(b).mtimeMs}catch{}return null}(b);null!==a&&a>3e5&&(0,d.rmSync)(b,{recursive:!0,force:!0})}catch{}}}function F(a,b){let{stage:c,copy:f}=function(a){let b=`${a}${B}`;return(0,d.rmSync)(b,{recursive:!0,force:!0}),k(b),j(b),{stage:b,copy:(0,e.join)(b,D)}}(b);try{a.prepare("VACUUM INTO ?").run(f),n(f),(0,d.renameSync)(f,b)}catch(a){try{(0,d.rmSync)(c,{recursive:!0,force:!0})}catch{}throw a}try{(0,d.rmSync)(c,{recursive:!0,force:!0})}catch{}}function G(a){return a.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function H(a){return Array.from({length:a},()=>"?").join(", ")}function I(a){return`%${G(a)}%`}function J(a){return`(${a.map(a=>`${a} LIKE ? ESCAPE '\\'`).join(" OR ")})`}let K=0;function L(a,b,c="DEFERRED"){if(a.isTransaction){let c=`aka_sp_${String(K+=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 M(a,b,c="DEFERRED"){let d=a.isTransaction;try{return L(a,b,c),!0}catch(b){if(!a.isTransaction&&d)throw b;return!1}}function N(a){process.stderr.write(`[aka] ${a}
|
|
2
|
-
`)}function O(a,b,c){return void 0!==a.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ? LIMIT 1").get(b,c)}function P(a,b,c){let d=c?.includeGenerated?"table_xinfo":"table_info";return a.prepare(`PRAGMA ${d}(${b})`).all().map(a=>a.name)}function Q(a,b){return void 0===b?a.all():Array.isArray(b)?a.all(...b):a.all(b)}function R(a,b){return void 0===b?a.get():Array.isArray(b)?a.get(...b):a.get(b)}function S(a){return 1===a||!0===a}function T(a){let b={};for(let[c,d]of Object.entries(a))b[c]=void 0===d?null:d;return b}function U(a,b,c){return R(a.prepare(b),c)?.n??0}function V(a,b,c){let d=new Map;for(let e of Q(a.prepare(b),c))d.set(e.k,e.n);return d}function W(a,b){let c=[];for(let d of a)try{c.push(b(d))}catch{}return c}function X(a){return"column"===a.kind?`column ${a.table}.${a.name}`:`table ${a.name}`}function Y(a){return a.split(/-->\s*statement-breakpoint/).map(a=>a.trim()).filter(a=>a.length>0)}let Z="0014_drop_legacy_events_findings";function $(a){let b=!1,c=[];for(let d of["events","findings"])try{let e=a.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${d}`).get();if(void 0===e){b=!0,c.push(`${d}:unreadable`);continue}e.n>0&&(b=!0),c.push(`${d}:${String(e.n)}:${String(e.hi)}`)}catch{b=!0,c.push(`${d}:unreadable`)}return{holdsRows:b,mark:c.join("|")}}let _=[{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 aa(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||(L(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 ab(a,b){if(null==a)return b;try{return JSON.parse(a)}catch{return b}}function ac(a){if(null!=a)try{let b=JSON.parse(a);if("object"==typeof b&&null!==b)return b}catch{}}function ad(a){return Buffer.from(JSON.stringify(a)).toString("base64url")}function ae(a){let b=ac(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 af="max(started_at, coalesce(ended_at, started_at))";function ag(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}let ah={session:"session",prompt:"prompt",response:"response",tool_call:"tool",hook:"hook",detection:"detection",share:"share",permission:"permission",commit:"commit",error:"error",active:"active"};function ai(a){if(!a)return[];let b=ab(a,null);return Array.isArray(b)?b:[]}let aj=f.tLs.ClaudeCode;function ak(a){let b=f.TUN.safeParse(a);return b.success?b.data:aj}function al(a,b,c){let d=Math.max(a.started_at,b.lastActivityMs),{status:e,endedAtMs:g}=function(a,b,c){if(a.status){let b=f.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:ak(a.harness),title:a.title||a.project||a.repo||`Session ${a.id.slice(0,8)}`,project:a.project??"",repo:a.repo??"",branches:ai(a.branches),startedAt:(0,f.q11)(a.started_at),endedAt:null===g?null:(0,f.q11)(g),status:e,turns:b.turns,findings:b.findings,shares:b.shares}}function am(a){let b=ah[a.event_type];if(!b)return null;let c=a.severity?f.U7X.safeParse(a.severity):null,d=a.link?f.Itg.safeParse(a.link):null;return{id:a.id,occurredAt:(0,f.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:S(a.internal),flagged:S(a.flagged)}}let an=`
|
|
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`,ao="event_type = 'session'",ap=`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 aq{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=ag();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??ag(),this.now()),d=U(this.db,`SELECT count(*) AS n FROM audit_events
|
|
18
|
-
WHERE ${ao} AND started_at >= ? AND started_at < ?
|
|
19
|
-
AND ${ap}`,[b,c]),e=this.now()-18e5,f=U(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(${af}) FROM audit_events e WHERE e.root_session_id = s.id),
|
|
25
|
-
s.started_at
|
|
26
|
-
)
|
|
27
|
-
) >= ?`,[e]),g=U(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:U(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:U(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?ae(a.cursor):null,c=a.to?(0,f.I8t)(a.to):this.now(),d=a.from?(0,f.I8t)(a.from):void 0,e=[ao],g=[];if(a.harness&&a.harness.length>0&&(e.push(`coalesce(json_extract(attributes, '$.harness'), '${aj}') IN (${H(a.harness.length)})`),g.push(...a.harness)),void 0!==d&&(e.push("started_at >= ?"),g.push(d)),e.push("started_at <= ?"),g.push(c),a.q){let b=I(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 '\\')))`),g.push(b,b,b,b,b,b)}let h=U(this.db,`SELECT count(*) AS n FROM audit_events
|
|
41
|
-
WHERE ${[...e,`NOT ${ap}`].join(" AND ")}`,g);a.excludeEmpty&&e.push(ap),b&&(e.push("(started_at < ? OR (started_at = ? AND id < ?))"),g.push(b.startedAtMs,b.startedAtMs,b.id));let i=a.limit,j=Q(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 ?`),[...g,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=>al(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?ad({startedAtMs:p.started_at,id:p.id}):null,emptyCount:h})}getSession(a){let b=R(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=Q(this.db.prepare(`SELECT ${an}
|
|
70
|
-
FROM audit_events
|
|
71
|
-
WHERE id = ? OR root_session_id = ?
|
|
72
|
-
ORDER BY started_at ASC, id ASC`),[a,a]).map(am).filter(a=>null!==a),d=R(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=R(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=Q(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=Q(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=U(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({...al(b,i,this.now()),host:b.host??"",cwd:b.cwd??"",models:g.length>0?g:ai(b.models),version:b.version??"",tokens:j,tools:Object.fromEntries(f.flatMap(a=>a.tool?[[a.tool,a.n]]:[])),files:ai(b.files),commits:h,events:c})}tokenReports(a){let b=this.readLlmCallLeaves(void 0===a?{}:{fromMs:a});return Promise.resolve((0,f.ryv)(b,f.q_t))}tokenReportForSession(a){return Promise.resolve((0,f.ryv)(this.readLlmCallLeaves({sessionId:a}),f.q_t)[0]??null)}harnessFacets(a){let b=Q(this.db.prepare(`SELECT DISTINCT coalesce(json_extract(attributes, '$.harness'), '${aj}') AS harness
|
|
89
|
-
FROM audit_events WHERE ${ao}${void 0===a?"":" AND started_at >= ?"}`),void 0===a?void 0:[a]),c=new Set;for(let a of b)c.add(ak(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)),W(Q(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=H(a.length);for(let d of Q(this.db.prepare(`SELECT root_session_id AS id, max(${af}) 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 Q(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 Q(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 Q(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 Q(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 ar{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){L(this.db,a)}insertAuditEvent(a){let b=(0,f.V9M)(a);this.insertStmt.run(T({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,f.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.messageId,x((0,f.tTV)(["audit_event_llm_call",b,c])));this.upsertLlmCallStmt.run(T({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,f.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.toolUseId,x((0,f.tTV)(["audit_event_tool_call",b,c])));this.insertStmt.run(T({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 R(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=ac(b.attributes)?.provider;if("string"==typeof c)return c}llmCallLeaves(){return Q(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 as{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,x((0,f.tTV)(["classified_data",b]))),d=(0,f.$BP)(a,c);return this.insertStmt.run(T({id:d.id,class:d.class,label:d.label,attributes:d.attributes})),c}}function at(a){return R(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 au{constructor(a){this.db=a}report(){let a=at(this.db);if(!a)return{scannedAt:null,skills:[],hooks:[],mcpServers:[],configFiles:[],topics:[]};let b=Q(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=Q(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=ac(a.attributes);b&&("skill"===a.objectType?d.push(function(a,b){let c={id:a.id,name:a.title??"(unnamed)",source:av(b.source)??"unknown",scope:av(b.scope)??"unknown",status:"unknown"},d=av(b.description);void 0!==d&&(c.description=d);let e=av(b.version);void 0!==e&&(c.installedVersion=e);let f=av(b.updated_at);return void 0!==f&&(c.updatedAt=f),c}(a,b)):"hook"===a.objectType?e.push(function(a,b,c){let d=av(b.command)??"",e=c.filter(a=>a.maskedMatch===d),f={id:a.id,event:av(b.event)??"unknown",command:d,scope:av(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=av(b.matcher);void 0!==g&&(f.matcher=g);let h=av(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:av(b.scope)??"unknown",transport:av(b.transport)??"unknown",trust:c.get(a.id)??"unapproved"},e=av(b.command);void 0!==e&&(d.command=e);let f=av(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=av(b.plugin_name);void 0!==g&&(d.pluginName=g);let h=av(b.marketplace);void 0!==h&&(d.marketplace=h);let i=av(b.project);return void 0!==i&&(d.project=i),d}(a,b,h)):g.push(function(a,b){let c=av(b.scope)??"unknown",d={id:a.id,name:a.title??"(unnamed)",path:a.location??"",scope:c,kind:av(b.kind)??"Configuration file",untracked:"local"===c},e=av(b.detail);void 0!==e&&(d.detail=e),"number"==typeof b.entry_count&&(d.entryCount=b.entry_count);let f=av(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=ac(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=Q(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 av(a){return"string"==typeof a?a:void 0}function aw(a){let b=ab(a,[]);if(!Array.isArray(b))return[];let c=[];for(let a of b)a&&"object"==typeof a&&c.push(a);return c}function ax(a,b){return a.version!==b.version||a.rulesJson!==b.rulesJson}class ay{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}listDetections(a){let b=Q(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:S(a.enabled),ruleCount:aw(a.rulesJson).length,policyId:a.policyId,...b&&ax(a,b)?{latestVersion:b.version}:{}}});return Promise.resolve((0,f.plk)(d,a))}availableByPack(){return new Map(Q(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=Q(this.db.prepare("SELECT enabled, rules_json AS rulesJson FROM installed_packs")),b=0,c=0,d=new Set;for(let e of a){S(e.enabled)&&(c+=1);let a=aw(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,f.pnU)(a);if(!b)return Promise.resolve(null);let{namespace:c,packId:d}=b,e=R(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 g=aw(e.rulesJson),h=g.map(a=>a.id).filter(a=>"string"==typeof a),i=this.countFindingsLast30d(h),j=this.availableByPack().get(`${e.namespace}/${e.packId}`),k=j?ax(e,j)?{available:!0,latestVersion:j.version,latestRuleCount:aw(j.rulesJson).length}:{available:!1,latestVersion:j.version}:null;return Promise.resolve((0,f.a45)({namespace:e.namespace,packId:e.packId,version:e.version,name:e.name,enabled:S(e.enabled),rules:g,updatedAt:new Date(e.updatedAt),policyId:e.policyId},i,k))}countFindingsLast30d(a){if(0===a.length)return 0;let b=this.now()-2592e6,c=H(a.length);return U(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 (${f.hfB})
|
|
148
|
-
AND d.rule_id IN (${c})`,[b,...a])}}class az{constructor(a){this.db=a}contentHashes(){return Promise.resolve(new Set(Q(this.db.prepare(`SELECT content_hash FROM audit_events
|
|
149
|
-
WHERE event_type IN (${f.hfB})`)).map(a=>a.content_hash)))}}let aA=864e5;class aB 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 aC 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 aD=`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)`,aE=`capability = 'reveal_to_model'
|
|
152
|
-
AND conditions IS NULL
|
|
153
|
-
AND ${aD}`;class aF{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 ${aD}`),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,v.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;L(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 aB(a.ruleId);this.insertExceptionRow(b,a,c)},"IMMEDIATE")}let d=R(this.db.prepare("SELECT * FROM exceptions WHERE id = :id"),{id:b});if(void 0===d)throw Error("exception row not found immediately after insert");return aG(d)}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,f.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 ${aD}`;return Promise.resolve(W(Q(this.db.prepare(`SELECT * FROM exceptions ${b} ORDER BY created_at DESC, rowid DESC`),a?.includeTerminal?{}:{now:this.now()}),aG))}getByIdPrefix(a){if(0===a.length)return Promise.resolve(void 0);let b=Q(this.db.prepare(String.raw`SELECT * FROM exceptions WHERE id LIKE :pattern ESCAPE '\' LIMIT 2`),{pattern:`${G(a)}%`});if(b.length>1)return Promise.reject(new aC(a));let c=b[0];if(!c)return Promise.resolve(void 0);try{return Promise.resolve(aG(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(W(Q(this.db.prepare(`SELECT * FROM exceptions
|
|
174
|
-
WHERE key_version = :keyVersion AND ${aD}
|
|
175
|
-
ORDER BY created_at DESC, rowid DESC`),{keyVersion:a,now:b}),a=>{let b=null===a.conditions?null:JSON.parse(a.conditions);return f.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,f.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-aA}),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(Q(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,f.q11)(a.blocked_at)})))}activeRevealGrant(a,b,c,d){try{let e=d??this.now(),f=R(this.db.prepare(`SELECT id FROM exceptions
|
|
178
|
-
WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
|
|
179
|
-
AND key_version = :keyVersion
|
|
180
|
-
AND ${aE}
|
|
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 aG(a){let b=null===a.conditions?null:JSON.parse(a.conditions);return f.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,f.q11)(a.expires_at),maxUses:a.max_uses,useCount:a.use_count,lastUsedAt:null===a.last_used_at?null:(0,f.q11)(a.last_used_at),justification:a.justification,conditions:b,createdBy:a.created_by,createdVia:a.created_via,createdAt:(0,f.q11)(a.created_at),updatedAt:(0,f.q11)(a.updated_at),revokedAt:null===a.revoked_at?null:(0,f.q11)(a.revoked_at),revokedBy:a.revoked_by,revokeReason:a.revoke_reason})}function aH(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 aI=`(
|
|
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 aJ(a,b){return(0,f._6W)({severity:a.maxSeverity,latestDetectedAt:a.latestDetectedAt,id:""},{severity:b.maxSeverity,latestDetectedAt:b.latestDetectedAt,id:""})}function aK(a){return null===a||""===a?[]:a.split(",")}function aL(a){return(0,f.xog)({kind:a.kind,findingKey:a.finding_key,latestResolutionStatus:a.latest_status})}class aM{constructor(a){this.db=a}recentFindings(a){let b=a?.limit??50;return Promise.resolve(Q(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 audit_events e
|
|
204
|
-
CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
|
|
205
|
-
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
206
|
-
WHERE +e.event_type IN (${f.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,f.q11)(a.occurred_at),sourceTool:a.source_tool,kind:a.kind})))}sessionFindingsCount(a){return a?Promise.resolve(U(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 (${f.hfB})`,{sessionId:a})):Promise.resolve(0)}sessionFirings(a){return Object.fromEntries(V(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 (${f.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,f.I8t)(a.from),d=`WHERE e.event_type IN (${f.hfB})${b}${void 0===c?"":" AND e.started_at >= :fromMs"}`,e={...a.sessionId?{sessionId:a.sessionId}:{},...void 0===c?{}:{fromMs:c}},g=this.groupAggregates(void 0!==a.q&&""!==a.q,{predicate:d,params:e}),h=Q(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 ${aI} 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,f.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:aL(a)})),i=(0,f.mAj)(h,{aggregates:g}),j={severity:a.severity,providers:a.provider,actions:a.action,statuses:a.status,subtype:a.subtype,q:a.q},k=(0,f.rG)(i,j),l=(0,f.A6E)((0,f.tXp)(i,j)),m=a.status??[],n={findings:l.reduce((a,b)=>{if(0===m.length)return a+b.instanceCount;let c=g.get(b.id);return a+(c?(0,f.Bfj)(c.statusInputs,m)??b.instanceCount:b.instanceCount)},0),groups:l.length},o=a.limit??f.goN,p=void 0===a.cursor?null:function(a){let b=ac(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,f._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??f.b2L,e=void 0===a.cursor?null:ae(a.cursor),g=(0,f.fj8)(c),h=[],i=0,j=!1;for(let e of this.scanFindingRows({sessionId:a.sessionId,from:a.from}))g.add(e),(0,f.am1)(e,c)&&(i+=1,h.length<d?(h.push((0,f.MgS)(e)),b=e):j=!0);let k=j&&b?ad({startedAtMs:(0,f.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:g.facets(),items:b.items,nextCursor:b.nextCursor})}return Promise.resolve({totals:{findings:i},facets:g.facets(),items:h,nextCursor:k})}pageAfter(a,b,c,d){let e,g=[],h=!1;for(let i of this.scanFindingRows({sessionId:d.sessionId,from:d.from,after:a}))if((0,f.am1)(i,b))if(g.length<c)g.push((0,f.MgS)(i)),e=i;else{h=!0;break}return{items:g,nextCursor:h&&e?ad({startedAtMs:(0,f.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,f.am1)(c,b))continue;e+=1;let a=d.get(c.repo);void 0===a&&(a=new Map,d.set(c.repo,a));let g=a.get(c.file);void 0===g&&(g=(0,f.SSj)(),a.set(c.file,g)),(0,f._5V)(g,c)}let g=0,h=[...d.entries()].map(([a,b])=>{g+=b.size;let c=[...b.entries()].map(([a,b])=>({file:a,instanceCount:b.instanceCount,maxSeverity:b.maxSeverity,latestDetectedAt:b.latestDetectedAt,...void 0===(0,f.JB8)(b.statuses)?{}:{status:(0,f.JB8)(b.statuses)},ruleIds:[...b.ruleIds].slice(0,20)})).sort(aJ),d=c.reduce((a,b)=>({instanceCount:a.instanceCount+b.instanceCount,maxSeverity:0>aJ(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,f.JB8)(e);return{repo:a,instanceCount:d.instanceCount,maxSeverity:d.maxSeverity,latestDetectedAt:d.latestDetectedAt,...void 0===h?{}:{status:h},files:c}});return h.sort(aJ),Promise.resolve({totals:{findings:e,repos:h.length,files:g},items:h.slice(0,c),hasMore:h.length>c})}*scanFindingRows(a){let b=[`e.event_type IN (${f.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,f.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
|
-
${aH("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=Q(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,f.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:aL(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 ${aI} 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:aK(b.source_tools),actionsTaken:aK(b.actions_taken),statusInputs:aK(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,f.q11)(b.latest_at),...a?{searchText:[b.repos??"",b.files??"",b.tool_names??""].filter(a=>""!==a).join(" ")}:{}}]))}healthSummary(){let a=U(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 (${f.hfB})`),b=Object.fromEntries(f.S8C.map(a=>[a,0]));for(let a of Q(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 (${f.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 Q(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 ${aI} latest
|
|
301
|
-
ON latest.finding_key = f.finding_key
|
|
302
|
-
WHERE e.event_type IN (${f.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=f.IgC,e=new Set(Q(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=Q(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 (${f.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 aN{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=z(a.ruleId,a.version),c=(0,f.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 aO{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 (${f.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,f.$3l)(a);this.insertStmt.run(T({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 aP(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 aQ=f.Jr;function aR(a){return a.map(a=>{var b;return`${a.namespace}/${a.packId}@${a.version}#${b=a.rulesJson,(0,v.createHash)("sha256").update(b).digest("hex")}`}).sort().join(",")}function aS(a){let b=/^(\d+)\.(\d+)\.(\d+)/.exec(a);return b?[Number(b[1]),Number(b[2]),Number(b[3])]:null}class aT{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()===aR(c))return;let d=Date.now();L(this.db,()=>{let a=this.mirrorState(),e=!1;for(let f of c){let c={id:(0,v.randomUUID)(),namespace:f.namespace,packId:f.packId,version:f.version,name:f.name,rulesJson:f.rulesJson,now:d},g=a.get(`${f.namespace}/${f.packId}`);void 0===g||!function(a,b){let c=aS(a.version);if(null===c)return!0;let d=aS(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}(f,g)?this.upsertAvailableStmt.run({...c,id:(0,v.randomUUID)(),recordedBy:b?.recordedBy??null}):e=!0,this.insertMissingStmt.run(c)}e||this.pruneAvailable(c.map(a=>`${a.namespace}/${a.packId}`))},"IMMEDIATE")}catch{}}mirrorState(){return new Map(Q(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=ab(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=Q(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 L(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=Q(this.db.prepare(`SELECT enabled, policy_id AS policyId, rules_json AS rulesJson, version,
|
|
366
|
-
namespace, pack_id AS packId
|
|
367
|
-
FROM installed_packs
|
|
368
|
-
ORDER BY namespace, pack_id`)),b={installedPacks:a.length,enabledPacks:0,rules:[],invalidRules:0,rejectedRules:[],ruleActions:new Map,ruleVersions:new Map,reversibleRules:new Set},c=(a,c,d)=>{b.rejectedRules.length>=10||b.rejectedRules.push({pack:a,ruleId:c,reason:d})};for(let d of a){let a;if(!S(d.enabled))continue;b.enabledPacks+=1;let e=(0,f.DhA)(d.policyId),g=(0,f.TdZ)(d.policyId),h=`${d.namespace}/${d.packId}`;try{a=JSON.parse(d.rulesJson)}catch{b.invalidRules+=1,c(h,null,"rules_json: malformed JSON");continue}if(!Array.isArray(a)){b.invalidRules+=1,c(h,null,"rules_json: not an array");continue}for(let i of a){let a=f.jON.safeParse(i);a.success?(b.rules.push(a.data),b.ruleActions.set(a.data.id,e),b.ruleVersions.set(a.data.id,d.version),g?b.reversibleRules.add(a.data.id):b.reversibleRules.delete(a.data.id)):(b.invalidRules+=1,c(h,function(a){if("object"!=typeof a||null===a)return null;let b=a.id;return f.jON.shape.id.safeParse(b).success?b:null}(i),function(a){let b=a.issues[0];if(!b)return"unknown";let c=b.path.map(a=>String(a)).join(".");return c?`${c}: ${b.code}`:b.code}(a.error)))}}return b}newestRecordedBinary(){let a=Q(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!==aP(e)&&(null===b||function(a,b){let c=aP(a),d=aP(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(R(this.db.prepare(`SELECT count(*) AS packs,
|
|
369
|
-
coalesce(sum(json_array_length(rules_json)), 0) AS rules,
|
|
370
|
-
coalesce(sum(enabled), 0) AS enabled
|
|
371
|
-
FROM installed_packs`))??{packs:0,rules:0,enabled:0})}countsByPolicyId(){return V(this.db,`SELECT coalesce(policy_id, '${aQ}') AS k, count(*) AS n
|
|
372
|
-
FROM installed_packs
|
|
373
|
-
GROUP BY k`)}listByPolicyId(a){return Q(this.db.prepare(`SELECT namespace, pack_id AS packId, name, enabled, rules_json AS rulesJson
|
|
374
|
-
FROM installed_packs
|
|
375
|
-
WHERE coalesce(policy_id, '${aQ}') = ?
|
|
376
|
-
ORDER BY name ASC`),[a]).map(a=>({id:`${a.namespace}/${a.packId}`,name:a.name,ruleCount:aw(a.rulesJson).length,enabled:S(a.enabled)}))}setPolicy(a,b,c){if(null!==c&&!f.HUb.safeParse(c).success)throw Error(`Unknown policy '${c}'. Must be one of: ${f.V0H.join(", ")}.`);return Number(this.db.prepare(`UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
|
|
377
|
-
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
|
|
378
|
-
WHERE namespace = :namespace AND pack_id = :packId`).run({enabled:+!!c,now:Date.now(),namespace:a,packId:b}).changes)>0}storedSignature(){return aR(Q(this.signatureStmt))}}class aU{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO inventory
|
|
379
|
-
(id, object_type, location, title, host_id, attributes, first_seen, last_seen)
|
|
380
|
-
VALUES
|
|
381
|
-
(:id, :objectType, :location, :title, :hostId, :attributes, :firstSeen, :lastSeen)
|
|
382
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
383
|
-
location = excluded.location,
|
|
384
|
-
title = excluded.title,
|
|
385
|
-
host_id = excluded.host_id,
|
|
386
|
-
attributes = excluded.attributes,
|
|
387
|
-
last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){var c,d;let e=(c=a.objectType,d=a.identityKey,x((0,f.tTV)(["inventory",c,d]))),g=(0,f.gzP)(a,e,b);return this.upsertStmt.run(T({id:g.id,objectType:g.objectType,location:g.location,title:g.title,hostId:g.hostId,attributes:g.attributes,firstSeen:g.firstSeen,lastSeen:g.lastSeen})),e}findById(a){return R(this.db.prepare("SELECT * FROM inventory WHERE id = :id"),{id:a})}distinctTitles(a){return Q(this.db.prepare(`SELECT DISTINCT title FROM inventory
|
|
388
|
-
WHERE object_type = :objectType AND title IS NOT NULL
|
|
389
|
-
ORDER BY title`),{objectType:a}).map(a=>a.title)}osVersions(){return Q(this.db.prepare(`SELECT DISTINCT os_version AS value FROM inventory
|
|
390
|
-
WHERE object_type = 'host' AND os_version IS NOT NULL
|
|
391
|
-
ORDER BY value`)).map(a=>a.value)}}let aV=["config","skill","mcp","hook"],aW=new Set(f.SHn.options),aX="(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))",aY={[f.tLs.ClaudeCode]:"Claude Code",[f.tLs.Cursor]:"Cursor",[f.tLs.Codex]:"Codex",[f.tLs.Antigravity]:"Antigravity"},aZ={accessCounts:{open:0,approved:0,blocked:0,total:0},findingsCount:0},a$=a=>a.toLowerCase().replace(/[\s-]/g,""),a_={ClaudeCode:a$(f.Zdp.ClaudeCode),Cursor:a$(f.Zdp.Cursor),Codex:a$(f.Zdp.Codex),Antigravity:a$(f.Zdp.Antigravity)};function a0(a,b){if(a.provider&&aW.has(a.provider))return a.provider;let c=a$(b.title??"");return c.includes(a_.ClaudeCode)||"claude"===c?f.tLs.ClaudeCode:c.includes(a_.Cursor)?f.tLs.Cursor:c.includes(a_.Codex)?f.tLs.Codex:c.includes(a_.Antigravity)?f.tLs.Antigravity:null}function a1(a){return a.some(a=>{let b=ab(a.attributes,{});return"sample"!==b.provenance&&a0(b,a)===f.tLs.ClaudeCode})}function a2(a){let b={id:a.id,type:a.assetType,name:a.name,sub:a.sub??"",flags:ab(a.flagsJson,[])};return"mcp"===a.assetType&&a.effectiveTrust&&(b.trust=a.effectiveTrust),b}function a3(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 a4(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:a7(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 a5(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 ${a7(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 a6(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 a7(a,b){return a.length>b?`${a.slice(0,b-1)}…`:a}function a8(a,b,c){let d=ab(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 a9(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 ba{constructor(a){this.db=a}getInventoryStats(){let a=V(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=U(this.db,`SELECT count(*) AS n FROM source_project WHERE ${aX}`);let c=V(this.db,`SELECT coalesce(o.trust, a.trust) AS k, count(*) AS n
|
|
392
|
-
FROM inventory_asset a
|
|
393
|
-
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
394
|
-
WHERE a.asset_type = 'mcp' AND coalesce(o.trust, a.trust) IS NOT NULL
|
|
395
|
-
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=U(this.db,`SELECT count(*) AS n FROM inventory
|
|
396
|
-
WHERE object_type = 'harness'
|
|
397
|
-
AND (last_seen >= :liveSince OR json_extract(attributes, '$.provenance') = 'sample')`,{liveSince:Date.now()-2592e6}),f=U(this.db,"SELECT count(*) AS n FROM inventory_asset WHERE flags_json <> '[]'"),g=U(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=a0(ab(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=>ab(a.attributes,{}).projectIds??[]))],g=this.fetchProjectsByIds(e),h=this.projectAggregates(e),i=this.configAssetRows(a,a1(b)),j=[];for(let[b,e]of c){let c=e.flatMap(a=>d.get(a.id)??[]),k=e.some(a=>"sample"!==ab(a.attributes,{}).provenance)&&b===f.tLs.ClaudeCode&&i.length>0?[...c,...i].sort((a,b)=>a.name.localeCompare(b.name)):c;if(a&&0===k.length)continue;let l=e[0];if(!l)continue;let m=ab(l.attributes,{}),n=[...new Set(e.flatMap(a=>ab(a.attributes,{}).projectIds??[]))].map(a=>g.get(a)).filter(a=>void 0!==a).map(a=>{let b=h.get(a.id)??aZ;return a8(a,b.accessCounts,b.findingsCount)}),o=e.reduce((a,b)=>a+(ab(b.attributes,{}).sessions??0),0),p=k.reduce((a,b)=>a+ab(b.flagsJson,[]).length,0),q=new Map;for(let a of k){let b=q.get(a.assetType);b?b.push(a2(a)):q.set(a.assetType,[a2(a)])}let r=aV.filter(a=>q.has(a)).map(a=>({type:a,assets:q.get(a)??[]}));j.push({id:b,label:m.label??aY[b],kind:m.kind??m.provider??b,version:m.harness_version??l.harnessVersion??"",sessions:o,assetCount:k.length,flagCount:p,projects:n,categories:r})}return Promise.resolve({items:j})}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 ab(a.flagsJson,[]))c.set(b,(c.get(b)??0)+1);let d={type:a,total:b.length,flagRollup:Object.fromEntries(c),items:b.map(a2)};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)=>aV.indexOf(a.type)-aV.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:ab(a.flagsJson,[]),description:a.description??null,trust:"mcp"===a.assetType?a.effectiveTrust??null:null,meta:ab(a.metaJson,{}),finding:null};if("mcp"===a.assetType&&null!==a.toolsJson){let c=ab(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)??aZ;return a8(a,b.accessCounts,b.findingsCount)})})}getProjectTree(a,b){let c=this.fetchProjectById(a);if(!c)return Promise.resolve(null);let d=ab(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(a9)})}if(void 0!==b.q&&""!==b.q)return Promise.resolve({project:e,path:f,files:this.fetchProjectFilesSearch(a,b.q).map(a9)});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(a9)})}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=ab(c.attributes,{});return Promise.resolve({...a9(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 d=this.fetchProjectFile(a,b);return!!d&&(c===d.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)
|
|
398
|
-
VALUES (:id, :projectId, :path, :access, :now, :now)
|
|
399
|
-
ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`).run({id:(0,v.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)
|
|
400
|
-
VALUES (:id, :assetId, :trust, :now, :now)
|
|
401
|
-
ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`).run({id:(0,v.randomUUID)(),assetId:a,trust:b,now:Date.now()}),this.configRowsCache=void 0,"ok"):"not_found"}fetchHarnessRows(){return Q(this.db.prepare(`SELECT id, title, attributes, harness_version AS harnessVersion
|
|
402
|
-
FROM inventory
|
|
403
|
-
WHERE object_type = 'harness'
|
|
404
|
-
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 (${H(a.length)})`;if(b){let a=I(b);e+=` AND ${J(["a.name","a.sub"])}`,d.push(a,a)}for(let a of Q(this.db.prepare(`SELECT ha.harness_id AS harnessInvId, a.id, a.asset_type AS assetType, a.name, a.sub,
|
|
405
|
-
a.description, a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
|
|
406
|
-
a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
|
|
407
|
-
FROM harness_asset ha
|
|
408
|
-
JOIN inventory_asset a ON a.id = ha.asset_id
|
|
409
|
-
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
410
|
-
WHERE ${e}
|
|
411
|
-
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 (${H(a.length)})`),d.push(...a)),b){let a=I(b);c.push(J(["a.name","a.sub"])),d.push(a,a)}let e=c.length?`WHERE ${c.join(" AND ")}`:"",f=this.mapAssetRows(Q(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
|
|
412
|
-
a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
|
|
413
|
-
a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
|
|
414
|
-
FROM inventory_asset a
|
|
415
|
-
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
416
|
-
${e}
|
|
417
|
-
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(Q(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
|
|
418
|
-
a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
|
|
419
|
-
a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
|
|
420
|
-
FROM inventory_asset a
|
|
421
|
-
LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
|
|
422
|
-
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??a1(this.fetchHarnessRows())))return[];let b=this.latestConfigScanId();if(null===b)return[];if(this.configRowsCache?.scanId===b)return this.configRowsCache.rows;let c=new au(this.db).report(),d=[...c.skills.map(a3),...c.hooks.map(a4),...c.mcpServers.map(a5),...c.configFiles.map(a6)].sort((a,b)=>a.name.localeCompare(b.name));return this.configRowsCache={scanId:b,rows:d},d}latestConfigScanId(){return at(this.db)?.id??null}fetchProjects(a){let b=`SELECT id, url, name, attributes, last_seen AS lastSeen FROM source_project
|
|
423
|
-
WHERE ${aX}`,c=[];if(a){let d=I(a);b+=` AND ${J(["name","url"])}`,c.push(d,d)}return b+=" ORDER BY name ASC",Q(this.db.prepare(b),c)}fetchProjectById(a){return R(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 Q(this.db.prepare(`SELECT id, url, name, attributes, last_seen AS lastSeen
|
|
424
|
-
FROM source_project WHERE id IN (${H(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 Q(this.db.prepare(`SELECT f.project_id AS projectId,
|
|
425
|
-
coalesce(o.access, f.default_access) AS eff,
|
|
426
|
-
count(*) AS n,
|
|
427
|
-
coalesce(sum(f.findings_count), 0) AS findings
|
|
428
|
-
FROM project_file f
|
|
429
|
-
LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
|
|
430
|
-
WHERE f.project_id IN (${H(a.length)})
|
|
431
|
-
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,
|
|
432
|
-
f.findings_count AS findingsCount, f.blocked_at AS blockedAtMs, f.note,
|
|
433
|
-
coalesce(o.access, f.default_access) AS effectiveAccess,
|
|
434
|
-
o.access AS overrideAccess
|
|
435
|
-
FROM project_file f
|
|
436
|
-
LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
|
|
437
|
-
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(Q(this.db.prepare(this.fileSelect("f.project_id = ? ORDER BY f.path ASC")),[a])):this.mapFileRows(Q(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path LIKE ? ESCAPE '\\' ORDER BY f.path ASC")),[a,`${G(b)}/%`]))}fetchProjectFilesSearch(a,b){let c=I(b);return this.mapFileRows(Q(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(Q(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(Q(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path = ?")),[a,b]))[0]??null}}class bb{constructor(a){this.db=a}readPolicies(){return Promise.resolve(W(Q(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 f.PEm.parse({id:a.id,scope:a.scope,target:b,action:a.action,enabled:S(a.enabled),customKeywords:c})}))}seedDefaults(){if(U(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)
|
|
438
|
-
VALUES (:id, 'global', :target, :action, 1, :now, :now)`);M(this.db,()=>{for(let[b,c]of Object.entries(f.unw))a.run({id:(0,v.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)
|
|
439
|
-
VALUES (:id, 'global', :target, :action, 1, :now, :now)
|
|
440
|
-
ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`).run({id:(0,v.randomUUID)(),target:JSON.stringify({category:a}),action:b,now:c})}capCategoryActions(){return Number(this.db.prepare(`UPDATE policies SET action='warn', updated_at=:now
|
|
441
|
-
WHERE scope='global' AND action IN ('block','redact')
|
|
442
|
-
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 bc{constructor(a){this.packs=a}getPolicyList(a){if("custom"===a)return Promise.resolve({items:[]});let b=this.packs.countsByPolicyId();return Promise.resolve({items:f.RRF.map(a=>({id:a,kind:"builtin",name:f.ZpU[a].name,enabled:!0,usedByCount:b.get(a)??0}))})}getPolicyStats(){let a=this.packs.countsByPolicyId(),b=f.V0H.reduce((b,c)=>b+(a.get(c)??0),0),c=f.V0H.length;return Promise.resolve({policies:c,builtin:c,custom:0,detectionsGoverned:b})}getPolicyDetail(a){let b=f.V0H.find(b=>b===a);if(void 0===b)return Promise.resolve(null);let c=f.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 bd{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
|
|
443
|
-
(id, project_id, path, name, origin, default_access, findings_count, blocked_at, note, created_at, updated_at)
|
|
444
|
-
VALUES
|
|
445
|
-
(:id, :projectId, :path, :name, :origin, :defaultAccess, 0, NULL, NULL, :now, :now)
|
|
446
|
-
ON CONFLICT (project_id, path) DO UPDATE SET
|
|
447
|
-
name = excluded.name,
|
|
448
|
-
origin = excluded.origin,
|
|
449
|
-
default_access = excluded.default_access,
|
|
450
|
-
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 d=Math.max(c,(R(this.maxStampStmt,{projectId:a})?.maxStamp??0)+1);for(let c of b.files)this.upsertStmt.run({id:(0,v.randomUUID)(),projectId:a,path:c.path,name:c.name,origin:c.origin,defaultAccess:c.defaultAccess,now:d});b.truncated||this.pruneStmt.run({projectId:a,now:d})}}class be{constructor(a,b=()=>Date.now(),c=()=>(0,v.randomUUID)()){this.db=a,this.now=b,this.newId=c,this.insertStmt=a.prepare(`INSERT INTO finding_resolution (id, finding_key, status, method, resolved_at, evidence, created_at)
|
|
451
|
-
VALUES (:id, :findingKey, :status, :method, :resolvedAt, :evidence, :createdAt)`),this.latestStmt=a.prepare(`SELECT status, method, resolved_at, evidence
|
|
452
|
-
FROM finding_resolution
|
|
453
|
-
WHERE finding_key = :findingKey
|
|
454
|
-
ORDER BY created_at DESC, rowid DESC
|
|
455
|
-
LIMIT 1`),this.openAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
|
|
456
|
-
FROM inspection_findings f
|
|
457
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
458
|
-
WHERE e.event_type = 'code_change'
|
|
459
|
-
AND json_extract(e.attributes, '$.file_path') = :path
|
|
460
|
-
AND f.finding_key IS NOT NULL
|
|
461
|
-
AND ${aH("f")} IS NOT 'resolved'`),this.resolvedAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
|
|
462
|
-
FROM inspection_findings f
|
|
463
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
464
|
-
WHERE e.event_type = 'code_change'
|
|
465
|
-
AND json_extract(e.attributes, '$.file_path') = :path
|
|
466
|
-
AND f.finding_key IS NOT NULL
|
|
467
|
-
AND ${aH("f")} = 'resolved'`)}insertResolution(a){this.insertStmt.run({id:this.newId(),findingKey:a.findingKey,status:f.GCf.parse(a.status),method:f.cqq.parse(a.method),resolvedAt:a.resolvedAt,evidence:a.evidence,createdAt:this.now()})}latestByKey(a){let b=R(this.latestStmt,{findingKey:a});if(b)return{status:b.status,method:b.method,resolvedAt:b.resolved_at,evidence:b.evidence??""}}openAtRestKeysForPath(a){return Q(this.openAtRestStmt,{path:a}).map(a=>a.finding_key)}resolvedAtRestKeysForPath(a){return Q(this.resolvedAtRestStmt,{path:a}).map(a=>a.finding_key)}}class bf{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO rule_probe_cache (rule_key, verdict, worst_probe_ms, checked_at)
|
|
468
|
-
VALUES (:ruleKey, :verdict, :worstProbeMs, :checkedAt)
|
|
469
|
-
ON CONFLICT (rule_key) DO UPDATE SET
|
|
470
|
-
verdict = excluded.verdict,
|
|
471
|
-
worst_probe_ms = excluded.worst_probe_ms,
|
|
472
|
-
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 R(this.readStmt,{ruleKey:a})}countQuarantined(){return R(this.countQuarantinedStmt,{})?.n??0}clearQuarantined(){let a=this.countQuarantined();return{refused:!M(this.db,()=>{this.clearQuarantinedStmt.run()}),cleared:a-this.countQuarantined()}}setVerdict(a,b,c){M(this.db,()=>{this.upsertStmt.run({ruleKey:a,verdict:b,worstProbeMs:c,checkedAt:Date.now()})})}}class bg{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
|
|
473
|
-
VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
|
|
474
|
-
ON CONFLICT (path) DO UPDATE SET
|
|
475
|
-
mtime = excluded.mtime,
|
|
476
|
-
content_hash = excluded.content_hash,
|
|
477
|
-
ruleset_hash = excluded.ruleset_hash,
|
|
478
|
-
scanned_at = excluded.scanned_at`),this.readStmt=a.prepare(`SELECT path, mtime, content_hash AS contentHash
|
|
479
|
-
FROM scan_ledger WHERE ruleset_hash = :rulesetHash`)}entriesForRuleset(a){return new Map(Q(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();M(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 bh(a,b){return void 0===a?b:Math.min(Math.max(1,Math.trunc(a)),f.u8Q)}let bi=`(v.occurrence_count > 1
|
|
480
|
-
OR (SELECT count(*) FROM secret_vault_sighting s WHERE s.pointer_id = v.pointer_id) > 1)`,bj=`v.pointer_id, v.category, v.rule_id, v.masked_match, v.provider,
|
|
481
|
-
v.occurrence_count, v.first_seen, v.last_seen`,bk=`
|
|
482
|
-
pointer_id AS pointerId,
|
|
483
|
-
value_fingerprint AS valueFingerprint,
|
|
484
|
-
fingerprint_key_version AS fingerprintKeyVersion,
|
|
485
|
-
key_version AS keyVersion,
|
|
486
|
-
format_version AS formatVersion,
|
|
487
|
-
category,
|
|
488
|
-
rule_id AS ruleId,
|
|
489
|
-
masked_match AS maskedMatch,
|
|
490
|
-
provider,
|
|
491
|
-
ciphertext,
|
|
492
|
-
nonce,
|
|
493
|
-
auth_tag AS authTag,
|
|
494
|
-
occurrence_count AS occurrenceCount,
|
|
495
|
-
first_seen AS firstSeen,
|
|
496
|
-
last_seen AS lastSeen`;function bl(a){let{provider:b,...c}=a;return null===b?c:{...c,provider:b}}class bm{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO secret_vault (
|
|
497
|
-
pointer_id, value_fingerprint, fingerprint_key_version, key_version,
|
|
498
|
-
format_version, category, rule_id, masked_match, provider,
|
|
499
|
-
ciphertext, nonce, auth_tag,
|
|
500
|
-
occurrence_count, first_seen, last_seen
|
|
501
|
-
) VALUES (
|
|
502
|
-
:pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
|
|
503
|
-
:formatVersion, :category, :ruleId, :maskedMatch, :provider,
|
|
504
|
-
:ciphertext, :nonce, :authTag,
|
|
505
|
-
1, :now, :now
|
|
506
|
-
)`),this.bumpStmt=a.prepare(`UPDATE secret_vault
|
|
507
|
-
SET occurrence_count = occurrence_count + 1, last_seen = :now
|
|
508
|
-
WHERE value_fingerprint = :valueFingerprint`),this.byPointerStmt=a.prepare(`SELECT ${bk} FROM secret_vault WHERE pointer_id = :pointerId`),this.byFingerprintStmt=a.prepare(`SELECT ${bk} FROM secret_vault WHERE value_fingerprint = :valueFingerprint`),this.listStmt=a.prepare(`SELECT ${bk} FROM secret_vault ORDER BY first_seen`),this.replaceCiphertextStmt=a.prepare(`UPDATE secret_vault
|
|
509
|
-
SET key_version = :keyVersion, ciphertext = :ciphertext, nonce = :nonce, auth_tag = :authTag
|
|
510
|
-
WHERE pointer_id = :pointerId`),this.refreshFingerprintStmt=a.prepare(`UPDATE secret_vault
|
|
511
|
-
SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
|
|
512
|
-
WHERE pointer_id = :pointerId`),this.derefStmt=a.prepare(`INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
|
|
513
|
-
VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`)}upsert(a,b){let c=!1;L(this.db,()=>{if(void 0===R(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint})){this.insertStmt.run(T({pointerId:a.pointerId,valueFingerprint:a.valueFingerprint,fingerprintKeyVersion:a.fingerprintKeyVersion,keyVersion:a.keyVersion,formatVersion:a.formatVersion??f.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=R(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint});if(void 0===d)throw Error("vault: row vanished immediately after write");return{row:bl(d),minted:c}}byPointerId(a){let b=R(this.byPointerStmt,{pointerId:a});return void 0===b?null:bl(b)}byValueFingerprint(a){let b=R(this.byFingerprintStmt,{valueFingerprint:a});return void 0===b?null:bl(b)}recordDeref(a){this.derefStmt.run(T({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 Q(this.listStmt).map(bl)}replaceCiphertext(a,b){this.replaceCiphertextStmt.run({pointerId:a,...b})}refreshFingerprint(a,b){this.refreshFingerprintStmt.run({pointerId:a,...b})}purgeAll(){let a=0;return L(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)
|
|
514
|
-
VALUES (:id, :pointerId, :location, :kind, :now, :now)
|
|
515
|
-
ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`).run({id:(0,v.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 Q(this.db.prepare(`SELECT pointer_id, location, kind, first_seen, last_seen
|
|
516
|
-
FROM secret_vault_sighting
|
|
517
|
-
WHERE pointer_id IN (${H(a.length)})
|
|
518
|
-
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=bh(a.limit,f.mBk),d=void 0===a.cursor?null:ae(a.cursor),e=null===d?"":"WHERE (v.last_seen < :cursorLastSeen OR (v.last_seen = :cursorLastSeen AND v.pointer_id < :cursorPointerId))",g=Q(this.db.prepare(`SELECT ${bj},
|
|
519
|
-
(SELECT e.id FROM exceptions e
|
|
520
|
-
WHERE e.rule_id = v.rule_id
|
|
521
|
-
AND e.value_fingerprint = v.value_fingerprint
|
|
522
|
-
AND e.key_version = v.fingerprint_key_version
|
|
523
|
-
AND ${aE}
|
|
524
|
-
LIMIT 1) AS grant_id
|
|
525
|
-
FROM secret_vault v
|
|
526
|
-
${e}
|
|
527
|
-
ORDER BY v.last_seen DESC, v.pointer_id DESC
|
|
528
|
-
LIMIT :limit`),T({now:b,limit:c+1,...null===d?{}:{cursorLastSeen:d.startedAtMs,cursorPointerId:d.id}})),h=g.length>c,i=h?g.slice(0,c):g,j=i[i.length-1];return{totals:{values:this.countEntries()},items:this.toInventoryEntries(i),nextCursor:h&&j?ad({startedAtMs:j.last_seen,id:j.pointer_id}):null}}listReuse(a={},b=Date.now()){var c;let d=bh(a.limit,f.mBk),e=void 0===a.cursor?null:function(a){let b=ac(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),g=null===e?"":`AND (v.occurrence_count < :cursorOccurrences
|
|
529
|
-
OR (v.occurrence_count = :cursorOccurrences AND v.pointer_id < :cursorPointerId))`,h=Q(this.db.prepare(`SELECT ${bj},
|
|
530
|
-
(SELECT e.id FROM exceptions e
|
|
531
|
-
WHERE e.rule_id = v.rule_id
|
|
532
|
-
AND e.value_fingerprint = v.value_fingerprint
|
|
533
|
-
AND e.key_version = v.fingerprint_key_version
|
|
534
|
-
AND ${aE}
|
|
535
|
-
LIMIT 1) AS grant_id
|
|
536
|
-
FROM secret_vault v
|
|
537
|
-
WHERE ${bi} ${g}
|
|
538
|
-
ORDER BY v.occurrence_count DESC, v.pointer_id DESC
|
|
539
|
-
LIMIT :limit`),T({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=bh(a.limit,f.hdu),c=void 0===a.cursor?null:ae(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 ")}`,g=Q(this.db.prepare(`SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
|
|
540
|
-
FROM secret_vault_deref ${e}
|
|
541
|
-
ORDER BY at DESC, id DESC LIMIT :limit`),T({limit:b+1,...null===c?{}:{cursorAt:c.startedAtMs,cursorId:c.id}})),h=g.length>b,i=h?g.slice(0,b):g,j=i[i.length-1],k=!0===a.includeBatched?0:U(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?ad({startedAtMs:j.at,id:j.id}):null,hiddenBatched:k}}countEntries(){return U(this.db,"SELECT COUNT(*) AS n FROM secret_vault")}countReused(){return U(this.db,`SELECT COUNT(*) AS n FROM secret_vault v WHERE ${bi}`)}}let bn=["critical","high","medium","low"],bo={block:"blocked",redact:"redacted",warn:"warned"},bp=["blocked","redacted","warned"],bq={[f.tLs.Antigravity]:{coverage:60,supported:!0},[f.tLs.Api]:{coverage:0,supported:!1},[f.tLs.ChatGpt]:{coverage:40,supported:!0},[f.tLs.ClaudeAi]:{coverage:40,supported:!0},[f.tLs.ClaudeCode]:{coverage:100,supported:!0},[f.tLs.Codex]:{coverage:80,supported:!0},[f.tLs.Copilot]:{coverage:0,supported:!1},[f.tLs.Cursor]:{coverage:0,supported:!1}},br={"7d":"day","30d":"day","3m":"week","6m":"week"};function bs(a){return 864e5*Math.floor(a/864e5)}function bt(a){return new Date(a).toISOString().slice(0,10)}class bu{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}severitySummary(){let a=new Map(Q(this.db.prepare(`SELECT d.severity AS severity,
|
|
542
|
-
COUNT(*) AS count,
|
|
543
|
-
SUM(CASE
|
|
544
|
-
WHEN e.event_type != 'code_change' THEN 1
|
|
545
|
-
WHEN f.finding_key IS NULL THEN 0
|
|
546
|
-
WHEN latest.status = 'resolved' THEN 1
|
|
547
|
-
ELSE 0
|
|
548
|
-
END) AS caught,
|
|
549
|
-
SUM(CASE
|
|
550
|
-
WHEN e.event_type = 'code_change'
|
|
551
|
-
AND f.finding_key IS NOT NULL
|
|
552
|
-
AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
|
|
553
|
-
ELSE 0
|
|
554
|
-
END) AS open_at_rest
|
|
555
|
-
FROM inspection_findings f
|
|
556
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
557
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
558
|
-
LEFT JOIN ${aI} latest
|
|
559
|
-
ON latest.finding_key = f.finding_key
|
|
560
|
-
WHERE e.event_type IN (${f.hfB})
|
|
561
|
-
GROUP BY d.severity`)).map(a=>[a.severity,a])),b=bn.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:f.KqW.options.map(a=>({provider:a,...bq[a]}))})}enforcementActions(a){let b=864e5*f.eI7[a],c=this.now(),d=c-b,e=this.findingsInRange(c-2*b,c),g={blocked:0,redacted:0,warned:0},h={blocked:0,redacted:0,warned:0};for(let a of e){let b=bo[a.actionTaken];b&&(a.occurredAt>=d?g[b]++:h[b]++)}let i=bp.map(a=>({kind:a,count:g[a],delta:g[a]-h[a]}));return Promise.resolve({range:a,total:i.reduce((a,b)=>a+b.count,0),actions:i})}findingsTimeseries(a){let b=br[a],c=("day"===b?1:7)*864e5,d=f.eI7[a],e="day"===b?d:Math.ceil(d/7),g=this.now(),h=bs(g)-(d-1)*864e5,i=this.findingsInRange(h,g),j=Array.from({length:e},(a,b)=>({timestamp:bt(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=br[a],c=("day"===b?1:7)*864e5,d=f.eI7[a],e="day"===b?d:Math.ceil(d/7),g=this.now(),h=bs(g)-(d-1)*864e5,i=Q(this.db.prepare(`SELECT DISTINCT f.finding_key AS finding_key,
|
|
562
|
-
COALESCE(f.first_detected_at, e.started_at) AS first_detected_at, d.severity AS severity,
|
|
563
|
-
latest.status AS latest_status,
|
|
564
|
-
latest.method AS latest_method,
|
|
565
|
-
latest.resolved_at AS latest_resolved_at
|
|
566
|
-
FROM finding_resolution fr
|
|
567
|
-
CROSS JOIN inspection_findings f ON f.finding_key = fr.finding_key
|
|
568
|
-
CROSS JOIN audit_events e ON e.id = f.audit_event_id
|
|
569
|
-
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
570
|
-
LEFT JOIN ${aI} latest
|
|
571
|
-
ON latest.finding_key = f.finding_key
|
|
572
|
-
WHERE fr.resolved_at >= :windowStart
|
|
573
|
-
AND e.event_type IN (${f.hfB})`),{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>=g)continue;let b=Math.floor((a.latest_resolved_at-h)/c);if(b<0||b>=e)continue;let d=`${String(b)}:${a.severity}`,f=Math.max(0,a.latest_resolved_at-a.first_detected_at);j.set(d,(j.get(d)??0)+f),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 bn){let c=`${String(b)}:${a}`,e=k.get(c)??0;d[a]=e>0?(j.get(c)??0)/e:null}return{timestamp:bt(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*f.eI7[a];return Promise.resolve({range:a,items:Q(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 (${f.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:Q(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 ${aI} latest
|
|
589
|
-
CROSS JOIN inspection_findings f ON f.finding_key = latest.finding_key
|
|
590
|
-
CROSS JOIN audit_events e ON e.id = f.audit_event_id
|
|
591
|
-
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
592
|
-
WHERE latest.status = 'resolved'
|
|
593
|
-
AND latest.method = 'fixed-at-source'
|
|
594
|
-
AND latest.resolved_at IS NOT NULL
|
|
595
|
-
AND e.event_type = 'code_change'
|
|
596
|
-
ORDER BY latest.resolved_at DESC
|
|
597
|
-
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 Q(this.db.prepare(`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
|
|
598
|
-
FROM inspection_findings f
|
|
599
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
600
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
601
|
-
WHERE e.started_at >= :from AND e.started_at < :to
|
|
602
|
-
AND e.event_type IN (${f.hfB})
|
|
603
|
-
ORDER BY e.started_at`),{from:a,to:b}).map(a=>({occurredAt:a.occurred_at,severity:a.severity,actionTaken:a.action_taken}))}}let bv=["provider","internal","external","ip"],bw="('http', 'ws')",bx=`LEFT JOIN egress_decision_override oh ON oh.host = d.host
|
|
604
|
-
LEFT JOIN egress_decision_override ol ON ol.destination_id = d.id AND ol.host IS NULL`;function by(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 bz(a,b){let c=b.map(a=>a.transport),d=b.map(a=>a.dataClass),e=b.reduce((a,b)=>a+b.callSiteCount,0),g=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,f.Gw9)(a.trust,a.overrideDecision),isCustom:(0,f.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(g).toISOString(),endpointCount:b.length,callSiteCount:e,transports:(0,f.by7)(c),dataClasses:(0,f.hzO)(d),review:(0,f.Fnc)(a.trust,c),network:"provider"===a.kind?null:ab(a.networkJson,null),endpoints:b.map(by)}}class bA{constructor(a){this.db=a}stats(){let a=U(this.db,"SELECT count(*) AS n FROM share_destination"),b=U(this.db,"SELECT count(*) AS n FROM share_endpoint"),c=U(this.db,"SELECT count(*) AS n FROM share_call_site"),d=U(this.db,`SELECT count(DISTINCT destination_id) AS n FROM share_endpoint
|
|
605
|
-
WHERE transport IN ${bw}`),e=U(this.db,`SELECT count(DISTINCT d.id) AS n
|
|
606
|
-
FROM share_destination d
|
|
607
|
-
LEFT JOIN share_endpoint e ON e.destination_id = d.id
|
|
608
|
-
AND e.transport IN ${bw}
|
|
609
|
-
WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`),f=V(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=V(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=>bz(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:bv.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:bz(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,f.C05)(b.map(a=>a.dataClass)),callSiteCount:a.callSiteCount,lastSeen:a.lastSeen})).sort((a,b)=>{let c=(0,f.WSs)(a.review.reasons)-(0,f.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,g=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=g.get(a.endpointId);c?c.push(b):g.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,f.Gw9)(a.trust,a.overrideDecision),isCustom:(0,f.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(e).toISOString(),transports:(0,f.by7)(d),dataClasses:(0,f.hzO)(b.map(a=>a.dataClass)),review:(0,f.Fnc)(a.trust,d),network:"provider"===a.kind?null:ab(a.networkJson,null),note:a.note,endpoints:b.map(a=>({...by(a),sites:g.get(a.id)??[]}))}}(b,c,d))}setEgressDecision(a,b){let c=!1;return L(this.db,()=>{let d=this.db.prepare("SELECT host FROM share_destination WHERE id = ?").get(a);void 0!==d&&(c=!0,this.db.prepare(`DELETE FROM egress_decision_override
|
|
610
|
-
WHERE host = :host OR (destination_id = :destinationId AND host IS NULL)`).run({host:d.host,destinationId:a}),null!==b&&this.db.prepare(`INSERT INTO egress_decision_override
|
|
611
|
-
(id, destination_id, host, decision, created_at, updated_at)
|
|
612
|
-
VALUES (:id, :destinationId, :host, :decision, :now, :now)`).run({id:(0,v.randomUUID)(),destinationId:a,host:d.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 L(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
|
|
613
|
-
WHERE project_key = :key
|
|
614
|
-
AND (:prefix = '' OR file = :prefix OR file LIKE :subtree ESCAPE '\\')
|
|
615
|
-
AND file NOT LIKE '.%'
|
|
616
|
-
AND file NOT LIKE '%/.%'`).run({key:a,prefix:c,subtree:`${G(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
|
|
617
|
-
WHERE project_key = ? AND file IN (${H(d.length)})`).run(a,...d)}}upsertHits(a,b,c,d){if(0===b.length)return;let e=this.db.prepare(`INSERT INTO share_destination
|
|
618
|
-
(id, kind, name, host, category, trust, network_json, last_seen, provenance,
|
|
619
|
-
created_at, updated_at)
|
|
620
|
-
VALUES (:id, :kind, :name, :host, :category, :trust, :networkJson, :now, 'scan', :now, :now)
|
|
621
|
-
ON CONFLICT (host) DO UPDATE SET
|
|
622
|
-
kind = excluded.kind,
|
|
623
|
-
name = excluded.name,
|
|
624
|
-
category = excluded.category,
|
|
625
|
-
trust = excluded.trust,
|
|
626
|
-
network_json = excluded.network_json,
|
|
627
|
-
last_seen = excluded.last_seen,
|
|
628
|
-
updated_at = excluded.updated_at`),f=this.db.prepare("SELECT id FROM share_destination WHERE host = ?"),g=this.db.prepare(`INSERT INTO share_endpoint
|
|
629
|
-
(id, destination_id, method, transport, url, template, data_class, last_seen,
|
|
630
|
-
created_at, updated_at)
|
|
631
|
-
VALUES (:id, :destinationId, :method, :transport, :url, :template, :dataClass, :now,
|
|
632
|
-
:now, :now)
|
|
633
|
-
ON CONFLICT (destination_id, method, url) DO UPDATE SET
|
|
634
|
-
transport = excluded.transport,
|
|
635
|
-
template = excluded.template,
|
|
636
|
-
data_class = excluded.data_class,
|
|
637
|
-
last_seen = excluded.last_seen,
|
|
638
|
-
updated_at = excluded.updated_at`),h=this.db.prepare("SELECT id FROM share_endpoint WHERE destination_id = ? AND method = ? AND url = ?"),i=this.db.prepare(`INSERT INTO share_call_site
|
|
639
|
-
(id, endpoint_id, project, project_key, file, line, snippet, dynamic, vendored,
|
|
640
|
-
project_id, created_at, updated_at)
|
|
641
|
-
VALUES (:id, :endpointId, :project, :projectKey, :file, :line, :snippet, :dynamic,
|
|
642
|
-
:vendored, :projectId, :now, :now)
|
|
643
|
-
ON CONFLICT (endpoint_id, project_key, file, line) DO UPDATE SET
|
|
644
|
-
snippet = excluded.snippet,
|
|
645
|
-
dynamic = excluded.dynamic,
|
|
646
|
-
vendored = excluded.vendored,
|
|
647
|
-
project = excluded.project,
|
|
648
|
-
project_id = COALESCE(excluded.project_id, share_call_site.project_id),
|
|
649
|
-
updated_at = excluded.updated_at`),j=new Map,k=new Map;for(let l of b){let b=j.get(l.host);void 0===b&&(e.run({id:(0,v.randomUUID)(),kind:l.kind,name:l.name,host:l.host,category:l.category,trust:l.trust,networkJson:null===l.network?null:JSON.stringify(l.network),now:d}),b=R(f,[l.host])?.id??"",j.set(l.host,b));let m=`${b}\0${l.method}\0${l.url}`,n=k.get(m);void 0===n&&(g.run({id:(0,v.randomUUID)(),destinationId:b,method:l.method,transport:l.transport,url:l.url,template:+!!l.template,dataClass:l.dataClass,now:d}),n=R(h,[b,l.method,l.url])?.id??"",k.set(m,n)),i.run({id:(0,v.randomUUID)(),endpointId:n,project:a.project,projectKey:a.projectKey,file:l.site.file,line:l.site.line,snippet:l.site.snippet,dynamic:+!!l.site.dynamic,vendored:+!!l.site.vendored,projectId:c,now:d})}}knownProjectId(a){return R(this.db.prepare(`SELECT project_id AS projectId FROM share_call_site
|
|
650
|
-
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
|
|
651
|
-
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
|
|
652
|
-
WHERE id IN (SELECT DISTINCT e.destination_id
|
|
653
|
-
FROM share_endpoint e
|
|
654
|
-
JOIN share_call_site c ON c.endpoint_id = e.id
|
|
655
|
-
WHERE c.project_key = :key)`).run({now:b,key:a})}pruneOrphans(){this.db.exec(`DELETE FROM share_endpoint
|
|
656
|
-
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
|
|
657
|
-
WHERE host IS NULL
|
|
658
|
-
AND destination_id IN (
|
|
659
|
-
SELECT d.id FROM share_destination d
|
|
660
|
-
WHERE NOT EXISTS (SELECT 1 FROM share_endpoint e WHERE e.destination_id = d.id))`),this.db.exec(`DELETE FROM share_destination
|
|
661
|
-
WHERE NOT EXISTS (
|
|
662
|
-
SELECT 1 FROM share_endpoint e WHERE e.destination_id = share_destination.id)`)}projectTotals(a){return{destinations:U(this.db,`SELECT count(DISTINCT e.destination_id) AS n
|
|
663
|
-
FROM share_endpoint e
|
|
664
|
-
JOIN share_call_site c ON c.endpoint_id = e.id
|
|
665
|
-
WHERE c.project_key = ?`,[a]),endpoints:U(this.db,"SELECT count(DISTINCT endpoint_id) AS n FROM share_call_site WHERE project_key = ?",[a]),callSites:U(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,
|
|
666
|
-
d.network_json AS networkJson, d.last_seen AS lastSeenMs,
|
|
667
|
-
d.created_at AS createdAt,
|
|
668
|
-
COALESCE(oh.decision, ol.decision) AS overrideDecision`,f=[],g=[];if(b&&b.length>0&&(f.push(`d.kind IN (${H(b.length)})`),g.push(...b)),c&&f.push(`(d.trust IN ('unverified', 'ip')
|
|
669
|
-
OR EXISTS (SELECT 1 FROM share_endpoint re
|
|
670
|
-
WHERE re.destination_id = d.id
|
|
671
|
-
AND re.transport IN ${bw}))`),a){let b=I(a);f.push(`(d.name LIKE ? ESCAPE '\\' OR d.category LIKE ? ESCAPE '\\' OR e.url LIKE ? ESCAPE '\\'
|
|
672
|
-
OR c.project LIKE ? ESCAPE '\\' OR c.file LIKE ? ESCAPE '\\')`),g.push(b,b,b,b,b),d=`SELECT DISTINCT ${e}
|
|
673
|
-
FROM share_destination d
|
|
674
|
-
${bx}
|
|
675
|
-
LEFT JOIN share_endpoint e ON e.destination_id = d.id
|
|
676
|
-
LEFT JOIN share_call_site c ON c.endpoint_id = e.id
|
|
677
|
-
${f.length?`WHERE ${f.join(" AND ")}`:""}
|
|
678
|
-
ORDER BY d.created_at ASC, d.id ASC`}else d=`SELECT ${e}
|
|
679
|
-
FROM share_destination d
|
|
680
|
-
${bx}
|
|
681
|
-
${f.length?`WHERE ${f.join(" AND ")}`:""}
|
|
682
|
-
ORDER BY d.created_at ASC, d.id ASC`;return Q(this.db.prepare(d),g).map(a=>this.mapDestRow(a))}fetchDestinationById(a){let b=R(this.db.prepare(`SELECT d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
|
|
683
|
-
d.network_json AS networkJson, d.last_seen AS lastSeenMs,
|
|
684
|
-
COALESCE(oh.decision, ol.decision) AS overrideDecision
|
|
685
|
-
FROM share_destination d
|
|
686
|
-
${bx}
|
|
687
|
-
WHERE d.id = ?`),[a]);return b?this.mapDestRow(b):null}fetchEndpoints(a){return 0===a.length?[]:Q(this.db.prepare(`SELECT e.id, e.destination_id AS destinationId, e.method, e.transport, e.url,
|
|
688
|
-
e.template, e.data_class AS dataClass, e.last_seen AS lastSeenMs,
|
|
689
|
-
count(c.id) AS callSiteCount
|
|
690
|
-
FROM share_endpoint e
|
|
691
|
-
LEFT JOIN share_call_site c ON c.endpoint_id = e.id
|
|
692
|
-
WHERE e.destination_id IN (${H(a.length)})
|
|
693
|
-
GROUP BY e.id
|
|
694
|
-
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?[]:Q(this.db.prepare(`SELECT id, endpoint_id AS endpointId, project, file, line, snippet, dynamic, vendored,
|
|
695
|
-
project_id AS projectId
|
|
696
|
-
FROM share_call_site
|
|
697
|
-
WHERE endpoint_id IN (${H(a.length)})
|
|
698
|
-
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 bB{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO source_project
|
|
699
|
-
(id, url, name, attributes, first_seen, last_seen)
|
|
700
|
-
VALUES
|
|
701
|
-
(:id, :url, :name, :attributes, :firstSeen, :lastSeen)
|
|
702
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
703
|
-
url = excluded.url,
|
|
704
|
-
name = excluded.name,
|
|
705
|
-
attributes = excluded.attributes,
|
|
706
|
-
last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){let c=y(a.url),d=(0,f.QCA)(a,c,b);return this.upsertStmt.run(T({id:d.id,url:d.url,name:d.name,attributes:d.attributes,firstSeen:d.firstSeen,lastSeen:d.lastSeen})),c}findById(a){return R(this.db.prepare("SELECT * FROM source_project WHERE id = :id"),{id:a})}distinctNames(){return Q(this.db.prepare(`SELECT DISTINCT name FROM source_project
|
|
707
|
-
WHERE name IS NOT NULL
|
|
708
|
-
ORDER BY name`)).map(a=>a.name)}}let bC=Symbol("aka.persistence.unsafeTestOnlyRawHandle");function bD(a,b){return b?{...a,hostId:b}:a}function bE(a){try{a.close()}catch{}}function bF(a){let b=new w.DatabaseSync(a);try{b.exec("PRAGMA journal_mode = WAL"),b.exec("PRAGMA busy_timeout = 2000"),b.exec("PRAGMA foreign_keys = ON")}catch(a){throw bE(b),a}return b}function bG(a){l(a);let b=(0,e.join)(a,h);E(b);let{db:c,events:g,findings:i,policies:j,installedPacks:k,scanLedger:n,secretVault:p,exceptions:q,resolutions:r,ruleProbeCache:s,security:t,detections:u,shares:w,policyCatalog:B,inventory:C,inventoryAssets:D,projectFiles:H,activity:I,sourceProject:J,auditEvents:K,classifiedData:Q,inspectionDefinitions:R,inspectionFindings:S,configInventory:U}=function(a){let b=bF(a);try{var c;if(c=b,O(c,"table","tenants")||P(c,"events").includes("tenant_id")){let c=function(a,b){let c;E(b);let e=A(b,"legacy"),f=!1;try{F(a,e),f=!0}catch(a){c=a}finally{a.close()}if(!f){N(`Could not snapshot the incompatible ${h} (${String(c)}); moving the store aside with its sidecars instead.`);let a=[];(0,d.renameSync)(b,e),a.push([e,b]);try{for(let c of m(b)){let f=`${e}${c.slice(b.length)}`;try{(0,d.renameSync)(c,f),a.push([f,c])}catch{(0,d.rmSync)(c,{force:!0})}}}catch(b){for(let[b,c]of a.reverse())try{(0,d.renameSync)(b,c)}catch{}throw b}return o(e),e}try{for(let a of((0,d.rmSync)(b,{force:!0}),m(b)))(0,d.rmSync)(a,{force:!0})}catch(a){if((0,d.existsSync)(b))try{(0,d.rmSync)(e,{force:!0})}catch{}throw a}return e}(b,a);b=bF(a),N(`Detected an older, incompatible (tenant-bearing) ${h}; backed it up to ${c} and created a fresh store.`)}!function(a,b){var c,d,e;let g=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)),i=0===h.size&&g>0,j=a.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)");for(let[b,c]of f.lFU.entries()){if(h.has(c.tag)||c.tag===Z)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?P(a,b.table,{includeGenerated:!0}).includes(b.name):O(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(X).join(", ")} while missing ${a.map(X).join(", ")} — the schema diverged from the migration history; refusing to replay or skip.`;throw N(b),Error(`[aka] ${b}`)}let f=d.length>0?e.length===d.length:i&&b<g,k=/PRAGMA foreign_keys\s*=\s*OFF/i.test(c.sql),l=Y(c.sql);k&&a.exec("PRAGMA foreign_keys = OFF");try{L(a,()=>{for(let b of l){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(f)continue}else if(O(a,"index",c))continue;a.exec(b)}if(k&&!f){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.`)}j.run(c.tag,Date.now())},"IMMEDIATE")}finally{k&&a.exec("PRAGMA foreign_keys = ON")}}g<f.lFU.length&&a.exec(`PRAGMA user_version = ${String(f.lFU.length)}`),c=a,d="audit_events",O(c,"table",d)&&(P(c,d).includes("synced_at")||c.exec(`ALTER TABLE ${d} ADD COLUMN synced_at integer`)),a.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
|
|
709
|
-
path TEXT PRIMARY KEY,
|
|
710
|
-
mtime TEXT NOT NULL,
|
|
711
|
-
content_hash TEXT NOT NULL,
|
|
712
|
-
ruleset_hash TEXT NOT NULL,
|
|
713
|
-
scanned_at INTEGER NOT NULL
|
|
714
|
-
)`),a.exec(`CREATE TABLE IF NOT EXISTS blocked_detections (
|
|
715
|
-
reference TEXT PRIMARY KEY,
|
|
716
|
-
rule_id TEXT NOT NULL,
|
|
717
|
-
category TEXT NOT NULL,
|
|
718
|
-
value_fingerprint TEXT NOT NULL,
|
|
719
|
-
key_version INTEGER NOT NULL,
|
|
720
|
-
masked_value TEXT NOT NULL,
|
|
721
|
-
session_id TEXT,
|
|
722
|
-
repo TEXT,
|
|
723
|
-
blocked_at INTEGER NOT NULL
|
|
724
|
-
)`),a.exec(`CREATE TABLE IF NOT EXISTS rule_probe_cache (
|
|
725
|
-
rule_key TEXT PRIMARY KEY,
|
|
726
|
-
verdict TEXT NOT NULL,
|
|
727
|
-
worst_probe_ms REAL NOT NULL,
|
|
728
|
-
checked_at INTEGER NOT NULL
|
|
729
|
-
)`),(e=a).exec(`CREATE TABLE IF NOT EXISTS \`_pack_write_gate\` (
|
|
730
|
-
\`id\` integer PRIMARY KEY NOT NULL,
|
|
731
|
-
\`open\` integer DEFAULT 0 NOT NULL,
|
|
732
|
-
CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)
|
|
733
|
-
)`),e.exec("INSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0)"),O(e,"table","installed_packs")&&e.exec(`CREATE TRIGGER IF NOT EXISTS trg_installed_packs_write_gate
|
|
734
|
-
BEFORE UPDATE OF version, name, rules_json ON installed_packs
|
|
735
|
-
WHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1
|
|
736
|
-
BEGIN SELECT RAISE(IGNORE); END`),function(a){if(!O(a,"table","audit_events"))return;let b=new Set(P(a,"audit_events",{includeGenerated:!0}));for(let c of _)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
|
|
737
|
-
FROM source_project
|
|
738
|
-
WHERE url IS NOT NULL AND id NOT LIKE 'sample:%'
|
|
739
|
-
ORDER BY last_seen DESC, id`).all().map(a=>({row:a,canonicalId:y(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)
|
|
740
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
741
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
742
|
-
first_seen = min(first_seen, excluded.first_seen),
|
|
743
|
-
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 = ?
|
|
744
|
-
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 = ?");L(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){N(`source_project id reconcile failed: ${String(a)}`)}}(a),!h.has(Z)&&function(a){try{if(!function(a){let b=a.prepare(`SELECT rowid AS rowid, id, source_tool AS sourceTool, kind, occurred_at AS occurredAt,
|
|
745
|
-
content_hash AS contentHash, content, metadata
|
|
746
|
-
FROM events WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO audit_events
|
|
747
|
-
(id, parent_id, root_session_id, event_type, started_at, content, content_hash, attributes)
|
|
748
|
-
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 aa(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),g=a?.sessionId??null;null!==g&&d.run(g,e.occurredAt),c.run(T({id:e.id,parentId:g,rootSessionId:g,eventType:e.kind,startedAt:e.occurredAt,content:e.content,contentHash:e.contentHash,attributes:(b={...e,metadata:a},JSON.stringify((0,f.$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,
|
|
749
|
-
span_start AS spanStart, span_end AS spanEnd, masked_match AS maskedMatch,
|
|
750
|
-
action_taken AS actionTaken, confidence, finding_key AS findingKey,
|
|
751
|
-
first_detected_at AS firstDetectedAt
|
|
752
|
-
FROM findings WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
|
|
753
|
-
(id, rule_id, name, category, severity, definition, version)
|
|
754
|
-
VALUES (:id, :ruleId, :name, :category, :severity, :definition, :version)`),d=a.prepare(`INSERT INTO inspection_findings
|
|
755
|
-
(id, audit_event_id, inspection_definition_id, classified_data_id,
|
|
756
|
-
span_start, span_end, masked_match, action_taken, confidence,
|
|
757
|
-
finding_key, first_detected_at)
|
|
758
|
-
VALUES
|
|
759
|
-
(:id, :auditEventId, :inspectionDefinitionId, NULL,
|
|
760
|
-
:spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
|
|
761
|
-
:findingKey, :firstDetectedAt)
|
|
762
|
-
ON CONFLICT(id) DO NOTHING
|
|
763
|
-
ON CONFLICT (finding_key) DO UPDATE SET
|
|
764
|
-
first_detected_at = CASE
|
|
765
|
-
WHEN first_detected_at IS NULL THEN excluded.first_detected_at
|
|
766
|
-
WHEN excluded.first_detected_at IS NULL THEN first_detected_at
|
|
767
|
-
ELSE min(first_detected_at, excluded.first_detected_at)
|
|
768
|
-
END`);return aa(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=z(e.ruleId,d),c.run(T({id:f,ruleId:e.ruleId,name:e.ruleId,category:e.category,severity:e.severity,definition:"",version:d})),b.set(a,f)}d.run(T({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 N(`legacy history backfill failed: ${String(a)}`),!1}}(a)&&function(a,b){let c=f.lFU.find(a=>a.tag===Z);if(!c)return;let d=void 0===b?void 0:$(a);if(void 0!==b&&d?.holdsRows===!0)try{var e=a,g=b;E(g);let c=A(g,"pre-drop");F(e,c)}catch(a){N(`legacy events/findings backup failed; deferring the drop: ${String(a)}`);return}try{L(a,()=>{if(!a.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(c.tag)){if(void 0!==d&&$(a).mark!==d.mark)return void N("legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first.");for(let b of Y(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){N(`legacy events/findings drop failed; deferring: ${String(a)}`)}}(a,b)}(b,a),o(a);let e=new bb(b),g=new aT(b),i={events:new az(b),findings:new aM(b),policies:e,installedPacks:g,scanLedger:new bg(b),secretVault:new bm(b),exceptions:new aF(b),resolutions:new be(b),ruleProbeCache:new bf(b),security:new bu(b),detections:new ay(b),shares:new bA(b),policyCatalog:new bc(g),inventory:new aU(b),inventoryAssets:new ba(b),projectFiles:new bd(b),activity:new aq(b),sourceProject:new bB(b),auditEvents:new ar(b),classifiedData:new as(b),inspectionDefinitions:new aN(b),inspectionFindings:new aO(b),configInventory:new au(b)};return e.seedDefaults(),{db:b,...i}}catch(a){throw bE(b),a}}(b);return{events:g,findings:i,policies:j,installedPacks:k,scanLedger:n,secretVault:p,exceptions:q,resolutions:r,ruleProbeCache:s,security:t,detections:u,shares:w,policyCatalog:B,inventory:C,inventoryAssets:D,activity:I,sourceProject:J,auditEvents:K,classifiedData:Q,inspectionDefinitions:R,inspectionFindings:S,recordCapture:function(a,b){M(c,()=>{let c=a.metadata?.sessionId;c&&K.ensureSessionRoot(c,a.occurredAt);let d=function(a,b,c=null){return x((0,f.tTV)(["capture",a??"no_session",b,c??"no_path"]))}(c??null,a.contentHash,a.metadata?.filePath??null);K.insertAuditEvent({id:d,eventType:a.kind,startedAt:a.occurredAt,parentId:c,rootSessionId:c,content:a.content,contentHash:a.contentHash,attributes:(0,f.$w9)(a)});let e=new Map;for(let a of b){if(c&&S.isSessionDuplicate(a.ruleId,a.maskedMatch,c)||S.isEventDuplicate(d,a.ruleId,a.maskedMatch,a.span.start,a.span.end))continue;let b=`${a.ruleId}@${(0,f.qmP)(a)}`,g=e.get(b);g||(g=R.upsert((0,f.jTf)(a)),e.set(b,g)),S.insertFinding({id:a.id,auditEventId:d,inspectionDefinitionId:g,span:a.span,maskedMatch:a.maskedMatch,actionTaken:a.actionTaken,confidence:a.confidence,findingKey:a.findingKey??void 0})}})},ensureInventory:function(a){let b={};return M(c,()=>{let c=Date.now();a.host&&(b.hostId=C.upsert(a.host,c)),a.harness&&(b.harnessId=C.upsert(bD(a.harness,b.hostId),c)),b.accountId=C.upsert(bD({objectType:"user",identityKey:"local",attributes:{source:"local"}},b.hostId),c),a.project&&(b.sourceProjectId=J.upsert(a.project,c))})?b:{}},recordConfigScan:function(a){M(c,()=>{let b=(0,f.I8t)(a.scanEvent.startedAt);for(let c of a.items)C.upsert(c,b);K.insertAuditEvent(a.scanEvent);let c=new Map;for(let b of a.definitions??[])c.set(`${b.ruleId}@${b.version}`,R.upsert(b));for(let b of a.findings??[]){let d=c.get(`${b.ruleId}@${b.version}`);d&&S.insertFinding({id:(0,v.randomUUID)(),auditEventId:a.scanEvent.id,inspectionDefinitionId:d,span:b.span,maskedMatch:b.maskedMatch,actionTaken:b.actionTaken,confidence:b.confidence})}})},recordProjectFiles:function(a,b){0!==b.files.length&&M(c,()=>{H.replaceForProject(a,b,Date.now())})},reconcileWorktreeProjects:function(a,b,d){try{let f=b.split(e.sep).join("/"),g=d.split(e.sep).join("/"),h=d===b?"":"url IN (:worktreePosix, :worktreeWin) OR ",i=c.prepare(`SELECT id FROM source_project
|
|
769
|
-
WHERE id <> :canonicalId
|
|
770
|
-
AND (${h}url LIKE :pattern ESCAPE '\\' OR url LIKE :patternWin ESCAPE '\\')`).all({canonicalId:a,...d===b?{}:{worktreePosix:g,worktreeWin:g.split("/").join("\\")},pattern:`${G(f)}/.claude/worktrees/%`,patternWin:`${G(f.split("/").join("\\"))}\\\\.claude\\\\worktrees\\\\%`});if(0===i.length)return;L(c,()=>{for(let{id:b}of i)c.prepare("UPDATE audit_events SET source_project_id = :canonicalId WHERE source_project_id = :id").run({canonicalId:a,id:b}),c.prepare("UPDATE OR IGNORE file_access_override SET project_id = :canonicalId WHERE project_id = :id").run({canonicalId:a,id:b}),c.prepare("DELETE FROM file_access_override WHERE project_id = :id").run({id:b}),c.prepare("DELETE FROM project_file WHERE project_id = :id").run({id:b}),c.prepare("DELETE FROM source_project WHERE id = :id").run({id:b})})}catch{}},configInventoryReport:()=>U.report(),facets:function(){return{hosts:C.distinctTitles("host"),harnesses:C.distinctTitles("harness"),osVersions:C.osVersions(),projects:J.distinctNames()}},purgeSampleData:()=>{!function(a){try{if(!a.prepare(`SELECT (
|
|
771
|
-
EXISTS(SELECT 1 FROM share_destination WHERE provenance = 'sample')
|
|
772
|
-
OR EXISTS(SELECT 1 FROM audit_events WHERE id LIKE 'sample:activity:%')
|
|
773
|
-
OR EXISTS(SELECT 1 FROM inventory_asset WHERE provenance = 'sample')
|
|
774
|
-
) AS n`).get().n)return;L(a,()=>{a.exec(`DELETE FROM share_call_site WHERE endpoint_id IN (
|
|
775
|
-
SELECT e.id FROM share_endpoint e
|
|
776
|
-
JOIN share_destination d ON d.id = e.destination_id
|
|
777
|
-
WHERE d.provenance = 'sample')`),a.exec(`DELETE FROM egress_decision_override WHERE destination_id IN (
|
|
778
|
-
SELECT id FROM share_destination WHERE provenance = 'sample')`),a.exec(`DELETE FROM share_endpoint WHERE destination_id IN (
|
|
779
|
-
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')
|
|
780
|
-
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 (
|
|
781
|
-
key TEXT PRIMARY KEY,
|
|
782
|
-
value TEXT NOT NULL
|
|
783
|
-
)`),a.exec("DELETE FROM app_meta WHERE key LIKE 'sample_seeded:%'")})}catch{}}(c)},transaction:async function a(a){c.exec("BEGIN");try{let b=await a();return c.exec("COMMIT"),b}catch(a){try{c.exec("ROLLBACK")}catch{}throw a}},close:()=>{c.close()},[bC]:c}}var bH=c(48161);let bI=new Set(["EEXIST","EACCES","EPERM","EBUSY"]),bJ=new Int32Array(new SharedArrayBuffer(4));class bK 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 bL(a){let b;try{b=(0,d.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 bM(a,b){let c,e=(0,v.randomUUID)();try{c=(0,d.openSync)(a,"wx",384)}catch(e){let c=e.code??"";if("EEXIST"===c||bI.has(c)&&((0,d.existsSync)(a)||function(a){let b=`${a}.probe-${(0,v.randomUUID)()}`;try{return(0,d.closeSync)((0,d.openSync)(b,"wx",384)),!0}catch{return!1}finally{try{(0,d.rmSync)(b,{force:!0})}catch{}}}(a)))return null;throw new bK("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,bH.hostname)()};try{(0,d.writeFileSync)(c,`${JSON.stringify(f)}
|
|
784
|
-
`)}catch{try{(0,d.closeSync)(c)}catch{}return(0,d.rmSync)(a,{force:!0}),null}try{(0,d.closeSync)(c)}catch{}return e}function bN(a){let b=a.filePath.replaceAll("\\","/");return(0,v.createHash)("sha256").update(`${a.ruleId}\0${b}\0${a.valueFingerprint}`).digest("hex")}function bO(a){return(0,e.join)(a,"exception.key")}let bP={exceptions:"key_version",blocked_detections:"key_version",secret_vault:"fingerprint_key_version"};class bQ 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 bR(a){let b,c=(0,e.join)(a,h);if(!(0,d.existsSync)(c))return 0;try{(b=new w.DatabaseSync(c,{readOnly:!0})).exec(`PRAGMA busy_timeout = ${String(250)}`);let a=0;for(let[c,d]of Object.entries(bP))try{let e=R(b.prepare(`SELECT MAX(${d}) AS v FROM ${c}`));a=Math.max(a,e?.v??0)}catch(a){if(1!==a.errcode)throw new bQ(a)}return a}catch(a){throw a instanceof bQ?a:new bQ(a)}finally{b?.close()}}function bS(a){return JSON.stringify({version:a.version,material:a.material.toString("base64")})}function bT(a){let b;try{b=(0,d.readFileSync)(bO(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:e,material:f}=c;if("number"!=typeof e||!Number.isInteger(e)||e<1)throw Error("exception key file is corrupt: bad version");if("string"!=typeof f)throw Error("exception key file is corrupt: bad material");let g=Buffer.from(f,"base64");if(32!==g.length)throw Error("exception key file is corrupt: bad material length");return{version:e,material:g}}function bU(a){let b=bT(a);return b?(n(bO(a)),b):function(a,b){l(a);let c=bO(a);if(t(c,`${bS(b)}
|
|
785
|
-
`))return b;let d=bT(a);if(d)return n(c),d;let e=r(c);throw new s(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:bR(a)+1,material:(0,v.randomBytes)(32)})}function bV(a){var b;let c=bT(a);return b={version:Math.max(c?.version??0,bR(a))+1,material:(0,v.randomBytes)(32)},l(a),q(bO(a),`${bS(b)}
|
|
786
|
-
`),b}function bW(a,b){return(0,v.createHmac)("sha256",a.material).update(b,"utf8").digest("hex")}function bX(a,b){var c;return(0,f.qEQ)(b,null===(c=a)?{status:"absent"}:{status:"present",version:c.version})}function bY(){return(0,e.join)((0,bH.homedir)(),".aka")}function bZ(a=bY()){return(0,e.join)(a,"settings")}function b$(a=bY()){return(0,e.join)(a,"data")}function b_(a=bY()){return(0,e.join)(a,"keys")}function b0(a=function(a=process.platform){return"darwin"===a?[e.posix.join("/Library","Application Support","AKASecurity",f.WRR),e.posix.join("/Library","Managed Preferences",f.WRR)]:"win32"===a?[e.win32.join("C:\\","ProgramData","AKASecurity",f.WRR)]:[e.posix.join("/etc","aka",f.WRR)]}()){for(let b of a){let a;try{a=(0,d.readFileSync)(b,"utf8")}catch{continue}let c=ac(a);if(!c)continue;let e=f.ZXz.safeParse(c);if(e.success)return e.data}return null}function b1(a,b,c=()=>new Date){if(!b)return a;let{values:d}=b,e={...a};return void 0!==d.runMode&&(e.runMode=d.runMode),void 0!==d.controlPlane&&(e.controlPlane={...d.controlPlane,attachedAt:a.controlPlane?.endpoint===d.controlPlane.endpoint?a.controlPlane.attachedAt:c().toISOString()}),void 0!==d.historicalAccess&&(e.historicalAccess=d.historicalAccess),void 0!==d.vaultKeyCustody&&(e.vaultKeyCustody=d.vaultKeyCustody),void 0!==d.vaultInlineReveal&&(e.vaultInlineReveal=d.vaultInlineReveal),void 0!==d.dataSharesInPlace&&(e.dataSharesInPlace=d.dataSharesInPlace),void 0!==d.vaultConsent&&(e.vaultConsent=d.vaultConsent?a.vaultConsent?.version===f.DzG?a.vaultConsent:{acknowledgedAt:c().toISOString(),version:f.DzG}:void 0),void 0!==d.modelJudgeConsent&&(e.modelJudgeConsent=d.modelJudgeConsent?a.modelJudgeConsent?.payloadVersion===f.kxf?a.modelJudgeConsent:{acknowledgedAt:c().toISOString(),payloadVersion:f.kxf}:void 0),e}c(51455);let b2="settings.json";function b3(a=bY()){return b1(b4(a),b0())}function b4(a){let b=function(a){let b;try{b=(0,d.readFileSync)(a,"utf8")}catch{return null}return ac(b)??null}((0,e.join)(bZ(a),b2));if(!b)return(0,f.i1j)();try{return f.hd_.parse(b)}catch{return(0,f.i1j)()}}class b5 extends Error{constructor(a){super(`refusing to write administratively locked settings: ${a.join(", ")}`),this.name="ManagedFieldError",this.fields=a}}function b6(a,b=bY(),c){let g=bZ(b);l(g);let h=(0,e.join)(g,b2),i=void 0===c?b0():c,j=i?{present:!0,...void 0===i.organization?{}:{organization:i.organization},lockedFields:i.lockedFields}:f.MhX;return function(a,b,c={}){let e=c.timeoutMs??5e3,f=c.staleMs??2e3,g=`${a}.lock`,h=Date.now()+e,i=bM(g,a);for(;null===i;){if(function(a,b){let c,e=`${a}.break`;try{c=(0,d.openSync)(e,"wx",384)}catch{return function(a){try{Date.now()-(0,d.statSync)(a).mtimeMs>=1e4&&(0,d.rmSync)(a,{force:!0})}catch{}}(e),!1}try{(0,d.closeSync)(c)}catch{}try{if(!(0,d.existsSync)(a)||!function(a,b,c){var e;if(!a)try{return Date.now()-(0,d.statSync)(b).mtimeMs>=c}catch{return!1}return!(Date.now()-a.at<c)&&(!(a.host===(0,bH.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>=(e=c,Math.max(30*e,6e4)))}(bL(a),a,b))return!1;return(0,d.rmSync)(a,{force:!0}),!0}catch{return!1}finally{try{(0,d.rmSync)(e,{force:!0})}catch{}}}(g,f)){i=bM(g,a);continue}if(Date.now()>=h)throw new bK("timeout",a,`still held after ${String(e)}ms`,bL(g)?.pid);Atomics.wait(bJ,0,0,5),i=bM(g,a)}try{var j;let c=b();if(j=c,"object"==typeof j&&null!==j&&"function"==typeof j.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(bL(a)?.token!==b)return;(0,d.rmSync)(a,{force:!0})}catch{}}(g,i)}}(h,()=>{let c=b4(b),d="function"==typeof a?a(c):a,e=function(a,b){let c=[],d=c=>c in b&&b[c]!==a[c],e="controlPlane"in b&&(b.controlPlane?.endpoint!==a.controlPlane?.endpoint||b.controlPlane?.label!==a.controlPlane?.label);return(d("runMode")||e)&&c.push("runMode"),d("historicalAccess")&&c.push("historicalAccess"),d("vaultKeyCustody")&&c.push("vaultKeyCustody"),d("vaultInlineReveal")&&c.push("vaultInlineReveal"),d("dataSharesInPlace")&&c.push("dataSharesInPlace"),"vaultConsent"in b&&(0,f.hds)(b.vaultConsent)!==(0,f.hds)(a.vaultConsent)&&c.push("vaultConsent"),"modelJudgeConsent"in b&&(0,f.DLF)(b.modelJudgeConsent)!==(0,f.DLF)(a.modelJudgeConsent)&&c.push("modelJudgeConsent"),c}(b1(c,i),d),g=j.present?e.filter(a=>j.lockedFields.includes(a)):[];if(g.length>0)throw new b5(g);let k=f.hd_.parse({...c,...function(a,b,c,d){if(!b.present)return a;let e=a=>(b.lockedFields.includes(a)||c.includes(a))&&!d.includes(a),f={...a};return e("runMode")&&(delete f.runMode,delete f.controlPlane),e("historicalAccess")&&delete f.historicalAccess,e("vaultConsent")&&delete f.vaultConsent,e("vaultKeyCustody")&&delete f.vaultKeyCustody,e("vaultInlineReveal")&&delete f.vaultInlineReveal,e("modelJudgeConsent")&&delete f.modelJudgeConsent,e("dataSharesInPlace")&&delete f.dataSharesInPlace,f}(d,j,function(a){if(!a)return[];let{values:b}=a,c=[];return(void 0!==b.runMode||void 0!==b.controlPlane)&&c.push("runMode"),void 0!==b.historicalAccess&&c.push("historicalAccess"),void 0!==b.vaultConsent&&c.push("vaultConsent"),void 0!==b.vaultKeyCustody&&c.push("vaultKeyCustody"),void 0!==b.vaultInlineReveal&&c.push("vaultInlineReveal"),void 0!==b.modelJudgeConsent&&c.push("modelJudgeConsent"),void 0!==b.dataSharesInPlace&&c.push("dataSharesInPlace"),c}(i),e),onboardedAt:d.onboardedAt??c.onboardedAt??new Date().toISOString()});return q(h,`${JSON.stringify(k,null,2)}
|
|
787
|
-
`),k})}let b7="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function b8(a){let b="",c=0,d=0;for(let e of a)for(c=c<<8|e,d+=8;d>=5;)b+=b7.charAt(c>>>d-5&31),d-=5;return d>0&&(b+=b7.charAt(c<<5-d&31)),b}function b9(a){let b=[],c=0,d=0;for(let e of a){let a=b7.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 ca(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 b8(Uint8Array.from(b))}function cb(a){let b=b=>Buffer.from((0,v.hkdfSync)("sha256",a,"aka:vault:v1",b,32));return{enc:b("aka:vault:enc:v1"),sign:b("aka:vault:sign:v1")}}function cc(a,b,c,d=f.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 cd(a,b,c,d){let e=(0,v.createCipheriv)("aes-256-gcm",a,d);return e.setAAD(c),{ciphertext:Buffer.concat([e.update(b,"utf8"),e.final()]),nonce:d,authTag:e.getAuthTag()}}function ce(a,b,c){try{let d=(0,v.createDecipheriv)("aes-256-gcm",a,b.nonce);return d.setAAD(c),d.setAuthTag(b.authTag),Buffer.concat([d.update(b.ciphertext),d.final()]).toString("utf8")}catch{return null}}function cf(a,b,c,d){return(0,v.createHmac)("sha256",a).update(cc(b,c,d,f.viY)).digest().subarray(0,10)}function cg(a,b,c,d,e){if(10!==e.length)return!1;let f=cf(a,b,c,d);return(0,v.timingSafeEqual)(f,Buffer.from(e))}var ch=c(31421);let ci={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 cj extends Error{constructor(a){super(`vault: key epoch ${String(a)} is not present in the keyring`),this.name="VaultKeyEpochMissingError",this.version=a}}let ck="vault.key",cl="aka-vault",cm="keyring";function cn(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 co(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 cp(){return{current:1,keys:new Map([[1,(0,v.randomBytes)(32)]])}}function cq(a){let b=Math.max(...a.keys.keys())+1,c=new Map(a.keys);return c.set(b,(0,v.randomBytes)(32)),{current:b,keys:c}}function cr(a){let b=a.keys.get(a.current);if(!b)throw new cj(a.current);return{material:b,version:a.current}}function cs(a,b){let c=a.keys.get(b);if(!c)throw new cj(b);return{material:c,version:b}}function ct(a){try{return Promise.resolve(a())}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}function cu(a){return a instanceof Error?a:Error(String(a))}let cv="owner",cw="vault: a key rotation is already in progress";function cx(a,b){try{k(a),j(a)}catch(a){if("EEXIST"===a.code)return!1;throw cu(a)}try{return(0,d.writeFileSync)((0,e.join)(a,cv),`${b}
|
|
788
|
-
`,{mode:384}),!0}catch(b){throw(0,d.rmSync)(a,{recursive:!0,force:!0}),cu(b)}}function cy(a,b){l(a);let c=function(a){let b,c=(0,e.join)(a,`${ck}.lock`),f=(0,v.randomBytes)(16).toString("hex");if(cx(c,f))return{lock:c,owner:f};try{b=(0,d.statSync)(c)}catch{throw Error(cw)}if(Date.now()-b.mtimeMs<6e4)throw Error(cw);let g=`${c}.stale.${f}`;try{let a=(0,d.statSync)(c);if(a.ino!==b.ino||a.mtimeMs!==b.mtimeMs)throw Error(cw);(0,d.renameSync)(c,g)}catch(a){if(a instanceof Error&&a.message===cw)throw a;throw Error(cw,{cause:a})}if((0,d.rmSync)(g,{recursive:!0,force:!0}),!cx(c,f))throw Error(cw);return{lock:c,owner:f}}(a);try{return b()}finally{!function(a){try{if((0,d.readFileSync)((0,e.join)(a.lock,cv),"utf8").trim()!==a.owner)return}catch{return}(0,d.rmSync)(a.lock,{recursive:!0,force:!0})}(c)}}class cz{#a;constructor(a){this.#a=a}get filePath(){return(0,e.join)(this.#a,ck)}loadOrCreate(){return ct(()=>{let a=this.#b();return a?(cA(this.filePath),cr(a)):cr(this.#c())})}rotate(){return ct(()=>cy(this.#a,()=>{let a=this.#b();return a?cr(this.#d(cq(a))):cr(this.#c())}))}materialFor(a){return ct(()=>{let b=this.#b();if(!b)throw new cj(a);return cs(b,a)})}#b(){let a;try{a=(0,d.readFileSync)(this.filePath,"utf8")}catch(a){if("ENOENT"===a.code)return null;throw a instanceof Error?a:Error(String(a))}return cn(a)}#c(){l(this.#a);let a=cp();if(t(this.filePath,`${co(a)}
|
|
789
|
-
`))return a;let b=this.#b();if(!b){let a=r(this.filePath);throw new s(`vault: cannot create a key file at ${this.filePath} — ${ci[a.kind]}`,a.cause)}return cA(this.filePath),b}#d(a){return l(this.#a),q(this.filePath,`${co(a)}
|
|
790
|
-
`),a}}function cA(a){try{(0,d.chmodSync)(a,384)}catch{}}let cB=(a,b)=>(0,ch.execFileSync)("/usr/bin/security",a,{encoding:"utf8",input:b,timeout:5e3,stdio:[void 0===b?"ignore":"pipe","pipe","ignore"]});function cC(a){let b=[];return"number"==typeof a.status&&b.push(`exit ${String(a.status)}`),"string"==typeof a.signal&&a.signal&&b.push(`signal ${a.signal}`),"string"==typeof a.code&&a.code&&b.push(a.code),b.length>0?b.join(", "):"unknown error"}function cD(a,b,c){let d=["add-generic-password",...b?["-U"]:[],"-s",cl,"-a",cm,"-X",Buffer.from(co(a),"utf8").toString("hex")];if(void 0!==c){if(/['\\\n\r\0]/.test(c))throw Error("vault: keychain path contains a quote, backslash, line break or NUL, which security -i cannot carry intact");d.push(`'${c}'`)}return`${d.join(" ")}
|
|
791
|
-
`}class cE{#a;#e;#f;#g;constructor(a,b=cB,c){if(b===cB&&"darwin"!==process.platform)throw Error(`keychain custody is not available on this platform (${process.platform}); use file custody`);this.#a=a,this.#e=b,this.#f=c,this.#g=void 0===c?[]:[c]}get keysDir(){return this.#a}loadOrCreate(){return ct(()=>{let a=this.#b();return a?cr(a):cr(this.#h(cp()))})}rotate(){return ct(()=>cy(this.#a,()=>{let a=this.#b();return a?cr(this.#i(cq(a))):cr(this.#h(cp()))}))}materialFor(a){return ct(()=>{let b=this.#b();if(!b)throw new cj(a);return cs(b,a)})}#b(){let a;try{a=this.#e(["find-generic-password","-s",cl,"-a",cm,"-w",...this.#g])}catch(a){if(44===a.status)return null;throw Error(`vault: keychain read failed (${cC(a)}); refusing to treat the failure as an absent keyring`)}let b=a.trim();if(0===b.length)return null;try{return cn(b)}catch(a){throw Error(`vault: keychain item is not a usable keyring (${a instanceof SyntaxError?"malformed JSON":a instanceof Error?a.message:"unknown"})`)}}#h(a){let b=cD(a,!1,this.#f);try{this.#e(["-i"],b)}catch(b){let a=this.#b();if(a)return a;throw Error(`vault: keychain write failed (${cC(b)})`)}return a}#i(a){let b=cD(a,!0,this.#f);try{this.#e(["-i"],b)}catch(a){throw Error(`vault: keychain write failed (${cC(a)})`)}return a}}function cF(a,b){return"keychain"===a?new cE(b):new cz(b)}let cG=Symbol("aka.vault.consentAbsent"),cH=Symbol("aka.vault.unavailable");function cI(a){if(!f.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,g,h]=b.slice(c+1).split(".");if(void 0===e||void 0===g||void 0===h)return null;try{let a=function(a){let b=b9(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=b9(g),c=b9(h);if(ca(a)!==e||b8(b)!==g||b8(c)!==h)return null;return{category:d,keyVersion:a,pointerId:b,tag:c}}catch{return null}}class cJ{#j;#k;#l;#m;#n;constructor(a){this.#j=a.repo,this.#k=a.keys,this.#l=a.isConsented,this.#m=a.verifyGrant,this.#n=a.now??(()=>Date.now())}async tokenize(a,b,c){if(!this.#l())return cG;let d=c(),e=bW(d,a),g=this.#j.byValueFingerprint(e),h=this.#n();if(g)return this.#j.upsert({...g,provider:g.provider??void 0},h),await this.#o(g.keyVersion,g.pointerId,g.category);let{material:i,version:j}=await this.#k.loadOrCreate(),k=cb(i),l=(0,v.randomBytes)(16),m=cc(j,l,b.category,f.viY),n=cd(k.enc,a,m,(0,v.randomBytes)(12)),{row:o}=this.#j.upsert({pointerId:b8(l),valueFingerprint:e,fingerprintKeyVersion:d.version,keyVersion:j,formatVersion:f.viY,category:b.category,ruleId:b.ruleId,maskedMatch:b.maskedMatch,provider:b.provider,ciphertext:n.ciphertext.toString("base64"),nonce:n.nonce.toString("base64"),authTag:n.authTag.toString("base64")},h);return await this.#o(o.keyVersion,o.pointerId,o.category)}async detokenize(a,b){let c,d,e=cI(a);if(!e)return cH;try{let a=await this.#k.materialFor(e.keyVersion);c=cb(a.material).sign}catch{return cH}if(!cg(c,e.keyVersion,e.pointerId,e.category,e.tag))return cH;let f=b8(e.pointerId),g=this.#j.byPointerId(f);if(!g)return this.#p(f,b,"unavailable"),cH;if(g.category!==e.category)return cH;if("model"===b.target){let a,c=b.grantId,d=this.#m;if(void 0===d||void 0===c||""===c)return this.#p(f,b,"refused"),cH;try{a=await d(c,{ruleId:g.ruleId,valueFingerprint:g.valueFingerprint,fingerprintKeyVersion:g.fingerprintKeyVersion})}catch{a=!1}if(!a)return this.#p(f,b,"refused"),cH}try{let a=await this.#k.materialFor(g.keyVersion);d=ce(cb(a.material).enc,{ciphertext:Buffer.from(g.ciphertext,"base64"),nonce:Buffer.from(g.nonce,"base64"),authTag:Buffer.from(g.authTag,"base64")},cc(g.keyVersion,e.pointerId,g.category,g.formatVersion))}catch{d=null}return null===d?(this.#p(f,b,"unavailable"),cH):(this.#p(f,b,"revealed"),d)}async revealEntry(a,b){let c=this.#j.byPointerId(a);if(!c)return this.#p(a,{target:"human",reason:b.reason},"unavailable"),cH;let d=await this.#q(c);return null===d?(this.#p(a,{target:"human",reason:b.reason},"unavailable"),cH):(this.#p(a,{target:"human",reason:b.reason},"revealed"),d)}async describePointer(a){let b=await this.#r(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.#r(a);return b?{ruleId:b.ruleId,valueFingerprint:b.valueFingerprint,fingerprintKeyVersion:b.fingerprintKeyVersion}:null}async rotateVaultKey(){let a=await this.#k.rotate(),b=cb(a.material).enc,c=0;for(let d of this.#j.listAll()){let e;if(d.keyVersion===a.version)continue;let f=b9(d.pointerId);try{let a=await this.#k.materialFor(d.keyVersion);e=ce(cb(a.material).enc,{ciphertext:Buffer.from(d.ciphertext,"base64"),nonce:Buffer.from(d.nonce,"base64"),authTag:Buffer.from(d.authTag,"base64")},cc(d.keyVersion,f,d.category,d.formatVersion))}catch{e=null}if(null===e)continue;let g=cd(b,e,cc(a.version,f,d.category,d.formatVersion),(0,v.randomBytes)(12));this.#j.replaceCiphertext(d.pointerId,{keyVersion:a.version,ciphertext:g.ciphertext.toString("base64"),nonce:g.nonce.toString("base64"),authTag:g.authTag.toString("base64")}),c+=1}return{version:a.version,reEncrypted:c}}async refreshFingerprints(a){let b=0;for(let c of this.#j.listAll())try{let d=await this.#q(c);if(null===d)continue;this.#j.refreshFingerprint(c.pointerId,{valueFingerprint:bW(a,d),fingerprintKeyVersion:a.version}),b+=1}catch{continue}return b}purgeVault(){let a=this.#j.purgeAll();return this.#j.recordDeref({id:(0,v.randomUUID)(),pointerId:"*",at:this.#n(),target:"human",reason:"purge",outcome:"unavailable",pointerCount:Math.max(a,1)}),a}async #o(a,b,c){var d;let e=b9(b),f=cb((await this.#k.materialFor(a)).material).sign;return d=cf(f,a,e,c),`[[aka:${c}:${ca(a)}.${b8(e)}.${b8(d)}]]`}async #q(a){try{let b=await this.#k.materialFor(a.keyVersion);return ce(cb(b.material).enc,{ciphertext:Buffer.from(a.ciphertext,"base64"),nonce:Buffer.from(a.nonce,"base64"),authTag:Buffer.from(a.authTag,"base64")},cc(a.keyVersion,b9(a.pointerId),a.category,a.formatVersion))}catch{return null}}async #r(a){let b=cI(a);if(!b)return null;try{let a=await this.#k.materialFor(b.keyVersion),c=cb(a.material).sign;if(!cg(c,b.keyVersion,b.pointerId,b.category,b.tag))return null}catch{return null}let c=this.#j.byPointerId(b8(b.pointerId));return c?.category!==b.category?null:c}#p(a,b,c){this.#j.recordDeref({id:(0,v.randomUUID)(),pointerId:a,at:this.#n(),target:b.target,reason:b.reason,outcome:c,...void 0===b.grantId?{}:{grantId:b.grantId},pointerCount:(0,f.kqf)(b.reason)?b.pointerCount??1:1})}}},85002:(a,b,c)=>{c.d(b,{S8C:()=>D,hxQ:()=>a2,Itg:()=>al,Nh0:()=>bR,QcD:()=>bQ,qeh:()=>dW,RRF:()=>df,ZpU:()=>dl,HUb:()=>de,hfB:()=>bG,unw:()=>dk,b2L:()=>U,goN:()=>R,Jr:()=>dm,hdu:()=>cB,mBk:()=>cA,gbA:()=>A,V8B:()=>bM,IgC:()=>da,aIg:()=>bp,iRC:()=>bN,GCf:()=>I,agn:()=>bS,tLs:()=>v,TUN:()=>w,SHn:()=>a8,rov:()=>cP,V0H:()=>dd,mzG:()=>V,v5Q:()=>S,OVs:()=>cF,LsM:()=>cD,bm0:()=>cE,WRR:()=>c1,u8Q:()=>cC,kxf:()=>cL,ZXz:()=>c4,MhX:()=>c5,viY:()=>cl,XZo:()=>co,jUf:()=>cq,PEm:()=>c8,KqW:()=>dN,eI7:()=>du,cqq:()=>J,eYL:()=>bT,JJC:()=>bU,jON:()=>aP,Zdp:()=>x,lFU:()=>d,N3u:()=>dV,PhW:()=>aj,BIx:()=>a4,DzG:()=>cI,NFD:()=>cH,hd_:()=>cS,_5V:()=>cj,tXp:()=>b6,plk:()=>a0,mAj:()=>b0,Fnc:()=>ea,ryv:()=>r,tTV:()=>ai,qmP:()=>c_,_6W:()=>b8,rG:()=>ca,Bfj:()=>b5,fj8:()=>cf,q_t:()=>p,i1j:()=>cT,xog:()=>b_,hzO:()=>ec,by7:()=>eb,Gw9:()=>d8,q11:()=>h,U7X:()=>B,JB8:()=>b$,kqf:()=>cv,y_0:()=>d9,qEQ:()=>bO,DLF:()=>cR,hds:()=>cK,I8t:()=>g,am1:()=>cc,SSj:()=>ci,K7s:()=>bV,jwX:()=>cp,TdZ:()=>dj,DhA:()=>dn,WSs:()=>ef,a45:()=>a$,N6N:()=>f,A6E:()=>b9,pnU:()=>a_,V9M:()=>cW,$w9:()=>c$,jTf:()=>c0,$BP:()=>cX,JAl:()=>cY,$3l:()=>cZ,MgS:()=>cg,gzP:()=>cU,QCA:()=>cV,C05:()=>ed});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');"},{tag:"0021_finding_resolution_resolved_at_index",sql:"CREATE INDEX `idx_finding_resolution_resolved_at` ON `finding_resolution` (`resolved_at`);\n"}],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(64450),t=c(46708),u=c(53078);let v={ClaudeCode:"claudecode",Cursor:"cursor",Copilot:"copilot",Codex:"codex",Antigravity:"antigravity",Windsurf:"windsurf",ClaudeDesktop:"claudedesktop",ChatGpt:"chatgpt",ClaudeAi:"claudeai",Api:"api"},w=s.k5(v).meta({id:"Harness"}),x={ClaudeCode:"claude-code",ClaudeDesktop:"claude-desktop",Cursor:"cursor",ChatGpt:"chatgpt",ClaudeAi:"claude-ai",Copilot:"github-copilot",Codex:"codex",Antigravity:"antigravity",Cli:"cli",Unknown:"unknown"},y=s.k5(x).meta({id:"SourceTool"}),z={[x.ClaudeCode]:v.ClaudeCode,[x.ClaudeDesktop]:v.ClaudeDesktop,[x.Copilot]:v.Copilot,[x.Cursor]:v.Cursor,[x.ChatGpt]:v.ChatGpt,[x.Codex]:v.Codex,[x.Antigravity]:v.Antigravity,[x.ClaudeAi]:v.ClaudeAi},A=s.k5(["pii","financial","secret","phi","code_context","code_flaw","custom","config"]).meta({id:"DetectionCategory"}),B=s.k5(["critical","high","medium","low"]).meta({id:"Severity"}),C=s.k5(["warn","redact","block","allow","log"]).meta({id:"ActionTaken"}),D=C.options,E=s.Ik({start:s.ai().int().nonnegative(),end:s.ai().int().nonnegative()}).meta({id:"Span"});s.Ik({id:s.Os(),eventId:s.Os(),ruleId:s.Yj(),category:A,severity:B,span:E,maskedMatch:s.Yj(),actionTaken:C,confidence:s.ai().min(0).max(1)}).meta({id:"Finding"}).meta({id:"DetectedFinding"});let F=s.k5(["blocked","redacted","warned","allowed","quarantined","monitored"]).meta({id:"FindingAction"}),G=w.extract(["ClaudeCode","ClaudeDesktop","Cursor","Copilot","ChatGpt","ClaudeAi","Codex","Antigravity","Api"]).meta({id:"FindingProvider"}),H=s.k5(["secret","pii","source_code","code_flaw","external_share","mcp_server","customer_data","financial","phi","custom"]).meta({id:"FindingCategory"});s.k5(["in-flight","at-rest"]).meta({id:"FindingOrigin"});let I=s.k5(["open","handled","resolved","dismissed"]).meta({id:"FindingStatus"}),J=s.k5(["enforced-in-flight","fixed-at-source","exception","acknowledged","false-positive","redetected"]).meta({id:"ResolutionMethod"}),K=s.Ik({maskedValue:s.Yj(),contextPrefix:s.Yj()}).meta({id:"FindingMatch"}),L=s.Ik({id:s.Yj(),name:s.Yj().nullable()}).meta({id:"FindingDetectionRef"}),M=s.Ik({id:s.Yj(),name:s.Yj()}).meta({id:"FindingPolicyRef"}),N=s.Ik({id:s.Yj(),provider:G,repo:s.Yj(),file:s.Yj(),toolName:s.Yj().optional(),action:F,detectedAt:t.w$(),confidence:s.ai().min(0).max(1),status:I.optional(),eventId:s.Yj().optional(),sessionId:s.Yj().optional()}).meta({id:"FindingInstance"}),O=s.Ik({id:s.Yj(),category:H,subtype:s.Yj(),severity:B,match:K,detection:L,policy:M,instanceCount:s.ai().int().nonnegative(),providers:s.YO(G),aggregateAction:F.nullable(),latestDetectedAt:t.w$(),instances:s.YO(N),status:I.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 P=s.Ik({value:s.Yj(),count:s.ai().int().nonnegative()}).meta({id:"FindingFacetItem"}),Q=s.Ik({severity:s.YO(P),subtype:s.YO(P),provider:s.YO(P),action:s.YO(P),status:s.YO(P),tool:s.YO(P).optional()}).meta({id:"FindingFacets"}),R=50,S=s.Ik({severity:s.YO(B).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(G).optional(),action:s.YO(F).optional(),status:s.YO(I).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:Q,items:s.YO(O),nextCursor:s.Yj().nullable(),sessionFirings:s.g1(s.Yj(),s.ai().int().nonnegative()).optional()}).meta({id:"ListGroupedFindingsResponse"}),s.Ik({action:F.exclude(["quarantined"]),instanceId:s.Yj().optional()}).meta({id:"ApplyFindingActionRequest"}),O.meta({id:"ApplyFindingActionResponse"}),s.Ik({severity:s.YO(B).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(G).optional(),action:s.YO(F).optional(),q:s.Yj().optional(),format:s.k5(["csv","json"]).optional()});let T=N.extend({groupId:s.Yj(),category:H,subtype:s.Yj(),severity:B,match:K,detection:L,policy:M}).meta({id:"FindingInstanceDetail"}),U=50,V=s.Ik({severity:s.YO(B).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(G).optional(),action:s.YO(F).optional(),status:s.YO(I).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:Q,items:s.YO(T),nextCursor:s.Yj().nullable()}).meta({id:"ListFindingInstancesResponse"});let W=s.Ik({file:s.Yj(),instanceCount:s.ai().int().nonnegative(),maxSeverity:B,latestDetectedAt:t.w$(),status:I.optional(),ruleIds:s.YO(s.Yj())}).meta({id:"FindingLocationFile"}),X=s.Ik({repo:s.Yj(),instanceCount:s.ai().int().nonnegative(),maxSeverity:B,latestDetectedAt:t.w$(),status:I.optional(),files:s.YO(W)}).meta({id:"FindingLocationRepo"});s.Ik({severity:s.YO(B).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(G).optional(),action:s.YO(F).optional(),status:s.YO(I).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(X),hasMore:s.zM()}).meta({id:"ListFindingLocationsResponse"});let Y=s.k5(["host","harness","user","skill","hook","mcp_server","config_file"]).meta({id:"InventoryObjectType"}),Z=s.k5(["session","run","tool_call","llm_call","source_lookup","prompt","response","code_change","tool_use","config_scan"]).meta({id:"AuditEventType"}),$=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 _=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:_});let aa=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 ab=s.Ik({ruleId:s.Yj().min(1),ruleName:s.Yj(),ruleVersion:s.Yj().min(1),category:A,severity:B,span:E,maskedMatch:s.Yj(),actionTaken:C,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:aa,inspections:s.YO(ab).default([])});let ac=s.Ik({objectType:Y,identityKey:s.Yj().min(1),location:s.Yj().optional(),title:s.Yj().optional(),hostId:s.Yj().optional(),attributes:$.default({})}).meta({id:"InventoryInput"}),ad=s.Ik({url:s.Yj().min(1),name:s.Yj().optional(),attributes:$.default({})}).meta({id:"SourceProjectInput"}),ae=s.Ik({id:s.Yj().min(1),eventType:Z,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:B.optional(),priority:s.Yj().optional(),content:s.Yj().optional(),contentHash:s.Yj().optional(),attributes:$.optional()}).meta({id:"AuditEventInput"});s.Ik({class:s.Yj().min(1),label:s.Yj().optional(),attributes:$.optional()});let af=s.Ik({ruleId:s.Yj().min(1),version:s.Yj().min(1),name:s.Yj(),category:A,severity:B,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:E,maskedMatch:s.Yj(),actionTaken:C,confidence:s.ai().min(0).max(1),findingKey:s.Yj().optional(),firstDetectedAt:t.w$().optional()}),s.Ik({host:ac.optional(),harness:ac.optional(),project:ad.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 ag=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(ag),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai().nullable(),costIsPartial:s.zM()});let ah=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 ai(a){return JSON.stringify(a)}s.Ik({models:s.YO(ah),sessionCount:s.ai().int().nonnegative(),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai(),costIsPartial:s.zM()});let aj=s.k5(["active","completed","interrupted","error"]),ak=s.k5(["session","prompt","response","tool","hook","detection","share","permission","commit","error","active"]),al=s.k5(["detections","shares","inventory"]),am=s.Ik({id:s.Yj(),occurredAt:t.w$(),kind:ak,title:s.Yj(),detail:s.Yj(),tool:s.Yj().nullable(),severity:B.nullable(),link:al.nullable(),targetId:s.Yj().nullable(),internal:s.zM(),flagged:s.zM()}).meta({id:"ActivityAuditEvent"}),an=s.Ik({id:s.Yj(),harness:w,title:s.Yj(),project:s.Yj(),repo:s.Yj(),branches:s.YO(s.Yj()),startedAt:t.w$(),endedAt:t.w$().nullable(),status:aj,turns:s.ai().int().nonnegative(),findings:s.ai().int().nonnegative(),shares:s.ai().int().nonnegative()}).meta({id:"ActivitySessionSummary"});an.extend({host:s.Yj(),cwd:s.Yj(),models:s.YO(s.Yj()),version:s.Yj(),tokens:ag,tools:s.g1(s.Yj(),s.ai().int().nonnegative()),files:s.YO(s.Yj()),commits:s.ai().int().nonnegative(),events:s.YO(am)}).meta({id:"ActivitySession"}),s.Ik({tz:s.Yj().optional()});let ao=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(w).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 ap=s.Ik({items:s.YO(an),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(am),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(w).optional(),from:s.KC([t.p6(),t.w$()]).optional(),to:s.KC([t.p6(),t.w$()]).optional()}),s.Ik({stats:ao,sessions:ap}).meta({id:"ActivityOverviewResponse"});let aq=s.k5(["user","project","local","plugin"]),ar=s.Ik({name:s.Yj().min(1),source:s.Yj().min(1),scope:aq,pluginName:s.Yj().optional(),version:s.Yj().optional(),description:s.Yj().optional(),updatedAt:t.w$().optional(),location:s.Yj().optional()}),as=s.Ik({event:s.Yj().min(1),matcher:s.Yj().optional(),command:s.Yj().min(1),timeout:s.ai().optional(),scope:aq,pluginName:s.Yj().optional(),location:s.Yj().optional()}),at=s.Ik({name:s.Yj().min(1),scope:aq,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()}),au=s.Ik({name:s.Yj().min(1),path:s.Yj().min(1),scope:aq,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(ar),hooks:s.YO(as),mcpServers:s.YO(at),configFiles:s.YO(au),errors:s.YO(s.Ik({source:s.Yj(),reason:s.Yj()}))});let av=s.Ik({ruleId:s.Yj().min(1),version:s.Yj().min(1),span:E,maskedMatch:s.Yj(),actionTaken:C,confidence:s.ai().min(0).max(1)});s.Ik({items:s.YO(ac),scanEvent:ae,definitions:s.YO(af).optional(),findings:s.YO(av).optional()}),s.Ik({specVersion:s.eu(1),endpoint:s.Yj().min(1),apiKey:s.Yj().min(1),keyPrefix:s.Yj().min(1).max(16).optional(),mintedAt:t.w$().optional()});let aw=s.Ik({packId:s.Yj().min(1),version:s.Yj().min(1),enabled:s.zM(),updatedAt:s.Yj().nullable()}).meta({id:"StorePosturePack"}),ax=s.Ik({total:s.ai().int().min(0),disabled:s.ai().int().min(0),byAction:s.Ik({warn:s.ai().int().min(0),redact:s.ai().int().min(0),block:s.ai().int().min(0),allow:s.ai().int().min(0),log:s.ai().int().min(0)}).strict()}).meta({id:"StorePosturePolicyCounts"}),ay=s.Ik({package:s.Yj().min(1).max(200),version:s.Yj().min(1).max(64),ossVersion:s.Yj().max(64).nullable(),policyBundleVersion:s.Yj().max(200).nullable(),policyFetchedAt:s.ai().int().min(0).max(0xe677d21fdbff).nullable()}).meta({id:"StorePosturePlugin"});s.Ik({deviceId:s.Os(),hostname:s.Yj().min(1).max(253),capturedAt:s.ai().int().min(0).max(0xe677d21fdbff),storePresent:s.zM(),schemaVersion:s.ai().int().min(0).max(0x7fffffff).nullable(),findingsTotal:s.ai().int().min(0).max(0x7fffffff),findingsFirstAt:s.ai().int().min(0).max(0xe677d21fdbff).nullable(),findingsLastAt:s.ai().int().min(0).max(0xe677d21fdbff).nullable(),packs:s.YO(aw).max(500),policyCounts:ax,plugin:ay.optional()}).meta({id:"StorePostureSnapshot"});let az="capture/";ae.extend({inspections:s.YO(ab).default([])}).refine(a=>a.inspections.every(a=>!a.ruleVersion.startsWith(az)),{message:`inspections[].ruleVersion must not start with \`${az}\` — that namespace is reserved for capture definitions the control plane mints itself`,path:["inspections"]}).meta({id:"RecordAuditEventRequest"}),s.Ik({accepted:s.ai().int().nonnegative(),duplicates:s.ai().int().nonnegative()});let aA=/^[^\p{Cc}\p{Cf}]*$/u,aB=a=>s.Yj().max(a).regex(aA,"must not contain control characters");s.Ik({tenantName:aB(200),userEmail:aB(320),role:aB(64),keyKind:aB(64),serverTime:aB(64)}),s.Ik({error:s.Ik({code:s.Yj().optional(),message:s.Yj().optional()}).optional()});let aC=s.Yj().regex(/^[a-z][a-z0-9-]*$/),aD=s.Yj().regex(/^[a-z][a-z0-9-]*$/),aE=s.Yj().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/),aF=s.k5(["labs","user","org"]),aG=s.k5(["keyword","regex"]).meta({id:"MatcherType"});s.k5(["safe","quarantined"]).meta({id:"RuleProbeVerdict"});let aH=s.re({type:s.eu("keyword"),keywords:s.YO(s.Yj().min(1)).min(1),caseSensitive:s.zM().default(!1)});function aI(a){return a.replace(/[gy]/g,"")}let aJ=s.re({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=>!function(a){return void 0===a||0===a}(a.captureGroup)||!function(a,b){try{let c=new RegExp(a,aI(b));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"]}).superRefine((a,b)=>{if(void 0===a.captureGroup)return;let c=function(a,b){try{let c=RegExp(`${a}|`,aI(b)).exec("");return c?c.length-1:void 0}catch{return}}(a.pattern,a.flags);void 0===c||a.captureGroup<=c||b.addIssue({code:"custom",path:["captureGroup"],message:`captureGroup ${String(a.captureGroup)} is out of range — the pattern declares ${String(c)} capture group(s), so valid values are 0-${String(c)}. An out-of-range group never matches, which would make the rule silently never fire.`})}),aK=s.gM("type",[aH,aJ]).meta({id:"Matcher"});aG.options;let aL=s.re({extensions:s.YO(s.Yj().regex(/^\.[A-Za-z0-9]+$/)).min(1)}).meta({id:"AppliesTo"}),aM=s.k5(["entropy","luhn"]).meta({id:"PostValidatorName"}),aN=s.KC([aM,s.re({name:aM,config:s.g1(s.Yj(),s.L5()).optional()})],{error:()=>`not a valid post-validator: use a bare name (${aM.options.map(a=>JSON.stringify(a)).join(" or ")}) or { "name": ..., "config": { ... } }. An unrecognized name would be a false-positive guard that never runs.`}).meta({id:"PostValidatorRef"}),aO=s.re({categories:s.YO(A).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"});s.re({label:s.Yj(),text:s.Yj().max(5e4),shouldMatch:s.zM(),filePath:s.Yj().optional(),expectedSpans:s.YO(s.re({start:s.ai(),end:s.ai()})).optional()}).meta({id:"RuleFixture"});let aP=s.re({specVersion:s.eu(1),id:s.Yj().regex(/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/),name:s.Yj(),category:A,severity:B,matcher:aK,appliesTo:aL.optional(),postValidators:s.YO(aN).optional(),requiresNearby:aO.optional(),examples:s.YO(s.Yj()).optional()}).meta({id:"Rule"}),aQ=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:aQ.optional(),license:s.Yj().optional(),sourceUrl:s.OZ().optional()}).meta({id:"PackManifest"});let aR=s.k5(["library"]).meta({id:"OriginEnum"}),aS=s.k5(["all","library","custom","customized","updates"]),aT=s.k5(["new","imported","update"]).meta({id:"LibraryStateEnum"}),aU=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"}),aV=s.Ik({id:s.Yj(),name:s.Yj(),version:aE,enabled:s.zM(),origin:aR,publisher:aC.optional(),publisherKind:aF.optional(),ruleCount:s.ai().int().nonnegative(),namespace:aC,packId:aD,policyId:s.Yj().optional(),latestVersion:aE.optional()}).meta({id:"DetectionListItem"});s.Ik({counts:aU,items:s.YO(aV)}).meta({id:"ListDetectionsResponse"}),s.Ik({filter:aS.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 aW=s.Ik({id:s.Yj(),name:s.Yj(),category:A,severity:B,matcher:aK}).meta({id:"DetectionRule"}),aX=s.Ik({available:s.zM(),latestVersion:aE,latestRuleCount:s.ai().int().nonnegative().optional()}).nullable().meta({id:"DetectionUpdate"});s.Ik({id:s.Yj(),name:s.Yj(),version:aE,enabled:s.zM(),origin:aR,publisher:aC.optional(),publisherKind:aF.optional(),ruleCount:s.ai().int().nonnegative(),namespace:aC,packId:aD,description:s.Yj().optional(),editedAt:t.w$(),findingsLast30d:s.ai().int().nonnegative(),latestVersion:aE.nullable().optional(),update:aX,rules:s.YO(aW),modified:s.zM(),policyId:s.Yj().optional()}).meta({id:"DetectionDetail"});let aY=s.Ik({id:s.Yj(),name:s.Yj(),publisher:aC,publisherKind:aF.optional(),category:A.optional(),version:aE,ruleCount:s.ai().int().nonnegative(),description:s.Yj().optional(),updatedAt:t.w$(),state:aT,importedAs:s.Yj().nullable()}).meta({id:"LibraryItem"});function aZ(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 a$(a,b,c){let d=a.rules.flatMap(a=>{let b=aK.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 a_(a){let b=a.indexOf("/");return b<1||b===a.length-1?null:{namespace:a.slice(0,b),packId:a.slice(b+1)}}function a0(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(aZ)}}s.Ik({categories:s.YO(A),items:s.YO(aY)}).meta({id:"ListLibraryResponse"}),s.Ik({libraryId:s.Yj().refine(a=>/^[^/]+\/[^/]+$/.test(a),{message:"libraryId must be in namespace/packId format"})}).meta({id:"ImportDetectionRequest"});let a1=s.k5(["project","skill","mcp","hook","config"]).meta({id:"AssetType"}),a2=s.k5(["open","approved","blocked"]).meta({id:"AccessLevel"}),a3=s.k5(["source","public-dep","vendored","config","data","docs","generated"]).meta({id:"Origin"}),a4=s.k5(["known-good","risky","unapproved"]).meta({id:"TrustLevel"}),a5=s.k5(["update","stale","conflict","unknown","change","untracked","risk","findings"]).meta({id:"Flag"}),a6=s.k5(["public","private"]).meta({id:"Visibility"}),a7=s.k5(["block","redact","warn"]).meta({id:"HarnessEventKind"}),a8=w.extract(["ClaudeCode","Cursor","Codex","Antigravity"]).meta({id:"HarnessId"}),a9=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"}),ba=s.Ik({id:s.Yj(),type:a1,name:s.Yj(),sub:s.Yj(),flags:s.YO(a5),trust:a4.optional()}).meta({id:"AssetSummary"}),bb=s.Ik({id:s.Yj(),name:s.Yj(),repo:s.Yj(),visibility:a6,language:s.Yj(),policyDefault:a2,updatedAt:t.w$(),accessCounts:a9,findingsCount:s.ai().int().nonnegative()}).meta({id:"ProjectSummary"}),bc=s.Ik({type:a1,assets:s.YO(ba)}),bd=s.Ik({id:a8,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(bb),categories:s.YO(bc)}).meta({id:"HarnessSummary"});s.Ik({items:s.YO(bd)}).meta({id:"ListHarnessesResponse"});let be=s.Ik({type:a1,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(ba)}).meta({id:"AssetGroup"});s.Ik({groups:s.YO(be)}).meta({id:"ListAssetsResponse"});let bf=s.Ik({name:s.Yj(),signature:s.Yj(),description:s.Yj(),write:s.zM(),risk:s.Yj().nullable()}).meta({id:"McpTool"}),bg=s.Ik({id:s.Yj(),title:s.Yj(),note:s.Yj()});ba.extend({description:s.Yj().nullable(),trust:a4.nullable(),meta:s.g1(s.Yj(),s.L5()),finding:bg.nullable(),tools:s.YO(bf).optional()}).meta({id:"AssetDetail"}),s.Ik({items:s.YO(bb)}).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 bh=s.Ik({path:s.Yj(),name:s.Yj(),origin:a3,access:a2,isCustom:s.zM(),findings:s.ai().int().nonnegative(),blockedAt:t.w$().nullable().optional(),note:s.Yj().nullable().optional()}).meta({id:"FileSummary"}),bi=s.Ik({name:s.Yj(),path:s.Yj(),accessCounts:a9}).meta({id:"FolderSummary"});s.Ik({project:s.Ik({id:s.Yj(),repo:s.Yj(),visibility:a6}),path:s.Yj(),folders:s.YO(bi).optional(),files:s.YO(bh)}).meta({id:"ProjectTreeResponse"}),bh.extend({project:s.Ik({repo:s.Yj(),visibility:a6,language:s.Yj(),policyDefault:a2,updatedAt:t.w$()}),findingsRefs:s.YO(s.Ik({id:s.Yj(),title:s.Yj()}))}).meta({id:"FileDetail"}),s.Ik({path:s.Yj(),access:a2}).meta({id:"SetFileAccessBody"}),s.Ik({file:bh,accessCounts:a9}).meta({id:"SetFileAccessResponse"}),s.Ik({trust:a4}).meta({id:"SetMcpTrustBody"});let bj=s.Ik({kind:a7,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(bj)}).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(a1).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 bk=s.k5(["provider","internal","external","ip"]).meta({id:"DestinationKind"}),bl=s.k5(["https","http","sftp","grpc","smtp","ws","wss"]).meta({id:"Transport"}),bm=s.k5(["secrets","pii","customer","source","telemetry","logs","metrics","none"]).meta({id:"DataClass"}),bn=bm.options,bo=s.k5(["recognized","internal","unverified","ip"]).meta({id:"ShareTrustLevel"}),bp=s.k5(["allow","block"]).meta({id:"EgressDecision"}),bq=s.k5(["allowed","blocked","review"]).meta({id:"EgressStatus"}),br=s.k5(["raw_ip","unverified_domain","plaintext_transport"]).meta({id:"ReviewReason"}),bs=s.k5(["GET","POST","PUT","DELETE","SDK","REF"]).meta({id:"HttpMethod"}),bt=s.Ik({needsReview:s.zM(),reasons:s.YO(br)}).meta({id:"ReviewInfo"}),bu=s.Ik({port:s.ai().int().nullable(),geo:s.Yj().nullable(),ptr:s.Yj().nullable()}).meta({id:"DestinationNetwork"}),bv=s.Ik({id:s.Yj(),method:bs,transport:bl,url:s.Yj(),template:s.zM(),dataClass:bm,lastSeen:t.w$(),callSiteCount:s.ai().int().nonnegative()}).meta({id:"EndpointSummary"}),bw=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"}),bx=bv.extend({sites:s.YO(bw)}).meta({id:"EndpointWithSites"}),by=s.Ik({id:s.Yj(),kind:bk,name:s.Yj(),host:s.Yj(),category:s.Yj(),trust:bo,status:bq,isCustom:s.zM(),lastSeen:t.w$(),endpointCount:s.ai().int().nonnegative(),callSiteCount:s.ai().int().nonnegative(),transports:s.YO(bl),dataClasses:s.YO(bm),review:bt,network:bu.nullable(),endpoints:s.YO(bv)}).meta({id:"ShareDestinationSummary"});by.omit({endpointCount:!0,callSiteCount:!0,endpoints:!0}).extend({note:s.Yj().nullable(),endpoints:s.YO(bx)}).meta({id:"ShareDestinationDetail"});let bz=s.Ik({id:s.Yj(),kind:bk,name:s.Yj(),host:s.Yj(),trust:bo,status:bq,review:bt,topDataClass:bm,callSiteCount:s.ai().int().nonnegative(),lastSeen:t.w$()}).meta({id:"ReviewDestination"}),bA=s.Ik({kind:bk,total:s.ai().int().nonnegative(),items:s.YO(by)}).meta({id:"ShareDestinationGroup"});s.Ik({groups:s.YO(bA)}).meta({id:"ListShareDestinationsResponse"}),s.Ik({items:s.YO(bz)}).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:bp.nullable()}).meta({id:"SetEgressDecisionBody"}),s.Ik({destination:by}).meta({id:"SetEgressDecisionResponse"}),s.Ik({q:s.Yj().optional(),kind:s.YO(bk).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(bk).optional()});let bB=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(bm).min(1),sdks:s.jg(bB,s.YO(s.Yj()))}).meta({id:"ProviderRegistryEntry"});let bC=s.Ik({file:s.Yj(),line:s.ai().int().positive(),snippet:s.Yj(),dynamic:s.zM(),vendored:s.zM()}).meta({id:"EgressCallSiteHit"}),bD=s.Ik({host:s.Yj(),kind:bk,name:s.Yj(),category:s.Yj(),trust:bo,network:bu.nullable(),method:bs,transport:bl,url:s.Yj(),template:s.zM(),dataClass:bm,site:bC}).meta({id:"ResolvedEgressHit"}),bE=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:bE,hits:s.YO(bD)}).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 bF=s.k5(["prompt","response","code_change","tool_use"]).meta({id:"EventKind"}),bG=bF.options.map(a=>`'${a}'`).join(","),bH=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"}),bI=s.Ik({id:s.Os(),sourceTool:y,kind:bF,occurredAt:t.w$(),contentHash:s.Yj(),content:s.Yj(),metadata:bH.optional()}).meta({id:"Event"}).meta({id:"IngestEvent"});s.Ik({events:s.YO(bI).min(1).max(100),dedupe:s.eu("content-hash").optional()}).meta({id:"IngestBatch"});let bJ=s.k5(["once","temporary","permanent"]),bK=s.Ik({repo:s.Yj().optional(),sourceTool:s.Yj().optional(),provider:s.Yj().optional()}).strict(),bL=s.k5(["suppress","reveal_to_model"]),bM=s.Ik({id:s.Os(),ruleId:s.Yj(),category:A,valueFingerprint:s.Yj().regex(/^[0-9a-f]{64}$/),keyVersion:s.ai().int().positive(),maskedValue:s.Yj(),capability:bL.default("suppress"),scope:bJ,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:bK.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()}),bN=bM.pick({id:!0,ruleId:!0,valueFingerprint:!0,keyVersion:!0,capability:!0,expiresAt:!0,maxUses:!0,useCount:!0,conditions:!0});function bO(a,b){return"present"===b.status&&b.version===a}bM.omit({valueFingerprint:!0});let bP=s.Yj().optional(),bQ=s.Ik({reference:s.Yj(),scope:s.Yj(),reason:s.Yj(),confirmation:bP}),bR=s.Ik({ruleId:s.Yj(),value:s.Yj(),scope:s.Yj(),reason:s.Yj(),confirmation:bP}),bS=s.Ik({pointer:s.Yj(),scope:s.Yj(),justification:s.Yj(),confirmation:bP}),bT=s.Ik({id:s.Yj(),reason:s.Yj()}),bU=s.Ik({confirmation:s.Yj()});function bV(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 bW(a){return({log:"monitored",block:"blocked",redact:"redacted",warn:"warned",allow:"allowed"})[a]??"allowed"}function bX(a){if("code_context"===a)return"source_code";let b=H.safeParse(a);return b.success?b.data:"custom"}function bY(a){return z[a]??v.Api}let bZ=["open","handled","dismissed","resolved"];function b$(a){let b=new Set(a.filter(a=>void 0!==a));if(0!==b.size){for(let a of bZ)if(b.has(a))return a}}function b_(a){return"code_change"!==a.kind?"handled":null===a.findingKey?"open":"resolved"===a.latestResolutionStatus?"resolved":"dismissed"===a.latestResolutionStatus?"dismissed":"open"}function b0(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:bY(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:bW(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(bY))].sort():f.map(a=>a.provider)).filter(a=>!j.has(a)&&(j.add(a),!0)),l=new Set(h?h.actionsTaken.map(bW):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=bX(b[0]?.category??"custom"),q={id:`category:${p}`,name:p},r={maskedValue:b[0]?.maskedMatch??"",contextPrefix:""},s=b$(h?h.statusInputs.map(b_):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&&(b3.set(t,[...l]),void 0!==h.searchText&&b1.set(t,b2(t,h.searchText))),g.push(t)}return g}let b1=new WeakMap;function b2(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 b3=new WeakMap;function b4(a){let b=b3.get(a);if(void 0!==b)return b;let c=[...new Set(a.instances.map(a=>a.action))];return b3.set(a,c),c}function b5(a,b){let c=new Set(b),d=0;for(let b of a){if(void 0===b.count)return null;c.has(b_(b))&&(d+=b.count)}return d}function b6(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=>b4(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=b1.get(a);if(void 0!==b)return b;let c=b2(a);return b1.set(a,c),c})(b).includes(a))}return c}let b7={critical:0,high:1,medium:2,low:3};function b8(a,b){let c=(b7[a.severity]??-1)-(b7[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 b9(a){return[...a].sort(b8)}function ca(a,b){let c=b6(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=b6(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=b6(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 b4(a))h.set(b,(h.get(b)??0)+1);let i=b6(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=b6(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 cb=["severity","subtype","providers","actions","statuses","tools","repo","file","q"];function cc(a,b,c){for(let d of cb)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(bY(a.sourceTool));case"actions":return!b.actions?.length||b.actions.includes(bW(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 cd(a){return[...a.entries()].map(([a,b])=>({value:a,count:b})).sort((a,b)=>b.count-a.count||a.value.localeCompare(b.value))}function ce(a,b){a.set(b,(a.get(b)??0)+1)}function cf(a){let b=new Map,c=new Map,d=new Map,e=new Map,f=new Map,g=new Map;return{add(h){cc(h,a,"severity")&&ce(b,h.severity),cc(h,a,"subtype")&&ce(c,h.ruleId),cc(h,a,"providers")&&ce(d,bY(h.sourceTool)),cc(h,a,"actions")&&ce(e,bW(h.actionTaken)),void 0!==h.status&&cc(h,a,"statuses")&&ce(f,h.status),void 0!==h.toolName&&cc(h,a,"tools")&&ce(g,h.toolName)},facets:()=>({severity:cd(b),subtype:cd(c),provider:cd(d),action:cd(e),status:cd(f),tool:cd(g)})}}function cg(a){let b=bX(a.category);return{id:a.id,provider:bY(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:bW(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 ch={critical:0,high:1,medium:2,low:3};function ci(){return{instanceCount:0,maxSeverityRank:Number.MAX_SAFE_INTEGER,maxSeverity:"low",latestDetectedAt:"",statuses:[],ruleIds:new Set}}function cj(a,b){a.instanceCount+=1;let c=ch[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 ck=s.Ik({id:s.Os(),namespace:aC,packId:aD,version:aE,name:s.Yj(),enabled:s.zM().default(!0),policyId:s.Yj().optional()}).meta({id:"InstalledPack"});s.Ik({namespace:aC,packId:aD,version:aE}).meta({id:"InstallPackRequest"}),s.Ik({items:s.YO(ck)}).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 cl=2,cm=A.options.join("|"),cn=RegExp(`\\[\\[aka:(?:${cm}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`),co=RegExp(`^${cn.source}$`);function cp(){return RegExp(cn.source,"g")}let cq=s.Yj().regex(co);s.Ik({category:A,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:A,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:A,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 cr=s.k5(["human","model"]),cs=s.k5(["display","explicit-reveal","view-render","model-input","remediation","purge"]),ct=s.k5(["revealed","refused","unavailable"]),cu=["display","view-render"];function cv(a){return cu.includes(a)}let cw=s.Ik({id:s.Os(),pointerId:s.Yj(),at:s.Yj(),target:cr,reason:cs,outcome:ct,grantId:s.Yj().optional(),pointerCount:s.ai().int().positive().default(1)}),cx=s.k5(["prompt","tool-input","tool-output","file","transcript"]),cy=s.Ik({location:s.Yj(),kind:cx,firstSeen:s.Yj(),lastSeen:s.Yj()}),cz=s.Ik({pointerId:s.Yj(),category:A,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(cy)}),cA=50,cB=50,cC=200,cD=s.Ik({limit:u.ai().int().min(1).max(cC).optional(),cursor:s.Yj().optional()});s.Ik({totals:s.Ik({values:s.ai().int().nonnegative()}),items:s.YO(cz),nextCursor:s.Yj().nullable()});let cE=s.Ik({limit:u.ai().int().min(1).max(cC).optional(),cursor:s.Yj().optional()});s.Ik({totals:s.Ik({reused:s.ai().int().nonnegative()}),items:s.YO(cz),nextCursor:s.Yj().nullable()});let cF=s.Ik({includeBatched:s.zM().optional(),limit:u.ai().int().min(1).max(cC).optional(),cursor:s.Yj().optional()});s.Ik({items:s.YO(cw),nextCursor:s.Yj().nullable(),hiddenBatched:s.ai().int().nonnegative()});let cG=s.Yj(),cH=s.k5(["masked","full","off"]),cI=1,cJ=s.Ik({acknowledgedAt:t.w$(),version:s.ai().int().positive()});function cK(a){return a?.version===cI}let cL=1,cM=s.k5(["standalone","attached"]),cN=s.Ik({endpoint:s.Yj().min(1),label:s.Yj().min(1).optional(),attachedAt:t.w$()}).meta({id:"ControlPlaneConnection"}),cO=s.k5(["redact","warn"]),cP=s.k5(["full","session-only"]),cQ=s.Ik({acknowledgedAt:t.w$(),payloadVersion:s.ai().int().positive()});function cR(a){return a?.payloadVersion===cL}let cS=s.Ik({specVersion:s.ai().int().positive().default(5),runMode:cM.default("standalone"),controlPlane:cN.optional(),policy:cO.default("redact"),historicalAccess:cP.default("session-only"),dataSharesInPlace:s.zM().default(!0),vaultConsent:cJ.optional(),vaultKeyCustody:cG.default("file"),vaultInlineReveal:cH.default("masked"),onboardedAt:t.w$().optional(),modelJudgeConsent:cQ.optional()});function cT(){return cS.parse({})}function cU(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 cV(a,b,c){return{id:b,url:a.url,name:a.name??null,attributes:JSON.stringify(a.attributes),firstSeen:c,lastSeen:c}}function cW(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 cX(a,b){return{id:b,class:a.class,label:a.label??null,attributes:a.attributes?JSON.stringify(a.attributes):null}}function cY(a,b){return{id:b,ruleId:a.ruleId,name:a.name,category:a.category,severity:a.severity,definition:a.definition,version:a.version}}function cZ(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 c$(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 c_(a){return`capture/${a.category}/${a.severity}`}function c0(a){return{ruleId:a.ruleId,version:c_(a),name:a.ruleId,category:a.category,severity:a.severity,definition:JSON.stringify({ruleId:a.ruleId})}}let c1="managed-settings.json",c2=s.k5(["runMode","historicalAccess","vaultConsent","vaultKeyCustody","vaultInlineReveal","modelJudgeConsent","dataSharesInPlace"]).meta({id:"ManagedSettingKey"}),c3=s.Ik({runMode:s.k5(["standalone","attached"]).optional(),controlPlane:s.Ik({endpoint:s.Yj().min(1),label:s.Yj().min(1).optional()}).optional(),historicalAccess:s.k5(["full","session-only"]).optional(),vaultConsent:s.zM().optional(),vaultKeyCustody:s.k5(["file","keychain"]).optional(),vaultInlineReveal:s.k5(["masked","full","off"]).optional(),modelJudgeConsent:s.zM().optional(),dataSharesInPlace:s.zM().optional()}).meta({id:"ManagedSettingsValues"}),c4=s.Ik({specVersion:s.ai().int().positive().default(1),organization:s.Yj().min(1).optional(),values:c3.default({}),lockedFields:s.YO(c2).default([])}).meta({id:"ManagedSettings"}),c5={present:!1,lockedFields:[]},c6=s.k5(["global","repo","user"]).meta({id:"PolicyScope"}),c7=s.KC([s.Ik({ruleId:s.Yj()}),s.Ik({category:A})]).meta({id:"PolicyTarget"}),c8=s.Ik({id:s.Os(),scope:c6,target:c7,action:C,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(c8),rules:s.YO(aP).optional(),rulesComplete:s.zM().optional(),exceptions:s.YO(bN).optional(),reversibleRuleIds:s.YO(s.Yj()).optional(),ruleVersions:s.g1(s.Yj(),s.Yj()).optional(),customKeywords:s.YO(s.Yj()),fetchedAt:t.w$()}).meta({id:"PolicyBundle"});let c9=["config"],da=A.options.filter(a=>!c9.includes(a)),db={secret:"critical",financial:"critical",code_flaw:"critical",pii:"high",phi:"high",custom:"high",code_context:"low",config:"low"},dc=s.k5(["builtin","custom"]).meta({id:"PolicyKind"}),dd=["monitor","warn","redact","vault","block"],de=s.k5(dd).meta({id:"BuiltinPolicyId"}),df=dd,dg={monitor:{name:"Monitor",action:"log",reversible:!1,description:"Log every match for audit. The request is allowed through untouched."},warn:{name:"Warn",action:"warn",reversible:!1,description:"Allow the request, but warn the user inline before it is sent."},redact:{name:"Redact",action:"redact",reversible:!1,description:"Strip the matched value from the request and destroy it, then continue. What was removed cannot be recovered."},vault:{name:"Redact & Vault",action:"redact",reversible:!0,description:"Strip the matched value from the request and keep an encrypted, recoverable copy in the local vault, leaving a pointer in its place. Needs the vault consent granted under Settings; without it this behaves as Redact."},block:{name:"Block",action:"block",reversible:!1,description:"Refuse the request entirely whenever any rule in this detection matches."}},dh=dd.filter(a=>!dg[a].reversible);dd.filter(a=>dg[a].reversible);let di=s.k5(dh).meta({id:"CategoryPolicyId"});function dj(a){let b=de.safeParse(a??dm);return dg[b.success?b.data:dm].reversible}let dk=Object.fromEntries(A.options.map(a=>[a,dg[function(a){if(c9.includes(a))return"monitor";let b=db[a];return"critical"===b||"high"===b?"warn":"monitor"}(a)].action])),dl=Object.fromEntries(dd.map(a=>[a,{id:a,...dg[a]}])),dm="monitor";function dn(a){let b=de.safeParse(a??dm);return dl[b.success?b.data:dm].action}let dp=s.Ik({id:s.Yj(),name:s.Yj(),ruleCount:s.ai().int().nonnegative(),enabled:s.zM()}).meta({id:"UsedByItem"}),dq=s.Ik({id:s.Yj(),kind:dc,name:s.Yj(),enabled:s.zM(),usedByCount:s.ai().int().nonnegative()}).meta({id:"PolicyListItem"});s.Ik({items:s.YO(dq)}).meta({id:"ListPoliciesResponse"}),s.Ik({specVersion:s.eu(1),id:s.Yj(),kind:dc,name:s.Yj(),enabled:s.zM(),description:s.Yj(),usedBy:s.YO(dp)}).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"});let dr=s.Ik({path:s.Yj().min(1),name:s.Yj().min(1),origin:a3,defaultAccess:a2});s.Ik({files:s.YO(dr),truncated:s.zM(),scannedAt:s.Yj()});let ds=["7d","30d","3m","6m"],dt=s.k5(ds).meta({id:"TimeRange"}),du={"7d":7,"30d":30,"3m":90,"6m":180};dt.catch("7d");let dv=s.k5(["still-valid","unknown","invalid"]),dw=s.Ik({filePath:s.Yj(),span:E.optional()}).strict(),dx=s.Ik({provider:s.Yj(),maskedToken:s.Yj(),where:dw,state:dv,observedAt:t.w$().optional()}).strict();s.Ik({provider:s.Yj(),maskedToken:s.Yj(),consolePath:s.Yj(),occurrenceSpread:s.ai().int().positive()}).strict();let dy=s.k5(["redact-rotation-checklist","redact-only","set-secret-redact","leave"]),dz=s.k5(["first-run","pre-push","secret-scan"]);s.Ik({entrySource:dz}).strict();let dA=s.Ik({id:dy,label:s.Yj()}),dB=s.Ik({kind:s.eu("decision"),entrySource:dz,secretCount:s.ai().int().positive(),prompt:s.Yj(),options:s.PV([dA.extend({id:s.eu("redact-rotation-checklist")}),dA.extend({id:s.eu("redact-only")}),dA.extend({id:s.eu("set-secret-redact")}),dA.extend({id:s.eu("leave")})])}),dC=s.Ik({kind:s.eu("no-decision")});s.gM("kind",[dB,dC]);let dD=s.Ik({severity:B,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(dD)}).meta({id:"SeveritySummaryResponse"}),s.Ik({range:s.k5(ds).default("7d")});let dE=s.k5(["blocked","redacted","warned"]).meta({id:"EnforcementActionKind"}),dF=s.Ik({kind:dE,count:s.ai().int().nonnegative(),delta:s.ai().int()}).meta({id:"EnforcementAction"});s.Ik({range:dt,total:s.ai().int().nonnegative(),actions:s.YO(dF)}).meta({id:"EnforcementActionsResponse"});let dG=s.k5(["day","week"]).meta({id:"TimeseriesGranularity"}),dH=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:dt,granularity:dG,points:s.YO(dH)}).meta({id:"FindingsTimeseriesResponse"});let dI=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:dt,granularity:dG,points:s.YO(dI)}).meta({id:"MttrTrendResponse"});let dJ=s.Ik({findingKey:s.Yj(),ruleId:s.Yj(),severity:B,path:s.Yj(),resolvedAt:t.w$(),detectedAt:t.w$()}).meta({id:"ResolvedFeedItem"});s.Ik({items:s.YO(dJ)}).meta({id:"RecentlyResolvedResponse"});let dK=["repo","user"],dL=s.k5(dK).meta({id:"SourceKind"}),dM=s.Ik({id:s.Yj(),name:s.Yj(),kind:dL,findingsCount:s.ai().int().nonnegative()}).meta({id:"TopSource"});s.Ik({range:dt,items:s.YO(dM)}).meta({id:"TopSourcesResponse"}),s.Ik({range:s.k5(ds).default("7d"),limit:u.ai().int().min(1).max(50).default(5),kind:s.k5(dK).optional()});let dN=w.extract(["ClaudeCode","Cursor","Codex","Antigravity","ClaudeAi","ChatGpt","Copilot","Api"]).meta({id:"Provider"}),dO=s.Ik({provider:dN,coverage:s.ai().int().min(0).max(100),supported:s.zM()}).meta({id:"ScanCoverageProvider"});s.Ik({range:dt,providers:s.YO(dO)}).meta({id:"ScanCoverageResponse"});let dP=s.k5(["repo","user","team","policy","share","rule"]).meta({id:"SubjectType"}),dQ=s.Ik({type:dP,id:s.Yj(),label:s.Yj()}).meta({id:"RecommendationSubject"}),dR=s.k5(["apply","navigate"]).meta({id:"RecommendationActionMode"}),dS=s.Ik({mode:dR,type:s.Yj(),label:s.Yj(),href:s.Yj().optional(),policyId:s.Yj().optional(),teamId:s.Yj().optional()}).meta({id:"RecommendationAction"}),dT=s.Ik({id:s.Yj(),category:s.Yj(),severity:B,title:s.Yj(),description:s.Yj(),subjects:s.YO(dQ),action:dS}).meta({id:"RecommendedAction"});s.Ik({items:s.YO(dT)}).meta({id:"RecommendedActionsResponse"}),s.Ik({limit:u.ai().int().min(1).max(20).default(3)});let dU=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:dU}).meta({id:"ApplyRecommendedActionResponse"}),s.Ik({id:s.Yj(),status:s.eu("dismissed")}).meta({id:"DismissRecommendedActionResponse"}),s.Ik({id:s.Yj()});let dV=s.Ik({historicalAccess:s.Yj(),modelJudgeConsent:s.zM(),vaultConsent:s.Yj(),vaultInlineReveal:s.Yj()}),dW=s.Ik({endpoint:s.Yj(),label:s.Yj().optional()});s.Ik({ruleId:s.Yj(),category:A,severity:B,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 dX=s.Ik({category:A,action:di,reasoning:s.Yj(),genuineCount:s.ai().int().nonnegative(),fpCount:s.ai().int().nonnegative(),fpIds:s.YO(s.Yj())});s.Ik({perCategory:s.YO(dX),notes:s.Yj()});let dY=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"]}),dZ=s.Ik({ruleId:s.Yj(),category:A,valueFingerprint:s.Yj(),keyVersion:s.ai().int().nonnegative()}),d$=s.Ik({pattern:s.Yj(),count:s.ai().int().nonnegative(),values:s.YO(dZ).min(1)}),d_=s.Ik({category:A,count:s.ai().int().nonnegative(),egress:s.zM()}),d0=s.Ik({counts:dY,routineCategories:s.YO(A),surfacedCategories:s.YO(A),findingKinds:s.YO(d_),posture:s.g1(A,de),maskedFindings:s.YO(dx).optional(),falsePositivePatterns:s.YO(d$).optional()}),d1=dX.pick({category:!0,genuineCount:!0,fpCount:!0}).extend({egress:s.zM()});s.Ik({categories:s.YO(d1),posture:s.g1(A,de)}),s.Ik({frame:d0,copy:s.Yj()}),s.k5(["scan","floor"]);let d2=s.Ik({id:s.k5(["enter-remediation","open-dashboard","not-now"]),label:s.Yj()}),d3=s.PV([d2.extend({id:s.eu("open-dashboard")}),d2.extend({id:s.eu("not-now")})]),d4=s.PV([d2.extend({id:s.eu("enter-remediation")}),d2.extend({id:s.eu("open-dashboard")}),d2.extend({id:s.eu("not-now")})]);s.Ik({worthALook:s.ai().int().nonnegative(),liveKeys:s.ai().int().nonnegative().optional(),options:s.KC([d3,d4])}).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 d5=new Set(["recognized","internal"]);function d6(a){return d5.has(a)?"allowed":"review"}function d7(a){return"block"===a?"blocked":"allowed"}function d8(a,b){return null===b?d6(a):d7(b)}function d9(a,b){return null!==b&&d7(b)!==d6(a)}function ea(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 eb(a){return Array.from(new Set(a))}function ec(a){let b=new Set(a);return bn.filter(a=>b.has(a))}function ed(a){return ec(a)[0]??"none"}let ee={raw_ip:0,unverified_domain:1,plaintext_transport:2};function ef(a){return 0===a.length?1/0:Math.min(...a.map(a=>ee[a]))}}};
|