@akasecurity/cli 0.9.4 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +18 -0
  2. package/dist/cli.js +2220 -410
  3. package/extension/background.js +1 -0
  4. package/extension/content.js +1 -0
  5. package/extension/icons/icon128.png +0 -0
  6. package/extension/icons/icon16.png +0 -0
  7. package/extension/icons/icon48.png +0 -0
  8. package/extension/manifest.json +39 -0
  9. package/extension/popup.html +69 -0
  10. package/extension/popup.js +1 -0
  11. package/native-host/host.js +31084 -0
  12. package/native-host/scan-worker.js +18006 -0
  13. package/package.json +12 -8
  14. package/web-ui/package.json +11 -7
  15. package/web-ui/packages/dashboard-ui/package.json +2 -0
  16. package/web-ui/packages/plugin-sdk/package.json +3 -1
  17. package/web-ui/packages/ui-kit/package.json +1 -0
  18. package/web-ui/rules/secrets/gcp-service-account.json +1 -1
  19. package/web-ui/web-ui/.next/BUILD_ID +1 -1
  20. package/web-ui/web-ui/.next/app-build-manifest.json +194 -56
  21. package/web-ui/web-ui/.next/app-path-routes-manifest.json +8 -8
  22. package/web-ui/web-ui/.next/build-manifest.json +8 -8
  23. package/web-ui/web-ui/.next/prerender-manifest.json +14 -14
  24. package/web-ui/web-ui/.next/required-server-files.json +5 -0
  25. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js +2 -2
  26. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js.nft.json +1 -1
  27. package/web-ui/web-ui/.next/server/app/(app)/activity/page_client-reference-manifest.js +1 -1
  28. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js +2 -2
  29. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js.nft.json +1 -1
  30. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page_client-reference-manifest.js +1 -1
  31. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js +2 -2
  32. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js.nft.json +1 -1
  33. package/web-ui/web-ui/.next/server/app/(app)/detections/page_client-reference-manifest.js +1 -1
  34. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js +2 -2
  35. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js.nft.json +1 -1
  36. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page_client-reference-manifest.js +1 -1
  37. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js +2 -2
  38. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js.nft.json +1 -1
  39. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page_client-reference-manifest.js +1 -1
  40. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js +2 -2
  41. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js.nft.json +1 -1
  42. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page_client-reference-manifest.js +1 -1
  43. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js +2 -2
  44. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js.nft.json +1 -1
  45. package/web-ui/web-ui/.next/server/app/(app)/findings/page_client-reference-manifest.js +1 -1
  46. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js +2 -2
  47. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js.nft.json +1 -1
  48. package/web-ui/web-ui/.next/server/app/(app)/inventory/page_client-reference-manifest.js +1 -1
  49. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js +2 -2
  50. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js.nft.json +1 -1
  51. package/web-ui/web-ui/.next/server/app/(app)/policies/page_client-reference-manifest.js +1 -1
  52. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js +2 -2
  53. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js.nft.json +1 -1
  54. package/web-ui/web-ui/.next/server/app/(app)/scan/page_client-reference-manifest.js +1 -1
  55. package/web-ui/web-ui/.next/server/app/(app)/security/page.js +2 -2
  56. package/web-ui/web-ui/.next/server/app/(app)/security/page.js.nft.json +1 -1
  57. package/web-ui/web-ui/.next/server/app/(app)/security/page_client-reference-manifest.js +1 -1
  58. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js +2 -2
  59. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js.nft.json +1 -1
  60. package/web-ui/web-ui/.next/server/app/(app)/settings/page_client-reference-manifest.js +1 -1
  61. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js +2 -2
  62. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js.nft.json +1 -1
  63. package/web-ui/web-ui/.next/server/app/(app)/updates/page_client-reference-manifest.js +1 -1
  64. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js +2 -2
  65. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js.nft.json +1 -1
  66. package/web-ui/web-ui/.next/server/app/(app)/vault/page_client-reference-manifest.js +1 -1
  67. package/web-ui/web-ui/.next/server/app/_not-found/page.js +2 -2
  68. package/web-ui/web-ui/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  69. package/web-ui/web-ui/.next/server/app/_not-found.html +1 -1
  70. package/web-ui/web-ui/.next/server/app/_not-found.rsc +2 -2
  71. package/web-ui/web-ui/.next/server/app/index.html +1 -1
  72. package/web-ui/web-ui/.next/server/app/index.rsc +2 -2
  73. package/web-ui/web-ui/.next/server/app/page.js +2 -2
  74. package/web-ui/web-ui/.next/server/app/page_client-reference-manifest.js +1 -1
  75. package/web-ui/web-ui/.next/server/app-paths-manifest.json +8 -8
  76. package/web-ui/web-ui/.next/server/chunks/114.js +792 -0
  77. package/web-ui/web-ui/.next/server/chunks/160.js +785 -0
  78. package/web-ui/web-ui/.next/server/chunks/243.js +1 -1
  79. package/web-ui/web-ui/.next/server/chunks/330.js +1 -1
  80. package/web-ui/web-ui/.next/server/chunks/333.js +1 -0
  81. package/web-ui/web-ui/.next/server/chunks/363.js +12 -0
  82. package/web-ui/web-ui/.next/server/chunks/528.js +73 -0
  83. package/web-ui/web-ui/.next/server/chunks/557.js +5 -0
  84. package/web-ui/web-ui/.next/server/chunks/561.js +123 -0
  85. package/web-ui/web-ui/.next/server/functions-config-manifest.json +6 -6
  86. package/web-ui/web-ui/.next/server/middleware-build-manifest.js +1 -1
  87. package/web-ui/web-ui/.next/server/middleware-manifest.json +5 -5
  88. package/web-ui/web-ui/.next/server/pages/404.html +1 -1
  89. package/web-ui/web-ui/.next/server/pages/500.html +1 -1
  90. package/web-ui/web-ui/.next/server/server-reference-manifest.js +1 -1
  91. package/web-ui/web-ui/.next/server/server-reference-manifest.json +1 -1
  92. package/web-ui/web-ui/.next/static/chunks/133-14f0f297836736b9.js +1 -0
  93. package/web-ui/web-ui/.next/static/chunks/539-b35890d398017f99.js +62 -0
  94. package/web-ui/web-ui/.next/static/chunks/992-ba273ebe2ac236a5.js +1 -0
  95. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/loading-0e999b82265bac84.js +1 -0
  96. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-90ea4cb1f1956a03.js +1 -0
  97. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/loading-0e999b82265bac84.js +1 -0
  98. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-d96aa1158bb1c630.js +1 -0
  99. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/loading-0e999b82265bac84.js +1 -0
  100. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-269fa2d4f47e6125.js +1 -0
  101. package/web-ui/web-ui/.next/static/chunks/app/(app)/error-092d6780c93209d5.js +1 -0
  102. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/loading-0e999b82265bac84.js +1 -0
  103. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-4ad5b60f476d7c6e.js +1 -0
  104. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/loading-0e999b82265bac84.js +1 -0
  105. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/loading-0e999b82265bac84.js +1 -0
  106. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-2bf76696fbe6e76d.js +1 -0
  107. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-5d2511a7c06dd645.js +1 -0
  108. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/loading-0e999b82265bac84.js +1 -0
  109. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-1891ec610b461455.js +1 -0
  110. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/loading-0e999b82265bac84.js +1 -0
  111. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-bc090490b3416d48.js +1 -0
  112. package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-d7a290e9b0dd8a15.js +1 -0
  113. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/loading-0e999b82265bac84.js +1 -0
  114. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-1d1a93a1e561ca82.js +1 -0
  115. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/loading-0e999b82265bac84.js +1 -0
  116. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-7a1a29a230626f96.js +1 -0
  117. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/loading-0e999b82265bac84.js +1 -0
  118. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-a7fa0e028623b7cb.js +1 -0
  119. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/loading-0e999b82265bac84.js +1 -0
  120. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-9729632fc8128534.js +1 -0
  121. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/loading-0e999b82265bac84.js +1 -0
  122. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-bda9e826a1ac1a00.js +1 -0
  123. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/loading-0e999b82265bac84.js +1 -0
  124. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-28116d3ce827e152.js +1 -0
  125. package/web-ui/web-ui/.next/static/chunks/app/page-315a9068831a3ad5.js +1 -0
  126. package/web-ui/web-ui/.next/static/chunks/{framework-3444de8758288822.js → framework-a566532c222ba944.js} +1 -1
  127. package/web-ui/web-ui/.next/static/chunks/{main-b13545f01f111855.js → main-f710385bb68f9de5.js} +1 -1
  128. package/web-ui/web-ui/.next/static/chunks/pages/{_app-7f0d920cc5af1c9f.js → _app-63f369037199ea68.js} +1 -1
  129. package/web-ui/web-ui/.next/static/chunks/pages/{_error-3d8b61361c4b2c6b.js → _error-41a11264bde7b852.js} +1 -1
  130. package/web-ui/web-ui/.next/static/css/0af7782f7a750368.css +2 -0
  131. package/web-ui/web-ui/.next/static/{cVKs25XbQsC1083sU5GOD → x4ixG3_q4UeyC_WNmSFdI}/_buildManifest.js +1 -1
  132. package/web-ui/web-ui/dist/scan-worker.js +18006 -0
  133. package/web-ui/web-ui/package.json +4 -3
  134. package/web-ui/web-ui/server.js +1 -1
  135. package/web-ui/web-ui/.next/server/chunks/28.js +0 -1
  136. package/web-ui/web-ui/.next/server/chunks/334.js +0 -2
  137. package/web-ui/web-ui/.next/server/chunks/514.js +0 -755
  138. package/web-ui/web-ui/.next/server/chunks/628.js +0 -84
  139. package/web-ui/web-ui/.next/server/chunks/817.js +0 -1
  140. package/web-ui/web-ui/.next/server/chunks/830.js +0 -750
  141. package/web-ui/web-ui/.next/server/chunks/949.js +0 -123
  142. package/web-ui/web-ui/.next/static/chunks/501-939e9e83b25a6293.js +0 -1
  143. package/web-ui/web-ui/.next/static/chunks/84-8205054e8901dbde.js +0 -62
  144. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-e3ce4be93d2f8ac5.js +0 -1
  145. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-8bb13b53c7bde504.js +0 -1
  146. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-07307e6d8ddb5cbf.js +0 -1
  147. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-aecbc7b6fbd143c2.js +0 -1
  148. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-1d468a1a0cf12aea.js +0 -1
  149. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-863e759b7e26c759.js +0 -1
  150. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-7636a56ffa40d5c6.js +0 -1
  151. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-c80a692b9d05f321.js +0 -1
  152. package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-01e6dceb36cb882f.js +0 -1
  153. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-d98e303b17524dad.js +0 -1
  154. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-178c53b1f56b5e97.js +0 -1
  155. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-7f69b2579337c729.js +0 -1
  156. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-7019a1567cd9aadd.js +0 -1
  157. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-90ce0ad1b9403f48.js +0 -1
  158. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-7ef77f76ff07ea1f.js +0 -1
  159. package/web-ui/web-ui/.next/static/chunks/app/page-3fbfddda391d9939.js +0 -1
  160. package/web-ui/web-ui/.next/static/css/10425160b1a85ff4.css +0 -2
  161. /package/web-ui/web-ui/.next/static/{cVKs25XbQsC1083sU5GOD → x4ixG3_q4UeyC_WNmSFdI}/_ssgManifest.js +0 -0
@@ -1,755 +0,0 @@
1
- "use strict";exports.id=514,exports.ids=[514],exports.modules={7514:(a,b,c)=>{c.d(b,{WR:()=>ah,qA:()=>ai,Pi:()=>b5,o8:()=>bx,Qo:()=>bg,Ru:()=>b1,KS:()=>bu,tI:()=>bs,_2:()=>bp,Dg:()=>bq,Wo:()=>bv,Rd:()=>bn,Ji:()=>bf,y9:()=>bm,xR:()=>bw,v5:()=>bo});var d=c(77598),e=c(73024),f=c(76760),g=c(79868),h=c(69882);function i(a){return(0,d.createHash)("sha256").update(a).digest("hex")}function j(a){return i((0,h.tTV)(["source_project",a]))}function k(a,b){return i((0,h.tTV)(["inspection_definition",a,b]))}function l(a){return a.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function m(a){return Array.from({length:a},()=>"?").join(", ")}function n(a){return`%${l(a)}%`}function o(a){return`(${a.map(a=>`${a} LIKE ? ESCAPE '\\'`).join(" OR ")})`}let p=0;function q(a,b,c="DEFERRED"){if(a.isTransaction){let c=`aka_sp_${String(p+=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 r(a,b,c="DEFERRED"){let d=a.isTransaction;try{return q(a,b,c),!0}catch(b){if(!a.isTransaction&&d)throw b;return!1}}function s(a){process.stderr.write(`[aka] ${a}
2
- `)}function t(a,b,c){return void 0!==a.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ? LIMIT 1").get(b,c)}function u(a,b,c){let d=c?.includeGenerated?"table_xinfo":"table_info";return a.prepare(`PRAGMA ${d}(${b})`).all().map(a=>a.name)}function v(a,b){return void 0===b?a.all():Array.isArray(b)?a.all(...b):a.all(b)}function w(a,b){return void 0===b?a.get():Array.isArray(b)?a.get(...b):a.get(b)}function x(a){return 1===a||!0===a}function y(a){let b={};for(let[c,d]of Object.entries(a))b[c]=void 0===d?null:d;return b}function z(a,b,c){return w(a.prepare(b),c)?.n??0}function A(a,b,c){let d=new Map;for(let e of v(a.prepare(b),c))d.set(e.k,e.n);return d}function B(a,b){let c=[];for(let d of a)try{c.push(b(d))}catch{}return c}let C="aka.db";function D(a,b){try{(0,e.chmodSync)(a,b)}catch{}}function E(a){(0,e.mkdirSync)(a,{recursive:!0,mode:448}),D(a,448)}function F(a){return[`${a}-wal`,`${a}-shm`,`${a}-journal`]}function G(a){try{if((0,e.lstatSync)(a).isSymbolicLink())return}catch{}D(a,384)}function H(a,b){let c=`${a}.${String(process.pid)}.tmp`;try{(0,e.rmSync)(c,{force:!0})}catch{}try{(0,e.writeFileSync)(c,b,{mode:384,flag:"wx"}),(0,e.renameSync)(c,a)}finally{try{(0,e.rmSync)(c,{force:!0})}catch{}}G(a)}function I(a){return"column"===a.kind?`column ${a.table}.${a.name}`:`table ${a.name}`}function J(a){return a.split(/-->\s*statement-breakpoint/).map(a=>a.trim()).filter(a=>a.length>0)}let K="0014_drop_legacy_events_findings",L=[{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 M(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||(q(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 N(a,b){if(null==a)return b;try{return JSON.parse(a)}catch{return b}}function O(a){if(null!=a)try{let b=JSON.parse(a);if("object"==typeof b&&null!==b)return b}catch{}}let P="max(started_at, coalesce(ended_at, started_at))";function Q(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}let R={session:"session",prompt:"prompt",response:"response",tool_call:"tool",hook:"hook",detection:"detection",share:"share",permission:"permission",commit:"commit",error:"error",active:"active"};function S(a){if(!a)return[];let b=N(a,null);return Array.isArray(b)?b:[]}function T(a){let b=h.TUN.safeParse(a);return b.success?b.data:"claudecode"}function U(a,b,c){let d=Math.max(a.started_at,b.lastActivityMs),{status:e,endedAtMs:f}=function(a,b,c){if(a.status){let b=h.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:T(a.harness),title:a.title||a.project||a.repo||`Session ${a.id.slice(0,8)}`,project:a.project??"",repo:a.repo??"",branches:S(a.branches),startedAt:(0,h.q11)(a.started_at),endedAt:null===f?null:(0,h.q11)(f),status:e,turns:b.turns,findings:b.findings,shares:b.shares}}function V(a){let b=R[a.event_type];if(!b)return null;let c=a.severity?h.U7X.safeParse(a.severity):null,d=a.link?h.Itg.safeParse(a.link):null;return{id:a.id,occurredAt:(0,h.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:x(a.internal),flagged:x(a.flagged)}}let W=`
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`,X="event_type = 'session'",Y=`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 Z{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=Q();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??Q(),this.now()),d=z(this.db,`SELECT count(*) AS n FROM audit_events
18
- WHERE ${X} AND started_at >= ? AND started_at < ?
19
- AND ${Y}`,[b,c]),e=this.now()-18e5,f=z(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(${P}) FROM audit_events e WHERE e.root_session_id = s.id),
25
- s.started_at
26
- )
27
- ) >= ?`,[e]),g=z(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:z(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:z(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){var b;let c=a.cursor?function(a){let b=O(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&"startedAtMs"in b&&"id"in b&&"number"==typeof b.startedAtMs&&"string"==typeof b.id?b:null}(a.cursor):null,d=a.to?(0,h.I8t)(a.to):this.now(),e=a.from?(0,h.I8t)(a.from):void 0,f=[X],g=[];if(a.harness&&a.harness.length>0&&(f.push(`coalesce(json_extract(attributes, '$.harness'), 'claudecode') IN (${m(a.harness.length)})`),g.push(...a.harness)),void 0!==e&&(f.push("started_at >= ?"),g.push(e)),f.push("started_at <= ?"),g.push(d),a.q){let b=n(a.q);f.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 i=z(this.db,`SELECT count(*) AS n FROM audit_events
41
- WHERE ${[...f,`NOT ${Y}`].join(" AND ")}`,g);a.excludeEmpty&&f.push(Y),c&&(f.push("(started_at < ? OR (started_at = ? AND id < ?))"),g.push(c.startedAtMs,c.startedAtMs,c.id));let j=a.limit,k=v(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 ${f.join(" AND ")}
52
- ORDER BY started_at DESC, id DESC
53
- LIMIT ?`),[...g,j+1]),l=k.length>j,o=l?k.slice(0,j):k,p=this.rollupsFor(o.map(a=>a.id)),q=this.now(),r=o.map(a=>U(a,p.get(a.id)??{turns:0,findings:0,shares:0,lastActivityMs:0},q)),s=o[o.length-1];return Promise.resolve({items:r,nextCursor:l&&s?(b={startedAtMs:s.started_at,id:s.id},Buffer.from(JSON.stringify(b)).toString("base64url")):null,emptyCount:i})}getSession(a){let b=w(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=v(this.db.prepare(`SELECT ${W}
70
- FROM audit_events
71
- WHERE id = ? OR root_session_id = ?
72
- ORDER BY started_at ASC, id ASC`),[a,a]).map(V).filter(a=>null!==a),d=w(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=w(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=v(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=v(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=z(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({...U(b,i,this.now()),host:b.host??"",cwd:b.cwd??"",models:g.length>0?g:S(b.models),version:b.version??"",tokens:j,tools:Object.fromEntries(f.flatMap(a=>a.tool?[[a.tool,a.n]]:[])),files:S(b.files),commits:h,events:c})}tokenReports(a){let b=this.readLlmCallLeaves(void 0===a?{}:{fromMs:a});return Promise.resolve((0,h.ryv)(b,h.q_t))}tokenReportForSession(a){return Promise.resolve((0,h.ryv)(this.readLlmCallLeaves({sessionId:a}),h.q_t)[0]??null)}harnessFacets(a){let b=v(this.db.prepare(`SELECT DISTINCT coalesce(json_extract(attributes, '$.harness'), 'claudecode') AS harness
89
- FROM audit_events WHERE ${X}${void 0===a?"":" AND started_at >= ?"}`),void 0===a?void 0:[a]),c=new Set;for(let a of b)c.add(T(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)),B(v(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=m(a.length);for(let d of v(this.db.prepare(`SELECT root_session_id AS id, max(${P}) 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 v(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 v(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 v(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 v(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 ${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){q(this.db,a)}insertAuditEvent(a){let b=(0,h.V9M)(a);this.insertStmt.run(y({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,h.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.messageId,i((0,h.tTV)(["audit_event_llm_call",b,c])));this.upsertLlmCallStmt.run(y({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,h.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.toolUseId,i((0,h.tTV)(["audit_event_tool_call",b,c])));this.insertStmt.run(y({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 w(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=O(b.attributes)?.provider;if("string"==typeof c)return c}llmCallLeaves(){return v(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 _{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,i((0,h.tTV)(["classified_data",b]))),d=(0,h.$BP)(a,c);return this.insertStmt.run(y({id:d.id,class:d.class,label:d.label,attributes:d.attributes})),c}}function aa(a){return w(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 ab{constructor(a){this.db=a}report(){let a=aa(this.db);if(!a)return{scannedAt:null,skills:[],hooks:[],mcpServers:[],configFiles:[],topics:[]};let b=v(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=v(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=O(a.attributes);b&&("skill"===a.objectType?d.push(function(a,b){let c={id:a.id,name:a.title??"(unnamed)",source:ac(b.source)??"unknown",scope:ac(b.scope)??"unknown",status:"unknown"},d=ac(b.description);void 0!==d&&(c.description=d);let e=ac(b.version);void 0!==e&&(c.installedVersion=e);let f=ac(b.updated_at);return void 0!==f&&(c.updatedAt=f),c}(a,b)):"hook"===a.objectType?e.push(function(a,b,c){let d=ac(b.command)??"",e=c.filter(a=>a.maskedMatch===d),f={id:a.id,event:ac(b.event)??"unknown",command:d,scope:ac(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=ac(b.matcher);void 0!==g&&(f.matcher=g);let h=ac(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:ac(b.scope)??"unknown",transport:ac(b.transport)??"unknown",trust:c.get(a.id)??"unapproved"},e=ac(b.command);void 0!==e&&(d.command=e);let f=ac(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=ac(b.plugin_name);void 0!==g&&(d.pluginName=g);let h=ac(b.marketplace);void 0!==h&&(d.marketplace=h);let i=ac(b.project);return void 0!==i&&(d.project=i),d}(a,b,h)):g.push(function(a,b){let c=ac(b.scope)??"unknown",d={id:a.id,name:a.title??"(unnamed)",path:a.location??"",scope:c,kind:ac(b.kind)??"Configuration file",untracked:"local"===c},e=ac(b.detail);void 0!==e&&(d.detail=e),"number"==typeof b.entry_count&&(d.entryCount=b.entry_count);let f=ac(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=O(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=v(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 ac(a){return"string"==typeof a?a:void 0}function ad(a){let b=N(a,[]);if(!Array.isArray(b))return[];let c=[];for(let a of b)a&&"object"==typeof a&&c.push(a);return c}function ae(a,b){return a.version!==b.version||a.rulesJson!==b.rulesJson}class af{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}listDetections(a){let b=v(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:x(a.enabled),ruleCount:ad(a.rulesJson).length,policyId:a.policyId,...b&&ae(a,b)?{latestVersion:b.version}:{}}});return Promise.resolve((0,h.plk)(d,a))}availableByPack(){return new Map(v(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=v(this.db.prepare("SELECT enabled, rules_json AS rulesJson FROM installed_packs")),b=0,c=0,d=new Set;for(let e of a){x(e.enabled)&&(c+=1);let a=ad(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,h.pnU)(a);if(!b)return Promise.resolve(null);let{namespace:c,packId:d}=b,e=w(this.db.prepare(`SELECT namespace, pack_id AS packId, version, name, enabled, policy_id AS policyId,
140
- rules_json AS rulesJson, updated_at AS updatedAt
141
- FROM installed_packs
142
- WHERE namespace = ? AND pack_id = ?`),[c,d]);if(!e)return Promise.resolve(null);let f=ad(e.rulesJson),g=f.map(a=>a.id).filter(a=>"string"==typeof a),i=this.countFindingsLast30d(g),j=this.availableByPack().get(`${e.namespace}/${e.packId}`),k=j?ae(e,j)?{available:!0,latestVersion:j.version,latestRuleCount:ad(j.rulesJson).length}:{available:!1,latestVersion:j.version}:null;return Promise.resolve((0,h.a45)({namespace:e.namespace,packId:e.packId,version:e.version,name:e.name,enabled:x(e.enabled),rules:f,updatedAt:new Date(e.updatedAt),policyId:e.policyId},i,k))}countFindingsLast30d(a){if(0===a.length)return 0;let b=this.now()-2592e6,c=m(a.length);return z(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 (${h.hfB})
148
- AND d.rule_id IN (${c})`,[b,...a])}}class ag{constructor(a){this.db=a}contentHashes(){return Promise.resolve(new Set(v(this.db.prepare(`SELECT content_hash FROM audit_events
149
- WHERE event_type IN (${h.hfB})`)).map(a=>a.content_hash)))}}let ah=864e5;class ai 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 aj 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 ak=`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)`,al=`capability = 'reveal_to_model'
152
- AND conditions IS NULL
153
- AND ${ak}`;class am{constructor(a){this.db=a,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 ${ak}`),this.insertBlockedStmt=a.prepare(`INSERT OR REPLACE INTO blocked_detections (reference, rule_id, category, value_fingerprint, key_version, masked_value, session_id, repo, blocked_at)
156
- VALUES (:reference, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue, :sessionId, :repo, :blockedAt)`),this.sweepBlockedStmt=a.prepare("DELETE FROM blocked_detections WHERE blocked_at <= :cutoff")}create(a){try{return Promise.resolve(this.createSync(a))}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}createSync(a){if(a.conditions?.provider!==void 0)throw Error("provider conditions are not supported yet — a grant with one would never apply");let b=(0,d.randomUUID)(),c=Date.now();try{this.insertExceptionRow(b,a,c)}catch(d){if(!(d instanceof Error&&(2067===d.errcode||d.message.includes("UNIQUE constraint failed"))))throw d;q(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 ai(a.ruleId);this.insertExceptionRow(b,a,c)},"IMMEDIATE")}let e=w(this.db.prepare("SELECT * FROM exceptions WHERE id = :id"),{id:b});if(void 0===e)throw Error("exception row not found immediately after insert");return an(e)}insertExceptionRow(a,b,c){this.db.prepare(`INSERT INTO exceptions (
164
- id, rule_id, category, value_fingerprint, key_version, masked_value,
165
- capability, scope, expires_at, max_uses, use_count, last_used_at,
166
- justification, conditions, created_by, created_via, created_at, updated_at
167
- ) VALUES (
168
- :id, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue,
169
- :capability, :scope, :expiresAt, :maxUses, 0, NULL, :justification,
170
- :conditions, :createdBy, :createdVia, :now, :now
171
- )`).run({id:a,ruleId:b.ruleId,category:b.category,valueFingerprint:b.valueFingerprint,keyVersion:b.keyVersion,maskedValue:b.maskedValue,capability:b.capability??"suppress",scope:b.scope,expiresAt:null===b.expiresAt?null:(0,h.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 ${ak}`;return Promise.resolve(B(v(this.db.prepare(`SELECT * FROM exceptions ${b} ORDER BY created_at DESC, rowid DESC`),a?.includeTerminal?{}:{now:Date.now()}),an))}getByIdPrefix(a){if(0===a.length)return Promise.resolve(void 0);let b=v(this.db.prepare(String.raw`SELECT * FROM exceptions WHERE id LIKE :pattern ESCAPE '\' LIMIT 2`),{pattern:`${l(a)}%`});if(b.length>1)return Promise.reject(new aj(a));let c=b[0];if(!c)return Promise.resolve(void 0);try{return Promise.resolve(an(c))}catch{return Promise.resolve(void 0)}}revoke(a,b,c){let d=Date.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=Date.now()){return Promise.resolve(1===Number(this.consumeStmt.run({id:a,now:b}).changes))}activeBundleEntries(a,b=Date.now()){return Promise.resolve(B(v(this.db.prepare(`SELECT * FROM exceptions
174
- WHERE key_version = :keyVersion AND ${ak}
175
- ORDER BY created_at DESC, rowid DESC`),{keyVersion:a,now:b}),a=>{let b=null===a.conditions?null:JSON.parse(a.conditions);return h.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,h.q11)(a.expires_at),maxUses:a.max_uses,useCount:a.use_count,conditions:b})}))}recordBlocked(a){let b=Date.now();return this.sweepBlockedStmt.run({cutoff:b-ah}),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(v(this.db.prepare(`SELECT * FROM blocked_detections
176
- WHERE blocked_at > :cutoff
177
- ORDER BY blocked_at DESC, rowid DESC`),{cutoff:Date.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,h.q11)(a.blocked_at)})))}activeRevealGrant(a,b,c,d=Date.now()){try{let e=w(this.db.prepare(`SELECT id FROM exceptions
178
- WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
179
- AND key_version = :keyVersion
180
- AND ${al}
181
- LIMIT 1`),{ruleId:a,valueFingerprint:b,keyVersion:c,now:d});return Promise.resolve(e??null)}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}sweepTerminal(a,b=Date.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 an(a){let b=null===a.conditions?null:JSON.parse(a.conditions);return h.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,h.q11)(a.expires_at),maxUses:a.max_uses,useCount:a.use_count,lastUsedAt:null===a.last_used_at?null:(0,h.q11)(a.last_used_at),justification:a.justification,conditions:b,createdBy:a.created_by,createdVia:a.created_via,createdAt:(0,h.q11)(a.created_at),updatedAt:(0,h.q11)(a.updated_at),revokedAt:null===a.revoked_at?null:(0,h.q11)(a.revoked_at),revokedBy:a.revoked_by,revokeReason:a.revoke_reason})}function ao(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 ap=`(
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 aq(a){return null===a||""===a?[]:a.split(",")}class ar{constructor(a){this.db=a}recentFindings(a){let b=a?.limit??50;return Promise.resolve(v(this.db.prepare(`SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
200
- f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
201
- json_extract(e.attributes, '$.source_tool') AS source_tool,
202
- e.event_type AS kind
203
- FROM inspection_findings f
204
- JOIN audit_events e ON e.id = f.audit_event_id
205
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
206
- WHERE e.event_type IN (${h.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,h.q11)(a.occurred_at),sourceTool:a.source_tool,kind:a.kind})))}sessionFindingsCount(a){return a?Promise.resolve(z(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 (${h.hfB})`,{sessionId:a})):Promise.resolve(0)}sessionFirings(a){return Object.fromEntries(A(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 (${h.hfB})
217
- GROUP BY d.rule_id`,{sessionId:a}))}listGroupedFindings(a){let b=a.sessionId?" AND e.root_session_id = :sessionId":"",c=`WHERE e.event_type IN (${h.hfB})${b}`,d=a.sessionId?{sessionId:a.sessionId}:{},e=this.groupAggregates(void 0!==a.q&&""!==a.q,{predicate:c,params:d}),f=v(this.db.prepare(`SELECT id, rule_id, category, severity, masked_match, action_taken, confidence,
218
- occurred_at, source_tool, repo, file, tool_name, kind, finding_key, latest_status
219
- FROM (
220
- SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
221
- d.severity AS severity, f.masked_match AS masked_match,
222
- f.action_taken AS action_taken, f.confidence AS confidence,
223
- e.started_at AS occurred_at,
224
- json_extract(e.attributes, '$.source_tool') AS source_tool,
225
- json_extract(e.attributes, '$.repo') AS repo,
226
- json_extract(e.attributes, '$.file_path') AS file,
227
- json_extract(e.attributes, '$.tool_name') AS tool_name,
228
- e.event_type AS kind, f.finding_key AS finding_key,
229
- latest.status AS latest_status,
230
- ROW_NUMBER() OVER (
231
- PARTITION BY d.rule_id
232
- ORDER BY e.started_at DESC, f.id DESC
233
- ) AS rn
234
- FROM inspection_findings f
235
- JOIN audit_events e ON e.id = f.audit_event_id
236
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
237
- LEFT JOIN ${ap} latest
238
- ON latest.finding_key = f.finding_key
239
- ${c}
240
- )
241
- WHERE rn <= :cap
242
- ORDER BY occurred_at DESC, id DESC`),{cap:200,...d}).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,h.q11)(a.occurred_at),sourceTool:a.source_tool,repo:a.repo??"",file:a.file??"",...null===a.tool_name?{}:{toolName:a.tool_name},status:(0,h.xog)({kind:a.kind,findingKey:a.finding_key,latestResolutionStatus:a.latest_status})})),g=(0,h.mAj)(f,{aggregates:e}),i={severity:a.severity,providers:a.provider,actions:a.action,statuses:a.status,subtype:a.subtype,q:a.q},j=(0,h.rG)(g,i),k=(0,h.A6E)((0,h.tXp)(g,i)),l=a.status??[],m={findings:k.reduce((a,b)=>{if(0===l.length)return a+b.instanceCount;let c=e.get(b.id);return a+(c?(0,h.Bfj)(c.statusInputs,l)??b.instanceCount:b.instanceCount)},0),groups:k.length},n=a.limit??h.goN,o=l.length>0?new Set(l):null;return Promise.resolve({totals:m,facets:j,items:k.slice(0,n).map(a=>o?{...a,instances:a.instances.filter(a=>void 0!==a.status&&o.has(a.status))}:a),nextCursor:null,...a.sessionId?{sessionFirings:this.sessionFirings(a.sessionId)}:{}})}groupAggregates(a,b){let c=a?`, group_concat(DISTINCT json_extract(e.attributes, '$.repo')) AS repos,
243
- group_concat(DISTINCT json_extract(e.attributes, '$.file_path')) AS files,
244
- 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,
245
- sum(tuple_count) AS instance_count,
246
- max(latest_at) AS latest_at,
247
- group_concat(source_tools) AS source_tools,
248
- group_concat(actions_taken) AS actions_taken,
249
- group_concat(status_tuple || '|' || tuple_count) AS status_inputs,
250
- group_concat(repos) AS repos,
251
- group_concat(files) AS files,
252
- group_concat(tool_names) AS tool_names
253
- FROM (
254
- SELECT d.rule_id AS rule_id,
255
- e.event_type || '|' ||
256
- (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '|' ||
257
- coalesce(latest.status, '') AS status_tuple,
258
- count(*) AS tuple_count,
259
- max(e.started_at) AS latest_at,
260
- group_concat(DISTINCT json_extract(e.attributes, '$.source_tool')) AS source_tools,
261
- group_concat(DISTINCT f.action_taken) AS actions_taken
262
- ${c}
263
- FROM inspection_findings f
264
- JOIN audit_events e ON e.id = f.audit_event_id
265
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
266
- LEFT JOIN ${ap} latest
267
- ON latest.finding_key = f.finding_key
268
- ${b.predicate}
269
- GROUP BY d.rule_id, status_tuple
270
- )
271
- GROUP BY rule_id`).all(b.params).map(b=>[b.rule_id,{instanceCount:b.instance_count,sourceTools:aq(b.source_tools),actionsTaken:aq(b.actions_taken),statusInputs:aq(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,h.q11)(b.latest_at),...a?{searchText:[b.repos??"",b.files??"",b.tool_names??""].filter(a=>""!==a).join(" ")}:{}}]))}healthSummary(){let a=z(this.db,`SELECT count(*) AS n FROM inspection_findings f
272
- JOIN audit_events e ON e.id = f.audit_event_id
273
- WHERE e.event_type IN (${h.hfB})`),b=Object.fromEntries(h.S8C.map(a=>[a,0]));for(let a of v(this.db.prepare(`SELECT f.action_taken AS action_taken, count(*) AS c
274
- FROM inspection_findings f
275
- JOIN audit_events e ON e.id = f.audit_event_id
276
- WHERE e.event_type IN (${h.hfB})
277
- 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 v(this.db.prepare(`SELECT d.severity AS severity, count(*) AS c
278
- FROM inspection_findings f
279
- JOIN audit_events e ON e.id = f.audit_event_id
280
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
281
- LEFT JOIN ${ap} latest
282
- ON latest.finding_key = f.finding_key
283
- WHERE e.event_type IN (${h.hfB})
284
- AND (latest.status IS NULL OR latest.status != 'resolved')
285
- GROUP BY d.severity`)))a.severity in c&&(c[a.severity]=a.c);let d=h.IgC,e=new Set(v(this.db.prepare(`SELECT DISTINCT json_extract(target, '$.category') AS category
286
- 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=v(this.db.prepare(`SELECT date(e.started_at / 1000, 'unixepoch') AS day, f.action_taken AS action, count(*) AS c
287
- FROM inspection_findings f
288
- JOIN audit_events e ON e.id = f.audit_event_id
289
- WHERE e.started_at >= :since
290
- AND e.event_type IN (${h.hfB})
291
- 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 as{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
292
- (id, rule_id, name, category, severity, definition, version)
293
- VALUES
294
- (:id, :ruleId, :name, :category, :severity, :definition, :version)`)}upsert(a){let b=k(a.ruleId,a.version),c=(0,h.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 at{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO inspection_findings
295
- (id, audit_event_id, inspection_definition_id, classified_data_id,
296
- span_start, span_end, masked_match, action_taken, confidence,
297
- finding_key, first_detected_at)
298
- VALUES
299
- (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
300
- :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
301
- :findingKey,
302
- COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
303
- ON CONFLICT(id) DO UPDATE SET
304
- inspection_definition_id = excluded.inspection_definition_id
305
- ON CONFLICT (finding_key) DO UPDATE SET
306
- audit_event_id = excluded.audit_event_id,
307
- inspection_definition_id = excluded.inspection_definition_id,
308
- classified_data_id = excluded.classified_data_id,
309
- span_start = excluded.span_start,
310
- span_end = excluded.span_end,
311
- masked_match = excluded.masked_match,
312
- action_taken = excluded.action_taken,
313
- confidence = excluded.confidence`),this.sessionDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
314
- JOIN audit_events e ON e.id = f.audit_event_id
315
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
316
- WHERE d.rule_id = :ruleId AND f.masked_match = :maskedMatch
317
- AND e.root_session_id = :sessionId
318
- AND e.event_type IN (${h.hfB})
319
- LIMIT 1`),this.eventDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
320
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
321
- WHERE f.audit_event_id = :auditEventId AND d.rule_id = :ruleId
322
- AND f.masked_match = :maskedMatch
323
- AND f.span_start = :spanStart AND f.span_end = :spanEnd
324
- 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,h.$3l)(a);this.insertStmt.run(y({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 au(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 av=h.Jr;function aw(a){return a.map(a=>{var b;return`${a.namespace}/${a.packId}@${a.version}#${b=a.rulesJson,(0,d.createHash)("sha1").update(b).digest("hex")}`}).sort().join(",")}function ax(a){let b=/^(\d+)\.(\d+)\.(\d+)/.exec(a);return b?[Number(b[1]),Number(b[2]),Number(b[3])]:null}class ay{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)
325
- VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
326
- 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)
327
- VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, :recordedBy, :now)
328
- ON CONFLICT (namespace, pack_id) DO UPDATE SET
329
- version = excluded.version,
330
- name = excluded.name,
331
- rules_json = excluded.rules_json,
332
- recorded_by = excluded.recorded_by,
333
- updated_at = excluded.updated_at
334
- WHERE available_packs.version <> excluded.version
335
- OR available_packs.name <> excluded.name
336
- 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()===aw(c))return;let e=Date.now();q(this.db,()=>{let a=this.mirrorState(),f=!1;for(let g of c){let c={id:(0,d.randomUUID)(),namespace:g.namespace,packId:g.packId,version:g.version,name:g.name,rulesJson:g.rulesJson,now:e},h=a.get(`${g.namespace}/${g.packId}`);void 0===h||!function(a,b){let c=ax(a.version);if(null===c)return!0;let d=ax(b.version);if(null===d)return!1;for(let a=0;a<3;a++){let b=c[a]??0,e=d[a]??0;if(b!==e)return b<e}for(let c of b.ruleIds)if(!a.ruleIds.has(c))return!0;return!1}(g,h)?this.upsertAvailableStmt.run({...c,id:(0,d.randomUUID)(),recordedBy:b?.recordedBy??null}):f=!0,this.insertMissingStmt.run(c)}f||this.pruneAvailable(c.map(a=>`${a.namespace}/${a.packId}`))},"IMMEDIATE")}catch{}}mirrorState(){return new Map(v(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=N(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=v(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 q(this.db,()=>{this.db.exec("UPDATE _pack_write_gate SET open = 1 WHERE id = 1");let d=this.db.prepare(`UPDATE installed_packs SET
337
- version = (SELECT a.version FROM available_packs a
338
- WHERE a.namespace = :namespace AND a.pack_id = :packId),
339
- name = (SELECT a.name FROM available_packs a
340
- WHERE a.namespace = :namespace AND a.pack_id = :packId),
341
- rules_json = (SELECT a.rules_json FROM available_packs a
342
- WHERE a.namespace = :namespace AND a.pack_id = :packId),
343
- updated_at = :now
344
- WHERE namespace = :namespace AND pack_id = :packId
345
- AND EXISTS (SELECT 1 FROM available_packs a
346
- 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=v(this.db.prepare("SELECT enabled, policy_id AS policyId, rules_json AS rulesJson, version FROM installed_packs")),b={installedPacks:a.length,enabledPacks:0,rules:[],invalidRules:0,ruleActions:new Map,ruleVersions:new Map};for(let c of a){let a;if(!x(c.enabled))continue;b.enabledPacks+=1;let d=(0,h.DhA)(c.policyId);try{a=JSON.parse(c.rulesJson)}catch{b.invalidRules+=1;continue}if(!Array.isArray(a)){b.invalidRules+=1;continue}for(let e of a){let a=h.jON.safeParse(e);a.success?(b.rules.push(a.data),b.ruleActions.set(a.data.id,d),b.ruleVersions.set(a.data.id,c.version)):b.invalidRules+=1}}return b}newestRecordedBinary(){let a=v(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!==au(e)&&(null===b||function(a,b){let c=au(a),d=au(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(w(this.db.prepare(`SELECT count(*) AS packs,
347
- coalesce(sum(json_array_length(rules_json)), 0) AS rules,
348
- coalesce(sum(enabled), 0) AS enabled
349
- FROM installed_packs`))??{packs:0,rules:0,enabled:0})}countsByPolicyId(){return A(this.db,`SELECT coalesce(policy_id, '${av}') AS k, count(*) AS n
350
- FROM installed_packs
351
- GROUP BY k`)}listByPolicyId(a){return v(this.db.prepare(`SELECT namespace, pack_id AS packId, name, enabled, rules_json AS rulesJson
352
- FROM installed_packs
353
- WHERE coalesce(policy_id, '${av}') = ?
354
- ORDER BY name ASC`),[a]).map(a=>({id:`${a.namespace}/${a.packId}`,name:a.name,ruleCount:ad(a.rulesJson).length,enabled:x(a.enabled)}))}setPolicy(a,b,c){if(null!==c&&!h.HUb.safeParse(c).success)throw Error(`Unknown policy '${c}'. Must be one of: ${h.V0H.join(", ")}.`);return Number(this.db.prepare(`UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
355
- 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
356
- WHERE namespace = :namespace AND pack_id = :packId`).run({enabled:+!!c,now:Date.now(),namespace:a,packId:b}).changes)>0}storedSignature(){return aw(v(this.signatureStmt))}}class az{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO inventory
357
- (id, object_type, location, title, host_id, attributes, first_seen, last_seen)
358
- VALUES
359
- (:id, :objectType, :location, :title, :hostId, :attributes, :firstSeen, :lastSeen)
360
- ON CONFLICT(id) DO UPDATE SET
361
- location = excluded.location,
362
- title = excluded.title,
363
- host_id = excluded.host_id,
364
- attributes = excluded.attributes,
365
- last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){var c,d;let e=(c=a.objectType,d=a.identityKey,i((0,h.tTV)(["inventory",c,d]))),f=(0,h.gzP)(a,e,b);return this.upsertStmt.run(y({id:f.id,objectType:f.objectType,location:f.location,title:f.title,hostId:f.hostId,attributes:f.attributes,firstSeen:f.firstSeen,lastSeen:f.lastSeen})),e}findById(a){return w(this.db.prepare("SELECT * FROM inventory WHERE id = :id"),{id:a})}distinctTitles(a){return v(this.db.prepare(`SELECT DISTINCT title FROM inventory
366
- WHERE object_type = :objectType AND title IS NOT NULL
367
- ORDER BY title`),{objectType:a}).map(a=>a.title)}osVersions(){return v(this.db.prepare(`SELECT DISTINCT os_version AS value FROM inventory
368
- WHERE object_type = 'host' AND os_version IS NOT NULL
369
- ORDER BY value`)).map(a=>a.value)}}let aA=["config","skill","mcp","hook"],aB=new Set(h.SHn.options),aC="(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))",aD={claudecode:"Claude Code",cursor:"Cursor",codex:"Codex"},aE={accessCounts:{open:0,approved:0,blocked:0,total:0},findingsCount:0};function aF(a,b){if(a.provider&&aB.has(a.provider))return a.provider;let c=(b.title??"").toLowerCase().replace(/[\s-]/g,"");return c.includes("claudecode")||"claude"===c?"claudecode":c.includes("cursor")?"cursor":c.includes("codex")?"codex":null}function aG(a){return a.some(a=>{let b=N(a.attributes,{});return"sample"!==b.provenance&&"claudecode"===aF(b,a)})}function aH(a){let b={id:a.id,type:a.assetType,name:a.name,sub:a.sub??"",flags:N(a.flagsJson,[])};return"mcp"===a.assetType&&a.effectiveTrust&&(b.trust=a.effectiveTrust),b}function aI(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 aJ(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:aM(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 aK(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 ${aM(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 aL(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 aM(a,b){return a.length>b?`${a.slice(0,b-1)}…`:a}function aN(a,b,c){let d=N(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 aO(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 aP{constructor(a){this.db=a}getInventoryStats(){let a=A(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=z(this.db,`SELECT count(*) AS n FROM source_project WHERE ${aC}`);let c=A(this.db,`SELECT coalesce(o.trust, a.trust) AS k, count(*) AS n
370
- FROM inventory_asset a
371
- LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
372
- WHERE a.asset_type = 'mcp' AND coalesce(o.trust, a.trust) IS NOT NULL
373
- 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=z(this.db,`SELECT count(*) AS n FROM inventory
374
- WHERE object_type = 'harness'
375
- AND (last_seen >= :liveSince OR json_extract(attributes, '$.provenance') = 'sample')`,{liveSince:Date.now()-2592e6}),f=z(this.db,"SELECT count(*) AS n FROM inventory_asset WHERE flags_json <> '[]'"),g=z(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=aF(N(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=>N(a.attributes,{}).projectIds??[]))],f=this.fetchProjectsByIds(e),g=this.projectAggregates(e),h=this.configAssetRows(a,aG(b)),i=[];for(let[b,e]of c){let c=e.flatMap(a=>d.get(a.id)??[]),j=e.some(a=>"sample"!==N(a.attributes,{}).provenance)&&"claudecode"===b&&h.length>0?[...c,...h].sort((a,b)=>a.name.localeCompare(b.name)):c;if(a&&0===j.length)continue;let k=e[0];if(!k)continue;let l=N(k.attributes,{}),m=[...new Set(e.flatMap(a=>N(a.attributes,{}).projectIds??[]))].map(a=>f.get(a)).filter(a=>void 0!==a).map(a=>{let b=g.get(a.id)??aE;return aN(a,b.accessCounts,b.findingsCount)}),n=e.reduce((a,b)=>a+(N(b.attributes,{}).sessions??0),0),o=j.reduce((a,b)=>a+N(b.flagsJson,[]).length,0),p=new Map;for(let a of j){let b=p.get(a.assetType);b?b.push(aH(a)):p.set(a.assetType,[aH(a)])}let q=aA.filter(a=>p.has(a)).map(a=>({type:a,assets:p.get(a)??[]}));i.push({id:b,label:l.label??aD[b],kind:l.kind??l.provider??b,version:l.harness_version??k.harnessVersion??"",sessions:n,assetCount:j.length,flagCount:o,projects:m,categories:q})}return Promise.resolve({items:i})}listAssets(a){let b=this.fetchAssets(a.type,a.q);if(0===b.length)return Promise.resolve({groups:[]});let c=new Map;for(let a of b){let b=c.get(a.assetType);b?b.push(a):c.set(a.assetType,[a])}let d=[...c.entries()].map(([a,b])=>{let c=new Map;for(let a of b)for(let b of N(a.flagsJson,[]))c.set(b,(c.get(b)??0)+1);let d={type:a,total:b.length,flagRollup:Object.fromEntries(c),items:b.map(aH)};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)=>aA.indexOf(a.type)-aA.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:N(a.flagsJson,[]),description:a.description??null,trust:"mcp"===a.assetType?a.effectiveTrust??null:null,meta:N(a.metaJson,{}),finding:null};if("mcp"===a.assetType&&null!==a.toolsJson){let c=N(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)??aE;return aN(a,b.accessCounts,b.findingsCount)})})}getProjectTree(a,b){let c=this.fetchProjectById(a);if(!c)return Promise.resolve(null);let d=N(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(aO)})}if(void 0!==b.q&&""!==b.q)return Promise.resolve({project:e,path:f,files:this.fetchProjectFilesSearch(a,b.q).map(aO)});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(aO)})}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=N(c.attributes,{});return Promise.resolve({...aO(d),project:{repo:c.url??"",visibility:e.visibility??"private",language:e.language??"",policyDefault:e.policyDefault??"approved",updatedAt:new Date(c.lastSeen).toISOString()},findingsRefs:[]})}setFileAccess(a,b,c){let e=this.fetchProjectFile(a,b);return!!e&&(c===e.defaultAccess?this.db.prepare("DELETE FROM file_access_override WHERE project_id = ? AND path = ?").run(a,b):this.db.prepare(`INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
376
- VALUES (:id, :projectId, :path, :access, :now, :now)
377
- ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`).run({id:(0,d.randomUUID)(),projectId:a,path:b,access:c,now:Date.now()}),!0)}setMcpTrust(a,b){let c=this.fetchAssetById(a);return c?"mcp"!==c.assetType?"not_mcp":(b===c.trust?this.db.prepare("DELETE FROM mcp_trust_override WHERE asset_id = ?").run(a):this.db.prepare(`INSERT INTO mcp_trust_override (id, asset_id, trust, created_at, updated_at)
378
- VALUES (:id, :assetId, :trust, :now, :now)
379
- ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`).run({id:(0,d.randomUUID)(),assetId:a,trust:b,now:Date.now()}),this.configRowsCache=void 0,"ok"):"not_found"}fetchHarnessRows(){return v(this.db.prepare(`SELECT id, title, attributes, harness_version AS harnessVersion
380
- FROM inventory
381
- WHERE object_type = 'harness'
382
- 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 (${m(a.length)})`;if(b){let a=n(b);e+=` AND ${o(["a.name","a.sub"])}`,d.push(a,a)}for(let a of v(this.db.prepare(`SELECT ha.harness_id AS harnessInvId, a.id, a.asset_type AS assetType, a.name, a.sub,
383
- a.description, a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
384
- a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
385
- FROM harness_asset ha
386
- JOIN inventory_asset a ON a.id = ha.asset_id
387
- LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
388
- WHERE ${e}
389
- 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 (${m(a.length)})`),d.push(...a)),b){let a=n(b);c.push(o(["a.name","a.sub"])),d.push(a,a)}let e=c.length?`WHERE ${c.join(" AND ")}`:"",f=this.mapAssetRows(v(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
390
- a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
391
- a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
392
- FROM inventory_asset a
393
- LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
394
- ${e}
395
- 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(v(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
396
- a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
397
- a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
398
- FROM inventory_asset a
399
- LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
400
- 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??aG(this.fetchHarnessRows())))return[];let b=this.latestConfigScanId();if(null===b)return[];if(this.configRowsCache?.scanId===b)return this.configRowsCache.rows;let c=new ab(this.db).report(),d=[...c.skills.map(aI),...c.hooks.map(aJ),...c.mcpServers.map(aK),...c.configFiles.map(aL)].sort((a,b)=>a.name.localeCompare(b.name));return this.configRowsCache={scanId:b,rows:d},d}latestConfigScanId(){return aa(this.db)?.id??null}fetchProjects(a){let b=`SELECT id, url, name, attributes, last_seen AS lastSeen FROM source_project
401
- WHERE ${aC}`,c=[];if(a){let d=n(a);b+=` AND ${o(["name","url"])}`,c.push(d,d)}return b+=" ORDER BY name ASC",v(this.db.prepare(b),c)}fetchProjectById(a){return w(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 v(this.db.prepare(`SELECT id, url, name, attributes, last_seen AS lastSeen
402
- FROM source_project WHERE id IN (${m(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 v(this.db.prepare(`SELECT f.project_id AS projectId,
403
- coalesce(o.access, f.default_access) AS eff,
404
- count(*) AS n,
405
- coalesce(sum(f.findings_count), 0) AS findings
406
- FROM project_file f
407
- LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
408
- WHERE f.project_id IN (${m(a.length)})
409
- 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,
410
- f.findings_count AS findingsCount, f.blocked_at AS blockedAtMs, f.note,
411
- coalesce(o.access, f.default_access) AS effectiveAccess,
412
- o.access AS overrideAccess
413
- FROM project_file f
414
- LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
415
- 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(v(this.db.prepare(this.fileSelect("f.project_id = ? ORDER BY f.path ASC")),[a])):this.mapFileRows(v(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path LIKE ? ESCAPE '\\' ORDER BY f.path ASC")),[a,`${l(b)}/%`]))}fetchProjectFilesSearch(a,b){let c=n(b);return this.mapFileRows(v(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(v(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(v(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path = ?")),[a,b]))[0]??null}}class aQ{constructor(a){this.db=a}readPolicies(){return Promise.resolve(B(v(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 h.PEm.parse({id:a.id,scope:a.scope,target:b,action:a.action,enabled:x(a.enabled),customKeywords:c})}))}seedDefaults(){if(z(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)
416
- VALUES (:id, 'global', :target, :action, 1, :now, :now)`);r(this.db,()=>{for(let[b,c]of Object.entries(h.unw))a.run({id:(0,d.randomUUID)(),target:JSON.stringify({category:b}),action:c,now:Date.now()})})}upsertCategoryAction(a,b){let c=Date.now();this.db.prepare(`INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
417
- VALUES (:id, 'global', :target, :action, 1, :now, :now)
418
- ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`).run({id:(0,d.randomUUID)(),target:JSON.stringify({category:a}),action:b,now:c})}capCategoryActions(){return Number(this.db.prepare(`UPDATE policies SET action='warn', updated_at=:now
419
- WHERE scope='global' AND action IN ('block','redact')
420
- 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 aR{constructor(a){this.packs=a}getPolicyList(a){if("custom"===a)return Promise.resolve({items:[]});let b=this.packs.countsByPolicyId();return Promise.resolve({items:h.RRF.map(a=>({id:a,kind:"builtin",name:h.ZpU[a].name,enabled:!0,usedByCount:b.get(a)??0}))})}getPolicyStats(){let a=this.packs.countsByPolicyId(),b=h.V0H.reduce((b,c)=>b+(a.get(c)??0),0),c=h.V0H.length;return Promise.resolve({policies:c,builtin:c,custom:0,detectionsGoverned:b})}getPolicyDetail(a){let b=h.V0H.find(b=>b===a);if(void 0===b)return Promise.resolve(null);let c=h.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 aS{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
421
- (id, project_id, path, name, origin, default_access, findings_count, blocked_at, note, created_at, updated_at)
422
- VALUES
423
- (:id, :projectId, :path, :name, :origin, :defaultAccess, 0, NULL, NULL, :now, :now)
424
- ON CONFLICT (project_id, path) DO UPDATE SET
425
- name = excluded.name,
426
- origin = excluded.origin,
427
- default_access = excluded.default_access,
428
- updated_at = excluded.updated_at`),this.pruneStmt=a.prepare("DELETE FROM project_file WHERE project_id = :projectId AND updated_at < :now")}replaceForProject(a,b,c){let e=Math.max(c,(w(this.maxStampStmt,{projectId:a})?.maxStamp??0)+1);for(let c of b.files)this.upsertStmt.run({id:(0,d.randomUUID)(),projectId:a,path:c.path,name:c.name,origin:c.origin,defaultAccess:c.defaultAccess,now:e});b.truncated||this.pruneStmt.run({projectId:a,now:e})}}class aT{constructor(a,b=()=>Date.now()){this.db=a,this.now=b,this.insertStmt=a.prepare(`INSERT INTO finding_resolution (id, finding_key, status, method, resolved_at, evidence, created_at)
429
- VALUES (:id, :findingKey, :status, :method, :resolvedAt, :evidence, :createdAt)`),this.latestStmt=a.prepare(`SELECT status, method, resolved_at, evidence
430
- FROM finding_resolution
431
- WHERE finding_key = :findingKey
432
- ORDER BY created_at DESC, rowid DESC
433
- LIMIT 1`),this.openAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
434
- FROM inspection_findings f
435
- JOIN audit_events e ON e.id = f.audit_event_id
436
- WHERE e.event_type = 'code_change'
437
- AND json_extract(e.attributes, '$.file_path') = :path
438
- AND f.finding_key IS NOT NULL
439
- AND ${ao("f")} IS NOT 'resolved'`),this.resolvedAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
440
- FROM inspection_findings f
441
- JOIN audit_events e ON e.id = f.audit_event_id
442
- WHERE e.event_type = 'code_change'
443
- AND json_extract(e.attributes, '$.file_path') = :path
444
- AND f.finding_key IS NOT NULL
445
- AND ${ao("f")} = 'resolved'`)}insertResolution(a){this.insertStmt.run({id:(0,d.randomUUID)(),findingKey:a.findingKey,status:h.GCf.parse(a.status),method:h.cqq.parse(a.method),resolvedAt:a.resolvedAt,evidence:a.evidence,createdAt:this.now()})}latestByKey(a){let b=w(this.latestStmt,{findingKey:a});if(b)return{status:b.status,method:b.method,resolvedAt:b.resolved_at,evidence:b.evidence??""}}openAtRestKeysForPath(a){return v(this.openAtRestStmt,{path:a}).map(a=>a.finding_key)}resolvedAtRestKeysForPath(a){return v(this.resolvedAtRestStmt,{path:a}).map(a=>a.finding_key)}}class aU{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO rule_probe_cache (rule_key, verdict, worst_probe_ms, checked_at)
446
- VALUES (:ruleKey, :verdict, :worstProbeMs, :checkedAt)
447
- ON CONFLICT (rule_key) DO UPDATE SET
448
- verdict = excluded.verdict,
449
- worst_probe_ms = excluded.worst_probe_ms,
450
- checked_at = excluded.checked_at`),this.readStmt=a.prepare("SELECT verdict, worst_probe_ms AS worstProbeMs FROM rule_probe_cache WHERE rule_key = :ruleKey")}getVerdict(a){return w(this.readStmt,{ruleKey:a})}setVerdict(a,b,c){r(this.db,()=>{this.upsertStmt.run({ruleKey:a,verdict:b,worstProbeMs:c,checkedAt:Date.now()})})}}class aV{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
451
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
452
- ON CONFLICT (path) DO UPDATE SET
453
- mtime = excluded.mtime,
454
- content_hash = excluded.content_hash,
455
- ruleset_hash = excluded.ruleset_hash,
456
- scanned_at = excluded.scanned_at`),this.readStmt=a.prepare(`SELECT path, mtime, content_hash AS contentHash
457
- FROM scan_ledger WHERE ruleset_hash = :rulesetHash`)}entriesForRuleset(a){return new Map(v(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();r(this.db,()=>{for(let c of a)this.upsertStmt.run({path:c.path,mtime:c.mtime,contentHash:c.contentHash,rulesetHash:c.rulesetHash,scannedAt:b})})}}let aW=`
458
- pointer_id AS pointerId,
459
- value_fingerprint AS valueFingerprint,
460
- fingerprint_key_version AS fingerprintKeyVersion,
461
- key_version AS keyVersion,
462
- format_version AS formatVersion,
463
- category,
464
- rule_id AS ruleId,
465
- masked_match AS maskedMatch,
466
- provider,
467
- ciphertext,
468
- nonce,
469
- auth_tag AS authTag,
470
- occurrence_count AS occurrenceCount,
471
- first_seen AS firstSeen,
472
- last_seen AS lastSeen`;function aX(a){let{provider:b,...c}=a;return null===b?c:{...c,provider:b}}class aY{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO secret_vault (
473
- pointer_id, value_fingerprint, fingerprint_key_version, key_version,
474
- format_version, category, rule_id, masked_match, provider,
475
- ciphertext, nonce, auth_tag,
476
- occurrence_count, first_seen, last_seen
477
- ) VALUES (
478
- :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
479
- :formatVersion, :category, :ruleId, :maskedMatch, :provider,
480
- :ciphertext, :nonce, :authTag,
481
- 1, :now, :now
482
- )`),this.bumpStmt=a.prepare(`UPDATE secret_vault
483
- SET occurrence_count = occurrence_count + 1, last_seen = :now
484
- WHERE value_fingerprint = :valueFingerprint`),this.byPointerStmt=a.prepare(`SELECT ${aW} FROM secret_vault WHERE pointer_id = :pointerId`),this.byFingerprintStmt=a.prepare(`SELECT ${aW} FROM secret_vault WHERE value_fingerprint = :valueFingerprint`),this.listStmt=a.prepare(`SELECT ${aW} FROM secret_vault ORDER BY first_seen`),this.replaceCiphertextStmt=a.prepare(`UPDATE secret_vault
485
- SET key_version = :keyVersion, ciphertext = :ciphertext, nonce = :nonce, auth_tag = :authTag
486
- WHERE pointer_id = :pointerId`),this.refreshFingerprintStmt=a.prepare(`UPDATE secret_vault
487
- SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
488
- WHERE pointer_id = :pointerId`),this.derefStmt=a.prepare(`INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
489
- VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`)}upsert(a,b){let c=!1;q(this.db,()=>{if(void 0===w(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint})){this.insertStmt.run(y({pointerId:a.pointerId,valueFingerprint:a.valueFingerprint,fingerprintKeyVersion:a.fingerprintKeyVersion,keyVersion:a.keyVersion,formatVersion:a.formatVersion??h.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=w(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint});if(void 0===d)throw Error("vault: row vanished immediately after write");return{row:aX(d),minted:c}}byPointerId(a){let b=w(this.byPointerStmt,{pointerId:a});return void 0===b?null:aX(b)}byValueFingerprint(a){let b=w(this.byFingerprintStmt,{valueFingerprint:a});return void 0===b?null:aX(b)}recordDeref(a){this.derefStmt.run(y({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 v(this.listStmt).map(aX)}replaceCiphertext(a,b){this.replaceCiphertextStmt.run({pointerId:a,...b})}refreshFingerprint(a,b){this.refreshFingerprintStmt.run({pointerId:a,...b})}purgeAll(){let a=0;return q(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)
490
- VALUES (:id, :pointerId, :location, :kind, :now, :now)
491
- ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`).run({id:(0,d.randomUUID)(),pointerId:a.pointerId,location:a.location,kind:a.kind,now:b})}listSightings(a){return v(this.db.prepare(`SELECT location, kind, first_seen, last_seen FROM secret_vault_sighting
492
- WHERE pointer_id = :pointerId ORDER BY last_seen DESC`),{pointerId:a}).map(a=>({location:a.location,kind:a.kind,firstSeen:new Date(a.first_seen).toISOString(),lastSeen:new Date(a.last_seen).toISOString()}))}listInventory(a=Date.now()){return v(this.db.prepare(`SELECT v.pointer_id, v.category, v.rule_id, v.masked_match, v.provider,
493
- v.occurrence_count, v.first_seen, v.last_seen,
494
- (SELECT e.id FROM exceptions e
495
- WHERE e.rule_id = v.rule_id
496
- AND e.value_fingerprint = v.value_fingerprint
497
- AND e.key_version = v.fingerprint_key_version
498
- AND ${al}
499
- LIMIT 1) AS grant_id
500
- FROM secret_vault v
501
- ORDER BY v.last_seen DESC`),{now: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:this.listSightings(a.pointer_id)}))}listDerefs(a){let b=a?.limit??200,c=a?.includeBatched===!0?"":"WHERE reason NOT IN ('display', 'view-render')",d=v(this.db.prepare(`SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
502
- FROM secret_vault_deref ${c}
503
- ORDER BY at DESC, rowid DESC LIMIT :limit`),{limit:b}),e=a?.includeBatched===!0?0:z(this.db,"SELECT count(*) AS n FROM secret_vault_deref WHERE reason IN ('display', 'view-render')");return{rows:d.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})),hiddenBatched:e}}countEntries(){return z(this.db,"SELECT COUNT(*) AS n FROM secret_vault")}}let aZ=["critical","high","medium","low"],a$={block:"blocked",redact:"redacted",warn:"warned"},a_=["blocked","redacted","warned"],a0=[{provider:"claudecode",coverage:100,supported:!0},{provider:"cursor",coverage:0,supported:!1},{provider:"codex",coverage:0,supported:!1},{provider:"chatgpt",coverage:0,supported:!1},{provider:"copilot",coverage:0,supported:!1},{provider:"api",coverage:0,supported:!1}],a1={"7d":"day","30d":"day","3m":"week","6m":"week"};function a2(a){return 864e5*Math.floor(a/864e5)}function a3(a){return new Date(a).toISOString().slice(0,10)}class a4{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}severitySummary(){let a=new Map(v(this.db.prepare(`SELECT d.severity AS severity,
504
- COUNT(*) AS count,
505
- SUM(CASE
506
- WHEN e.event_type != 'code_change' THEN 1
507
- WHEN f.finding_key IS NULL THEN 0
508
- WHEN latest.status = 'resolved' THEN 1
509
- ELSE 0
510
- END) AS caught,
511
- SUM(CASE
512
- WHEN e.event_type = 'code_change'
513
- AND f.finding_key IS NOT NULL
514
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
515
- ELSE 0
516
- END) AS open_at_rest
517
- FROM inspection_findings f
518
- JOIN audit_events e ON e.id = f.audit_event_id
519
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
520
- LEFT JOIN ${ap} latest
521
- ON latest.finding_key = f.finding_key
522
- WHERE e.event_type IN (${h.hfB})
523
- GROUP BY d.severity`)).map(a=>[a.severity,a])),b=aZ.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:a0.map(a=>({...a}))})}enforcementActions(a){let b=864e5*h.eI7[a],c=this.now(),d=c-b,e=this.findingsInRange(c-2*b,c),f={blocked:0,redacted:0,warned:0},g={blocked:0,redacted:0,warned:0};for(let a of e){let b=a$[a.actionTaken];b&&(a.occurredAt>=d?f[b]++:g[b]++)}let i=a_.map(a=>({kind:a,count:f[a],delta:f[a]-g[a]}));return Promise.resolve({range:a,total:i.reduce((a,b)=>a+b.count,0),actions:i})}findingsTimeseries(a){let b=a1[a],c=("day"===b?1:7)*864e5,d=h.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),g=a2(f)-(d-1)*864e5,i=this.findingsInRange(g,f),j=Array.from({length:e},(a,b)=>({timestamp:a3(g+b*c),critical:0,high:0,medium:0}));for(let a of i){let b=j[Math.floor((a.occurredAt-g)/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=a1[a],c=("day"===b?1:7)*864e5,d=h.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),g=a2(f)-(d-1)*864e5,i=v(this.db.prepare(`SELECT COALESCE(f.first_detected_at, e.started_at) AS first_detected_at, d.severity AS severity,
524
- latest.status AS latest_status,
525
- latest.method AS latest_method,
526
- latest.resolved_at AS latest_resolved_at
527
- FROM inspection_findings f
528
- JOIN audit_events e ON e.id = f.audit_event_id
529
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
530
- LEFT JOIN ${ap} latest
531
- ON latest.finding_key = f.finding_key
532
- WHERE f.finding_key IS NOT NULL
533
- AND e.event_type IN (${h.hfB})
534
- AND EXISTS (
535
- SELECT 1 FROM finding_resolution fr
536
- WHERE fr.finding_key = f.finding_key
537
- AND fr.resolved_at >= :windowStart
538
- )`),{windowStart:g}),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<g||a.latest_resolved_at>=f)continue;let b=Math.floor((a.latest_resolved_at-g)/c);if(b<0||b>=e)continue;let d=`${String(b)}:${a.severity}`,h=Math.max(0,a.latest_resolved_at-a.first_detected_at);j.set(d,(j.get(d)??0)+h),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 aZ){let c=`${String(b)}:${a}`,e=k.get(c)??0;d[a]=e>0?(j.get(c)??0)/e:null}return{timestamp:a3(g+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*h.eI7[a];return Promise.resolve({range:a,items:v(this.db.prepare(`SELECT json_extract(e.attributes, '$.repo') AS repo, count(*) AS c
539
- FROM inspection_findings f
540
- JOIN audit_events e ON e.id = f.audit_event_id
541
- WHERE e.started_at >= :from AND e.started_at < :to
542
- AND e.event_type IN (${h.hfB})
543
- AND json_extract(e.attributes, '$.repo') IS NOT NULL
544
- AND json_extract(e.attributes, '$.repo') != ''
545
- GROUP BY repo
546
- ORDER BY c DESC, repo
547
- 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:v(this.db.prepare(`SELECT f.finding_key AS finding_key,
548
- d.rule_id AS rule_id,
549
- d.severity AS severity,
550
- json_extract(e.attributes, '$.file_path') AS path,
551
- COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
552
- latest.resolved_at AS latest_resolved_at
553
- FROM inspection_findings f
554
- JOIN audit_events e ON e.id = f.audit_event_id
555
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
556
- LEFT JOIN ${ap} latest
557
- ON latest.finding_key = f.finding_key
558
- WHERE e.event_type = 'code_change'
559
- AND f.finding_key IS NOT NULL
560
- AND latest.status = 'resolved'
561
- AND latest.method = 'fixed-at-source'
562
- AND latest.resolved_at IS NOT NULL
563
- ORDER BY latest_resolved_at DESC
564
- 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 v(this.db.prepare(`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
565
- FROM inspection_findings f
566
- JOIN audit_events e ON e.id = f.audit_event_id
567
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
568
- WHERE e.started_at >= :from AND e.started_at < :to
569
- AND e.event_type IN (${h.hfB})
570
- ORDER BY e.started_at`),{from:a,to:b}).map(a=>({occurredAt:a.occurred_at,severity:a.severity,actionTaken:a.action_taken}))}}let a5=["provider","internal","external","ip"],a6="('http', 'ws')",a7=`LEFT JOIN egress_decision_override oh ON oh.host = d.host
571
- LEFT JOIN egress_decision_override ol ON ol.destination_id = d.id AND ol.host IS NULL`;function a8(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 a9(a,b){let c=b.map(a=>a.transport),d=b.map(a=>a.dataClass),e=b.reduce((a,b)=>a+b.callSiteCount,0),f=b.length>0?Math.max(...b.map(a=>a.lastSeenMs)):a.lastSeenMs;return{id:a.id,kind:a.kind,name:a.name,host:a.host,category:a.category,trust:a.trust,status:(0,h.Gw9)(a.trust,a.overrideDecision),isCustom:(0,h.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(f).toISOString(),endpointCount:b.length,callSiteCount:e,transports:(0,h.by7)(c),dataClasses:(0,h.hzO)(d),review:(0,h.Fnc)(a.trust,c),network:"provider"===a.kind?null:N(a.networkJson,null),endpoints:b.map(a8)}}class ba{constructor(a){this.db=a}stats(){let a=z(this.db,"SELECT count(*) AS n FROM share_destination"),b=z(this.db,"SELECT count(*) AS n FROM share_endpoint"),c=z(this.db,"SELECT count(*) AS n FROM share_call_site"),d=z(this.db,`SELECT count(DISTINCT destination_id) AS n FROM share_endpoint
572
- WHERE transport IN ${a6}`),e=z(this.db,`SELECT count(DISTINCT d.id) AS n
573
- FROM share_destination d
574
- LEFT JOIN share_endpoint e ON e.destination_id = d.id
575
- AND e.transport IN ${a6}
576
- WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`),f=A(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=A(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=>a9(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:a5.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:a9(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,h.C05)(b.map(a=>a.dataClass)),callSiteCount:a.callSiteCount,lastSeen:a.lastSeen})).sort((a,b)=>{let c=(0,h.WSs)(a.review.reasons)-(0,h.WSs)(b.review.reasons);return 0!==c?c:b.lastSeen.localeCompare(a.lastSeen)})})}getDestination(a){let b=this.fetchDestinationById(a);if(!b)return Promise.resolve(null);let c=this.fetchEndpoints([b.id]),d=this.fetchCallSites(c.map(a=>a.id));return Promise.resolve(function(a,b,c){let d=b.map(a=>a.transport),e=b.length>0?Math.max(...b.map(a=>a.lastSeenMs)):a.lastSeenMs,f=new Map;for(let a of c.slice(0,200)){let b={id:a.id,project:a.project,file:a.file,line:a.line,snippet:a.snippet,dynamic:a.dynamic,vendored:a.vendored,projectId:a.projectId},c=f.get(a.endpointId);c?c.push(b):f.set(a.endpointId,[b])}return{id:a.id,kind:a.kind,name:a.name,host:a.host,category:a.category,trust:a.trust,status:(0,h.Gw9)(a.trust,a.overrideDecision),isCustom:(0,h.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(e).toISOString(),transports:(0,h.by7)(d),dataClasses:(0,h.hzO)(b.map(a=>a.dataClass)),review:(0,h.Fnc)(a.trust,d),network:"provider"===a.kind?null:N(a.networkJson,null),note:a.note,endpoints:b.map(a=>({...a8(a),sites:f.get(a.id)??[]}))}}(b,c,d))}setEgressDecision(a,b){let c=!1;return q(this.db,()=>{let e=this.db.prepare("SELECT host FROM share_destination WHERE id = ?").get(a);void 0!==e&&(c=!0,this.db.prepare(`DELETE FROM egress_decision_override
577
- WHERE host = :host OR (destination_id = :destinationId AND host IS NULL)`).run({host:e.host,destinationId:a}),null!==b&&this.db.prepare(`INSERT INTO egress_decision_override
578
- (id, destination_id, host, decision, created_at, updated_at)
579
- VALUES (:id, :destinationId, :host, :decision, :now, :now)`).run({id:(0,d.randomUUID)(),destinationId:a,host:e.host,decision:b,now:Date.now()}))},"IMMEDIATE"),c}recordProjectEgress(a){let{hits:b,droppedFiles:c,truncated:d}=function(a,b){if(a.length<=5e3)return{hits:[...a],droppedFiles:[],truncated:!1};if("walk"===b)return{hits:a.slice(0,5e3),droppedFiles:[],truncated:!0};let c=new Map;for(let b of a){let a=c.get(b.site.file);void 0===a?c.set(b.site.file,[b]):a.push(b)}let d=[],e=[];for(let[a,b]of c)d.length+b.length>5e3?e.push(a):d.push(...b);return{hits:d,droppedFiles:e,truncated:!0}}(a.hits,a.reconcile.mode),e=function(a,b){if("walk"===a.mode||0===b.length)return a;let c=new Set(b);return{mode:"ledger",scannedFiles:a.scannedFiles.filter(a=>!c.has(a)),deletedFiles:a.deletedFiles.filter(a=>!c.has(a))}}(a.reconcile,c),f=Date.now(),g={destinations:0,endpoints:0,callSites:0,truncated:d,droppedFiles:c};return q(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
580
- WHERE project_key = :key
581
- AND (:prefix = '' OR file = :prefix OR file LIKE :subtree ESCAPE '\\')
582
- AND file NOT LIKE '.%'
583
- AND file NOT LIKE '%/.%'`).run({key:a,prefix:c,subtree:`${l(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
584
- WHERE project_key = ? AND file IN (${m(d.length)})`).run(a,...d)}}upsertHits(a,b,c,e){if(0===b.length)return;let f=this.db.prepare(`INSERT INTO share_destination
585
- (id, kind, name, host, category, trust, network_json, last_seen, provenance,
586
- created_at, updated_at)
587
- VALUES (:id, :kind, :name, :host, :category, :trust, :networkJson, :now, 'scan', :now, :now)
588
- ON CONFLICT (host) DO UPDATE SET
589
- kind = excluded.kind,
590
- name = excluded.name,
591
- category = excluded.category,
592
- trust = excluded.trust,
593
- network_json = excluded.network_json,
594
- last_seen = excluded.last_seen,
595
- updated_at = excluded.updated_at`),g=this.db.prepare("SELECT id FROM share_destination WHERE host = ?"),h=this.db.prepare(`INSERT INTO share_endpoint
596
- (id, destination_id, method, transport, url, template, data_class, last_seen,
597
- created_at, updated_at)
598
- VALUES (:id, :destinationId, :method, :transport, :url, :template, :dataClass, :now,
599
- :now, :now)
600
- ON CONFLICT (destination_id, method, url) DO UPDATE SET
601
- transport = excluded.transport,
602
- template = excluded.template,
603
- data_class = excluded.data_class,
604
- last_seen = excluded.last_seen,
605
- updated_at = excluded.updated_at`),i=this.db.prepare("SELECT id FROM share_endpoint WHERE destination_id = ? AND method = ? AND url = ?"),j=this.db.prepare(`INSERT INTO share_call_site
606
- (id, endpoint_id, project, project_key, file, line, snippet, dynamic, vendored,
607
- project_id, created_at, updated_at)
608
- VALUES (:id, :endpointId, :project, :projectKey, :file, :line, :snippet, :dynamic,
609
- :vendored, :projectId, :now, :now)
610
- ON CONFLICT (endpoint_id, project_key, file, line) DO UPDATE SET
611
- snippet = excluded.snippet,
612
- dynamic = excluded.dynamic,
613
- vendored = excluded.vendored,
614
- project = excluded.project,
615
- project_id = COALESCE(excluded.project_id, share_call_site.project_id),
616
- updated_at = excluded.updated_at`),k=new Map,l=new Map;for(let m of b){let b=k.get(m.host);void 0===b&&(f.run({id:(0,d.randomUUID)(),kind:m.kind,name:m.name,host:m.host,category:m.category,trust:m.trust,networkJson:null===m.network?null:JSON.stringify(m.network),now:e}),b=w(g,[m.host])?.id??"",k.set(m.host,b));let n=`${b}\0${m.method}\0${m.url}`,o=l.get(n);void 0===o&&(h.run({id:(0,d.randomUUID)(),destinationId:b,method:m.method,transport:m.transport,url:m.url,template:+!!m.template,dataClass:m.dataClass,now:e}),o=w(i,[b,m.method,m.url])?.id??"",l.set(n,o)),j.run({id:(0,d.randomUUID)(),endpointId:o,project:a.project,projectKey:a.projectKey,file:m.site.file,line:m.site.line,snippet:m.site.snippet,dynamic:+!!m.site.dynamic,vendored:+!!m.site.vendored,projectId:c,now:e})}}knownProjectId(a){return w(this.db.prepare(`SELECT project_id AS projectId FROM share_call_site
617
- 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
618
- 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
619
- WHERE id IN (SELECT DISTINCT e.destination_id
620
- FROM share_endpoint e
621
- JOIN share_call_site c ON c.endpoint_id = e.id
622
- WHERE c.project_key = :key)`).run({now:b,key:a})}pruneOrphans(){this.db.exec(`DELETE FROM share_endpoint
623
- 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
624
- WHERE host IS NULL
625
- AND destination_id IN (
626
- SELECT d.id FROM share_destination d
627
- WHERE NOT EXISTS (SELECT 1 FROM share_endpoint e WHERE e.destination_id = d.id))`),this.db.exec(`DELETE FROM share_destination
628
- WHERE NOT EXISTS (
629
- SELECT 1 FROM share_endpoint e WHERE e.destination_id = share_destination.id)`)}projectTotals(a){return{destinations:z(this.db,`SELECT count(DISTINCT e.destination_id) AS n
630
- FROM share_endpoint e
631
- JOIN share_call_site c ON c.endpoint_id = e.id
632
- WHERE c.project_key = ?`,[a]),endpoints:z(this.db,"SELECT count(DISTINCT endpoint_id) AS n FROM share_call_site WHERE project_key = ?",[a]),callSites:z(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,
633
- d.network_json AS networkJson, d.last_seen AS lastSeenMs,
634
- d.created_at AS createdAt,
635
- COALESCE(oh.decision, ol.decision) AS overrideDecision`,f=[],g=[];if(b&&b.length>0&&(f.push(`d.kind IN (${m(b.length)})`),g.push(...b)),c&&f.push(`(d.trust IN ('unverified', 'ip')
636
- OR EXISTS (SELECT 1 FROM share_endpoint re
637
- WHERE re.destination_id = d.id
638
- AND re.transport IN ${a6}))`),a){let b=n(a);f.push(`(d.name LIKE ? ESCAPE '\\' OR d.category LIKE ? ESCAPE '\\' OR e.url LIKE ? ESCAPE '\\'
639
- OR c.project LIKE ? ESCAPE '\\' OR c.file LIKE ? ESCAPE '\\')`),g.push(b,b,b,b,b),d=`SELECT DISTINCT ${e}
640
- FROM share_destination d
641
- ${a7}
642
- LEFT JOIN share_endpoint e ON e.destination_id = d.id
643
- LEFT JOIN share_call_site c ON c.endpoint_id = e.id
644
- ${f.length?`WHERE ${f.join(" AND ")}`:""}
645
- ORDER BY d.created_at ASC, d.id ASC`}else d=`SELECT ${e}
646
- FROM share_destination d
647
- ${a7}
648
- ${f.length?`WHERE ${f.join(" AND ")}`:""}
649
- ORDER BY d.created_at ASC, d.id ASC`;return v(this.db.prepare(d),g).map(a=>this.mapDestRow(a))}fetchDestinationById(a){let b=w(this.db.prepare(`SELECT d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
650
- d.network_json AS networkJson, d.last_seen AS lastSeenMs,
651
- COALESCE(oh.decision, ol.decision) AS overrideDecision
652
- FROM share_destination d
653
- ${a7}
654
- WHERE d.id = ?`),[a]);return b?this.mapDestRow(b):null}fetchEndpoints(a){return 0===a.length?[]:v(this.db.prepare(`SELECT e.id, e.destination_id AS destinationId, e.method, e.transport, e.url,
655
- e.template, e.data_class AS dataClass, e.last_seen AS lastSeenMs,
656
- count(c.id) AS callSiteCount
657
- FROM share_endpoint e
658
- LEFT JOIN share_call_site c ON c.endpoint_id = e.id
659
- WHERE e.destination_id IN (${m(a.length)})
660
- GROUP BY e.id
661
- 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?[]:v(this.db.prepare(`SELECT id, endpoint_id AS endpointId, project, file, line, snippet, dynamic, vendored,
662
- project_id AS projectId
663
- FROM share_call_site
664
- WHERE endpoint_id IN (${m(a.length)})
665
- 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
666
- (id, url, name, attributes, first_seen, last_seen)
667
- VALUES
668
- (:id, :url, :name, :attributes, :firstSeen, :lastSeen)
669
- ON CONFLICT(id) DO UPDATE SET
670
- url = excluded.url,
671
- name = excluded.name,
672
- attributes = excluded.attributes,
673
- last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){let c=j(a.url),d=(0,h.QCA)(a,c,b);return this.upsertStmt.run(y({id:d.id,url:d.url,name:d.name,attributes:d.attributes,firstSeen:d.firstSeen,lastSeen:d.lastSeen})),c}findById(a){return w(this.db.prepare("SELECT * FROM source_project WHERE id = :id"),{id:a})}distinctNames(){return v(this.db.prepare(`SELECT DISTINCT name FROM source_project
674
- WHERE name IS NOT NULL
675
- ORDER BY name`)).map(a=>a.name)}}function bc(a,b){return b?{...a,hostId:b}:a}function bd(a){try{a.close()}catch{}}function be(a){let b=new g.DatabaseSync(a);try{b.exec("PRAGMA journal_mode = WAL"),b.exec("PRAGMA busy_timeout = 2000"),b.exec("PRAGMA foreign_keys = ON")}catch(a){throw bd(b),a}return b}function bf(a){E(a);let{db:b,events:c,findings:g,policies:m,installedPacks:n,scanLedger:o,secretVault:p,exceptions:v,resolutions:w,ruleProbeCache:x,security:z,detections:A,shares:B,policyCatalog:H,inventory:N,inventoryAssets:O,projectFiles:P,activity:Q,sourceProject:R,auditEvents:S,classifiedData:T,inspectionDefinitions:U,inspectionFindings:V,configInventory:W}=function(a){let b=be(a);try{var c;if(c=b,t(c,"table","tenants")||u(c,"events").includes("tenant_id")){b.close();let c=function(a){let b=`${a}.legacy.${String(Date.now())}.bak`;for(let c of((0,e.renameSync)(a,b),G(b),F(a)))(0,e.existsSync)(c)&&(0,e.rmSync)(c);return b}(a);b=be(a),s(`Detected an older, incompatible (tenant-bearing) ${C}; backed it up to ${c} and created a fresh store.`)}for(let c of(!function(a,b){var c,d,e;let f=a.prepare("PRAGMA user_version").get().user_version;a.exec("CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)");let g=new Set(a.prepare("SELECT tag FROM migration_ledger").all().map(a=>a.tag)),i=0===g.size&&f>0,l=a.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)");for(let[b,c]of h.lFU.entries()){if(g.has(c.tag)||c.tag===K)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?u(a,b.table,{includeGenerated:!0}).includes(b.name):t(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(I).join(", ")} while missing ${a.map(I).join(", ")} — the schema diverged from the migration history; refusing to replay or skip.`;throw s(b),Error(`[aka] ${b}`)}let h=d.length>0?e.length===d.length:i&&b<f,j=/PRAGMA foreign_keys\s*=\s*OFF/i.test(c.sql),k=J(c.sql);j&&a.exec("PRAGMA foreign_keys = OFF");try{q(a,()=>{for(let b of k){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(h)continue}else if(t(a,"index",c))continue;a.exec(b)}if(j&&!h){let b=a.prepare("PRAGMA foreign_key_check").all();if(b.length>0)throw Error(`[aka] sqlite migration ${c.tag} left ${String(b.length)} foreign-key violation(s); rolling back.`)}l.run(c.tag,Date.now())},"IMMEDIATE")}finally{j&&a.exec("PRAGMA foreign_keys = ON")}}f<h.lFU.length&&a.exec(`PRAGMA user_version = ${String(h.lFU.length)}`),c=a,d="audit_events",t(c,"table",d)&&(u(c,d).includes("synced_at")||c.exec(`ALTER TABLE ${d} ADD COLUMN synced_at integer`)),a.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
676
- path TEXT PRIMARY KEY,
677
- mtime TEXT NOT NULL,
678
- content_hash TEXT NOT NULL,
679
- ruleset_hash TEXT NOT NULL,
680
- scanned_at INTEGER NOT NULL
681
- )`),a.exec(`CREATE TABLE IF NOT EXISTS blocked_detections (
682
- reference TEXT PRIMARY KEY,
683
- rule_id TEXT NOT NULL,
684
- category TEXT NOT NULL,
685
- value_fingerprint TEXT NOT NULL,
686
- key_version INTEGER NOT NULL,
687
- masked_value TEXT NOT NULL,
688
- session_id TEXT,
689
- repo TEXT,
690
- blocked_at INTEGER NOT NULL
691
- )`),a.exec(`CREATE TABLE IF NOT EXISTS rule_probe_cache (
692
- rule_key TEXT PRIMARY KEY,
693
- verdict TEXT NOT NULL,
694
- worst_probe_ms REAL NOT NULL,
695
- checked_at INTEGER NOT NULL
696
- )`),(e=a).exec(`CREATE TABLE IF NOT EXISTS \`_pack_write_gate\` (
697
- \`id\` integer PRIMARY KEY NOT NULL,
698
- \`open\` integer DEFAULT 0 NOT NULL,
699
- CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)
700
- )`),e.exec("INSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0)"),t(e,"table","installed_packs")&&e.exec(`CREATE TRIGGER IF NOT EXISTS trg_installed_packs_write_gate
701
- BEFORE UPDATE OF version, name, rules_json ON installed_packs
702
- WHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1
703
- BEGIN SELECT RAISE(IGNORE); END`),function(a){if(!t(a,"table","audit_events"))return;let b=new Set(u(a,"audit_events",{includeGenerated:!0}));for(let c of L)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
704
- FROM source_project
705
- WHERE url IS NOT NULL AND id NOT LIKE 'sample:%'
706
- ORDER BY last_seen DESC, id`).all().map(a=>({row:a,canonicalId:j(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)
707
- VALUES (?, ?, ?, ?, ?, ?)
708
- ON CONFLICT(id) DO UPDATE SET
709
- first_seen = min(first_seen, excluded.first_seen),
710
- 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 = ?
711
- 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 = ?");q(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){s(`source_project id reconcile failed: ${String(a)}`)}}(a),!g.has(K)&&function(a){try{if(!function(a){let b=a.prepare(`SELECT rowid AS rowid, id, source_tool AS sourceTool, kind, occurred_at AS occurredAt,
712
- content_hash AS contentHash, content, metadata
713
- FROM events WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO audit_events
714
- (id, parent_id, root_session_id, event_type, started_at, content, content_hash, attributes)
715
- 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 M(a,"events",b,a=>{for(let e of a){var b;let a=function(a){if(null!==a)try{return JSON.parse(a)}catch{return}}(e.metadata),f=a?.sessionId??null;null!==f&&d.run(f,e.occurredAt),c.run(y({id:e.id,parentId:f,rootSessionId:f,eventType:e.kind,startedAt:e.occurredAt,content:e.content,contentHash:e.contentHash,attributes:(b={...e,metadata:a},JSON.stringify((0,h.$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,
716
- span_start AS spanStart, span_end AS spanEnd, masked_match AS maskedMatch,
717
- action_taken AS actionTaken, confidence, finding_key AS findingKey,
718
- first_detected_at AS firstDetectedAt
719
- FROM findings WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
720
- (id, rule_id, name, category, severity, definition, version)
721
- VALUES (:id, :ruleId, :name, :category, :severity, :definition, :version)`),d=a.prepare(`INSERT INTO inspection_findings
722
- (id, audit_event_id, inspection_definition_id, classified_data_id,
723
- span_start, span_end, masked_match, action_taken, confidence,
724
- finding_key, first_detected_at)
725
- VALUES
726
- (:id, :auditEventId, :inspectionDefinitionId, NULL,
727
- :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
728
- :findingKey, :firstDetectedAt)
729
- ON CONFLICT(id) DO NOTHING
730
- ON CONFLICT (finding_key) DO UPDATE SET
731
- first_detected_at = CASE
732
- WHEN first_detected_at IS NULL THEN excluded.first_detected_at
733
- WHEN excluded.first_detected_at IS NULL THEN first_detected_at
734
- ELSE min(first_detected_at, excluded.first_detected_at)
735
- END`);return M(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=k(e.ruleId,d),c.run(y({id:f,ruleId:e.ruleId,name:e.ruleId,category:e.category,severity:e.severity,definition:"",version:d})),b.set(a,f)}d.run(y({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 s(`legacy history backfill failed: ${String(a)}`),!1}}(a)&&function(a,b){let c=h.lFU.find(a=>a.tag===K);if(c){if(b)try{var d=a,e=b;let c=`${e}.pre-drop.${String(Date.now())}.bak`;d.prepare("VACUUM INTO ?").run(c),G(c)}catch(a){s(`legacy events/findings backup failed; deferring the drop: ${String(a)}`);return}try{q(a,()=>{if(!a.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(c.tag)){for(let b of J(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){s(`legacy events/findings drop failed; deferring: ${String(a)}`)}}}(a,b)}(b,a),[a,...F(a)]))D(c,384);let d=new aQ(b),f=new ay(b),g={events:new ag(b),findings:new ar(b),policies:d,installedPacks:f,scanLedger:new aV(b),secretVault:new aY(b),exceptions:new am(b),resolutions:new aT(b),ruleProbeCache:new aU(b),security:new a4(b),detections:new af(b),shares:new ba(b),policyCatalog:new aR(f),inventory:new az(b),inventoryAssets:new aP(b),projectFiles:new aS(b),activity:new Z(b),sourceProject:new bb(b),auditEvents:new $(b),classifiedData:new _(b),inspectionDefinitions:new as(b),inspectionFindings:new at(b),configInventory:new ab(b)};return d.seedDefaults(),{db:b,...g}}catch(a){throw bd(b),a}}((0,f.join)(a,C));return{events:c,findings:g,policies:m,installedPacks:n,scanLedger:o,secretVault:p,exceptions:v,resolutions:w,ruleProbeCache:x,security:z,detections:A,shares:B,policyCatalog:H,inventory:N,inventoryAssets:O,activity:Q,sourceProject:R,auditEvents:S,classifiedData:T,inspectionDefinitions:U,inspectionFindings:V,recordCapture:function(a,c){r(b,()=>{let b=a.metadata?.sessionId;b&&S.ensureSessionRoot(b,a.occurredAt);let d=function(a,b,c=null){return i((0,h.tTV)(["capture",a??"no_session",b,c??"no_path"]))}(b??null,a.contentHash,a.metadata?.filePath??null);S.insertAuditEvent({id:d,eventType:a.kind,startedAt:a.occurredAt,parentId:b,rootSessionId:b,content:a.content,contentHash:a.contentHash,attributes:(0,h.$w9)(a)});let e=new Map;for(let a of c){if(b&&V.isSessionDuplicate(a.ruleId,a.maskedMatch,b)||V.isEventDuplicate(d,a.ruleId,a.maskedMatch,a.span.start,a.span.end))continue;let c=`${a.ruleId}@${(0,h.qmP)(a)}`,f=e.get(c);f||(f=U.upsert((0,h.jTf)(a)),e.set(c,f)),V.insertFinding({id:a.id,auditEventId:d,inspectionDefinitionId:f,span:a.span,maskedMatch:a.maskedMatch,actionTaken:a.actionTaken,confidence:a.confidence,findingKey:a.findingKey??void 0})}})},ensureInventory:function(a){let c={};return r(b,()=>{let b=Date.now();a.host&&(c.hostId=N.upsert(a.host,b)),a.harness&&(c.harnessId=N.upsert(bc(a.harness,c.hostId),b)),c.accountId=N.upsert(bc({objectType:"user",identityKey:"local",attributes:{source:"local"}},c.hostId),b),a.project&&(c.sourceProjectId=R.upsert(a.project,b))})?c:{}},recordConfigScan:function(a){r(b,()=>{let b=(0,h.I8t)(a.scanEvent.startedAt);for(let c of a.items)N.upsert(c,b);S.insertAuditEvent(a.scanEvent);let c=new Map;for(let b of a.definitions??[])c.set(`${b.ruleId}@${b.version}`,U.upsert(b));for(let b of a.findings??[]){let e=c.get(`${b.ruleId}@${b.version}`);e&&V.insertFinding({id:(0,d.randomUUID)(),auditEventId:a.scanEvent.id,inspectionDefinitionId:e,span:b.span,maskedMatch:b.maskedMatch,actionTaken:b.actionTaken,confidence:b.confidence})}})},recordProjectFiles:function(a,c){0!==c.files.length&&r(b,()=>{P.replaceForProject(a,c,Date.now())})},reconcileWorktreeProjects:function(a,c,d){try{let e=c.split(f.sep).join("/"),g=d.split(f.sep).join("/"),h=d===c?"":"url IN (:worktreePosix, :worktreeWin) OR ",i=b.prepare(`SELECT id FROM source_project
736
- WHERE id <> :canonicalId
737
- AND (${h}url LIKE :pattern ESCAPE '\\' OR url LIKE :patternWin ESCAPE '\\')`).all({canonicalId:a,...d===c?{}:{worktreePosix:g,worktreeWin:g.split("/").join("\\")},pattern:`${l(e)}/.claude/worktrees/%`,patternWin:`${l(e.split("/").join("\\"))}\\\\.claude\\\\worktrees\\\\%`});if(0===i.length)return;q(b,()=>{for(let{id:c}of i)b.prepare("UPDATE audit_events SET source_project_id = :canonicalId WHERE source_project_id = :id").run({canonicalId:a,id:c}),b.prepare("UPDATE OR IGNORE file_access_override SET project_id = :canonicalId WHERE project_id = :id").run({canonicalId:a,id:c}),b.prepare("DELETE FROM file_access_override WHERE project_id = :id").run({id:c}),b.prepare("DELETE FROM project_file WHERE project_id = :id").run({id:c}),b.prepare("DELETE FROM source_project WHERE id = :id").run({id:c})})}catch{}},configInventoryReport:()=>W.report(),facets:function(){return{hosts:N.distinctTitles("host"),harnesses:N.distinctTitles("harness"),osVersions:N.osVersions(),projects:R.distinctNames()}},purgeSampleData:()=>{!function(a){try{if(!a.prepare(`SELECT (
738
- EXISTS(SELECT 1 FROM share_destination WHERE provenance = 'sample')
739
- OR EXISTS(SELECT 1 FROM audit_events WHERE id LIKE 'sample:activity:%')
740
- OR EXISTS(SELECT 1 FROM inventory_asset WHERE provenance = 'sample')
741
- ) AS n`).get().n)return;q(a,()=>{a.exec(`DELETE FROM share_call_site WHERE endpoint_id IN (
742
- SELECT e.id FROM share_endpoint e
743
- JOIN share_destination d ON d.id = e.destination_id
744
- WHERE d.provenance = 'sample')`),a.exec(`DELETE FROM egress_decision_override WHERE destination_id IN (
745
- SELECT id FROM share_destination WHERE provenance = 'sample')`),a.exec(`DELETE FROM share_endpoint WHERE destination_id IN (
746
- 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')
747
- 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 (
748
- key TEXT PRIMARY KEY,
749
- value TEXT NOT NULL
750
- )`),a.exec("DELETE FROM app_meta WHERE key LIKE 'sample_seeded:%'")})}catch{}}(b)},transaction:async function a(a){b.exec("BEGIN");try{let c=await a();return b.exec("COMMIT"),c}catch(a){try{b.exec("ROLLBACK")}catch{}throw a}},close:()=>{b.close()}}}function bg(a){let b=a.filePath.replaceAll("\\","/");return(0,d.createHash)("sha256").update(`${a.ruleId}\0${b}\0${a.valueFingerprint}`).digest("hex")}function bh(a){return(0,f.join)(a,"exception.key")}let bi={exceptions:"key_version",blocked_detections:"key_version",secret_vault:"fingerprint_key_version"};class bj 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 bk(a){let b,c=(0,f.join)(a,C);if(!(0,e.existsSync)(c))return 0;try{(b=new g.DatabaseSync(c,{readOnly:!0})).exec(`PRAGMA busy_timeout = ${String(250)}`);let a=0;for(let[c,d]of Object.entries(bi))try{let e=w(b.prepare(`SELECT MAX(${d}) AS v FROM ${c}`));a=Math.max(a,e?.v??0)}catch(a){if(1!==a.errcode)throw new bj(a)}return a}catch(a){throw a instanceof bj?a:new bj(a)}finally{b?.close()}}function bl(a,b){E(a);let c=bh(a),d=JSON.stringify({version:b.version,material:b.material.toString("base64")});return H(c,`${d}
751
- `),b}function bm(a){let b;try{b=(0,e.readFileSync)(bh(a),"utf8")}catch(a){if("ENOENT"===a.code)return null;throw a instanceof Error?a:Error(String(a))}let c=JSON.parse(b);if("object"!=typeof c||null===c)throw Error("exception key file is corrupt: not a JSON object");let{version:d,material:f}=c;if("number"!=typeof d||!Number.isInteger(d)||d<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:d,material:g}}function bn(a){let b=bm(a);return b?(G(bh(a)),b):bl(a,{version:bk(a)+1,material:(0,d.randomBytes)(32)})}function bo(a){let b=bm(a);return bl(a,{version:Math.max(b?.version??0,bk(a))+1,material:(0,d.randomBytes)(32)})}function bp(a,b){return(0,d.createHmac)("sha256",a.material).update(b,"utf8").digest("hex")}function bq(a,b){var c;return(0,h.qEQ)(b,null===(c=a)?{status:"absent"}:{status:"present",version:c.version})}c(51455);var br=c(48161);function bs(){return(0,f.join)((0,br.homedir)(),".aka")}function bt(a=bs()){return(0,f.join)(a,"settings")}function bu(a=bs()){return(0,f.join)(a,"data")}function bv(a=bs()){return(0,f.join)(a,"keys")}function bw(a=bs()){let b=function(a){let b;try{b=(0,e.readFileSync)(a,"utf8")}catch{return null}return O(b)??null}((0,f.join)(bt(a),"settings.json"));if(!b)return(0,h.i1j)();try{return h.hd_.parse(b)}catch{return(0,h.i1j)()}}function bx(a,b=bs()){let c=bt(b),d=bw(b),e=h.hd_.parse({...d,...a,onboardedAt:a.onboardedAt??d.onboardedAt??new Date().toISOString()});return E(c),H((0,f.join)(c,"settings.json"),`${JSON.stringify(e,null,2)}
752
- `),e}let by="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function bz(a){let b="",c=0,d=0;for(let e of a)for(c=c<<8|e,d+=8;d>=5;)b+=by.charAt(c>>>d-5&31),d-=5;return d>0&&(b+=by.charAt(c<<5-d&31)),b}function bA(a){let b=[],c=0,d=0;for(let e of a){let a=by.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 bB(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 bz(Uint8Array.from(b))}function bC(a){let b=b=>Buffer.from((0,d.hkdfSync)("sha256",a,"aka:vault:v1",b,32));return{enc:b("aka:vault:enc:v1"),sign:b("aka:vault:sign:v1")}}function bD(a,b,c,d=h.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 bE(a,b,c,e){let f=(0,d.createCipheriv)("aes-256-gcm",a,e);return f.setAAD(c),{ciphertext:Buffer.concat([f.update(b,"utf8"),f.final()]),nonce:e,authTag:f.getAuthTag()}}function bF(a,b,c){try{let e=(0,d.createDecipheriv)("aes-256-gcm",a,b.nonce);return e.setAAD(c),e.setAuthTag(b.authTag),Buffer.concat([e.update(b.ciphertext),e.final()]).toString("utf8")}catch{return null}}function bG(a,b,c,e){return(0,d.createHmac)("sha256",a).update(bD(b,c,e,h.viY)).digest().subarray(0,10)}function bH(a,b,c,e,f){if(10!==f.length)return!1;let g=bG(a,b,c,e);return(0,d.timingSafeEqual)(g,Buffer.from(f))}var bI=c(31421);class bJ extends Error{constructor(a){super(`vault: key epoch ${String(a)} is not present in the keyring`),this.name="VaultKeyEpochMissingError",this.version=a}}let bK="vault.key",bL="aka-vault",bM="keyring";function bN(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 bO(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 bP(){return{current:1,keys:new Map([[1,(0,d.randomBytes)(32)]])}}function bQ(a){let b=Math.max(...a.keys.keys())+1,c=new Map(a.keys);return c.set(b,(0,d.randomBytes)(32)),{current:b,keys:c}}function bR(a){let b=a.keys.get(a.current);if(!b)throw new bJ(a.current);return{material:b,version:a.current}}function bS(a,b){let c=a.keys.get(b);if(!c)throw new bJ(b);return{material:c,version:b}}function bT(a){try{return Promise.resolve(a())}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}function bU(a){return a instanceof Error?a:Error(String(a))}let bV="owner",bW="vault: a key rotation is already in progress";function bX(a,b){try{(0,e.mkdirSync)(a)}catch(a){if("EEXIST"===a.code)return!1;throw bU(a)}try{return(0,e.writeFileSync)((0,f.join)(a,bV),`${b}
753
- `,{mode:384}),!0}catch(b){throw(0,e.rmSync)(a,{recursive:!0,force:!0}),bU(b)}}function bY(a,b){E(a);let c=function(a){let b,c=(0,f.join)(a,`${bK}.lock`),g=(0,d.randomBytes)(16).toString("hex");if(bX(c,g))return{lock:c,owner:g};try{b=(0,e.statSync)(c)}catch{throw Error(bW)}if(Date.now()-b.mtimeMs<6e4)throw Error(bW);let h=`${c}.stale.${g}`;try{let a=(0,e.statSync)(c);if(a.ino!==b.ino||a.mtimeMs!==b.mtimeMs)throw Error(bW);(0,e.renameSync)(c,h)}catch(a){if(a instanceof Error&&a.message===bW)throw a;throw Error(bW,{cause:a})}if((0,e.rmSync)(h,{recursive:!0,force:!0}),!bX(c,g))throw Error(bW);return{lock:c,owner:g}}(a);try{return b()}finally{!function(a){try{if((0,e.readFileSync)((0,f.join)(a.lock,bV),"utf8").trim()!==a.owner)return}catch{return}(0,e.rmSync)(a.lock,{recursive:!0,force:!0})}(c)}}class bZ{#a;constructor(a){this.#a=a}get filePath(){return(0,f.join)(this.#a,bK)}loadOrCreate(){return bT(()=>{let a=this.#b();return a?(b$(this.filePath),bR(a)):bR(this.#c())})}rotate(){return bT(()=>bY(this.#a,()=>{let a=this.#b();return a?bR(this.#d(bQ(a))):bR(this.#c())}))}materialFor(a){return bT(()=>{let b=this.#b();if(!b)throw new bJ(a);return bS(b,a)})}#b(){let a;try{a=(0,e.readFileSync)(this.filePath,"utf8")}catch(a){if("ENOENT"===a.code)return null;throw a instanceof Error?a:Error(String(a))}return bN(a)}#c(){E(this.#a);let a=bP();try{(0,e.writeFileSync)(this.filePath,`${bO(a)}
754
- `,{flag:"wx",mode:384})}catch(b){if("EEXIST"!==b.code)throw bU(b);let a=this.#b();if(!a)throw Error("vault: key file vanished during first mint",{cause:b});return a}return b$(this.filePath),a}#d(a){E(this.#a);let b=this.filePath,c=`${b}.tmp`;return(0,e.writeFileSync)(c,`${bO(a)}
755
- `,{mode:384}),(0,e.renameSync)(c,b),b$(b),a}}function b$(a){try{(0,e.chmodSync)(a,384)}catch{}}let b_=a=>(0,bI.execFileSync)("/usr/bin/security",a,{encoding:"utf8",stdio:["ignore","pipe","ignore"]});class b0{#a;#e;constructor(a,b=b_){if(b===b_&&"darwin"!==process.platform)throw Error(`keychain custody is not available on this platform (${process.platform}); use file custody`);this.#a=a,this.#e=b}get keysDir(){return this.#a}loadOrCreate(){return bT(()=>{let a=this.#b();return a?bR(a):bR(this.#f(bP()))})}rotate(){return bT(()=>bY(this.#a,()=>{let a=this.#b();return a?bR(this.#g(bQ(a))):bR(this.#f(bP()))}))}materialFor(a){return bT(()=>{let b=this.#b();if(!b)throw new bJ(a);return bS(b,a)})}#b(){let a;try{a=this.#e(["find-generic-password","-s",bL,"-a",bM,"-w"])}catch(a){if(44===a.status)return null;throw Error(`vault: keychain read failed (${a instanceof Error?a.message:String(a)}); refusing to treat the failure as an absent keyring`,{cause:a})}let b=a.trim();return 0===b.length?null:bN(b)}#f(a){let b=["add-generic-password","-s",bL,"-a",bM,"-w",bO(a)];try{this.#e(b)}catch(b){let a=this.#b();if(a)return a;throw bU(b)}return a}#g(a){return this.#e(["add-generic-password","-U","-s",bL,"-a",bM,"-w",bO(a)]),a}}function b1(a,b){return"keychain"===a?new b0(b):new bZ(b)}let b2=Symbol("aka.vault.consentAbsent"),b3=Symbol("aka.vault.unavailable");function b4(a){if(!h.XZo.test(a))return null;let b=a.slice(6,-2),c=b.indexOf(":");if(c<0)return null;let d=b.slice(0,c),[e,f,g]=b.slice(c+1).split(".");if(void 0===e||void 0===f||void 0===g)return null;try{let a=function(a){let b=bA(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=bA(f),c=bA(g);if(bB(a)!==e||bz(b)!==f||bz(c)!==g)return null;return{category:d,keyVersion:a,pointerId:b,tag:c}}catch{return null}}class b5{#h;#i;#j;#k;#l;#m;constructor(a){this.#h=a.repo,this.#i=a.keys,this.#j=a.fingerprintKey,this.#k=a.isConsented,this.#l=a.verifyGrant,this.#m=a.now??(()=>Date.now())}async tokenize(a,b){if(!this.#k())return b2;let c=bp(this.#j,a),e=this.#h.byValueFingerprint(c),f=this.#m();if(e)return this.#h.upsert({...e,provider:e.provider??void 0},f),await this.#n(e.keyVersion,e.pointerId,e.category);let{material:g,version:i}=await this.#i.loadOrCreate(),j=bC(g),k=(0,d.randomBytes)(16),l=bD(i,k,b.category,h.viY),m=bE(j.enc,a,l,(0,d.randomBytes)(12)),{row:n}=this.#h.upsert({pointerId:bz(k),valueFingerprint:c,fingerprintKeyVersion:this.#j.version,keyVersion:i,formatVersion:h.viY,category:b.category,ruleId:b.ruleId,maskedMatch:b.maskedMatch,provider:b.provider,ciphertext:m.ciphertext.toString("base64"),nonce:m.nonce.toString("base64"),authTag:m.authTag.toString("base64")},f);return await this.#n(n.keyVersion,n.pointerId,n.category)}async detokenize(a,b){let c,d,e=b4(a);if(!e)return b3;try{let a=await this.#i.materialFor(e.keyVersion);c=bC(a.material).sign}catch{return b3}if(!bH(c,e.keyVersion,e.pointerId,e.category,e.tag))return b3;let f=bz(e.pointerId),g=this.#h.byPointerId(f);if(!g)return this.#o(f,b,"unavailable"),b3;if(g.category!==e.category)return b3;if("model"===b.target){let a,c=b.grantId,d=this.#l;if(void 0===d||void 0===c||""===c)return this.#o(f,b,"refused"),b3;try{a=await d(c,{ruleId:g.ruleId,valueFingerprint:g.valueFingerprint,fingerprintKeyVersion:g.fingerprintKeyVersion})}catch{a=!1}if(!a)return this.#o(f,b,"refused"),b3}try{let a=await this.#i.materialFor(g.keyVersion);d=bF(bC(a.material).enc,{ciphertext:Buffer.from(g.ciphertext,"base64"),nonce:Buffer.from(g.nonce,"base64"),authTag:Buffer.from(g.authTag,"base64")},bD(g.keyVersion,e.pointerId,g.category,g.formatVersion))}catch{d=null}return null===d?(this.#o(f,b,"unavailable"),b3):(this.#o(f,b,"revealed"),d)}async revealEntry(a,b){let c=this.#h.byPointerId(a);if(!c)return this.#o(a,{target:"human",reason:b.reason},"unavailable"),b3;let d=await this.#p(c);return null===d?(this.#o(a,{target:"human",reason:b.reason},"unavailable"),b3):(this.#o(a,{target:"human",reason:b.reason},"revealed"),d)}async describePointer(a){let b=await this.#q(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.#q(a);return b?{ruleId:b.ruleId,valueFingerprint:b.valueFingerprint,fingerprintKeyVersion:b.fingerprintKeyVersion}:null}async rotateVaultKey(){let a=await this.#i.rotate(),b=bC(a.material).enc,c=0;for(let e of this.#h.listAll()){let f;if(e.keyVersion===a.version)continue;let g=bA(e.pointerId);try{let a=await this.#i.materialFor(e.keyVersion);f=bF(bC(a.material).enc,{ciphertext:Buffer.from(e.ciphertext,"base64"),nonce:Buffer.from(e.nonce,"base64"),authTag:Buffer.from(e.authTag,"base64")},bD(e.keyVersion,g,e.category,e.formatVersion))}catch{f=null}if(null===f)continue;let h=bE(b,f,bD(a.version,g,e.category,e.formatVersion),(0,d.randomBytes)(12));this.#h.replaceCiphertext(e.pointerId,{keyVersion:a.version,ciphertext:h.ciphertext.toString("base64"),nonce:h.nonce.toString("base64"),authTag:h.authTag.toString("base64")}),c+=1}return{version:a.version,reEncrypted:c}}async refreshFingerprints(a){let b=0;for(let c of this.#h.listAll())try{let d=await this.#p(c);if(null===d)continue;this.#h.refreshFingerprint(c.pointerId,{valueFingerprint:bp(a,d),fingerprintKeyVersion:a.version}),b+=1}catch{continue}return b}purgeVault(){let a=this.#h.purgeAll();return this.#h.recordDeref({id:(0,d.randomUUID)(),pointerId:"*",at:this.#m(),target:"human",reason:"purge",outcome:"unavailable",pointerCount:Math.max(a,1)}),a}async #n(a,b,c){var d;let e=bA(b),f=bC((await this.#i.materialFor(a)).material).sign;return d=bG(f,a,e,c),`[[aka:${c}:${bB(a)}.${bz(e)}.${bz(d)}]]`}async #p(a){try{let b=await this.#i.materialFor(a.keyVersion);return bF(bC(b.material).enc,{ciphertext:Buffer.from(a.ciphertext,"base64"),nonce:Buffer.from(a.nonce,"base64"),authTag:Buffer.from(a.authTag,"base64")},bD(a.keyVersion,bA(a.pointerId),a.category,a.formatVersion))}catch{return null}}async #q(a){let b=b4(a);if(!b)return null;try{let a=await this.#i.materialFor(b.keyVersion),c=bC(a.material).sign;if(!bH(c,b.keyVersion,b.pointerId,b.category,b.tag))return null}catch{return null}let c=this.#h.byPointerId(bz(b.pointerId));return c?.category!==b.category?null:c}#o(a,b,c){this.#h.recordDeref({id:(0,d.randomUUID)(),pointerId:a,at:this.#m(),target:b.target,reason:b.reason,outcome:c,...void 0===b.grantId?{}:{grantId:b.grantId},pointerCount:(0,h.kqf)(b.reason)?b.pointerCount??1:1})}}},69882:(a,b,c)=>{c.d(b,{S8C:()=>y,hxQ:()=>ap,Itg:()=>ad,RRF:()=>a4,ZpU:()=>a7,HUb:()=>a3,hfB:()=>aj,unw:()=>a6,goN:()=>N,Jr:()=>a8,gbA:()=>v,V8B:()=>aK,IgC:()=>a_,aIg:()=>bD,iRC:()=>aL,GCf:()=>E,TUN:()=>O,SHn:()=>av,rov:()=>cr,V0H:()=>a2,kxf:()=>co,viY:()=>b6,XZo:()=>b9,jUf:()=>cb,PEm:()=>aZ,eI7:()=>cH,cqq:()=>F,jON:()=>aV,lFU:()=>d,PhW:()=>ab,uQz:()=>cq,BIx:()=>ar,DzG:()=>cl,NFD:()=>ck,hd_:()=>ct,tXp:()=>b1,plk:()=>bx,mAj:()=>bX,Fnc:()=>dn,ryv:()=>r,tTV:()=>aa,qmP:()=>cC,rG:()=>b4,Bfj:()=>b0,q_t:()=>p,i1j:()=>cu,xog:()=>bW,hzO:()=>dq,by7:()=>dp,Gw9:()=>dl,q11:()=>h,U7X:()=>w,kqf:()=>cg,y_0:()=>dm,qEQ:()=>aM,hds:()=>cn,I8t:()=>g,jwX:()=>ca,DhA:()=>a9,WSs:()=>dt,a45:()=>bv,N6N:()=>f,A6E:()=>b3,pnU:()=>bw,V9M:()=>cx,$w9:()=>cB,jTf:()=>cD,$BP:()=>cy,JAl:()=>cz,$3l:()=>cA,gzP:()=>cv,QCA:()=>cw,C05:()=>dr});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;"}],e=/^(\d+)([mh])$/;function f(a,b=Date.now()){let c=a.trim().toLowerCase();return"once"===c?{scope:"once",expiresAt:new Date(b+18e5).toISOString(),maxUses:1}:"permanent"===c?{scope:"permanent",expiresAt:null,maxUses:null}:{scope:"temporary",expiresAt:new Date(b+function(a){let b=e.exec(a.trim()),c=b?Number(b[1]):0;if(!b||c<=0)throw Error(`invalid duration '${a}' — use <n>m or <n>h (e.g. 30m, 1h, 24h)`);let d=c*("h"===b[2]?36e5:6e4);if(d>864e5)throw Error(`duration '${a}' exceeds the 24h maximum for --for — use --permanent (revocable any time) for an open-ended grant`);return d}(c)).toISOString(),maxUses:null}}function g(a){return new Date(a).getTime()}function h(a){return new Date(a).toISOString()}function i(a,b){return{input:a,output:b,cacheWrite5m:1.25*a,cacheWrite1h:2*a,cacheRead:.1*a,webSearch:.01}}let j={input:0,output:0,cacheWrite5m:0,cacheWrite1h:0,cacheRead:0,webSearch:0},k={"claude-fable-5":i(10,50),"claude-opus-4-8":i(5,25),"claude-opus-4-7":i(5,25),"claude-opus-4-6":i(5,25),"claude-opus-4-5":i(5,25),"claude-sonnet-5":i(3,15),"claude-sonnet-4-6":i(3,15),"claude-sonnet-4-5":i(3,15),"claude-haiku-4-5":i(1,5)},l={...Object.fromEntries(Object.entries(k).map(([a,b])=>[`anthropic/${a}`,b])),"ollama/*":j,"local/*":j},m={standard:1,batch:.5,priority:1.5},n=Object.keys(k);function o(a){let b=a.replace(/^(us|eu|apac|global)\./,"").replace(/^anthropic[./]/,"").replace(/@[\w-]+$/,"").replace(/-v\d+:\d+$/,"").replace(/:\d+$/,"").replace(/-\d{8}$/,"");for(let a of n)if(b===a)return a;return b}let p={normalizeModelId(a,b){let c=a.trim().toLowerCase();if("ollama"===c||"local"===c)return{provider:c,model:"*"};if("anthropic"===c||"bedrock"===c||"vertex"===c)return{provider:c,model:o(b)};let d=/^anthropic\/(.+)$/.exec(b);return d?.[1]!==void 0?{provider:c,model:o(d[1])}:{provider:c,model:b}},costFor({provider:a,model:b,usage:c}){var d;let e=this.normalizeModelId(a,b),f=l[`${e.provider}/${e.model}`];return void 0===f?null:((c.inputTokens??0)*f.input+(c.outputTokens??0)*f.output+(c.cacheWrite1hTokens??0)*f.cacheWrite1h+(c.cacheWrite5mTokens??0)*f.cacheWrite5m+(c.cacheReadTokens??0)*f.cacheRead)/1e6*(void 0===(d=c.serviceTier)?1:m[d]??1)+(c.webSearchRequests??0)*f.webSearch}};new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1});let q=a=>a??0;function r(a,b){let c=new Map;for(let{sessionId:d,attributes:e}of a){let a=e.provider??"unknown",f=e.model??"unknown",g=`${a} ${f}`,h=c.get(d);void 0===h&&(h=new Map,c.set(d,h));let i=h.get(g);void 0===i&&(i={provider:a,model:f,input:0,output:0,cacheCreation:0,cacheRead:0,costUsd:0,priced:!1},h.set(g,i)),i.input+=q(e.input_tokens),i.output+=q(e.output_tokens),i.cacheCreation+=q(e.cache_creation_input_tokens),i.cacheRead+=q(e.cache_read_input_tokens);let j=b.costFor({provider:a,model:f,usage:function(a){let b={inputTokens:q(a.input_tokens),outputTokens:q(a.output_tokens),cacheWrite1hTokens:q(a.ephemeral_1h_input_tokens),cacheWrite5mTokens:q(a.ephemeral_5m_input_tokens),cacheReadTokens:q(a.cache_read_input_tokens),webSearchRequests:q(a.web_search_requests)};return void 0!==a.service_tier&&(b.serviceTier=a.service_tier),b}(e)});null!==j&&(i.costUsd+=j,i.priced=!0)}let d=[];for(let[a,b]of c){let c=[],e=0,f=0,g=!1,h=!1;for(let d of b.values()){let b=d.input+d.output+d.cacheCreation+d.cacheRead;e+=b;let i=d.priced?d.costUsd:null;null===i?h=!0:(g=!0,f+=i),c.push({sessionId:a,model:d.model,provider:d.provider,inputTokens:d.input,outputTokens:d.output,cacheCreation:d.cacheCreation,cacheRead:d.cacheRead,totalTokens:b,estimatedCostUsd:i})}c.sort((a,b)=>b.totalTokens-a.totalTokens),d.push({sessionId:a,rollups:c,totalTokens:e,estimatedCostUsd:g?f:null,costIsPartial:h})}return d.sort((a,b)=>b.totalTokens-a.totalTokens),d}var s=c(14901),t=c(54206),u=c(8004);let v=s.k5(["pii","financial","secret","phi","code_context","code_flaw","custom","config"]).meta({id:"DetectionCategory"}),w=s.k5(["critical","high","medium","low"]).meta({id:"Severity"}),x=s.k5(["warn","redact","block","allow","log"]).meta({id:"ActionTaken"}),y=x.options,z=s.Ik({start:s.ai().int().nonnegative(),end:s.ai().int().nonnegative()}).meta({id:"Span"}),A=s.Ik({id:s.Os(),eventId:s.Os(),ruleId:s.Yj(),category:v,severity:w,span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1)}).meta({id:"Finding"});A.meta({id:"DetectedFinding"});let B=s.k5(["blocked","redacted","warned","allowed","quarantined","monitored"]).meta({id:"FindingAction"}),C=s.k5(["claudecode","claudedesktop","cursor","copilot","chatgpt","api"]).meta({id:"FindingProvider"}),D=s.k5(["secret","pii","source_code","external_share","mcp_server","customer_data","financial","phi","custom"]).meta({id:"FindingCategory"});s.k5(["in-flight","at-rest"]).meta({id:"FindingOrigin"});let E=s.k5(["open","handled","resolved","dismissed"]).meta({id:"FindingStatus"}),F=s.k5(["enforced-in-flight","fixed-at-source","exception","acknowledged","false-positive","redetected"]).meta({id:"ResolutionMethod"}),G=s.Ik({maskedValue:s.Yj(),contextPrefix:s.Yj()}).meta({id:"FindingMatch"}),H=s.Ik({id:s.Yj(),name:s.Yj().nullable()}).meta({id:"FindingDetectionRef"}),I=s.Ik({id:s.Yj(),name:s.Yj()}).meta({id:"FindingPolicyRef"}),J=s.Ik({id:s.Yj(),provider:C,repo:s.Yj(),file:s.Yj(),toolName:s.Yj().optional(),action:B,detectedAt:t.w$(),confidence:s.ai().min(0).max(1),status:E.optional()}).meta({id:"FindingInstance"}),K=s.Ik({id:s.Yj(),category:D,subtype:s.Yj(),severity:w,match:G,detection:H,policy:I,instanceCount:s.ai().int().nonnegative(),providers:s.YO(C),aggregateAction:B.nullable(),latestDetectedAt:t.w$(),instances:s.YO(J),status:E.optional()}).meta({id:"FindingGroup"});s.Ik({findings:s.ai().int().nonnegative(),groups:s.ai().int().nonnegative(),bySeverity:s.Ik({critical:s.ai().int().nonnegative(),high:s.ai().int().nonnegative(),medium:s.ai().int().nonnegative(),low:s.ai().int().nonnegative()})}).meta({id:"FindingStats"});let L=s.Ik({value:s.Yj(),count:s.ai().int().nonnegative()}).meta({id:"FindingFacetItem"}),M=s.Ik({severity:s.YO(L),subtype:s.YO(L),provider:s.YO(L),action:s.YO(L),status:s.YO(L)}).meta({id:"FindingFacets"}),N=50;s.Ik({severity:s.YO(w).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(C).optional(),action:s.YO(B).optional(),status:s.YO(E).optional(),q:s.Yj().optional(),sessionId:s.Yj().optional(),groupBy:s.eu("type").optional(),limit:u.ai().int().min(1).max(100).optional(),cursor:s.Yj().optional()}),s.Ik({totals:s.Ik({findings:s.ai().int().nonnegative(),groups:s.ai().int().nonnegative()}),facets:M,items:s.YO(K),nextCursor:s.Yj().nullable(),sessionFirings:s.g1(s.Yj(),s.ai().int().nonnegative()).optional()}).meta({id:"ListGroupedFindingsResponse"}),s.Ik({action:B.exclude(["quarantined"]),instanceId:s.Yj().optional()}).meta({id:"ApplyFindingActionRequest"}),K.meta({id:"ApplyFindingActionResponse"}),s.Ik({severity:s.YO(w).optional(),subtype:s.YO(s.Yj()).optional(),provider:s.YO(C).optional(),action:s.YO(B).optional(),q:s.Yj().optional(),format:s.k5(["csv","json"]).optional()}),J.extend({groupId:s.Yj(),category:D,subtype:s.Yj(),severity:w,match:G,detection:H,policy:I}).meta({id:"FindingInstanceDetail"});let O=s.k5(["claudecode","cursor","copilot","codex","windsurf","claudedesktop","chatgpt","api"]).meta({id:"Harness"}),P={"claude-code":"claudecode","claude-desktop":"claudedesktop","github-copilot":"copilot",cursor:"cursor",chatgpt:"chatgpt"},Q=s.k5(["host","harness","user","skill","hook","mcp_server","config_file"]).meta({id:"InventoryObjectType"}),R=s.k5(["session","run","tool_call","llm_call","source_lookup","prompt","response","code_change","tool_use","config_scan"]).meta({id:"AuditEventType"}),S=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 T=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:T});let U=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 V=s.Ik({ruleId:s.Yj().min(1),ruleName:s.Yj(),ruleVersion:s.Yj().min(1),category:v,severity:w,span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1)});s.Ik({sessionId:s.Yj().min(1),toolUseId:s.Yj().min(1),parentId:s.Yj().min(1),rootSessionId:s.Yj().min(1),startedAt:t.w$(),attributes:U,inspections:s.YO(V).default([])});let W=s.Ik({objectType:Q,identityKey:s.Yj().min(1),location:s.Yj().optional(),title:s.Yj().optional(),hostId:s.Yj().optional(),attributes:S.default({})}).meta({id:"InventoryInput"}),X=s.Ik({url:s.Yj().min(1),name:s.Yj().optional(),attributes:S.default({})}).meta({id:"SourceProjectInput"}),Y=s.Ik({id:s.Yj().min(1),eventType:R,startedAt:t.w$(),endedAt:t.w$().optional(),parentId:s.Yj().optional(),rootSessionId:s.Yj().optional(),hostId:s.Yj().optional(),harnessId:s.Yj().optional(),sourceProjectId:s.Yj().optional(),severity:w.optional(),priority:s.Yj().optional(),content:s.Yj().optional(),contentHash:s.Yj().optional(),attributes:S.optional()}).meta({id:"AuditEventInput"});s.Ik({class:s.Yj().min(1),label:s.Yj().optional(),attributes:S.optional()});let Z=s.Ik({ruleId:s.Yj().min(1),version:s.Yj().min(1),name:s.Yj(),category:v,severity:w,definition:s.Yj()});s.Ik({id:s.Yj().min(1),auditEventId:s.Yj().min(1),inspectionDefinitionId:s.Yj().min(1),classifiedDataId:s.Yj().optional(),span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1),findingKey:s.Yj().optional(),firstDetectedAt:t.w$().optional()}),s.Ik({host:W.optional(),harness:W.optional(),project:X.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 $=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($),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai().nullable(),costIsPartial:s.zM()});let _=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 aa(a){return JSON.stringify(a)}s.Ik({models:s.YO(_),sessionCount:s.ai().int().nonnegative(),totalTokens:s.ai().int().nonnegative(),estimatedCostUsd:s.ai(),costIsPartial:s.zM()});let ab=s.k5(["active","completed","interrupted","error"]),ac=s.k5(["session","prompt","response","tool","hook","detection","share","permission","commit","error","active"]),ad=s.k5(["detections","shares","inventory"]),ae=s.Ik({id:s.Yj(),occurredAt:t.w$(),kind:ac,title:s.Yj(),detail:s.Yj(),tool:s.Yj().nullable(),severity:w.nullable(),link:ad.nullable(),targetId:s.Yj().nullable(),internal:s.zM(),flagged:s.zM()}).meta({id:"ActivityAuditEvent"}),af=s.Ik({id:s.Yj(),harness:O,title:s.Yj(),project:s.Yj(),repo:s.Yj(),branches:s.YO(s.Yj()),startedAt:t.w$(),endedAt:t.w$().nullable(),status:ab,turns:s.ai().int().nonnegative(),findings:s.ai().int().nonnegative(),shares:s.ai().int().nonnegative()}).meta({id:"ActivitySessionSummary"});af.extend({host:s.Yj(),cwd:s.Yj(),models:s.YO(s.Yj()),version:s.Yj(),tokens:$,tools:s.g1(s.Yj(),s.ai().int().nonnegative()),files:s.YO(s.Yj()),commits:s.ai().int().nonnegative(),events:s.YO(ae)}).meta({id:"ActivitySession"}),s.Ik({tz:s.Yj().optional()});let ag=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(O).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 ah=s.Ik({items:s.YO(af),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(ae),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(O).optional(),from:s.KC([t.p6(),t.w$()]).optional(),to:s.KC([t.p6(),t.w$()]).optional()}),s.Ik({stats:ag,sessions:ah}).meta({id:"ActivityOverviewResponse"});let ai=s.k5(["prompt","response","code_change","tool_use"]).meta({id:"EventKind"}),aj=ai.options.map(a=>`'${a}'`).join(","),ak=s.k5(["claude-code","claude-desktop","cursor","chatgpt","github-copilot","cli","unknown"]).meta({id:"SourceTool"}),al=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"}),am=s.Ik({id:s.Os(),sourceTool:ak,kind:ai,occurredAt:t.w$(),contentHash:s.Yj(),content:s.Yj(),metadata:al.optional()}).meta({id:"Event"}),an=am.meta({id:"IngestEvent"});s.Ik({events:s.YO(an).min(1).max(100),dedupe:s.eu("content-hash").optional()}).meta({id:"IngestBatch"});let ao=s.k5(["project","skill","mcp","hook","config"]).meta({id:"AssetType"}),ap=s.k5(["open","approved","blocked"]).meta({id:"AccessLevel"}),aq=s.k5(["source","public-dep","vendored","config","data","docs","generated"]).meta({id:"Origin"}),ar=s.k5(["known-good","risky","unapproved"]).meta({id:"TrustLevel"}),as=s.k5(["update","stale","conflict","unknown","change","untracked","risk","findings"]).meta({id:"Flag"}),at=s.k5(["public","private"]).meta({id:"Visibility"}),au=s.k5(["block","redact","warn"]).meta({id:"HarnessEventKind"}),av=s.k5(["claudecode","cursor","codex"]).meta({id:"HarnessId"}),aw=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"}),ax=s.Ik({id:s.Yj(),type:ao,name:s.Yj(),sub:s.Yj(),flags:s.YO(as),trust:ar.optional()}).meta({id:"AssetSummary"}),ay=s.Ik({id:s.Yj(),name:s.Yj(),repo:s.Yj(),visibility:at,language:s.Yj(),policyDefault:ap,updatedAt:t.w$(),accessCounts:aw,findingsCount:s.ai().int().nonnegative()}).meta({id:"ProjectSummary"}),az=s.Ik({type:ao,assets:s.YO(ax)}),aA=s.Ik({id:av,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(ay),categories:s.YO(az)}).meta({id:"HarnessSummary"});s.Ik({items:s.YO(aA)}).meta({id:"ListHarnessesResponse"});let aB=s.Ik({type:ao,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(ax)}).meta({id:"AssetGroup"});s.Ik({groups:s.YO(aB)}).meta({id:"ListAssetsResponse"});let aC=s.Ik({name:s.Yj(),signature:s.Yj(),description:s.Yj(),write:s.zM(),risk:s.Yj().nullable()}).meta({id:"McpTool"}),aD=s.Ik({id:s.Yj(),title:s.Yj(),note:s.Yj()});ax.extend({description:s.Yj().nullable(),trust:ar.nullable(),meta:s.g1(s.Yj(),s.L5()),finding:aD.nullable(),tools:s.YO(aC).optional()}).meta({id:"AssetDetail"}),s.Ik({items:s.YO(ay)}).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 aE=s.Ik({path:s.Yj(),name:s.Yj(),origin:aq,access:ap,isCustom:s.zM(),findings:s.ai().int().nonnegative(),blockedAt:t.w$().nullable().optional(),note:s.Yj().nullable().optional()}).meta({id:"FileSummary"}),aF=s.Ik({name:s.Yj(),path:s.Yj(),accessCounts:aw}).meta({id:"FolderSummary"});s.Ik({project:s.Ik({id:s.Yj(),repo:s.Yj(),visibility:at}),path:s.Yj(),folders:s.YO(aF).optional(),files:s.YO(aE)}).meta({id:"ProjectTreeResponse"}),aE.extend({project:s.Ik({repo:s.Yj(),visibility:at,language:s.Yj(),policyDefault:ap,updatedAt:t.w$()}),findingsRefs:s.YO(s.Ik({id:s.Yj(),title:s.Yj()}))}).meta({id:"FileDetail"}),s.Ik({path:s.Yj(),access:ap}).meta({id:"SetFileAccessBody"}),s.Ik({file:aE,accessCounts:aw}).meta({id:"SetFileAccessResponse"}),s.Ik({trust:ar}).meta({id:"SetMcpTrustBody"});let aG=s.Ik({kind:au,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(aG)}).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(ao).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 aH=s.k5(["once","temporary","permanent"]),aI=s.Ik({repo:s.Yj().optional(),sourceTool:s.Yj().optional(),provider:s.Yj().optional()}).strict(),aJ=s.k5(["suppress","reveal_to_model"]),aK=s.Ik({id:s.Os(),ruleId:s.Yj(),category:v,valueFingerprint:s.Yj().regex(/^[0-9a-f]{64}$/),keyVersion:s.ai().int().positive(),maskedValue:s.Yj(),capability:aJ.default("suppress"),scope:aH,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:aI.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()}),aL=aK.pick({id:!0,ruleId:!0,valueFingerprint:!0,keyVersion:!0,capability:!0,expiresAt:!0,maxUses:!0,useCount:!0,conditions:!0});function aM(a,b){return"present"===b.status&&b.version===a}s.k5(["keyword","regex","validator"]).meta({id:"MatcherType"}),s.k5(["safe","quarantined"]).meta({id:"RuleProbeVerdict"});let aN=s.Ik({type:s.eu("keyword"),keywords:s.YO(s.Yj().min(1)).min(1),caseSensitive:s.zM().default(!1)}),aO=s.Ik({type:s.eu("regex"),pattern:s.Yj().min(1).max(2e3),flags:s.Yj().default("gi"),captureGroup:s.ai().int().nonnegative().optional()}).refine(a=>(function(a,b){try{return new RegExp(a,b),!0}catch{return!1}})(a.pattern,a.flags),{message:"pattern/flags do not form a valid JavaScript regular expression",path:["pattern"]}).refine(a=>void 0!==a.captureGroup||!function(a,b){try{let c=new RegExp(a,b.replace(/[gy]/g,""));return c.exec("")?.[0].length===0}catch{return!1}}(a.pattern,a.flags),{message:'a whole-match regex that can match the empty string (e.g. "\\d*", "a?", "(?:)") can hang the matcher — scope the quantifier to a captureGroup, or require at least one character',path:["pattern"]}),aP=s.Ik({type:s.eu("validator"),name:s.k5(["luhn","entropy","ssn-checksum"]),config:s.g1(s.Yj(),s.L5()).optional()}),aQ=s.gM("type",[aN,aO,aP]).meta({id:"Matcher"}),aR=s.Ik({extensions:s.YO(s.Yj().regex(/^\.[A-Za-z0-9]+$/)).min(1)}).meta({id:"AppliesTo"}),aS=s.KC([s.Yj(),s.Ik({name:s.Yj(),config:s.g1(s.Yj(),s.L5()).optional()})]).meta({id:"PostValidatorRef"}),aT=s.Ik({categories:s.YO(v).min(1).optional(),ruleIds:s.YO(s.Yj().min(1)).min(1).optional(),labels:s.YO(s.Yj().min(1)).min(1).optional(),windowChars:s.ai().int().positive().default(160),confidenceBoost:s.ai().min(0).max(.3).optional()}).refine(a=>(a.categories?.length??0)+(a.ruleIds?.length??0)+(a.labels?.length??0)>0,{message:"requiresNearby needs at least one of categories, ruleIds, or labels"}).meta({id:"RequiresNearby"}),aU=s.Ik({label:s.Yj(),text:s.Yj().max(5e4),shouldMatch:s.zM(),filePath:s.Yj().optional(),expectedSpans:s.YO(s.Ik({start:s.ai(),end:s.ai()})).optional()}).meta({id:"RuleFixture"}),aV=s.Ik({specVersion:s.eu(1),id:s.Yj().regex(/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/),name:s.Yj(),category:v,severity:w,matcher:aQ,appliesTo:aR.optional(),postValidators:s.YO(aS).optional(),requiresNearby:aT.optional(),examples:s.YO(s.Yj()).optional()}).meta({id:"Rule"}),aW=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:aW.optional(),license:s.Yj().optional(),sourceUrl:s.OZ().optional()}).meta({id:"PackManifest"});let aX=s.k5(["global","repo","user"]).meta({id:"PolicyScope"}),aY=s.KC([s.Ik({ruleId:s.Yj()}),s.Ik({category:v})]).meta({id:"PolicyTarget"}),aZ=s.Ik({id:s.Os(),scope:aX,target:aY,action:x,enabled:s.zM().default(!0),customKeywords:s.YO(s.Yj()).optional(),name:s.Yj().optional()}).meta({id:"Policy"});s.Ik({version:s.Yj(),policies:s.YO(aZ),rules:s.YO(aV).optional(),rulesComplete:s.zM().optional(),exceptions:s.YO(aL).optional(),ruleVersions:s.g1(s.Yj(),s.Yj()).optional(),customKeywords:s.YO(s.Yj()),fetchedAt:t.w$()}).meta({id:"PolicyBundle"});let a$=["config"],a_=v.options.filter(a=>!a$.includes(a)),a0={secret:"critical",financial:"critical",code_flaw:"critical",pii:"high",phi:"high",custom:"high",code_context:"low",config:"low"},a1=s.k5(["builtin","custom"]).meta({id:"PolicyKind"}),a2=["monitor","warn","redact","block"],a3=s.k5(a2).meta({id:"BuiltinPolicyId"}),a4=a2,a5={monitor:{name:"Monitor",action:"log",description:"Log every match for audit. The request is allowed through untouched."},warn:{name:"Warn",action:"warn",description:"Allow the request, but warn the user inline before it is sent."},redact:{name:"Redact",action:"redact",description:"Automatically strip the matched value from the request, then continue."},block:{name:"Block",action:"block",description:"Refuse the request entirely whenever any rule in this detection matches."}},a6=Object.fromEntries(v.options.map(a=>[a,a5[function(a){if(a$.includes(a))return"monitor";let b=a0[a];return"critical"===b||"high"===b?"warn":"monitor"}(a)].action])),a7=Object.fromEntries(a2.map(a=>[a,{id:a,...a5[a]}])),a8="monitor";function a9(a){let b=a3.safeParse(a??a8);return a7[b.success?b.data:a8].action}let ba=s.Ik({id:s.Yj(),name:s.Yj(),ruleCount:s.ai().int().nonnegative(),enabled:s.zM()}).meta({id:"UsedByItem"}),bb=s.Ik({id:s.Yj(),kind:a1,name:s.Yj(),enabled:s.zM(),usedByCount:s.ai().int().nonnegative()}).meta({id:"PolicyListItem"});s.Ik({specVersion:s.eu(1),id:s.Yj(),kind:a1,name:s.Yj(),enabled:s.zM(),description:s.Yj(),usedBy:s.YO(ba)}).meta({id:"PolicyDetail"}),s.Ik({policies:s.ai().int().nonnegative(),builtin:s.ai().int().nonnegative(),custom:s.ai().int().nonnegative(),detectionsGoverned:s.ai().int().nonnegative()}).meta({id:"PolicyStatsResponse"}),s.Ik({cursor:s.Yj().optional(),limit:u.ai().int().min(1).max(200).default(50),sourceTool:s.Yj().optional(),kind:s.Yj().optional(),from:t.w$().optional(),to:t.w$().optional()}),s.Ik({items:s.YO(am),nextCursor:s.Yj().nullable()}).meta({id:"ListEventsResponse"}),s.Ik({accepted:s.ai().int().nonnegative(),duplicates:s.ai().int().nonnegative()}).meta({id:"IngestResponse"}),s.Ik({cursor:s.Yj().optional(),limit:u.ai().int().min(1).max(200).default(50),severity:s.Yj().optional(),category:s.Yj().optional(),eventId:s.Os().optional()}),s.Ik({items:s.YO(A),nextCursor:s.Yj().nullable()}).meta({id:"ListFindingsResponse"}),s.Ik({items:s.YO(bb)}).meta({id:"ListPoliciesResponse"}),aZ.omit({id:!0}).meta({id:"CreatePolicyRequest"}),aZ.partial().required({id:!0}).meta({id:"UpdatePolicyRequest"}),s.Ik({accepted:s.zM()}).meta({id:"RecordAuditEventResponse"}),s.Ik({error:s.Ik({code:s.Yj(),message:s.Yj(),details:s.L5().optional()})}).meta({id:"ErrorResponse"});let bc=s.k5(["user","project","local","plugin"]),bd=s.Ik({name:s.Yj().min(1),source:s.Yj().min(1),scope:bc,pluginName:s.Yj().optional(),version:s.Yj().optional(),description:s.Yj().optional(),updatedAt:t.w$().optional(),location:s.Yj().optional()}),be=s.Ik({event:s.Yj().min(1),matcher:s.Yj().optional(),command:s.Yj().min(1),timeout:s.ai().optional(),scope:bc,pluginName:s.Yj().optional(),location:s.Yj().optional()}),bf=s.Ik({name:s.Yj().min(1),scope:bc,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()}),bg=s.Ik({name:s.Yj().min(1),path:s.Yj().min(1),scope:bc,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(bd),hooks:s.YO(be),mcpServers:s.YO(bf),configFiles:s.YO(bg),errors:s.YO(s.Ik({source:s.Yj(),reason:s.Yj()}))});let bh=s.Ik({ruleId:s.Yj().min(1),version:s.Yj().min(1),span:z,maskedMatch:s.Yj(),actionTaken:x,confidence:s.ai().min(0).max(1)});s.Ik({items:s.YO(W),scanEvent:Y,definitions:s.YO(Z).optional(),findings:s.YO(bh).optional()});let bi=s.Yj().regex(/^[a-z][a-z0-9-]*$/),bj=s.Yj().regex(/^[a-z][a-z0-9-]*$/),bk=s.Yj().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/),bl=s.k5(["labs","user","org"]),bm=s.k5(["library"]).meta({id:"OriginEnum"}),bn=s.k5(["all","library","custom","customized","updates"]),bo=s.k5(["new","imported","update"]).meta({id:"LibraryStateEnum"}),bp=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"}),bq=s.Ik({id:s.Yj(),name:s.Yj(),version:bk,enabled:s.zM(),origin:bm,publisher:bi.optional(),publisherKind:bl.optional(),ruleCount:s.ai().int().nonnegative(),namespace:bi,packId:bj,policyId:s.Yj().optional(),latestVersion:bk.optional()}).meta({id:"DetectionListItem"});s.Ik({counts:bp,items:s.YO(bq)}).meta({id:"ListDetectionsResponse"}),s.Ik({filter:bn.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 br=s.Ik({id:s.Yj(),name:s.Yj(),category:v,severity:w,matcher:aQ}).meta({id:"DetectionRule"}),bs=s.Ik({available:s.zM(),latestVersion:bk,latestRuleCount:s.ai().int().nonnegative().optional()}).nullable().meta({id:"DetectionUpdate"});s.Ik({id:s.Yj(),name:s.Yj(),version:bk,enabled:s.zM(),origin:bm,publisher:bi.optional(),publisherKind:bl.optional(),ruleCount:s.ai().int().nonnegative(),namespace:bi,packId:bj,description:s.Yj().optional(),editedAt:t.w$(),findingsLast30d:s.ai().int().nonnegative(),latestVersion:bk.nullable().optional(),update:bs,rules:s.YO(br),modified:s.zM(),policyId:s.Yj().optional()}).meta({id:"DetectionDetail"});let bt=s.Ik({id:s.Yj(),name:s.Yj(),publisher:bi,publisherKind:bl.optional(),category:v.optional(),version:bk,ruleCount:s.ai().int().nonnegative(),description:s.Yj().optional(),updatedAt:t.w$(),state:bo,importedAs:s.Yj().nullable()}).meta({id:"LibraryItem"});function bu(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 bv(a,b,c){let d=a.rules.flatMap(a=>{let b=aQ.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 bw(a){let b=a.indexOf("/");return b<1||b===a.length-1?null:{namespace:a.slice(0,b),packId:a.slice(b+1)}}function bx(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(bu)}}s.Ik({categories:s.YO(v),items:s.YO(bt)}).meta({id:"ListLibraryResponse"}),s.Ik({libraryId:s.Yj().refine(a=>/^[^/]+\/[^/]+$/.test(a),{message:"libraryId must be in namespace/packId format"})}).meta({id:"ImportDetectionRequest"});let by=s.k5(["provider","internal","external","ip"]).meta({id:"DestinationKind"}),bz=s.k5(["https","http","sftp","grpc","smtp","ws","wss"]).meta({id:"Transport"}),bA=s.k5(["secrets","pii","customer","source","telemetry","logs","metrics","none"]).meta({id:"DataClass"}),bB=bA.options,bC=s.k5(["recognized","internal","unverified","ip"]).meta({id:"ShareTrustLevel"}),bD=s.k5(["allow","block"]).meta({id:"EgressDecision"}),bE=s.k5(["allowed","blocked","review"]).meta({id:"EgressStatus"}),bF=s.k5(["raw_ip","unverified_domain","plaintext_transport"]).meta({id:"ReviewReason"}),bG=s.k5(["GET","POST","PUT","DELETE","SDK","REF"]).meta({id:"HttpMethod"}),bH=s.Ik({needsReview:s.zM(),reasons:s.YO(bF)}).meta({id:"ReviewInfo"}),bI=s.Ik({port:s.ai().int().nullable(),geo:s.Yj().nullable(),ptr:s.Yj().nullable()}).meta({id:"DestinationNetwork"}),bJ=s.Ik({id:s.Yj(),method:bG,transport:bz,url:s.Yj(),template:s.zM(),dataClass:bA,lastSeen:t.w$(),callSiteCount:s.ai().int().nonnegative()}).meta({id:"EndpointSummary"}),bK=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"}),bL=bJ.extend({sites:s.YO(bK)}).meta({id:"EndpointWithSites"}),bM=s.Ik({id:s.Yj(),kind:by,name:s.Yj(),host:s.Yj(),category:s.Yj(),trust:bC,status:bE,isCustom:s.zM(),lastSeen:t.w$(),endpointCount:s.ai().int().nonnegative(),callSiteCount:s.ai().int().nonnegative(),transports:s.YO(bz),dataClasses:s.YO(bA),review:bH,network:bI.nullable(),endpoints:s.YO(bJ)}).meta({id:"ShareDestinationSummary"});bM.omit({endpointCount:!0,callSiteCount:!0,endpoints:!0}).extend({note:s.Yj().nullable(),endpoints:s.YO(bL)}).meta({id:"ShareDestinationDetail"});let bN=s.Ik({id:s.Yj(),kind:by,name:s.Yj(),host:s.Yj(),trust:bC,status:bE,review:bH,topDataClass:bA,callSiteCount:s.ai().int().nonnegative(),lastSeen:t.w$()}).meta({id:"ReviewDestination"}),bO=s.Ik({kind:by,total:s.ai().int().nonnegative(),items:s.YO(bM)}).meta({id:"ShareDestinationGroup"});s.Ik({groups:s.YO(bO)}).meta({id:"ListShareDestinationsResponse"}),s.Ik({items:s.YO(bN)}).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:bD.nullable()}).meta({id:"SetEgressDecisionBody"}),s.Ik({destination:bM}).meta({id:"SetEgressDecisionResponse"}),s.Ik({q:s.Yj().optional(),kind:s.YO(by).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(by).optional()});let bP=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(bA).min(1),sdks:s.jg(bP,s.YO(s.Yj()))}).meta({id:"ProviderRegistryEntry"});let bQ=s.Ik({file:s.Yj(),line:s.ai().int().positive(),snippet:s.Yj(),dynamic:s.zM(),vendored:s.zM()}).meta({id:"EgressCallSiteHit"}),bR=s.Ik({host:s.Yj(),kind:by,name:s.Yj(),category:s.Yj(),trust:bC,network:bI.nullable(),method:bG,transport:bz,url:s.Yj(),template:s.zM(),dataClass:bA,site:bQ}).meta({id:"ResolvedEgressHit"}),bS=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"});function bT(a){return({log:"monitored",block:"blocked",redact:"redacted",warn:"warned",allow:"allowed"})[a]??"allowed"}function bU(a){return P[a]??"api"}s.Ik({projectKey:s.Yj().min(1),project:s.Yj(),projectId:s.Yj().nullable(),reconcile:bS,hits:s.YO(bR)}).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 bV=["open","handled","dismissed","resolved"];function bW(a){return"code_change"!==a.kind?"handled":null===a.findingKey?"open":"resolved"===a.latestResolutionStatus?"resolved":"dismissed"===a.latestResolutionStatus?"dismissed":"open"}function bX(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){var h;let f=b.map(a=>{let b=c?.get(a.id)??a.actionTaken;return{id:a.id,provider:bU(a.sourceTool),repo:a.repo,file:a.file,...void 0===a.toolName?{}:{toolName:a.toolName},action:bT(b),detectedAt:a.occurredAt,confidence:a.confidence,status:a.status}}),i=e?.get(a),j=i?.latestDetectedAt??b.reduce((a,b)=>b.occurredAt>a?b.occurredAt:a,b[0]?.occurredAt??new Date(0).toISOString()),k=new Set,l=(i?[...new Set(i.sourceTools.map(bU))].sort():f.map(a=>a.provider)).filter(a=>!k.has(a)&&(k.add(a),!0)),m=new Set(i?i.actionsTaken.map(bT):f.map(a=>a.action)),n=1===m.size?[...m][0]??null:null,o=b[0]?.severity??"low",p={id:a,name:d?.get(a)??null},q="code_context"===(h=b[0]?.category??"custom")?"source_code":h,r={id:`category:${q}`,name:q},s={maskedValue:b[0]?.maskedMatch??"",contextPrefix:""},t=function(a){let b=new Set(a.filter(a=>void 0!==a));if(0!==b.size){for(let a of bV)if(b.has(a))return a}}(i?i.statusInputs.map(bW):f.map(a=>a.status)),u={id:a,category:q,subtype:a,severity:o,match:s,detection:p,policy:r,instanceCount:i?.instanceCount??f.length,providers:l,aggregateAction:n,latestDetectedAt:j,instances:f,status:t};i&&(b$.set(u,[...m]),void 0!==i.searchText&&bY.set(u,bZ(u,i.searchText))),g.push(u)}return g}let bY=new WeakMap;function bZ(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 b$=new WeakMap;function b_(a){let b=b$.get(a);if(void 0!==b)return b;let c=[...new Set(a.instances.map(a=>a.action))];return b$.set(a,c),c}function b0(a,b){let c=new Set(b),d=0;for(let b of a){if(void 0===b.count)return null;c.has(bW(b))&&(d+=b.count)}return d}function b1(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=>b_(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=bY.get(a);if(void 0!==b)return b;let c=bZ(a);return bY.set(a,c),c})(b).includes(a))}return c}let b2={critical:0,high:1,medium:2,low:3};function b3(a){return[...a].sort((a,b)=>{let c=(b2[a.severity]??-1)-(b2[b.severity]??-1);return 0!==c?c:b.latestDetectedAt.localeCompare(a.latestDetectedAt)})}function b4(a,b){let c=b1(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=b1(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=b1(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 b_(a))h.set(b,(h.get(b)??0)+1);let i=b1(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=b1(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 b5=s.Ik({id:s.Os(),namespace:bi,packId:bj,version:bk,name:s.Yj(),enabled:s.zM().default(!0),policyId:s.Yj().optional()}).meta({id:"InstalledPack"});s.Ik({namespace:bi,packId:bj,version:bk}).meta({id:"InstallPackRequest"}),s.Ik({items:s.YO(b5)}).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 b6=2,b7=v.options.join("|"),b8=RegExp(`\\[\\[aka:(?:${b7}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`),b9=RegExp(`^${b8.source}$`);function ca(){return RegExp(b8.source,"g")}let cb=s.Yj().regex(b9);s.Ik({category:v,keyVersion:s.ai().int().positive(),pointerId:s.Yj(),tag:s.Yj()}),s.Ik({pointerId:s.Yj(),valueFingerprint:s.Yj().regex(/^[0-9a-f]{64}$/),fingerprintKeyVersion:s.ai().int().positive(),keyVersion:s.ai().int().positive(),category:v,ruleId:s.Yj(),maskedMatch:s.Yj(),provider:s.Yj().optional(),ciphertext:s.Yj(),nonce:s.Yj(),authTag:s.Yj(),occurrenceCount:s.ai().int().nonnegative(),firstSeen:s.Yj(),lastSeen:s.Yj()}),s.Ik({category:v,provider:s.Yj().optional(),maskedMatch:s.Yj(),occurrences:s.ai().int().nonnegative(),firstSeen:s.Yj(),lastSeen:s.Yj()}),s.Ik({ruleId:s.Yj(),valueFingerprint:s.Yj().regex(/^[0-9a-f]{64}$/),fingerprintKeyVersion:s.ai().int().positive()});let cc=s.k5(["human","model"]),cd=s.k5(["display","explicit-reveal","view-render","model-input","remediation","purge"]),ce=s.k5(["revealed","refused","unavailable"]),cf=["display","view-render"];function cg(a){return cf.includes(a)}s.Ik({id:s.Os(),pointerId:s.Yj(),at:s.Yj(),target:cc,reason:cd,outcome:ce,grantId:s.Yj().optional(),pointerCount:s.ai().int().positive().default(1)});let ch=s.k5(["prompt","tool-input","tool-output","file","transcript"]),ci=s.Ik({location:s.Yj(),kind:ch,firstSeen:s.Yj(),lastSeen:s.Yj()});s.Ik({pointerId:s.Yj(),category:v,provider:s.Yj().optional(),maskedMatch:s.Yj(),occurrences:s.ai().int().nonnegative(),firstSeen:s.Yj(),lastSeen:s.Yj(),revealGrantId:s.Yj().nullable(),sightings:s.YO(ci)});let cj=s.Yj(),ck=s.k5(["masked","full","off"]),cl=1,cm=s.Ik({acknowledgedAt:t.w$(),version:s.ai().int().positive()});function cn(a){return a?.version===cl}let co=1,cp=s.k5(["standalone"]),cq=s.k5(["redact","warn"]),cr=s.k5(["full","session-only"]),cs=s.Ik({acknowledgedAt:t.w$(),payloadVersion:s.ai().int().positive()}),ct=s.Ik({specVersion:s.ai().int().positive().default(5),runMode:s.vk(a=>"attached"===a?"standalone":a,cp.default("standalone")),policy:cq.default("redact"),historicalAccess:cr.default("session-only"),dataSharesInPlace:s.zM().default(!0),vaultConsent:cm.optional(),vaultKeyCustody:cj.default("file"),vaultInlineReveal:ck.default("masked"),onboardedAt:t.w$().optional(),modelJudgeConsent:cs.optional()});function cu(){return ct.parse({})}function cv(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 cw(a,b,c){return{id:b,url:a.url,name:a.name??null,attributes:JSON.stringify(a.attributes),firstSeen:c,lastSeen:c}}function cx(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 cy(a,b){return{id:b,class:a.class,label:a.label??null,attributes:a.attributes?JSON.stringify(a.attributes):null}}function cz(a,b){return{id:b,ruleId:a.ruleId,name:a.name,category:a.category,severity:a.severity,definition:a.definition,version:a.version}}function cA(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 cB(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 cC(a){return`capture/${a.category}/${a.severity}`}function cD(a){return{ruleId:a.ruleId,version:cC(a),name:a.ruleId,category:a.category,severity:a.severity,definition:JSON.stringify({ruleId:a.ruleId})}}let cE=s.Ik({path:s.Yj().min(1),name:s.Yj().min(1),origin:aq,defaultAccess:ap});s.Ik({files:s.YO(cE),truncated:s.zM(),scannedAt:s.Yj()});let cF=["7d","30d","3m","6m"],cG=s.k5(cF).meta({id:"TimeRange"}),cH={"7d":7,"30d":30,"3m":90,"6m":180};cG.catch("7d");let cI=s.k5(["still-valid","unknown","invalid"]),cJ=s.Ik({filePath:s.Yj(),span:z.optional()}).strict(),cK=s.Ik({provider:s.Yj(),maskedToken:s.Yj(),where:cJ,state:cI,observedAt:t.w$().optional()}).strict();s.Ik({provider:s.Yj(),maskedToken:s.Yj(),consolePath:s.Yj(),occurrenceSpread:s.ai().int().positive()}).strict();let cL=s.k5(["redact-rotation-checklist","redact-only","set-secret-redact","leave"]),cM=s.k5(["first-run","pre-push","secret-scan"]);s.Ik({entrySource:cM}).strict();let cN=s.Ik({id:cL,label:s.Yj()}),cO=s.Ik({kind:s.eu("decision"),entrySource:cM,secretCount:s.ai().int().positive(),prompt:s.Yj(),options:s.PV([cN.extend({id:s.eu("redact-rotation-checklist")}),cN.extend({id:s.eu("redact-only")}),cN.extend({id:s.eu("set-secret-redact")}),cN.extend({id:s.eu("leave")})])}),cP=s.Ik({kind:s.eu("no-decision")});s.gM("kind",[cO,cP]),s.Ik({rules:s.YO(aV).min(1).max(100),text:s.Yj().max(5e4).optional(),fixtures:s.YO(aU).max(200).optional()}).refine(a=>void 0!==a.text||(a.fixtures?.length??0)>0,{message:"Provide `text`, `fixtures`, or both — there must be something to test"}).meta({id:"TestRulesRequest"});let cQ=s.Ik({ruleId:s.Yj(),category:v,severity:w,span:z,confidence:s.ai().min(0).max(1),match:s.Yj()}).meta({id:"RuleTestMatch"}),cR=s.Ik({label:s.Yj(),shouldMatch:s.zM(),didMatch:s.zM(),passed:s.zM(),matches:s.YO(cQ)}).meta({id:"FixtureResult"});s.Ik({adhoc:s.Ik({matches:s.YO(cQ)}).optional(),fixtures:s.YO(cR),summary:s.Ik({total:s.ai().int().nonnegative(),passed:s.ai().int().nonnegative(),failed:s.ai().int().nonnegative()}),unsupportedRuleIds:s.YO(s.Yj())}).meta({id:"TestRulesResponse"});let cS=s.Ik({severity:w,count:s.ai().int().nonnegative(),caught:s.ai().int().nonnegative().optional(),openAtRest:s.ai().int().nonnegative().optional()}).meta({id:"SeveritySummaryItem"});s.Ik({total:s.ai().int().nonnegative(),needsRemediation:s.ai().int().nonnegative().optional(),bySeverity:s.YO(cS)}).meta({id:"SeveritySummaryResponse"}),s.Ik({range:s.k5(cF).default("7d")});let cT=s.k5(["blocked","redacted","warned"]).meta({id:"EnforcementActionKind"}),cU=s.Ik({kind:cT,count:s.ai().int().nonnegative(),delta:s.ai().int()}).meta({id:"EnforcementAction"});s.Ik({range:cG,total:s.ai().int().nonnegative(),actions:s.YO(cU)}).meta({id:"EnforcementActionsResponse"});let cV=s.k5(["day","week"]).meta({id:"TimeseriesGranularity"}),cW=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:cG,granularity:cV,points:s.YO(cW)}).meta({id:"FindingsTimeseriesResponse"});let cX=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:cG,granularity:cV,points:s.YO(cX)}).meta({id:"MttrTrendResponse"});let cY=s.Ik({findingKey:s.Yj(),ruleId:s.Yj(),severity:w,path:s.Yj(),resolvedAt:t.w$(),detectedAt:t.w$()}).meta({id:"ResolvedFeedItem"});s.Ik({items:s.YO(cY)}).meta({id:"RecentlyResolvedResponse"});let cZ=["repo","user"],c$=s.k5(cZ).meta({id:"SourceKind"}),c_=s.Ik({id:s.Yj(),name:s.Yj(),kind:c$,findingsCount:s.ai().int().nonnegative()}).meta({id:"TopSource"});s.Ik({range:cG,items:s.YO(c_)}).meta({id:"TopSourcesResponse"}),s.Ik({range:s.k5(cF).default("7d"),limit:u.ai().int().min(1).max(50).default(5),kind:s.k5(cZ).optional()});let c0=s.k5(["claudecode","cursor","codex","chatgpt","copilot","api"]).meta({id:"Provider"}),c1=s.Ik({provider:c0,coverage:s.ai().int().min(0).max(100),supported:s.zM()}).meta({id:"ScanCoverageProvider"});s.Ik({range:cG,providers:s.YO(c1)}).meta({id:"ScanCoverageResponse"});let c2=s.k5(["repo","user","team","policy","share","rule"]).meta({id:"SubjectType"}),c3=s.Ik({type:c2,id:s.Yj(),label:s.Yj()}).meta({id:"RecommendationSubject"}),c4=s.k5(["apply","navigate"]).meta({id:"RecommendationActionMode"}),c5=s.Ik({mode:c4,type:s.Yj(),label:s.Yj(),href:s.Yj().optional(),policyId:s.Yj().optional(),teamId:s.Yj().optional()}).meta({id:"RecommendationAction"}),c6=s.Ik({id:s.Yj(),category:s.Yj(),severity:w,title:s.Yj(),description:s.Yj(),subjects:s.YO(c3),action:c5}).meta({id:"RecommendedAction"});s.Ik({items:s.YO(c6)}).meta({id:"RecommendedActionsResponse"}),s.Ik({limit:u.ai().int().min(1).max(20).default(3)});let c7=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:c7}).meta({id:"ApplyRecommendedActionResponse"}),s.Ik({id:s.Yj(),status:s.eu("dismissed")}).meta({id:"DismissRecommendedActionResponse"}),s.Ik({id:s.Yj()}),s.Ik({ruleId:s.Yj(),category:v,severity:w,maskedMatch:s.Yj(),rawMatch:s.Yj(),context:s.Yj(),filePath:s.Yj().optional(),confidence:s.ai().min(0).max(1),id:s.Yj().optional(),valueFingerprint:s.Yj().optional(),keyVersion:s.ai().int().nonnegative().optional()});let c8=s.Ik({category:v,action:a3,reasoning:s.Yj(),genuineCount:s.ai().int().nonnegative(),fpCount:s.ai().int().nonnegative(),fpIds:s.YO(s.Yj())});s.Ik({perCategory:s.YO(c8),notes:s.Yj()});let c9=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"]}),da=s.Ik({ruleId:s.Yj(),category:v,valueFingerprint:s.Yj(),keyVersion:s.ai().int().nonnegative()}),db=s.Ik({pattern:s.Yj(),count:s.ai().int().nonnegative(),values:s.YO(da).min(1)}),dc=s.Ik({category:v,count:s.ai().int().nonnegative(),egress:s.zM()}),dd=s.Ik({counts:c9,routineCategories:s.YO(v),surfacedCategories:s.YO(v),findingKinds:s.YO(dc),posture:s.g1(v,a3),maskedFindings:s.YO(cK).optional(),falsePositivePatterns:s.YO(db).optional()}),de=c8.pick({category:!0,genuineCount:!0,fpCount:!0}).extend({egress:s.zM()});s.Ik({categories:s.YO(de),posture:s.g1(v,a3)}),s.Ik({frame:dd,copy:s.Yj()}),s.k5(["scan","floor"]);let df=s.Ik({id:s.k5(["enter-remediation","open-dashboard","not-now"]),label:s.Yj()}),dg=s.PV([df.extend({id:s.eu("open-dashboard")}),df.extend({id:s.eu("not-now")})]),dh=s.PV([df.extend({id:s.eu("enter-remediation")}),df.extend({id:s.eu("open-dashboard")}),df.extend({id:s.eu("not-now")})]);s.Ik({worthALook:s.ai().int().nonnegative(),liveKeys:s.ai().int().nonnegative().optional(),options:s.KC([dg,dh])}).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 di=new Set(["recognized","internal"]);function dj(a){return di.has(a)?"allowed":"review"}function dk(a){return"block"===a?"blocked":"allowed"}function dl(a,b){return null===b?dj(a):dk(b)}function dm(a,b){return null!==b&&dk(b)!==dj(a)}function dn(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 dp(a){return Array.from(new Set(a))}function dq(a){let b=new Set(a);return bB.filter(a=>b.has(a))}function dr(a){return dq(a)[0]??"none"}let ds={raw_ip:0,unverified_domain:1,plaintext_transport:2};function dt(a){return 0===a.length?1/0:Math.min(...a.map(a=>ds[a]))}}};