@akasecurity/cli 0.9.10 → 0.9.12

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 (120) hide show
  1. package/README.md +12 -12
  2. package/dist/cli.js +3706 -1895
  3. package/extension/content.js +1 -1
  4. package/extension/manifest.json +1 -1
  5. package/native-host/host.js +2270 -1336
  6. package/native-host/scan-worker.js +388 -74
  7. package/native-host/sync.js +587 -138
  8. package/package.json +6 -6
  9. package/web-ui/package.json +1 -1
  10. package/web-ui/web-ui/.next/BUILD_ID +1 -1
  11. package/web-ui/web-ui/.next/app-build-manifest.json +81 -81
  12. package/web-ui/web-ui/.next/app-path-routes-manifest.json +5 -5
  13. package/web-ui/web-ui/.next/build-manifest.json +2 -2
  14. package/web-ui/web-ui/.next/prerender-manifest.json +14 -14
  15. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js +2 -2
  16. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js.nft.json +1 -1
  17. package/web-ui/web-ui/.next/server/app/(app)/activity/page_client-reference-manifest.js +1 -1
  18. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js +2 -2
  19. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js.nft.json +1 -1
  20. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page_client-reference-manifest.js +1 -1
  21. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js +2 -2
  22. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js.nft.json +1 -1
  23. package/web-ui/web-ui/.next/server/app/(app)/detections/page_client-reference-manifest.js +1 -1
  24. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js +2 -2
  25. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js.nft.json +1 -1
  26. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page_client-reference-manifest.js +1 -1
  27. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js +1 -1
  28. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js.nft.json +1 -1
  29. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page_client-reference-manifest.js +1 -1
  30. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js +1 -1
  31. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js.nft.json +1 -1
  32. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page_client-reference-manifest.js +1 -1
  33. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js +2 -2
  34. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js.nft.json +1 -1
  35. package/web-ui/web-ui/.next/server/app/(app)/findings/page_client-reference-manifest.js +1 -1
  36. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js +2 -2
  37. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js.nft.json +1 -1
  38. package/web-ui/web-ui/.next/server/app/(app)/inventory/page_client-reference-manifest.js +1 -1
  39. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js +2 -2
  40. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js.nft.json +1 -1
  41. package/web-ui/web-ui/.next/server/app/(app)/policies/page_client-reference-manifest.js +1 -1
  42. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js +3 -3
  43. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js.nft.json +1 -1
  44. package/web-ui/web-ui/.next/server/app/(app)/scan/page_client-reference-manifest.js +1 -1
  45. package/web-ui/web-ui/.next/server/app/(app)/security/page.js +2 -2
  46. package/web-ui/web-ui/.next/server/app/(app)/security/page.js.nft.json +1 -1
  47. package/web-ui/web-ui/.next/server/app/(app)/security/page_client-reference-manifest.js +1 -1
  48. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js +2 -2
  49. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js.nft.json +1 -1
  50. package/web-ui/web-ui/.next/server/app/(app)/settings/page_client-reference-manifest.js +1 -1
  51. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js +2 -2
  52. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js.nft.json +1 -1
  53. package/web-ui/web-ui/.next/server/app/(app)/updates/page_client-reference-manifest.js +1 -1
  54. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js +2 -2
  55. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js.nft.json +1 -1
  56. package/web-ui/web-ui/.next/server/app/(app)/vault/page_client-reference-manifest.js +1 -1
  57. package/web-ui/web-ui/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  58. package/web-ui/web-ui/.next/server/app/_not-found.html +1 -1
  59. package/web-ui/web-ui/.next/server/app/_not-found.rsc +2 -2
  60. package/web-ui/web-ui/.next/server/app/index.html +1 -1
  61. package/web-ui/web-ui/.next/server/app/index.rsc +2 -2
  62. package/web-ui/web-ui/.next/server/app/page_client-reference-manifest.js +1 -1
  63. package/web-ui/web-ui/.next/server/app-paths-manifest.json +5 -5
  64. package/web-ui/web-ui/.next/server/chunks/121.js +1 -0
  65. package/web-ui/web-ui/.next/server/chunks/290.js +6 -0
  66. package/web-ui/web-ui/.next/server/chunks/475.js +1 -1
  67. package/web-ui/web-ui/.next/server/chunks/589.js +1 -1
  68. package/web-ui/web-ui/.next/server/chunks/611.js +1015 -0
  69. package/web-ui/web-ui/.next/server/chunks/7.js +1 -1
  70. package/web-ui/web-ui/.next/server/chunks/816.js +1 -0
  71. package/web-ui/web-ui/.next/server/chunks/935.js +1 -1
  72. package/web-ui/web-ui/.next/server/chunks/968.js +1006 -0
  73. package/web-ui/web-ui/.next/server/functions-config-manifest.json +6 -6
  74. package/web-ui/web-ui/.next/server/middleware-manifest.json +5 -5
  75. package/web-ui/web-ui/.next/server/pages/404.html +1 -1
  76. package/web-ui/web-ui/.next/server/pages/500.html +1 -1
  77. package/web-ui/web-ui/.next/server/server-reference-manifest.js +1 -1
  78. package/web-ui/web-ui/.next/server/server-reference-manifest.json +1 -1
  79. package/web-ui/web-ui/.next/static/chunks/{526-026c69b926a17dbb.js → 526-f0156de7831566b3.js} +1 -1
  80. package/web-ui/web-ui/.next/static/chunks/674-d8237c5d0faa4a53.js +1 -0
  81. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-a27c8937989448e4.js +1 -0
  82. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-2b805f9e1f995092.js +1 -0
  83. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-a87cfee370c4e0f4.js +1 -0
  84. package/web-ui/web-ui/.next/static/chunks/app/(app)/error-190085728a856072.js +1 -0
  85. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/{page-0fcffe4b9dff201f.js → page-4e214491c7be8d43.js} +1 -1
  86. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-c1bb992ee1f12566.js +1 -0
  87. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-f16ba40d88e414b1.js +1 -0
  88. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-59c76da638f22b0e.js +1 -0
  89. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-c37447caf89a86e1.js +1 -0
  90. package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-cb3c8c7b6b33414c.js +1 -0
  91. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/{page-b90748d139a546c9.js → page-ab639e48f60ad7ee.js} +1 -1
  92. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-494614fccc8c62cc.js +1 -0
  93. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-a3095119b3e87341.js +1 -0
  94. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-469613d499e41093.js +1 -0
  95. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-5b32bd569c9569d9.js +1 -0
  96. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-3152ceb31f024b8d.js +1 -0
  97. package/web-ui/web-ui/.next/static/css/6e72259eccdf4435.css +2 -0
  98. package/web-ui/web-ui/dist/scan-worker.js +388 -74
  99. package/web-ui/web-ui/.next/server/chunks/389.js +0 -903
  100. package/web-ui/web-ui/.next/server/chunks/667.js +0 -894
  101. package/web-ui/web-ui/.next/server/chunks/851.js +0 -1
  102. package/web-ui/web-ui/.next/server/chunks/950.js +0 -6
  103. package/web-ui/web-ui/.next/static/chunks/907-207847c57011ba44.js +0 -1
  104. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-e4f94a75c631ce86.js +0 -1
  105. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-d70fcc5612f380b7.js +0 -1
  106. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-e1823ce15bb6277d.js +0 -1
  107. package/web-ui/web-ui/.next/static/chunks/app/(app)/error-14165283b00c8626.js +0 -1
  108. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-c95079a2acd284fd.js +0 -1
  109. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-4b9f034bd078f5d3.js +0 -1
  110. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-b97fc083884ef341.js +0 -1
  111. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-e96e7e947ed5f279.js +0 -1
  112. package/web-ui/web-ui/.next/static/chunks/app/(app)/layout-83072d434c6b6b0e.js +0 -1
  113. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-7a46abe149271870.js +0 -1
  114. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-f4a1ee202d6e60a4.js +0 -1
  115. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-2ec6d863f1a31792.js +0 -1
  116. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-b388003fb0d3efd1.js +0 -1
  117. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-6bda74d234a1376a.js +0 -1
  118. package/web-ui/web-ui/.next/static/css/81a7ed955b02c959.css +0 -2
  119. /package/web-ui/web-ui/.next/static/{k7tk0MLkPITbi_x6JL01X → PMeePXfXsQ2xxrXppySG_}/_buildManifest.js +0 -0
  120. /package/web-ui/web-ui/.next/static/{k7tk0MLkPITbi_x6JL01X → PMeePXfXsQ2xxrXppySG_}/_ssgManifest.js +0 -0
@@ -0,0 +1,1015 @@
1
+ "use strict";exports.id=611,exports.ids=[611],exports.modules={32611:(a,b,c)=>{c.d(b,{WR:()=>a3,qA:()=>a4,qk:()=>bx,Pi:()=>du,o8:()=>by,zd:()=>i,Qo:()=>cE,Ru:()=>dq,KS:()=>bl,tI:()=>bj,_2:()=>cN,Dg:()=>cO,gt:()=>cR,lG:()=>B,Wo:()=>bm,Rd:()=>cL,Ji:()=>cw,R8:()=>E,Hg:()=>D,XK:()=>C,y9:()=>cK,cn:()=>cQ,xR:()=>bv,Zu:()=>G,v5:()=>cM,Cn:()=>cS,VL:()=>bk,Yf:()=>cD,sF:()=>F,g5:()=>u});var d=c(73024),e=c(76760);let f="policy-cache.json",g="attached-state.json",h=[f,"attached-sync-state.json",g,"attached-forward-drops.json","attached-history-sync.json"];function i(a){for(let b of h)try{(0,d.rmSync)((0,e.join)(a,b),{force:!0})}catch{}}var j=c(75046),k=c(75919);let l="aka.db";function m(a,b){if(!function(a){try{return(0,d.lstatSync)(a).isSymbolicLink()}catch{return!1}}(a))try{(0,d.chmodSync)(a,b)}catch{}}function n(a){m(a,448)}function o(a,b=!1){(0,d.mkdirSync)(a,{recursive:b,mode:448})}function p(a){o(a,!0),n(a)}function q(a){return[`${a}-wal`,`${a}-shm`,`${a}-journal`]}function r(a){m(a,384)}function s(a){for(let b of[a,...q(a)])m(b,384)}function t(a,b){(0,d.writeFileSync)(a,b,{mode:384,flag:"wx"})}function u(a,b){let c=`${a}.${String(process.pid)}.tmp`;try{(0,d.rmSync)(c,{force:!0})}catch{}try{t(c,b),(0,d.renameSync)(c,a)}finally{try{(0,d.rmSync)(c,{force:!0})}catch{}}r(a)}function v(a){try{if((0,d.lstatSync)(a).isSymbolicLink())return{kind:"symlink"};return{kind:"gone"}}catch(a){if("ENOENT"===a.code)return{kind:"gone"};return{kind:"unknown",cause:a}}}class w extends Error{constructor(a,b){super(a,void 0===b?void 0:{cause:b}),this.code="key-unclaimable",this.name="KeyUnclaimableError"}}function x(a,b){let c,e=`${a}.${String(process.pid)}.${String(k.threadId)}.new`;try{(0,d.rmSync)(e,{force:!0})}catch{}try{t(e,b),c=function(a,b,c){try{return(0,d.linkSync)(a,b),!0}catch(b){let a=b.code;if("EEXIST"===a)return!1;if(!y.has(a??""))throw b}try{return t(b,c),!0}catch(a){if("EEXIST"===a.code)return!1;throw a}}(e,a,b)}finally{try{(0,d.rmSync)(e,{force:!0})}catch{}}return c&&r(a),c}let y=new Set(["EPERM","ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL"]);function z(a){return(0,e.join)(a,j.leE)}let A=new Set(["localhost","127.0.0.1","::1","[::1]"]);function B(a){let b;try{b=new URL(a)}catch{return!1}return"https:"===b.protocol||"http:"===b.protocol&&A.has(b.hostname)}function C(a,b){let c=D(a,b);return c.usable?{usable:!0}:c}function D(a,b){let c,e,f=z(a),g=function(a){let b=(0,d.lstatSync)(a,{throwIfNoEntry:!1});if(void 0===b)return"absent";if(b.isSymbolicLink())return"untrusted";let c=(0,d.statSync)(a,{throwIfNoEntry:!1});if(void 0===c)return"absent";let e=process.getuid?.();if(void 0!==e&&c.uid!==e)return"untrusted";if("win32"!==process.platform&&(511&c.mode)!=384)try{(0,d.chmodSync)(a,384)}catch{return"untrusted"}return"ok"}(f);if("absent"===g)return{usable:!1,reason:"absent"};if("untrusted"===g)return{usable:!1,reason:"untrusted-file"};try{c=(0,d.readFileSync)(f,"utf8")}catch(a){return{usable:!1,reason:"ENOENT"===a.code?"absent":"unreadable"}}try{e=JSON.parse(c)}catch{return{usable:!1,reason:"malformed"}}let h=j.yi_.safeParse(e);return h.success?B(h.data.endpoint)?void 0!==b&&b.endpoint!==h.data.endpoint?{usable:!1,reason:"endpoint-mismatch",credentialEndpoint:h.data.endpoint,settingsEndpoint:b.endpoint}:{usable:!0,credential:h.data}:{usable:!1,reason:"unsafe-endpoint"}:{usable:!1,reason:"malformed"}}function E(a,b){let c=D(a,b);return c.usable?c.credential:null}function F(a,b){if(!B(b.endpoint))throw Error(`refusing to store a control-plane credential for a non-HTTPS endpoint: ${b.endpoint}`);p(a),u(z(a),`${JSON.stringify(b,null,2)}
2
+ `)}function G(a){let b=z(a),c=void 0!==(0,d.lstatSync)(b,{throwIfNoEntry:!1});return(0,d.rmSync)(b,{force:!0}),c}var H=c(77598),I=c(79868);function J(a){return(0,H.createHash)("sha256").update(a).digest("hex")}function K(a){return J((0,j.tTV)(["source_project",a]))}function L(a,b){return J((0,j.tTV)(["inspection_definition",a,b]))}function M(a,b){return`${a}.${b}.${String(Date.now())}.${(0,H.randomUUID)().slice(0,8)}.bak`}let N=".partial",O=`.bak${N}`,P="copy";function Q(a){let b,c=(0,e.dirname)(a),f=`${(0,e.basename)(a)}.`;try{b=(0,d.readdirSync)(c)}catch{return}for(let a of b){if(!a.startsWith(f)||!a.endsWith(O))continue;let b=(0,e.join)(c,a);try{let a=function(a){for(let b of[(0,e.join)(a,P),a])try{return Date.now()-(0,d.statSync)(b).mtimeMs}catch{}return null}(b);null!==a&&a>3e5&&(0,d.rmSync)(b,{recursive:!0,force:!0})}catch{}}}function R(a,b){let{stage:c,copy:f}=function(a){let b=`${a}${N}`;return(0,d.rmSync)(b,{recursive:!0,force:!0}),o(b),n(b),{stage:b,copy:(0,e.join)(b,P)}}(b);try{a.prepare("VACUUM INTO ?").run(f),r(f),(0,d.renameSync)(f,b)}catch(a){try{(0,d.rmSync)(c,{recursive:!0,force:!0})}catch{}throw a}try{(0,d.rmSync)(c,{recursive:!0,force:!0})}catch{}}let S=new TextDecoder;function T(a){return null===a?null:"string"==typeof a?a.toLowerCase():"number"==typeof a||"bigint"==typeof a?String(a).toLowerCase():S.decode(a).toLowerCase()}function U(a){return a.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function V(a){return Array.from({length:a},()=>"?").join(", ")}function W(a){return`%${U(a)}%`}function X(a){return`(${a.map(a=>`${a} LIKE ? ESCAPE '\\'`).join(" OR ")})`}let Y=0;function Z(a,b,c="DEFERRED"){if(a.isTransaction){let c=`aka_sp_${String(Y+=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 $(a,b,c="DEFERRED"){let d=a.isTransaction;try{return Z(a,b,c),!0}catch(b){if(!a.isTransaction&&d)throw b;return!1}}function _(a){process.stderr.write(`[aka] ${a}
3
+ `)}function aa(a,b,c){return void 0!==a.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ? LIMIT 1").get(b,c)}function ab(a,b){return aa(a,"index",b)}function ac(a,b,c){let d=c?.includeGenerated?"table_xinfo":"table_info";return a.prepare(`PRAGMA ${d}(${b})`).all().map(a=>a.name)}function ad(a,b){return void 0===b?a.all():Array.isArray(b)?a.all(...b):a.all(b)}function ae(a,b){return void 0===b?a.get():Array.isArray(b)?a.get(...b):a.get(b)}function af(a){return 1===a||!0===a}function ag(a){let b={};for(let[c,d]of Object.entries(a))b[c]=void 0===d?null:d;return b}function ah(a,b,c){return ae(a.prepare(b),c)?.n??0}function ai(a,b,c){let d=new Map;for(let e of ad(a.prepare(b),c))d.set(e.k,e.n);return d}function aj(a,b){let c=[];for(let d of a)try{c.push(b(d))}catch{}return c}let ak=["prompt","response","tool_use"],al=ak.map(a=>`'${a}'`).join(", "),am=["session","llm_call","tool_call"],an=am.map(a=>`'${a}'`).join(", "),ao=[...am,...ak],ap=ao.map(a=>`'${a}'`).join(", "),aq=`
4
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
5
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
6
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
7
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
8
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
9
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
10
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
11
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
12
+ -- added later lands in no bucket and fails the sum assertion, instead
13
+ -- of silently joining this one.
14
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
15
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
16
+ THEN 1 ELSE 0 END) AS failed,
17
+ COUNT(*) AS total`,ar=`
18
+ WHERE event_type IN (${ap})
19
+ AND (
20
+ event_type IN (${an})
21
+ OR synced_at IS NOT NULL
22
+ OR outbox_owed = 1
23
+ )`,as=`id,
24
+ parent_id AS parentId,
25
+ root_session_id AS rootSessionId,
26
+ event_type AS eventType,
27
+ host_id AS hostId,
28
+ harness_id AS harnessId,
29
+ source_project_id AS sourceProjectId,
30
+ started_at AS startedAt,
31
+ ended_at AS endedAt,
32
+ severity,
33
+ priority,
34
+ content,
35
+ content_hash AS contentHash,
36
+ attributes`;class at{constructor(a){this.db=a,this.ensureRowStmt=a.prepare("INSERT OR IGNORE INTO history_sync (id) VALUES (1)"),this.sessionsStmt=a.prepare(`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
37
+ FROM audit_events
38
+ WHERE synced_at IS NULL
39
+ AND event_type IN (${an})
40
+ AND started_at < :before
41
+ GROUP BY sessionId
42
+ ORDER BY earliest
43
+ LIMIT :limit`),this.rowsStmt=a.prepare(`SELECT ${as}
44
+ FROM audit_events
45
+ WHERE synced_at IS NULL
46
+ AND event_type IN (${an})
47
+ AND started_at < :before
48
+ AND COALESCE(root_session_id, id) = :sessionId
49
+ ORDER BY (event_type = 'session') DESC, started_at
50
+ LIMIT :limit`),this.captureRowsStmt=a.prepare(`SELECT ${as}
51
+ FROM audit_events
52
+ WHERE synced_at IS NULL
53
+ AND sync_claimed_at IS NULL
54
+ AND outbox_owed = 1
55
+ AND event_type IN (${al})
56
+ AND started_at < :before
57
+ ORDER BY started_at
58
+ LIMIT :limit`),this.markOwedStmt=a.prepare("UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL"),this.markCaptureBacklogOwedStmt=a.prepare(`UPDATE audit_events SET outbox_owed = 1
59
+ WHERE synced_at IS NULL
60
+ AND event_type IN (${al})
61
+ AND started_at < :before`),this.stampStmt=a.prepare(`UPDATE audit_events
62
+ SET synced_at = :at,
63
+ sync_claimed_at = NULL,
64
+ sync_failed_at = :failedAt,
65
+ sync_failure = :failure
66
+ WHERE id = :id`),this.claimRowStmt=a.prepare("UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL"),this.releaseRowStmt=a.prepare("UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id"),this.releaseStaleClaimsStmt=a.prepare(`UPDATE audit_events SET sync_claimed_at = NULL
67
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`),this.partitionStmt=a.prepare(`SELECT${aq}
68
+ FROM audit_events${ar}`),this.partitionByKindStmt=a.prepare(`SELECT event_type AS kind,${aq}
69
+ FROM audit_events INDEXED BY idx_audit_events_sync${ar}
70
+ GROUP BY event_type`),this.countsStmt=a.prepare(`SELECT
71
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
72
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
73
+ SUM(CASE WHEN synced_at = ${String(-1)}
74
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
75
+ THEN 1 ELSE 0 END) AS skipped,
76
+ SUM(CASE WHEN synced_at = ${String(-1)}
77
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
78
+ SUM(CASE WHEN synced_at = ${String(-1)}
79
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
80
+ FROM audit_events
81
+ WHERE event_type IN (${an})`),this.captureSkipCountStmt=a.prepare(`SELECT COUNT(*) AS skipped
82
+ FROM audit_events
83
+ WHERE synced_at = ${String(-1)}
84
+ AND event_type IN (${al})`),this.fingerprintStmt=a.prepare(`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
85
+ FROM history_sync WHERE id = 1`),this.setFingerprintStmt=a.prepare(`UPDATE history_sync
86
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
87
+ WHERE id = 1`),this.disownCapturesStmt=a.prepare(`UPDATE audit_events SET outbox_owed = NULL
88
+ WHERE outbox_owed IS NOT NULL
89
+ AND event_type IN (${al})
90
+ AND started_at < :attachedAt`),this.rearmStmt=a.prepare(`UPDATE audit_events
91
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
92
+ WHERE (synced_at > 0
93
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
94
+ AND event_type IN (${an})`),this.claimStmt=a.prepare(`UPDATE history_sync
95
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
96
+ WHERE id = 1
97
+ AND (owner_pid IS NULL
98
+ OR heartbeat_at IS NULL
99
+ OR heartbeat_at < :staleBefore
100
+ OR heartbeat_at > :now)`),this.heartbeatStmt=a.prepare("UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid"),this.releaseStmt=a.prepare(`UPDATE history_sync
101
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
102
+ WHERE id = 1 AND owner_pid = :pid`),this.closeWindowStmt=a.prepare(`UPDATE audit_events
103
+ SET synced_at = ${String(-1)},
104
+ sync_failed_at = :at,
105
+ sync_failure = 'detached_undelivered'
106
+ WHERE synced_at IS NULL
107
+ AND event_type IN (${an})
108
+ AND started_at >= :attachedAt`),this.releaseBoundaryStmt=a.prepare("UPDATE history_sync SET backlog_before = NULL WHERE id = 1"),this.freezeBoundaryStmt=a.prepare("UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1"),this.leaseStmt=a.prepare(`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
109
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
110
+ FROM history_sync WHERE id = 1`),this.inspectionsStmt=a.prepare(`SELECT d.rule_id AS ruleId,
111
+ d.name AS ruleName,
112
+ d.version AS ruleVersion,
113
+ d.category AS category,
114
+ d.severity AS severity,
115
+ f.span_start AS spanStart,
116
+ f.span_end AS spanEnd,
117
+ f.masked_match AS maskedMatch,
118
+ f.action_taken AS actionTaken,
119
+ f.confidence AS confidence
120
+ FROM inspection_findings f
121
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
122
+ WHERE f.audit_event_id = :auditEventId
123
+ ORDER BY f.span_start, f.id`)}inspectionsFor(a){return ad(this.inspectionsStmt,{auditEventId:a})}pendingSessions(a,b){return ad(this.sessionsStmt,{limit:a,before:b}).map(a=>a.sessionId)}pendingRows(a,b,c){return ad(this.rowsStmt,{sessionId:a,limit:b,before:c})}pendingCaptureRows(a,b){return ad(this.captureRowsStmt,{limit:a,before:b})}markCaptureOwed(a){this.markOwedStmt.run({id:a})}markCaptureBacklogOwed(a){return Number(this.markCaptureBacklogOwedStmt.run({before:a}).changes)}markSynced(a,b){this.stampAll(a,b,null)}markSkipped(a,b){this.stampAll(a,-1,"payload_invalid",b)}markRefused(a,b){this.stampAll(a,-1,"deployment_refused",b)}eachInTransaction(a,b){0!==a.length&&Z(this.db,()=>{for(let c of a)b(c)},"IMMEDIATE")}stampAll(a,b,c,d){if(0===a.length)return;let e=null===c?null:d??null;Z(this.db,()=>{for(let d of a)this.stampStmt.run({at:b,failedAt:e,failure:c,id:d})},"IMMEDIATE")}claimRows(a,b){this.eachInTransaction(a,a=>this.claimRowStmt.run({at:b,id:a}))}releaseRows(a){this.eachInTransaction(a,a=>this.releaseRowStmt.run({id:a}))}releaseStaleClaims(a){return Number(this.releaseStaleClaimsStmt.run({staleBefore:a}).changes)}partitionByKind(){return ad(this.partitionByKindStmt,{}).map(a=>({kind:a.kind,queued:a.queued??0,inProgress:a.inProgress??0,synced:a.synced??0,failed:a.failed??0,refused:a.refused??0,detached:a.detached??0,total:a.total??0}))}partition(){let a=ae(this.partitionStmt,{});return{queued:a?.queued??0,inProgress:a?.inProgress??0,synced:a?.synced??0,failed:a?.failed??0,refused:a?.refused??0,detached:a?.detached??0,total:a?.total??0}}counts(a){let b=ae(this.countsStmt,{before:a}),c=ae(this.captureSkipCountStmt);return{pending:b?.pending??0,sent:b?.sent??0,skipped:b?.skipped??0,refused:b?.refused??0,detached:b?.detached??0,capturesSkipped:c?.skipped??0}}deployment(){let a=ae(this.fingerprintStmt);return{fingerprint:a?.fingerprint??void 0,backlogBefore:a?.backlogBefore??void 0}}rearmFor(a,b,c){this.ensureRowStmt.run(),Z(this.db,()=>{let d=ae(this.fingerprintStmt)?.fingerprint;this.rearmStmt.run(),null!=d&&d!==a&&this.disownCapturesStmt.run({attachedAt:b}),void 0!==c&&this.markCaptureBacklogOwedStmt.run({before:c}),this.setFingerprintStmt.run({fingerprint:a,backlogBefore:b})},"IMMEDIATE")}closeAttachedWindow(a,b){this.ensureRowStmt.run(),Z(this.db,()=>{let c=ae(this.fingerprintStmt),d=c?.backlogBefore??a;this.closeWindowStmt.run({at:b,attachedAt:d}),this.releaseBoundaryStmt.run()},"IMMEDIATE")}freezeBoundary(a){this.ensureRowStmt.run(),this.freezeBoundaryStmt.run({backlogBefore:a})}claim(a,b,c,d){this.ensureRowStmt.run();let e=!1;return Z(this.db,()=>{e=1===this.claimStmt.run({pid:a,host:b,now:c,staleBefore:c-d}).changes},"IMMEDIATE"),e}heartbeat(a,b){this.heartbeatStmt.run({now:b,pid:a})}release(a){this.releaseStmt.run({pid:a})}lease(){return ae(this.leaseStmt)}}let au=j.AJV.options;function av(a){return"column"===a.kind?`column ${a.table}.${a.name}`:`table ${a.name}`}function aw(a){return a.split(/-->\s*statement-breakpoint/).map(a=>a.trim()).filter(a=>a.length>0)}let ax="0014_drop_legacy_events_findings";function ay(a){let b=!1,c=[];for(let d of["events","findings"])try{let e=a.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${d}`).get();if(void 0===e){b=!0,c.push(`${d}:unreadable`);continue}e.n>0&&(b=!0),c.push(`${d}:${String(e.n)}:${String(e.hi)}`)}catch{b=!0,c.push(`${d}:unreadable`)}return{holdsRows:b,mark:c.join("|")}}let az=[{name:"input_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"},{name:"output_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"},{name:"cache_creation_input_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"},{name:"cache_read_input_tokens",ddl:"ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"},{name:"model",ddl:"ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"},{name:"provider",ddl:"ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"}];function aA(a,b,c,d){let e=function(a,b){let c=a.prepare("SELECT last_rowid AS lastRowid FROM legacy_copy_watermark WHERE source = ?").get(b);return c?.lastRowid??0}(a,b),f=0;for(;f<1e3;){let g=c.all(e,200);if(0===g.length||(Z(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 (?, ?)
124
+ ON CONFLICT(source) DO UPDATE SET last_rowid = excluded.last_rowid`).run(b,c)},"IMMEDIATE"),f+=g.length,g.length<200))return!0}return!1}function aB(a,b){if(null==a)return b;try{return JSON.parse(a)}catch{return b}}function aC(a){if(null!=a)try{let b=JSON.parse(a);if("object"==typeof b&&null!==b)return b}catch{}}function aD(a){return Buffer.from(JSON.stringify(a)).toString("base64url")}function aE(a){let b=aC(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&"startedAtMs"in b&&"id"in b&&Number.isInteger(b.startedAtMs)&&"string"==typeof b.id?b:null}function aF(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}let aG={session:"session",prompt:"prompt",response:"response",tool_call:"tool",hook:"hook",detection:"detection",share:"share",permission:"permission",commit:"commit",error:"error",active:"active"},aH=Object.keys(aG).map(a=>`'${a}'`).join(", ");function aI(a){if(!a)return[];let b=aB(a,null);return Array.isArray(b)?b:[]}let aJ=j.tLs.ClaudeCode;function aK(a){let b=j.TUN.safeParse(a);return b.success?b.data:aJ}function aL(a,b,c){let d=Math.max(a.started_at,b.lastActivityMs),{status:e,endedAtMs:f}=function(a,b,c){if(a.status){let b=j.PhW.safeParse(a.status);if(b.success)return{status:b.data,endedAtMs:a.ended_at}}return null!==a.ended_at?{status:"completed",endedAtMs:a.ended_at}:b>=c-18e5?{status:"active",endedAtMs:null}:{status:"completed",endedAtMs:b}}(a,d,c);return{id:a.id,harness:aK(a.harness),title:a.title||a.project||a.repo||`Session ${a.id.slice(0,8)}`,project:a.project??"",repo:a.repo??"",branches:aI(a.branches),startedAt:(0,j.q11)(a.started_at),endedAt:null===f?null:(0,j.q11)(f),status:e,turns:b.turns,findings:b.findings,shares:b.shares}}function aM(a){let b=aG[a.event_type];if(!b)return null;let c=a.severity?j.U7X.safeParse(a.severity):null,d=a.link?j.Itg.safeParse(a.link):null;return{id:a.id,occurredAt:(0,j.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:af(a.internal),flagged:af(a.flagged),bodyExpired:null!==a.content_expired_at&&(a.title??"")===""}}let aN=`
125
+ id,
126
+ event_type,
127
+ started_at,
128
+ coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
129
+ content_expired_at,
130
+ coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
131
+ coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
132
+ json_extract(attributes, '$.severity') AS severity,
133
+ json_extract(attributes, '$.link') AS link,
134
+ json_extract(attributes, '$.targetId') AS target_id,
135
+ json_extract(attributes, '$.internal') AS internal,
136
+ json_extract(attributes, '$.flagged') AS flagged`,aO=`
137
+ SELECT root_session_id AS sessionId,
138
+ provider,
139
+ model,
140
+ service_tier AS serviceTier,
141
+ coalesce(sum(input_tokens), 0) AS inputTokens,
142
+ coalesce(sum(output_tokens), 0) AS outputTokens,
143
+ coalesce(sum(cache_creation_input_tokens), 0) AS cacheCreationTokens,
144
+ coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
145
+ coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
146
+ coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
147
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests`,aP="event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL",aQ="GROUP BY root_session_id, provider, model, service_tier";function aR(a){return a.map(a=>{let b={input_tokens:a.inputTokens,output_tokens:a.outputTokens,cache_creation_input_tokens:a.cacheCreationTokens,cache_read_input_tokens:a.cacheReadTokens,ephemeral_1h_input_tokens:a.ephemeral1hTokens,ephemeral_5m_input_tokens:a.ephemeral5mTokens,web_search_requests:a.webSearchRequests};return null!==a.provider&&(b.provider=a.provider),null!==a.model&&(b.model=a.model),null!==a.serviceTier&&(b.service_tier=a.serviceTier),{sessionId:a.sessionId,attributes:b}})}let aS="event_type = 'session'",aT=`EXISTS (
148
+ SELECT 1 FROM audit_events c
149
+ WHERE c.root_session_id = audit_events.id
150
+ AND c.event_type NOT IN ('hook', 'config_scan'))`;class aU{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=aF();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??aF(),this.now()),d=ah(this.db,`SELECT count(*) AS n FROM audit_events
151
+ WHERE ${aS} AND started_at >= ? AND started_at < ?
152
+ AND ${aT}`,[b,c]),e=this.now()-18e5,f=ah(this.db,`SELECT count(*) AS n FROM audit_events s INDEXED BY sqlite_autoindex_audit_events_1
153
+ WHERE s.event_type = 'session' AND s.ended_at IS NULL
154
+ AND s.id IN (
155
+ SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
156
+ UNION
157
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
158
+ WHERE started_at >= ?
159
+ UNION
160
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
161
+ WHERE ended_at >= ?)`,[e,e,e]),g=ah(this.db,`SELECT count(*) AS n FROM audit_events
162
+ WHERE event_type = 'tool_call' AND started_at >= ? AND started_at < ?`,[b,c]);return Promise.resolve({sessionsToday:d,liveNow:f,toolCallsToday:g,findingsToday:ah(this.db,`SELECT count(*) AS n FROM inspection_findings f
163
+ JOIN audit_events e ON e.id = f.audit_event_id
164
+ WHERE e.started_at >= ? AND e.started_at < ?`,[b,c]),egressToday:ah(this.db,`SELECT count(DISTINCT json_extract(attributes, '$.destination')) AS n
165
+ FROM audit_events
166
+ WHERE event_type = 'share' AND started_at >= ? AND started_at < ?`,[b,c])})}listSessions(a){let b=a.cursor?aE(a.cursor):null,c=a.to?(0,j.I8t)(a.to):this.now(),d=a.from?(0,j.I8t)(a.from):void 0,e=[aS],f=[];if(a.harness&&a.harness.length>0&&(e.push(`coalesce(json_extract(attributes, '$.harness'), '${aJ}') IN (${V(a.harness.length)})`),f.push(...a.harness)),void 0!==d&&(e.push("started_at >= ?"),f.push(d)),e.push("started_at <= ?"),f.push(c),a.q){let b=W(a.q);e.push(`(content LIKE ? ESCAPE '\\'
167
+ OR json_extract(attributes, '$.project') LIKE ? ESCAPE '\\'
168
+ OR json_extract(attributes, '$.repo') LIKE ? ESCAPE '\\'
169
+ OR json_extract(attributes, '$.branches') LIKE ? ESCAPE '\\'
170
+ OR EXISTS (
171
+ SELECT 1 FROM audit_events d
172
+ WHERE d.root_session_id = audit_events.id
173
+ AND (d.content LIKE ? ESCAPE '\\'
174
+ OR coalesce(json_extract(d.attributes, '$.detail'),
175
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`),f.push(b,b,b,b,b,b)}let g=ah(this.db,`SELECT count(*) AS n FROM audit_events
176
+ WHERE ${[...e,`NOT ${aT}`].join(" AND ")}`,f);a.excludeEmpty&&e.push(aT),b&&(e.push("(started_at < ? OR (started_at = ? AND id < ?))"),f.push(b.startedAtMs,b.startedAtMs,b.id));let h=a.limit,i=ad(this.db.prepare(`SELECT id,
177
+ json_extract(attributes, '$.harness') AS harness,
178
+ content AS title,
179
+ json_extract(attributes, '$.project') AS project,
180
+ json_extract(attributes, '$.repo') AS repo,
181
+ json_extract(attributes, '$.branches') AS branches,
182
+ json_extract(attributes, '$.status') AS status,
183
+ started_at,
184
+ ended_at
185
+ FROM audit_events
186
+ WHERE ${e.join(" AND ")}
187
+ ORDER BY started_at DESC, id DESC
188
+ LIMIT ?`),[...f,h+1]),k=i.length>h,l=k?i.slice(0,h):i,m=this.rollupsFor(l.map(a=>a.id)),n=this.now(),o=l.map(a=>aL(a,m.get(a.id)??{turns:0,findings:0,shares:0,lastActivityMs:0},n)),p=l[l.length-1];return Promise.resolve({items:o,nextCursor:k&&p?aD({startedAtMs:p.started_at,id:p.id}):null,emptyCount:g})}getSession(a){let b=ae(this.db.prepare(`SELECT id,
189
+ json_extract(attributes, '$.harness') AS harness,
190
+ content AS title,
191
+ json_extract(attributes, '$.project') AS project,
192
+ json_extract(attributes, '$.repo') AS repo,
193
+ json_extract(attributes, '$.branches') AS branches,
194
+ json_extract(attributes, '$.status') AS status,
195
+ json_extract(attributes, '$.host') AS host,
196
+ json_extract(attributes, '$.cwd') AS cwd,
197
+ json_extract(attributes, '$.models') AS models,
198
+ json_extract(attributes, '$.version') AS version,
199
+ json_extract(attributes, '$.files') AS files,
200
+ started_at,
201
+ ended_at
202
+ FROM audit_events
203
+ WHERE id = ? AND event_type = 'session'
204
+ LIMIT 1`),[a]);if(!b)return Promise.resolve(null);let c=ad(this.db.prepare(`SELECT ${aN}
205
+ FROM audit_events
206
+ WHERE (id = ? OR root_session_id = ?) AND event_type IN (${aH})
207
+ ORDER BY started_at ASC, id ASC`),[a,a]).map(aM).filter(a=>null!==a),d=ae(this.db.prepare(`SELECT
208
+ coalesce(sum(input_tokens), 0) AS input,
209
+ coalesce(sum(output_tokens), 0) AS output,
210
+ coalesce(sum(cache_creation_input_tokens), 0) AS cache_creation,
211
+ coalesce(sum(cache_read_input_tokens), 0) AS cache_read
212
+ FROM audit_events INDEXED BY idx_audit_session_type
213
+ WHERE root_session_id = ? AND event_type = 'llm_call'`),[a])??{input:0,output:0,cache_creation:0,cache_read:0},e=ae(this.db.prepare(`SELECT model, provider FROM audit_events INDEXED BY idx_audit_session_type
214
+ WHERE root_session_id = ? AND event_type = 'llm_call'
215
+ ORDER BY started_at ASC, id ASC
216
+ LIMIT 1`),[a]),f=ad(this.db.prepare(`SELECT coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
217
+ count(*) AS n
218
+ FROM audit_events INDEXED BY idx_audit_session
219
+ WHERE root_session_id = ? AND event_type = 'tool_call'
220
+ GROUP BY coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool'))`),[a]),g=ad(this.db.prepare(`SELECT DISTINCT model FROM audit_events INDEXED BY idx_audit_session_type
221
+ WHERE root_session_id = ? AND event_type = 'llm_call' AND model IS NOT NULL AND model <> ''
222
+ ORDER BY model`),[a]).map(a=>a.model),h=ah(this.db,`SELECT count(*) AS n FROM audit_events INDEXED BY idx_audit_session
223
+ WHERE root_session_id = ? AND event_type = 'commit'`,[a]),i=this.rollupsFor([a]).get(a)??{turns:0,findings:0,shares:0,lastActivityMs:0},j={sessionId:a,model:e?.model??"",provider:e?.provider??"",inputTokens:d.input,outputTokens:d.output,cacheCreation:d.cache_creation,cacheRead:d.cache_read,totalTokens:d.input+d.output+d.cache_creation+d.cache_read,estimatedCostUsd:null};return Promise.resolve({...aL(b,i,this.now()),host:b.host??"",cwd:b.cwd??"",models:g.length>0?g:aI(b.models),version:b.version??"",tokens:j,tools:Object.fromEntries(f.flatMap(a=>a.tool?[[a.tool,a.n]]:[])),files:aI(b.files),commits:h,events:c})}tokenReports(a){let b=ad(this.db.prepare(`${aO}
224
+ FROM audit_events INDEXED BY idx_audit_llm_usage
225
+ WHERE ${aP}${void 0===a?"":" AND started_at >= ?"}
226
+ ${aQ}`),void 0===a?void 0:[a]);return Promise.resolve((0,j.ryv)(aR(b),j.q_t))}tokenReportForSession(a){let b=ad(this.db.prepare(`${aO}
227
+ FROM audit_events
228
+ WHERE ${aP} AND root_session_id = ?
229
+ ${aQ}`),[a]);return Promise.resolve((0,j.ryv)(aR(b),j.q_t)[0]??null)}harnessFacets(a){let b=ad(this.db.prepare(`SELECT DISTINCT coalesce(json_extract(attributes, '$.harness'), '${aJ}') AS harness
230
+ FROM audit_events WHERE ${aS}${void 0===a?"":" AND started_at >= ?"}`),void 0===a?void 0:[a]),c=new Set;for(let a of b)c.add(aK(a.harness));return Promise.resolve([...c])}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=V(a.length);for(let c of ad(this.db.prepare(`SELECT ids.value AS id,
231
+ (SELECT max(started_at) FROM audit_events e WHERE e.root_session_id = ids.value) AS ms,
232
+ (SELECT max(ended_at) FROM audit_events e
233
+ WHERE e.root_session_id = ids.value AND e.ended_at IS NOT NULL) AS me
234
+ FROM json_each(?) AS ids`),[JSON.stringify(a)])){let a=b.get(c.id),d=Math.max(c.ms??0,c.me??0);a&&d>0&&(a.lastActivityMs=d)}for(let d of ad(this.db.prepare(`SELECT root_session_id AS id, count(*) AS n
235
+ FROM audit_events INDEXED BY idx_audit_session_prompt
236
+ WHERE root_session_id IN (${c}) AND event_type = 'prompt'
237
+ 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 ad(this.db.prepare(`SELECT root_session_id AS id,
238
+ count(DISTINCT json_extract(attributes, '$.run_key')) AS n
239
+ FROM audit_events INDEXED BY idx_audit_session_run_key
240
+ WHERE root_session_id IN (${c}) AND event_type = 'llm_call'
241
+ AND json_extract(attributes, '$.run_key') IS NOT NULL
242
+ 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 ad(this.db.prepare(`SELECT e.root_session_id AS id, count(*) AS n FROM inspection_findings f
243
+ JOIN audit_events e ON e.id = f.audit_event_id
244
+ WHERE e.root_session_id IN (${c})
245
+ 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 ad(this.db.prepare(`SELECT root_session_id AS id,
246
+ count(DISTINCT json_extract(attributes, '$.destination')) AS n
247
+ FROM audit_events INDEXED BY idx_audit_session_share
248
+ WHERE root_session_id IN (${c}) AND event_type = 'share'
249
+ 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 aV{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO audit_events
250
+ (id, parent_id, root_session_id, event_type,
251
+ host_id, harness_id, source_project_id, started_at, ended_at,
252
+ severity, priority, content, content_hash, attributes)
253
+ VALUES
254
+ (:id, :parentId, :rootSessionId, :eventType,
255
+ :hostId, :harnessId, :sourceProjectId, :startedAt, :endedAt,
256
+ :severity, :priority, :content, :contentHash, :attributes)`),this.upsertLlmCallStmt=a.prepare(`INSERT INTO audit_events
257
+ (id, parent_id, root_session_id, event_type,
258
+ host_id, harness_id, source_project_id, started_at, ended_at,
259
+ severity, priority, content, content_hash, attributes)
260
+ VALUES
261
+ (:id, :parentId, :rootSessionId, :eventType,
262
+ :hostId, :harnessId, :sourceProjectId, :startedAt, :endedAt,
263
+ :severity, :priority, :content, :contentHash, :attributes)
264
+ ON CONFLICT(id) DO UPDATE SET
265
+ attributes = excluded.attributes,
266
+ ended_at = excluded.ended_at
267
+ WHERE COALESCE(json_extract(excluded.attributes, '$.output_tokens'), 0)
268
+ > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)`),this.upsertSessionRootStmt=a.prepare(`INSERT OR IGNORE INTO audit_events
269
+ (id, parent_id, root_session_id, event_type,
270
+ host_id, harness_id, source_project_id, started_at, ended_at,
271
+ severity, priority, content, content_hash, attributes)
272
+ VALUES
273
+ (:id, :parentId, :rootSessionId, :eventType,
274
+ :hostId, :harnessId, :sourceProjectId, :startedAt, :endedAt,
275
+ :severity, :priority, :content, :contentHash, :attributes)
276
+ ON CONFLICT(id) DO UPDATE SET
277
+ parent_id = excluded.parent_id,
278
+ root_session_id = excluded.root_session_id,
279
+ host_id = excluded.host_id,
280
+ harness_id = excluded.harness_id,
281
+ source_project_id = excluded.source_project_id,
282
+ started_at = min(audit_events.started_at, excluded.started_at),
283
+ ended_at = excluded.ended_at,
284
+ severity = excluded.severity,
285
+ priority = excluded.priority,
286
+ content = excluded.content,
287
+ content_hash = excluded.content_hash,
288
+ attributes = excluded.attributes
289
+ WHERE audit_events.attributes IS NULL AND excluded.attributes IS NOT NULL`)}runInTransaction(a){Z(this.db,a)}insertAuditEvent(a){let b=(0,j.V9M)(a);Number.isFinite(b.startedAt)&&("session"===b.eventType?this.upsertSessionRootStmt:this.insertStmt).run(ag({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,j.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.messageId,J((0,j.tTV)(["audit_event_llm_call",b,c])));this.upsertLlmCallStmt.run(ag({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,j.I8t)(a.startedAt);if(!Number.isFinite(d))return;let e=(b=a.sessionId,c=a.toolUseId,J((0,j.tTV)(["audit_event_tool_call",b,c])));this.insertStmt.run(ag({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 ae(this.db.prepare("SELECT * FROM audit_events WHERE id = :id"),{id:a})}sessionProvider(a){let b=this.findById(a);if(!b?.attributes)return;let c=aC(b.attributes)?.provider;if("string"==typeof c)return c}llmCallLeaves(){return ad(this.db.prepare(`SELECT root_session_id AS sessionId, attributes
290
+ FROM audit_events
291
+ WHERE event_type = 'llm_call' AND attributes IS NOT NULL`))}}class aW{constructor(a){this.db=a;let b=a=>`
292
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
293
+ FROM audit_events
294
+ WHERE content IS NOT NULL
295
+ AND started_at < :cutoff
296
+ AND event_type IN (${j.hfB})
297
+ ${a}
298
+ ORDER BY started_at
299
+ LIMIT :limit`;this.candidatesStmt=this.db.prepare(b("")),this.candidatesSyncSafeStmt=this.db.prepare(b(`AND (event_type NOT IN (${al}) OR synced_at IS NOT NULL)`)),this.heldBySyncStmt=this.db.prepare(`
300
+ SELECT COUNT(*) AS n
301
+ FROM audit_events
302
+ WHERE content IS NOT NULL
303
+ AND started_at < :cutoff
304
+ AND event_type IN (${al})
305
+ AND synced_at IS NULL`),this.expireStmt=this.db.prepare("UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id")}preview(a){let b=a.maxRows??5e4,c=(a.sweepSyncLane?this.candidatesStmt:this.candidatesSyncSafeStmt).all({cutoff:a.cutoff,limit:b});return{rowsExpired:c.length,bytesFreed:c.reduce((a,b)=>a+b.bytes,0),rowsHeldBySync:this.countHeldBySync(a)}}expire(a){let b=a.batchSize??500,c=a.maxRows??5e4,d=a.sweepSyncLane?this.candidatesStmt:this.candidatesSyncSafeStmt,e=0,f=0,g=!0;for(;e<c;){let h=Math.min(b,c-e),i=d.all({cutoff:a.cutoff,limit:h});if(0===i.length||(Z(this.db,()=>{for(let b of i)this.expireStmt.run({id:b.id,now:a.now})},"IMMEDIATE"),e+=i.length,f+=i.reduce((a,b)=>a+b.bytes,0),i.length<h))break;e>=c&&(g=0===d.all({cutoff:a.cutoff,limit:1}).length)}return{rowsExpired:e,bytesFreed:f,rowsHeldBySync:this.countHeldBySync(a),done:g}}countHeldBySync(a){return a.sweepSyncLane?0:this.heldBySyncStmt.get({cutoff:a.cutoff}).n}}class aX{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO classified_data (id, class, label, attributes)
306
+ VALUES (:id, :class, :label, :attributes)`)}upsert(a){var b;let c=(b=a.class,J((0,j.tTV)(["classified_data",b]))),d=(0,j.$BP)(a,c);return this.insertStmt.run(ag({id:d.id,class:d.class,label:d.label,attributes:d.attributes})),c}}function aY(a){return ae(a.prepare(`SELECT id, started_at, attributes FROM audit_events
307
+ WHERE event_type = 'config_scan'
308
+ ORDER BY started_at DESC, id DESC LIMIT 1`))}class aZ{constructor(a){this.db=a}report(){let a=aY(this.db);if(!a)return{scannedAt:null,skills:[],hooks:[],mcpServers:[],configFiles:[],topics:[]};let b=ad(this.db.prepare(`SELECT id, object_type AS objectType, title, location, attributes FROM inventory
309
+ WHERE object_type IN ('skill', 'hook', 'mcp_server', 'config_file') AND last_seen >= :startedAt
310
+ ORDER BY object_type, title`),{startedAt:a.started_at}),c=ad(this.db.prepare(`SELECT f.masked_match AS maskedMatch, d.rule_id AS ruleId, d.name AS name
311
+ FROM inspection_findings f
312
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
313
+ WHERE f.audit_event_id = :scanId`),{scanId:a.id}),d=[],e=[],f=[],g=[],h=this.trustOverrides();for(let a of b){let b=aC(a.attributes);b&&("skill"===a.objectType?d.push(function(a,b){let c={id:a.id,name:a.title??"(unnamed)",source:a$(b.source)??"unknown",scope:a$(b.scope)??"unknown",status:"unknown"},d=a$(b.description);void 0!==d&&(c.description=d);let e=a$(b.version);void 0!==e&&(c.installedVersion=e);let f=a$(b.updated_at);return void 0!==f&&(c.updatedAt=f),c}(a,b)):"hook"===a.objectType?e.push(function(a,b,c){let d=a$(b.command)??"",e=c.filter(a=>a.maskedMatch===d),f={id:a.id,event:a$(b.event)??"unknown",command:d,scope:a$(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=a$(b.matcher);void 0!==g&&(f.matcher=g);let h=a$(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:a$(b.scope)??"unknown",transport:a$(b.transport)??"unknown",trust:c.get(a.id)??"unapproved"},e=a$(b.command);void 0!==e&&(d.command=e);let f=a$(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=a$(b.plugin_name);void 0!==g&&(d.pluginName=g);let h=a$(b.marketplace);void 0!==h&&(d.marketplace=h);let i=a$(b.project);return void 0!==i&&(d.project=i),d}(a,b,h)):g.push(function(a,b){let c=a$(b.scope)??"unknown",d={id:a.id,name:a.title??"(unnamed)",path:a.location??"",scope:c,kind:a$(b.kind)??"Configuration file",untracked:"local"===c},e=a$(b.detail);void 0!==e&&(d.detail=e),"number"==typeof b.entry_count&&(d.entryCount=b.entry_count);let f=a$(b.updated_at);return void 0!==f&&(d.updatedAt=f),d}(a,b)))}return{scannedAt:new Date(a.started_at).toISOString(),skills:d,hooks:e,mcpServers:f,configFiles:g,topics:function(a,b,c,d,e){let f=[],g=a.filter(a=>"update_available"===a.status).length,h={topic:"skills",count:a.length};g>0&&(h.attention=`${String(g)} updates`),f.push(h);let i=b.filter(a=>"egress"===a.status).length,j=b.filter(a=>"conflict"===a.status).length,k=b.filter(a=>"unknown"===a.status).length,l=[];i>0&&l.push(`${String(i)} egress`),k>0&&l.push(`${String(k)} unknown`),j>0&&l.push(`${String(j)} conflict${j>1?"s":""}`);let m={topic:"hooks",count:b.length};l.length>0&&(m.attention=l.join(" \xb7 ")),f.push(m);let n=c.filter(a=>"unapproved"===a.trust).length,o={topic:"mcp",count:c.length};n>0&&(o.attention=`${String(n)} unapproved`),f.push(o);let p=d.filter(a=>a.untracked).length,q={topic:"config_files",count:d.length};p>0&&(q.attention=`${String(p)} untracked`),f.push(q);let r=function(a){let b=aC(a)?.errors;return"number"==typeof b?b:0}(e),s={topic:"configuration",count:r};return r>0&&(s.attention=`${String(r)} sources failed to parse`),f.push(s),f}(d,e,f,g,a.attributes)}}trustOverrides(){let a=ad(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 a$(a){return"string"==typeof a?a:void 0}function a_(a){let b=aB(a,[]);if(!Array.isArray(b))return[];let c=[];for(let a of b)a&&"object"==typeof a&&c.push(a);return c}function a0(a,b){return a.version!==b.version||a.rulesJson!==b.rulesJson}class a1{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}listDetections(a){let b=ad(this.db.prepare(`SELECT namespace, pack_id AS packId, version, name, enabled, policy_id AS policyId,
314
+ rules_json AS rulesJson
315
+ 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:af(a.enabled),ruleCount:a_(a.rulesJson).length,policyId:a.policyId,...b&&a0(a,b)?{latestVersion:b.version}:{}}});return Promise.resolve((0,j.plk)(d,a))}availableByPack(){return new Map(ad(this.db.prepare(`SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson
316
+ FROM available_packs`)).map(a=>[`${a.namespace}/${a.packId}`,a]))}getDetectionStats(){let a=ad(this.db.prepare("SELECT enabled, rules_json AS rulesJson FROM installed_packs")),b=0,c=0,d=new Set;for(let e of a){af(e.enabled)&&(c+=1);let a=a_(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,j.pnU)(a);if(!b)return Promise.resolve(null);let{namespace:c,packId:d}=b,e=ae(this.db.prepare(`SELECT namespace, pack_id AS packId, version, name, enabled, policy_id AS policyId,
317
+ rules_json AS rulesJson, updated_at AS updatedAt
318
+ FROM installed_packs
319
+ WHERE namespace = ? AND pack_id = ?`),[c,d]);if(!e)return Promise.resolve(null);let f=a_(e.rulesJson),g=f.map(a=>a.id).filter(a=>"string"==typeof a),h=this.countFindingsLast30d(g),i=this.availableByPack().get(`${e.namespace}/${e.packId}`),k=i?a0(e,i)?{available:!0,latestVersion:i.version,latestRuleCount:a_(i.rulesJson).length}:{available:!1,latestVersion:i.version}:null;return Promise.resolve((0,j.a45)({namespace:e.namespace,packId:e.packId,version:e.version,name:e.name,enabled:af(e.enabled),rules:f,updatedAt:new Date(e.updatedAt),policyId:e.policyId},h,k))}countFindingsLast30d(a){if(0===a.length)return 0;let b=this.now()-2592e6,c=V(a.length);return ah(this.db,`SELECT count(*) AS n
320
+ FROM inspection_findings f
321
+ JOIN audit_events e ON e.id = f.audit_event_id
322
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
323
+ WHERE e.started_at >= ?
324
+ AND e.event_type IN (${j.hfB})
325
+ AND d.rule_id IN (${c})`,[b,...a])}}class a2{constructor(a){this.db=a}contentHashes(){return Promise.resolve(new Set(ad(this.db.prepare(`SELECT content_hash FROM audit_events
326
+ WHERE event_type IN (${j.hfB})`)).map(a=>a.content_hash)))}}let a3=864e5;class a4 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 a5 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 a6=`revoked_at IS NULL
327
+ AND (expires_at IS NULL OR expires_at > :now)
328
+ AND (max_uses IS NULL OR use_count < max_uses)`,a7=`capability = 'reveal_to_model'
329
+ AND conditions IS NULL
330
+ AND ${a6}`;class a8{constructor(a,b=()=>Date.now()){this.db=a,this.now=b,this.consumeStmt=a.prepare(`UPDATE exceptions
331
+ SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
332
+ WHERE id = :id AND ${a6}`),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)
333
+ 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,H.randomUUID)(),c=this.now();try{this.insertExceptionRow(b,a,c)}catch(d){if(!(d instanceof Error&&(2067===d.errcode||d.message.includes("UNIQUE constraint failed"))))throw d;Z(this.db,()=>{if(1!==Number(this.db.prepare(`UPDATE exceptions
334
+ SET revoked_at = :now, revoked_by = :revokedBy,
335
+ revoke_reason = 'superseded by a new grant for the same value',
336
+ updated_at = :now
337
+ WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
338
+ AND key_version = :keyVersion AND revoked_at IS NULL
339
+ AND ((expires_at IS NOT NULL AND expires_at <= :now)
340
+ 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 a4(a.ruleId);this.insertExceptionRow(b,a,c)},"IMMEDIATE")}let d=ae(this.db.prepare("SELECT * FROM exceptions WHERE id = :id"),{id:b});if(void 0===d)throw Error("exception row not found immediately after insert");return a9(d)}insertExceptionRow(a,b,c){this.db.prepare(`INSERT INTO exceptions (
341
+ id, rule_id, category, value_fingerprint, key_version, masked_value,
342
+ capability, scope, expires_at, max_uses, use_count, last_used_at,
343
+ justification, conditions, created_by, created_via, created_at, updated_at
344
+ ) VALUES (
345
+ :id, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue,
346
+ :capability, :scope, :expiresAt, :maxUses, 0, NULL, :justification,
347
+ :conditions, :createdBy, :createdVia, :now, :now
348
+ )`).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,j.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 ${a6}`;return Promise.resolve(aj(ad(this.db.prepare(`SELECT * FROM exceptions ${b} ORDER BY created_at DESC, rowid DESC`),a?.includeTerminal?{}:{now:this.now()}),a9))}getByIdPrefix(a){if(0===a.length)return Promise.resolve(void 0);let b=ad(this.db.prepare(String.raw`SELECT * FROM exceptions WHERE id LIKE :pattern ESCAPE '\' LIMIT 2`),{pattern:`${U(a)}%`});if(b.length>1)return Promise.reject(new a5(a));let c=b[0];if(!c)return Promise.resolve(void 0);try{return Promise.resolve(a9(c))}catch{return Promise.resolve(void 0)}}revoke(a,b,c){let d=this.now();return Promise.resolve(1===Number(this.db.prepare(`UPDATE exceptions
349
+ SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
350
+ WHERE id = :id AND revoked_at IS NULL`).run({id:a,revokedBy:b,reason:c??null,now:d}).changes))}consume(a,b=this.now()){return Promise.resolve(1===Number(this.consumeStmt.run({id:a,now:b}).changes))}activeBundleEntries(a,b=this.now()){return Promise.resolve(aj(ad(this.db.prepare(`SELECT * FROM exceptions
351
+ WHERE key_version = :keyVersion AND ${a6}
352
+ ORDER BY created_at DESC, rowid DESC`),{keyVersion:a,now:b}),a=>{let b=null===a.conditions?null:JSON.parse(a.conditions);return j.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,j.q11)(a.expires_at),maxUses:a.max_uses,useCount:a.use_count,conditions:b})}))}recordBlocked(a){let b=this.now();return this.sweepBlockedStmt.run({cutoff:b-a3}),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(ad(this.db.prepare(`SELECT * FROM blocked_detections
353
+ WHERE blocked_at > :cutoff
354
+ ORDER BY blocked_at DESC, rowid DESC`),{cutoff:this.now()-a}).map(a=>({reference:a.reference,ruleId:a.rule_id,category:a.category,valueFingerprint:a.value_fingerprint,keyVersion:a.key_version,maskedValue:a.masked_value,sessionId:a.session_id,repo:a.repo,blockedAt:(0,j.q11)(a.blocked_at)})))}activeRevealGrant(a,b,c,d){try{let e=d??this.now(),f=ae(this.db.prepare(`SELECT id FROM exceptions
355
+ WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
356
+ AND key_version = :keyVersion
357
+ AND ${a7}
358
+ LIMIT 1`),{ruleId:a,valueFingerprint:b,keyVersion:c,now:e});return Promise.resolve(f??null)}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}sweepTerminal(a,b=this.now()){return Promise.resolve(Number(this.db.prepare(`DELETE FROM exceptions
359
+ WHERE updated_at < :cutoff
360
+ AND (revoked_at IS NOT NULL
361
+ OR (expires_at IS NOT NULL AND expires_at <= :now)
362
+ OR (max_uses IS NOT NULL AND use_count >= max_uses))`).run({cutoff:b-a,now:b}).changes))}}function a9(a){let b=null===a.conditions?null:JSON.parse(a.conditions);return j.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,j.q11)(a.expires_at),maxUses:a.max_uses,useCount:a.use_count,lastUsedAt:null===a.last_used_at?null:(0,j.q11)(a.last_used_at),justification:a.justification,conditions:b,createdBy:a.created_by,createdVia:a.created_via,createdAt:(0,j.q11)(a.created_at),updatedAt:(0,j.q11)(a.updated_at),revokedAt:null===a.revoked_at?null:(0,j.q11)(a.revoked_at),revokedBy:a.revoked_by,revokeReason:a.revoke_reason})}function ba(a){return`(
363
+ SELECT fr.status FROM finding_resolution fr
364
+ WHERE fr.finding_key = ${a}.finding_key
365
+ ORDER BY fr.created_at DESC, fr.rowid DESC
366
+ LIMIT 1
367
+ )`}let bb=`(
368
+ SELECT finding_key, status, method, resolved_at FROM (
369
+ SELECT fr.finding_key, fr.status, fr.method, fr.resolved_at,
370
+ ROW_NUMBER() OVER (
371
+ PARTITION BY fr.finding_key
372
+ ORDER BY fr.created_at DESC, fr.rowid DESC
373
+ ) AS rn
374
+ FROM finding_resolution fr
375
+ ) WHERE rn = 1
376
+ )`;function bc(a){return null===a||""===a?[]:a.split(",")}function bd(a){return{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,j.q11)(a.occurred_at),sourceTool:a.source_tool,repo:a.repo??"",file:a.file??"",...null===a.tool_name?{}:{toolName:a.tool_name},eventId:a.event_id,...null===a.session_id?{}:{sessionId:a.session_id},status:(0,j.xog)({kind:a.kind,findingKey:a.finding_key,latestResolutionStatus:a.latest_status}),delivery:(0,j.xHz)({kind:a.kind,syncedAt:a.synced_at,syncClaimedAt:a.sync_claimed_at,syncFailedAt:a.sync_failed_at,syncFailure:a.sync_failure,outboxOwed:a.outbox_owed})}}let be=`f.id AS id, d.rule_id AS rule_id, d.category AS category,
377
+ d.severity AS severity, f.masked_match AS masked_match,
378
+ f.action_taken AS action_taken, f.confidence AS confidence,
379
+ e.started_at AS occurred_at,
380
+ e.source_tool AS source_tool,
381
+ e.repo AS repo,
382
+ e.file_path AS file,
383
+ e.tool_name AS tool_name,
384
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
385
+ e.event_type AS kind, f.finding_key AS finding_key,
386
+ ${ba("f")} AS latest_status,
387
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
388
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
389
+ e.outbox_owed AS outbox_owed`;class bf{constructor(a){this.db=a}recentFindings(a){let b=a?.limit??50;return Promise.resolve(ad(this.db.prepare(`SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
390
+ f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
391
+ e.source_tool AS source_tool,
392
+ e.event_type AS kind
393
+ FROM audit_events e
394
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
395
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
396
+ WHERE +e.event_type IN (${j.hfB})
397
+ ORDER BY e.started_at DESC, f.rowid DESC
398
+ 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,j.q11)(a.occurred_at),sourceTool:a.source_tool,kind:a.kind})))}sessionFindingsCount(a){return a?Promise.resolve(ah(this.db,`SELECT count(*) AS n FROM inspection_findings f
399
+ JOIN audit_events e ON e.id = f.audit_event_id
400
+ WHERE e.root_session_id = :sessionId
401
+ AND e.event_type IN (${j.hfB})`,{sessionId:a})):Promise.resolve(0)}sessionFirings(a){return Object.fromEntries(ai(this.db,`SELECT d.rule_id AS k, count(*) AS n
402
+ FROM inspection_findings f
403
+ JOIN audit_events e ON e.id = f.audit_event_id
404
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
405
+ WHERE e.root_session_id = :sessionId
406
+ AND e.event_type NOT IN (${j.hfB})
407
+ GROUP BY d.rule_id`,{sessionId:a}))}listFindingTypes(a){let b=a.sessionId?" AND e.root_session_id = :sessionId":"",c=void 0===a.from?void 0:(0,j.I8t)(a.from),d=`WHERE e.event_type IN (${j.hfB})${b}${void 0===c?"":" AND e.started_at >= :fromMs"}`,e={...a.sessionId?{sessionId:a.sessionId}:{},...void 0===c?{}:{fromMs:c}},f=this.groupAggregates(void 0!==a.q&&""!==a.q,{predicate:d,params:e}),g=(0,j.Ple)(f),h={severity:a.severity,providers:a.provider,actions:a.action,statuses:a.status,subtype:a.subtype,q:a.q},i=(0,j.rG)(g,h),k=(0,j.X0p)((0,j.tXp)(g,h)),l=a.status??[],m={findings:k.reduce((a,b)=>{if(0===l.length)return a+b.instanceCount;let c=f.get(b.id);return a+(c?(0,j.Bfj)(c.statusInputs,l)??b.instanceCount:b.instanceCount)},0),types:k.length},n=a.limit??j.IYX,o=void 0===a.cursor?null:function(a){let b=aC(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&"string"==typeof b.sev&&"string"==typeof b.t&&"string"==typeof b.id?{severity:b.sev,latestDetectedAt:b.t,id:b.id}:null}(a.cursor),p=null===o?0:function(a,b){let c=a.findIndex(a=>(0,j._6W)(a,b)>0);return -1===c?a.length:c}(k,o),q=k.slice(p,p+n),r=q.at(-1),s=p+n<k.length&&r?function(a){let b={sev:a.severity,t:a.latestDetectedAt,id:a.id};return Buffer.from(JSON.stringify(b)).toString("base64url")}(r):null,t=void 0===a.includeId||""===a.includeId?void 0:function(a,b,c){if(!b.some(a=>a.id===c))return a.find(a=>a.id===c)}(k,q,a.includeId);return Promise.resolve({totals:m,facets:i,items:[...q,...t?[t]:[]],nextCursor:s,...a.sessionId?{sessionFirings:this.sessionFirings(a.sessionId)}:{}})}listFindingInstances(a){let b,c={severity:a.severity,subtype:a.subtype,providers:a.provider,actions:a.action,statuses:a.status,deliveries:a.deployment,tools:a.tool,repo:a.repo,file:a.file,q:a.q},d=a.limit??j.b2L,e=void 0===a.cursor?null:aE(a.cursor),f=null===e?()=>!0:a=>{let b=(0,j.I8t)(a.occurredAt);return b<=e.startedAtMs&&(b<e.startedAtMs||a.id<e.id)},g=(0,j.fj8)(c),h=[],i=0,k=!1;for(let e of this.scanFindingRows({sessionId:a.sessionId,from:a.from}))g.add(e),(0,j.am1)(e,c)&&(i+=1,f(e)&&(h.length<d?(h.push((0,j.MgS)(e)),b=e):k=!0));let l=k&&b?aD({startedAtMs:(0,j.I8t)(b.occurredAt),id:b.id}):null;return Promise.resolve({totals:{findings:i},facets:g.facets(),items:h,nextCursor:l})}listFindingLocations(a){let b={severity:a.severity,subtype:a.subtype,providers:a.provider,actions:a.action,statuses:a.status,deliveries:a.deployment,tools:a.tool,q:a.q},c=a.limit??j.p$t,d=void 0===a.cursor?null:function(a){let b=aC(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&"string"==typeof b.sev&&"string"==typeof b.t&&"string"==typeof b.r&&"string"==typeof b.f?{maxSeverity:b.sev,latestDetectedAt:b.t,repo:b.r,file:b.f}:null}(a.cursor),e=new Map,f=(0,j.fj8)(b),g=0;for(let c of this.scanFindingRows({sessionId:a.sessionId,from:a.from})){if(f.add(c),!(0,j.am1)(c,b))continue;g+=1;let a=e.get(c.repo);void 0===a&&(a=new Map,e.set(c.repo,a));let d=a.get(c.file);void 0===d&&(d=(0,j.SSj)(),a.set(c.file,d)),(0,j._5V)(d,c)}let h=[];for(let[a,b]of e)for(let[c,d]of b){let b=(0,j.JB8)(d.statuses);h.push({id:(0,j.ZoN)(a,c),repo:a,file:c,instanceCount:d.instanceCount,maxSeverity:d.maxSeverity,latestDetectedAt:d.latestDetectedAt,...void 0===b?{}:{status:b},ruleIds:[...d.ruleIds]})}h.sort(j.hml);let i=null===d?0:function(a,b){let c=a.findIndex(a=>(0,j.hml)(a,b)>0);return -1===c?a.length:c}(h,d),k=h.slice(i,i+c),l=k.at(-1),m=i+c<h.length&&l?function(a){let b={sev:a.maxSeverity,t:a.latestDetectedAt,r:a.repo,f:a.file};return Buffer.from(JSON.stringify(b)).toString("base64url")}(l):null,n=void 0===a.includeId||""===a.includeId?void 0:function(a,b,c){if(!b.some(a=>a.id===c))return a.find(a=>a.id===c)}(h,k,a.includeId);return Promise.resolve({totals:{findings:g,locations:h.length},facets:f.facets(),items:[...k,...n?[n]:[]],nextCursor:m})}*scanFindingRows(a){let{sql:b,params:c}=this.findingScanSql(a);for(let a of function*(a,b){for(let c of void 0===b?a.iterate():Array.isArray(b)?a.iterate(...b):a.iterate(b))yield c}(this.db.prepare(b),c))yield bd(a)}findingInstance(a){let b=this.db.prepare(`SELECT ${be}
408
+ FROM inspection_findings f
409
+ JOIN audit_events e ON e.id = f.audit_event_id
410
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
411
+ WHERE f.id = ?`).get(a);return Promise.resolve(void 0===b?null:(0,j.MgS)(bd(b)))}findingScanSql(a){let b=[`+e.event_type IN (${j.hfB})`],c=[];return void 0!==a.sessionId&&""!==a.sessionId&&(b.push("e.root_session_id = ?"),c.push(a.sessionId)),void 0!==a.from&&(b.push("e.started_at >= ?"),c.push((0,j.I8t)(a.from))),{sql:`SELECT ${be}
412
+ FROM audit_events e
413
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
414
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
415
+ WHERE ${b.join(" AND ")}
416
+ ORDER BY e.started_at DESC, f.id DESC`,params:c}}groupAggregates(a,b){let c=a?`, group_concat(DISTINCT e.repo) AS repos,
417
+ group_concat(DISTINCT e.file_path) AS files,
418
+ group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names`:", NULL AS repos, NULL AS files, NULL AS tool_names";return new Map(this.db.prepare(`SELECT rule_id,
419
+ -- BARE columns beside max(latest_at), which is deliberate and
420
+ -- is SQLite's documented behaviour: with a single min()/max()
421
+ -- in an aggregate query, every bare column takes its value from
422
+ -- the row that produced the extremum. So these are the severity
423
+ -- and category of the definition whose finding is NEWEST, which
424
+ -- is what the row-based build they replaced read off its first
425
+ -- (newest-first) row.
426
+ --
427
+ -- min() is WRONG here and was the defect: inspection_definitions
428
+ -- holds one row per rule VERSION (see its writer — a version bump
429
+ -- mints a new row), so a rule whose severity moved between
430
+ -- versions has several, and min() picks the ALPHABETICALLY
431
+ -- smallest — 'low' over 'medium', but 'critical' over 'high'.
432
+ -- That is arbitrary in direction, and it feeds the badge, the
433
+ -- filter, the facet counts and the primary sort key.
434
+ --
435
+ -- Adding a second min()/max() aggregate here would make these
436
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
437
+ severity,
438
+ category,
439
+ sum(tuple_count) AS instance_count,
440
+ max(latest_at) AS latest_at,
441
+ group_concat(source_tools) AS source_tools,
442
+ group_concat(actions_taken) AS actions_taken,
443
+ group_concat(status_tuple || '|' || tuple_count) AS status_inputs,
444
+ group_concat(repos) AS repos,
445
+ group_concat(files) AS files,
446
+ group_concat(tool_names) AS tool_names
447
+ FROM (
448
+ SELECT d.rule_id AS rule_id,
449
+ -- Severity and category are columns of the DEFINITION, and
450
+ -- a rule can have SEVERAL definitions (one per version), so
451
+ -- these are grouped on below and resolved to the newest
452
+ -- firing version by the outer query's bare-column select.
453
+ -- They ride the aggregate because the type build has no rows
454
+ -- to read them off — see buildFindingTypes.
455
+ d.severity AS severity,
456
+ d.category AS category,
457
+ e.event_type || '|' ||
458
+ (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '|' ||
459
+ coalesce(latest.status, '') AS status_tuple,
460
+ count(*) AS tuple_count,
461
+ max(e.started_at) AS latest_at,
462
+ group_concat(DISTINCT e.source_tool) AS source_tools,
463
+ group_concat(DISTINCT f.action_taken) AS actions_taken
464
+ ${c}
465
+ FROM inspection_findings f
466
+ JOIN audit_events e ON e.id = f.audit_event_id
467
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
468
+ LEFT JOIN ${bb} latest
469
+ ON latest.finding_key = f.finding_key
470
+ ${b.predicate}
471
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
472
+ )
473
+ GROUP BY rule_id`).all(b.params).map(b=>[b.rule_id,{instanceCount:b.instance_count,severity:b.severity,category:b.category,sourceTools:bc(b.source_tools),actionsTaken:bc(b.actions_taken),statusInputs:bc(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,j.q11)(b.latest_at),...a?{searchText:[b.repos??"",b.files??"",b.tool_names??""].filter(a=>""!==a).join(" ")}:{}}]))}healthSummary(){let a=ah(this.db,`SELECT count(*) AS n FROM inspection_findings f
474
+ JOIN audit_events e ON e.id = f.audit_event_id
475
+ WHERE e.event_type IN (${j.hfB})`),b=Object.fromEntries(j.S8C.map(a=>[a,0]));for(let a of ad(this.db.prepare(`SELECT f.action_taken AS action_taken, count(*) AS c
476
+ FROM inspection_findings f
477
+ JOIN audit_events e ON e.id = f.audit_event_id
478
+ WHERE e.event_type IN (${j.hfB})
479
+ GROUP BY f.action_taken`)))Object.hasOwn(b,a.action_taken)&&(b[a.action_taken]=a.c);let c={critical:0,high:0,medium:0,low:0};for(let a of ad(this.db.prepare(`SELECT d.severity AS severity, count(*) AS c
480
+ FROM inspection_findings f
481
+ JOIN audit_events e ON e.id = f.audit_event_id
482
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
483
+ LEFT JOIN ${bb} latest
484
+ ON latest.finding_key = f.finding_key
485
+ WHERE e.event_type IN (${j.hfB})
486
+ AND (latest.status IS NULL OR latest.status != 'resolved')
487
+ GROUP BY d.severity`)))Object.hasOwn(c,a.severity)&&(c[a.severity]=a.c);let d=j.IgC,e=new Set(ad(this.db.prepare(`SELECT DISTINCT json_extract(target, '$.category') AS category
488
+ 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=ad(this.db.prepare(`SELECT date(e.started_at / 1000, 'unixepoch') AS day, f.action_taken AS action, count(*) AS c
489
+ FROM inspection_findings f
490
+ JOIN audit_events e ON e.id = f.audit_event_id
491
+ WHERE e.started_at >= :since
492
+ AND e.event_type IN (${j.hfB})
493
+ 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 bg{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
494
+ (id, rule_id, name, category, severity, definition, version)
495
+ VALUES
496
+ (:id, :ruleId, :name, :category, :severity, :definition, :version)`)}upsert(a){let b=L(a.ruleId,a.version),c=(0,j.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 bh{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO inspection_findings
497
+ (id, audit_event_id, inspection_definition_id, classified_data_id,
498
+ span_start, span_end, masked_match, action_taken, confidence,
499
+ finding_key, first_detected_at)
500
+ VALUES
501
+ (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
502
+ :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
503
+ :findingKey,
504
+ COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
505
+ ON CONFLICT(id) DO UPDATE SET
506
+ inspection_definition_id = excluded.inspection_definition_id
507
+ ON CONFLICT (finding_key) DO UPDATE SET
508
+ audit_event_id = excluded.audit_event_id,
509
+ inspection_definition_id = excluded.inspection_definition_id,
510
+ classified_data_id = excluded.classified_data_id,
511
+ span_start = excluded.span_start,
512
+ span_end = excluded.span_end,
513
+ masked_match = excluded.masked_match,
514
+ action_taken = excluded.action_taken,
515
+ confidence = excluded.confidence`),this.sessionDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
516
+ JOIN audit_events e ON e.id = f.audit_event_id
517
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
518
+ WHERE d.rule_id = :ruleId AND f.masked_match = :maskedMatch
519
+ AND e.root_session_id = :sessionId
520
+ AND e.event_type IN (${j.hfB})
521
+ LIMIT 1`),this.eventDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
522
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
523
+ WHERE f.audit_event_id = :auditEventId AND d.rule_id = :ruleId
524
+ AND f.masked_match = :maskedMatch
525
+ AND f.span_start = :spanStart AND f.span_end = :spanEnd
526
+ 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,j.$3l)(a);this.insertStmt.run(ag({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}))}}c(51455);var bi=c(48161);function bj(){return(0,e.join)((0,bi.homedir)(),".aka")}function bk(a=bj()){return(0,e.join)(a,"settings")}function bl(a=bj()){return(0,e.join)(a,"data")}function bm(a=bj()){return(0,e.join)(a,"keys")}let bn=new Set(["EEXIST","EACCES","EPERM","EBUSY"]),bo=new Int32Array(new SharedArrayBuffer(4));class bp extends Error{constructor(a,b,c,d,e){super(`cannot lock ${b} for writing: ${c}`+(void 0===d?"":` (held by pid ${String(d)})`),e),this.name="FileLockError",this.reason=a,this.file=b,this.holderPid=d}}function bq(a){let b;try{b=(0,d.readFileSync)(a,"utf8")}catch{return null}try{let{pid:a,token:c,at:d,host:e}=JSON.parse(b);if("number"!=typeof a||"string"!=typeof c||"number"!=typeof d)return null;return{pid:a,token:c,at:d,host:"string"==typeof e?e:""}}catch{return null}}function br(a,b){let c,e=(0,H.randomUUID)();try{c=(0,d.openSync)(a,"wx",384)}catch(e){let c=e.code??"";if("EEXIST"===c||bn.has(c)&&((0,d.existsSync)(a)||function(a){let b=`${a}.probe-${(0,H.randomUUID)()}`;try{return(0,d.closeSync)((0,d.openSync)(b,"wx",384)),!0}catch{return!1}finally{try{(0,d.rmSync)(b,{force:!0})}catch{}}}(a)))return null;throw new bp("unavailable",b,e instanceof Error?e.message:String(e),void 0,{cause:e})}let f={pid:process.pid,token:e,at:Date.now(),host:(0,bi.hostname)()};try{(0,d.writeFileSync)(c,`${JSON.stringify(f)}
527
+ `)}catch{try{(0,d.closeSync)(c)}catch{}return(0,d.rmSync)(a,{force:!0}),null}try{(0,d.closeSync)(c)}catch{}return e}function bs(a=function(a=process.platform){return"darwin"===a?[e.posix.join("/Library","Application Support","AKASecurity",j.WRR),e.posix.join("/Library","Managed Preferences",j.WRR)]:"win32"===a?[e.win32.join("C:\\","ProgramData","AKASecurity",j.WRR)]:[e.posix.join("/etc","aka",j.WRR)]}()){for(let b of a){let a;try{a=(0,d.readFileSync)(b,"utf8")}catch{continue}let c=aC(a);if(!c)continue;let e=j.ZXz.safeParse(c);if(e.success)return e.data}return null}function bt(a,b,c=()=>new Date){if(!b)return a;let{values:d}=b,e={...a};return void 0!==d.runMode&&(e.runMode=d.runMode),void 0!==d.controlPlane&&(e.controlPlane={...d.controlPlane,attachedAt:a.controlPlane?.endpoint===d.controlPlane.endpoint?a.controlPlane.attachedAt:c().toISOString()}),void 0!==d.historicalAccess&&(e.historicalAccess=d.historicalAccess),void 0!==d.vaultKeyCustody&&(e.vaultKeyCustody=d.vaultKeyCustody),void 0!==d.vaultInlineReveal&&(e.vaultInlineReveal=d.vaultInlineReveal),void 0!==d.dataSharesInPlace&&(e.dataSharesInPlace=d.dataSharesInPlace),void 0!==d.redactFallback&&(e.redactFallback=d.redactFallback),void 0!==d.bodyRetention&&(e.bodyRetention=d.bodyRetention),void 0!==d.vaultConsent&&(e.vaultConsent=d.vaultConsent?a.vaultConsent?.version===j.DzG?a.vaultConsent:{acknowledgedAt:c().toISOString(),version:j.DzG}:void 0),void 0!==d.modelJudgeConsent&&(e.modelJudgeConsent=d.modelJudgeConsent?a.modelJudgeConsent?.payloadVersion===j.kxf?a.modelJudgeConsent:{acknowledgedAt:c().toISOString(),payloadVersion:j.kxf}:void 0),e}let bu="settings.json";function bv(a=bj()){return bt(bw(a),bs())}function bw(a){let b=function(a){let b;try{b=(0,d.readFileSync)(a,"utf8")}catch{return null}return aC(b)??null}((0,e.join)(bk(a),bu));if(!b)return(0,j.i1j)();try{return j.hd_.parse(b)}catch{return(0,j.i1j)()}}class bx extends Error{constructor(a){super(`refusing to write administratively locked settings: ${a.join(", ")}`),this.name="ManagedFieldError",this.fields=a}}function by(a,b=bj(),c){let f=bk(b);p(f);let g=(0,e.join)(f,bu),h=void 0===c?bs():c,i=h?{present:!0,...void 0===h.organization?{}:{organization:h.organization},lockedFields:h.lockedFields,...void 0===h.unknownLockedFields?{}:{unknownLockedCount:h.unknownLockedFields.length},...void 0===h.unknownValueFields?{}:{unknownValueCount:h.unknownValueFields.length}}:j.MhX;return function(a,b,c={}){let e=c.timeoutMs??5e3,f=c.staleMs??2e3,g=`${a}.lock`,h=Date.now()+e,i=br(g,a);for(;null===i;){if(function(a,b){let c,e=`${a}.break`;try{c=(0,d.openSync)(e,"wx",384)}catch{return function(a){try{Date.now()-(0,d.statSync)(a).mtimeMs>=1e4&&(0,d.rmSync)(a,{force:!0})}catch{}}(e),!1}try{(0,d.closeSync)(c)}catch{}try{if(!(0,d.existsSync)(a)||!function(a,b,c){var e;if(!a)try{return Date.now()-(0,d.statSync)(b).mtimeMs>=c}catch{return!1}return!(Date.now()-a.at<c)&&(!(a.host===(0,bi.hostname)()&&function(a){if(!Number.isInteger(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"ESRCH"!==a.code}}(a.pid))||Date.now()-a.at>=(e=c,Math.max(30*e,6e4)))}(bq(a),a,b))return!1;return(0,d.rmSync)(a,{force:!0}),!0}catch{return!1}finally{try{(0,d.rmSync)(e,{force:!0})}catch{}}}(g,f)){i=br(g,a);continue}if(Date.now()>=h)throw new bp("timeout",a,`still held after ${String(e)}ms`,bq(g)?.pid);Atomics.wait(bo,0,0,5),i=br(g,a)}try{var j;let c=b();if(j=c,"object"==typeof j&&null!==j&&"function"==typeof j.then)throw c.then(()=>void 0,()=>void 0),TypeError(`withFileLock(${a}) was given an async body; the lock is released as soon as it returns, so the awaited work would run unguarded. Pass a synchronous function.`);return c}finally{!function(a,b){try{if(bq(a)?.token!==b)return;(0,d.rmSync)(a,{force:!0})}catch{}}(g,i)}}(g,()=>{let c=bw(b),d="function"==typeof a?a(c):a,e=function(a,b){let c=[],d=c=>c in b&&b[c]!==a[c],e="controlPlane"in b&&(b.controlPlane?.endpoint!==a.controlPlane?.endpoint||b.controlPlane?.label!==a.controlPlane?.label);(d("runMode")||e)&&c.push("runMode"),d("historicalAccess")&&c.push("historicalAccess"),d("vaultKeyCustody")&&c.push("vaultKeyCustody"),d("vaultInlineReveal")&&c.push("vaultInlineReveal"),d("dataSharesInPlace")&&c.push("dataSharesInPlace"),d("redactFallback")&&c.push("redactFallback");let f=b.bodyRetention;return void 0!==f&&(f.enabled!==a.bodyRetention.enabled||f.retainDays!==a.bodyRetention.retainDays)&&c.push("bodyRetention"),"vaultConsent"in b&&(0,j.hds)(b.vaultConsent)!==(0,j.hds)(a.vaultConsent)&&c.push("vaultConsent"),"modelJudgeConsent"in b&&(0,j.DLF)(b.modelJudgeConsent)!==(0,j.DLF)(a.modelJudgeConsent)&&c.push("modelJudgeConsent"),c}(bt(c,h),d),f=i.present?e.filter(a=>i.lockedFields.includes(a)):[];if(f.length>0)throw new bx(f);let k=j.hd_.parse({...c,...function(a,b,c,d){if(!b.present)return a;let e=a=>(b.lockedFields.includes(a)||c.includes(a))&&!d.includes(a),f={...a};return e("runMode")&&(delete f.runMode,delete f.controlPlane),e("historicalAccess")&&delete f.historicalAccess,e("vaultConsent")&&delete f.vaultConsent,e("vaultKeyCustody")&&delete f.vaultKeyCustody,e("vaultInlineReveal")&&delete f.vaultInlineReveal,e("modelJudgeConsent")&&delete f.modelJudgeConsent,e("dataSharesInPlace")&&delete f.dataSharesInPlace,e("redactFallback")&&delete f.redactFallback,e("bodyRetention")&&delete f.bodyRetention,f}(d,i,function(a){if(!a)return[];let{values:b}=a,c=[];return(void 0!==b.runMode||void 0!==b.controlPlane)&&c.push("runMode"),void 0!==b.historicalAccess&&c.push("historicalAccess"),void 0!==b.vaultConsent&&c.push("vaultConsent"),void 0!==b.vaultKeyCustody&&c.push("vaultKeyCustody"),void 0!==b.vaultInlineReveal&&c.push("vaultInlineReveal"),void 0!==b.modelJudgeConsent&&c.push("modelJudgeConsent"),void 0!==b.dataSharesInPlace&&c.push("dataSharesInPlace"),void 0!==b.redactFallback&&c.push("redactFallback"),void 0!==b.bodyRetention&&c.push("bodyRetention"),c}(h),e),onboardedAt:d.onboardedAt??c.onboardedAt??new Date().toISOString()});return u(g,`${JSON.stringify(k,null,2)}
528
+ `),k})}class bz extends Error{constructor(a,b,c,d){super(function(a,b,c,d){switch(d){case"lock":return`refusing to re-assign '${a}': its policy is set by the connected control plane`;case"disable":return`refusing to disable '${a}': it is governed by the connected control plane`;case"floor":return`refusing to set '${a}' to '${b??"unassigned"}': the connected control plane requires at least '${c}'`}}(a,b,c,d)),this.name="PolicyFloorError",this.pack=a,this.attempted=b,this.floor=c,this.refusal=d}}function bA(a=bj()){if(!(0,j.lgf)(bv(a)))return null;let b=function(a=bj()){try{let b=(0,d.readFileSync)((0,e.join)(bl(a),f),"utf8"),c=JSON.parse(b);if("object"!=typeof c||null===c)return null;return j.vap.parse(c.bundle)}catch{return null}}(a);if(null===b)return null;let c=function(a){let b=new Map,c=new Map;for(let d of a)d.enabled&&("ruleId"in d.target?b.has(d.target.ruleId)||b.set(d.target.ruleId,d.action):c.has(d.target.category)||c.set(d.target.category,d.action));return{byRuleId:b,byCategory:c}}(b.policies);return{floorFor:a=>(function(a,b,{byRuleId:c,byCategory:d}){let e=null;for(let b of a){let a=c.get(b.id)??d.get(b.category);void 0!==a&&(e=null===e?a:(0,j.Lq6)(e,a))}return null===e?null:{floor:(0,j.GWi)(e),locked:function(a,b,c){let d=new Set(b.map(a=>a.id)),e=new Set(b.map(a=>a.category)),f=b.some(a=>c.has(a.id));return a.some(a=>!!a.enabled&&"authored"===a.provenance&&("ruleId"in a.target?d.has(a.target.ruleId):f&&e.has(a.target.category)))}(b,a,c)}})(a,b.policies,c)}}function bB(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 bC=j.Jr;function bD(a){return a.map(a=>{var b;return`${a.namespace}/${a.packId}@${a.version}#${b=a.rulesJson,(0,H.createHash)("sha256").update(b).digest("hex")}`}).sort().join(",")}function bE(a){let b=/^(\d+)\.(\d+)\.(\d+)/.exec(a);return b?[Number(b[1]),Number(b[2]),Number(b[3])]:null}class bF{constructor(a,b){this.db=a,this.baseDir=b,this.insertMissingStmt=a.prepare(`INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
529
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
530
+ 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)
531
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, :recordedBy, :now)
532
+ ON CONFLICT (namespace, pack_id) DO UPDATE SET
533
+ version = excluded.version,
534
+ name = excluded.name,
535
+ rules_json = excluded.rules_json,
536
+ recorded_by = excluded.recorded_by,
537
+ updated_at = excluded.updated_at
538
+ WHERE available_packs.version <> excluded.version
539
+ OR available_packs.name <> excluded.name
540
+ 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"),this.packRulesStmt=a.prepare(`SELECT rules_json AS rulesJson FROM installed_packs
541
+ WHERE namespace = ? AND pack_id = ?`)}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()===bD(c))return;let d=Date.now();Z(this.db,()=>{let a=this.mirrorState(),e=!1;for(let f of c){let c={id:(0,H.randomUUID)(),namespace:f.namespace,packId:f.packId,version:f.version,name:f.name,rulesJson:f.rulesJson,now:d},g=a.get(`${f.namespace}/${f.packId}`);void 0===g||!function(a,b){let c=bE(a.version);if(null===c)return!0;let d=bE(b.version);if(null===d)return!1;for(let a=0;a<3;a++){let b=c[a]??0,e=d[a]??0;if(b!==e)return b<e}for(let c of b.ruleIds)if(!a.ruleIds.has(c))return!0;return!1}(f,g)?this.upsertAvailableStmt.run({...c,id:(0,H.randomUUID)(),recordedBy:b?.recordedBy??null}):e=!0,this.insertMissingStmt.run(c)}e||this.pruneAvailable(c.map(a=>`${a.namespace}/${a.packId}`))},"IMMEDIATE")}catch{}}mirrorState(){return new Map(ad(this.db.prepare("SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs")).map(a=>[`${a.namespace}/${a.packId}`,{version:a.version,ruleIds:function(a){let b=new Set,c=aB(a,[]);if(!Array.isArray(c))return b;for(let a of c)if(a&&"object"==typeof a){let c=a.id;"string"==typeof c&&b.add(c)}return b}(a.rulesJson)}]))}pruneAvailable(a){let b=ad(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 Z(this.db,()=>{this.db.exec("UPDATE _pack_write_gate SET open = 1 WHERE id = 1");let d=this.db.prepare(`UPDATE installed_packs SET
542
+ version = (SELECT a.version FROM available_packs a
543
+ WHERE a.namespace = :namespace AND a.pack_id = :packId),
544
+ name = (SELECT a.name FROM available_packs a
545
+ WHERE a.namespace = :namespace AND a.pack_id = :packId),
546
+ rules_json = (SELECT a.rules_json FROM available_packs a
547
+ WHERE a.namespace = :namespace AND a.pack_id = :packId),
548
+ updated_at = :now
549
+ WHERE namespace = :namespace AND pack_id = :packId
550
+ AND EXISTS (SELECT 1 FROM available_packs a
551
+ 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=ad(this.db.prepare(`SELECT enabled, policy_id AS policyId, rules_json AS rulesJson, version,
552
+ namespace, pack_id AS packId
553
+ FROM installed_packs
554
+ ORDER BY namespace, pack_id`)),b={installedPacks:a.length,enabledPacks:0,rules:[],invalidRules:0,rejectedRules:[],ruleActions:new Map,ruleVersions:new Map,reversibleRules:new Set},c=(a,c,d)=>{b.rejectedRules.length>=10||b.rejectedRules.push({pack:a,ruleId:c,reason:d})};for(let d of a){let a;if(!af(d.enabled))continue;b.enabledPacks+=1;let e=(0,j.DhA)(d.policyId),f=(0,j.TdZ)(d.policyId),g=`${d.namespace}/${d.packId}`;try{a=JSON.parse(d.rulesJson)}catch{b.invalidRules+=1,c(g,null,"rules_json: malformed JSON");continue}if(!Array.isArray(a)){b.invalidRules+=1,c(g,null,"rules_json: not an array");continue}for(let h of a){let a=j.jON.safeParse(h);a.success?(b.rules.push(a.data),b.ruleActions.set(a.data.id,e),b.ruleVersions.set(a.data.id,d.version),f?b.reversibleRules.add(a.data.id):b.reversibleRules.delete(a.data.id)):(b.invalidRules+=1,c(g,function(a){if("object"!=typeof a||null===a)return null;let b=a.id;return j.jON.shape.id.safeParse(b).success?b:null}(h),function(a){let b=a.issues[0];if(!b)return"unknown";let c=b.path.map(a=>String(a)).join(".");return c?`${c}: ${b.code}`:b.code}(a.error)))}}return b}newestRecordedBinary(){let a=ad(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!==bB(e)&&(null===b||function(a,b){let c=bB(a),d=bB(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(ae(this.db.prepare(`SELECT count(*) AS packs,
555
+ coalesce(sum(json_array_length(rules_json)), 0) AS rules,
556
+ coalesce(sum(enabled), 0) AS enabled
557
+ FROM installed_packs`))??{packs:0,rules:0,enabled:0})}countsByPolicyId(){return ai(this.db,`SELECT coalesce(policy_id, '${bC}') AS k, count(*) AS n
558
+ FROM installed_packs
559
+ GROUP BY k`)}listByPolicyId(a){return ad(this.db.prepare(`SELECT namespace, pack_id AS packId, name, enabled, rules_json AS rulesJson
560
+ FROM installed_packs
561
+ WHERE coalesce(policy_id, '${bC}') = ?
562
+ ORDER BY name ASC`),[a]).map(a=>({id:`${a.namespace}/${a.packId}`,name:a.name,ruleCount:a_(a.rulesJson).length,enabled:af(a.enabled)}))}packFloorRules(a,b){let c=ae(this.packRulesStmt,[a,b]);return c?a_(c.rulesJson).map(a=>({id:a.id,category:a.category})):[]}policyFloor(a,b){return void 0===this.baseDir?null:function(a,b=bj()){let c=bA(b);return null===c?null:c.floorFor(a)}(this.packFloorRules(a,b),this.baseDir)}policyFloors(a){let b=new Map;if(void 0===this.baseDir)return b;let c=bA(this.baseDir);if(null===c)return b;for(let d of a){let a=c.floorFor(this.packFloorRules(d.namespace,d.packId));null!==a&&b.set(`${d.namespace}/${d.packId}`,a)}return b}setPolicy(a,b,c){if(null!==c&&!j.HUb.safeParse(c).success)throw Error(`Unknown policy '${c}'. Must be one of: ${j.V0H.join(", ")}.`);let d=this.policyFloor(a,b);if(null!==d){let e=function(a,b){if(b.locked)return"lock";let c=a??j.Jr;return(0,j.T2I)((0,j.fhc)(c),(0,j.fhc)(b.floor))?null:"floor"}(c,d);if(null!==e)throw new bz(`${a}/${b}`,c,d.floor,e)}return Number(this.db.prepare(`UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
563
+ WHERE namespace = :namespace AND pack_id = :packId`).run({policyId:c,now:Date.now(),namespace:a,packId:b}).changes)>0}setEnabled(a,b,c){let d=this.policyFloor(a,b);if(null!==d){let e=null===d||c?null:"disable";if(null!==e)throw new bz(`${a}/${b}`,null,d.floor,e)}return Number(this.db.prepare(`UPDATE installed_packs SET enabled = :enabled, updated_at = :now
564
+ WHERE namespace = :namespace AND pack_id = :packId`).run({enabled:+!!c,now:Date.now(),namespace:a,packId:b}).changes)>0}storedSignature(){return bD(ad(this.signatureStmt))}}class bG{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO inventory
565
+ (id, object_type, location, title, host_id, attributes, first_seen, last_seen)
566
+ VALUES
567
+ (:id, :objectType, :location, :title, :hostId, :attributes, :firstSeen, :lastSeen)
568
+ ON CONFLICT(id) DO UPDATE SET
569
+ location = excluded.location,
570
+ title = excluded.title,
571
+ host_id = excluded.host_id,
572
+ attributes = excluded.attributes,
573
+ last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){var c,d;let e=(c=a.objectType,d=a.identityKey,J((0,j.tTV)(["inventory",c,d]))),f=(0,j.gzP)(a,e,b);return this.upsertStmt.run(ag({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 ae(this.db.prepare("SELECT * FROM inventory WHERE id = :id"),{id:a})}distinctTitles(a){return ad(this.db.prepare(`SELECT DISTINCT title FROM inventory
574
+ WHERE object_type = :objectType AND title IS NOT NULL
575
+ ORDER BY title`),{objectType:a}).map(a=>a.title)}osVersions(){return ad(this.db.prepare(`SELECT DISTINCT os_version AS value FROM inventory
576
+ WHERE object_type = 'host' AND os_version IS NOT NULL
577
+ ORDER BY value`)).map(a=>a.value)}}let bH=["config","skill","mcp","hook"],bI=new Set(j.SHn.options),bJ="(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))",bK={[j.tLs.ClaudeCode]:"Claude Code",[j.tLs.Cursor]:"Cursor",[j.tLs.Codex]:"Codex",[j.tLs.Antigravity]:"Antigravity"},bL={accessCounts:{open:0,approved:0,blocked:0,total:0},findingsCount:0},bM=a=>a.toLowerCase().replace(/[\s-]/g,""),bN={ClaudeCode:bM(j.Zdp.ClaudeCode),Cursor:bM(j.Zdp.Cursor),Codex:bM(j.Zdp.Codex),Antigravity:bM(j.Zdp.Antigravity)};function bO(a,b){if(a.provider&&bI.has(a.provider))return a.provider;let c=bM(b.title??"");return c.includes(bN.ClaudeCode)||"claude"===c?j.tLs.ClaudeCode:c.includes(bN.Cursor)?j.tLs.Cursor:c.includes(bN.Codex)?j.tLs.Codex:c.includes(bN.Antigravity)?j.tLs.Antigravity:null}function bP(a){return a.some(a=>{let b=aB(a.attributes,{});return"sample"!==b.provenance&&bO(b,a)===j.tLs.ClaudeCode})}function bQ(a){let b={id:a.id,type:a.assetType,name:a.name,sub:a.sub??"",flags:aB(a.flagsJson,[])};return"mcp"===a.assetType&&a.effectiveTrust&&(b.trust=a.effectiveTrust),b}function bR(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 bS(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:bV(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 bT(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 ${bV(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 bU(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 bV(a,b){return a.length>b?`${a.slice(0,b-1)}…`:a}function bW(a,b,c){let d=aB(a.attributes,{});return{id:a.id,name:a.name??"",repo:a.url??"",visibility:d.visibility??"private",language:d.language??"",policyDefault:d.policyDefault??"approved",updatedAt:new Date(a.lastSeen).toISOString(),accessCounts:b,findingsCount:c}}function bX(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 bY{constructor(a){this.db=a}getInventoryStats(){let a=ai(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=ah(this.db,`SELECT count(*) AS n FROM source_project WHERE ${bJ}`);let c=ai(this.db,`SELECT coalesce(o.trust, a.trust) AS k, count(*) AS n
578
+ FROM inventory_asset a
579
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
580
+ WHERE a.asset_type = 'mcp' AND coalesce(o.trust, a.trust) IS NOT NULL
581
+ 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=ah(this.db,`SELECT count(*) AS n FROM inventory
582
+ WHERE object_type = 'harness'
583
+ AND (last_seen >= :liveSince OR json_extract(attributes, '$.provenance') = 'sample')`,{liveSince:Date.now()-2592e6}),f=ah(this.db,"SELECT count(*) AS n FROM inventory_asset WHERE flags_json <> '[]'"),g=ah(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=bO(aB(a.attributes,{}),a);if(!b)continue;let d=c.get(b);d?d.push(a):c.set(b,[a])}let d=this.assetsByHarness(b.map(a=>a.id),a),e=[...new Set(b.flatMap(a=>aB(a.attributes,{}).projectIds??[]))],f=this.fetchProjectsByIds(e),g=this.projectAggregates(e),h=this.configAssetRows(a,bP(b)),i=[];for(let[b,e]of c){let c=e.flatMap(a=>d.get(a.id)??[]),k=e.some(a=>"sample"!==aB(a.attributes,{}).provenance)&&b===j.tLs.ClaudeCode&&h.length>0?[...c,...h].sort((a,b)=>a.name.localeCompare(b.name)):c;if(a&&0===k.length)continue;let l=e[0];if(!l)continue;let m=aB(l.attributes,{}),n=[...new Set(e.flatMap(a=>aB(a.attributes,{}).projectIds??[]))].map(a=>f.get(a)).filter(a=>void 0!==a).map(a=>{let b=g.get(a.id)??bL;return bW(a,b.accessCounts,b.findingsCount)}),o=e.reduce((a,b)=>a+(aB(b.attributes,{}).sessions??0),0),p=k.reduce((a,b)=>a+aB(b.flagsJson,[]).length,0),q=new Map;for(let a of k){let b=q.get(a.assetType);b?b.push(bQ(a)):q.set(a.assetType,[bQ(a)])}let r=bH.filter(a=>q.has(a)).map(a=>({type:a,assets:q.get(a)??[]}));i.push({id:b,label:m.label??bK[b],kind:m.kind??m.provider??b,version:m.harness_version??l.harnessVersion??"",sessions:o,assetCount:k.length,flagCount:p,projects:n,categories:r})}return Promise.resolve({items: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 aB(a.flagsJson,[]))c.set(b,(c.get(b)??0)+1);let d={type:a,total:b.length,flagRollup:Object.fromEntries(c),items:b.map(bQ)};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)=>bH.indexOf(a.type)-bH.indexOf(b.type)),Promise.resolve({groups:d})}getAsset(a){let b=this.fetchAssetById(a);return Promise.resolve(b?function(a){let b={id:a.id,type:a.assetType,name:a.name,sub:a.sub??"",flags:aB(a.flagsJson,[]),description:a.description??null,trust:"mcp"===a.assetType?a.effectiveTrust??null:null,meta:aB(a.metaJson,{}),finding:null};if("mcp"===a.assetType&&null!==a.toolsJson){let c=aB(a.toolsJson,[]);b.tools="unapproved"===a.effectiveTrust?c.map(a=>({...a,risk:a.risk??"Tool access blocked: MCP server trust is unapproved."})):c}return b}(b):null)}listProjects(a){let b=this.fetchProjects(a),c=this.projectAggregates(b.map(a=>a.id));return Promise.resolve({items:b.map(a=>{let b=c.get(a.id)??bL;return bW(a,b.accessCounts,b.findingsCount)})})}getProjectTree(a,b){let c=this.fetchProjectById(a);if(!c)return Promise.resolve(null);let d=aB(c.attributes,{}),e={id:c.id,repo:c.url??"",visibility:d.visibility??"private"},f=b.path??"";if("blocked"===b.filter){let b=this.fetchProjectFilesBlocked(a);return b.sort((a,b)=>(b.blockedAtMs??0)-(a.blockedAtMs??0)),Promise.resolve({project:e,path:f,files:b.map(bX)})}if(void 0!==b.q&&""!==b.q)return Promise.resolve({project:e,path:f,files:this.fetchProjectFilesSearch(a,b.q).map(bX)});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(bX)})}getProjectFile(a,b){let c=this.fetchProjectById(a);if(!c)return Promise.resolve(null);let d=this.fetchProjectFile(a,b);if(!d)return Promise.resolve(null);let e=aB(c.attributes,{});return Promise.resolve({...bX(d),project:{repo:c.url??"",visibility:e.visibility??"private",language:e.language??"",policyDefault:e.policyDefault??"approved",updatedAt:new Date(c.lastSeen).toISOString()},findingsRefs:[]})}setFileAccess(a,b,c){let d=this.fetchProjectFile(a,b);return!!d&&(c===d.defaultAccess?this.db.prepare("DELETE FROM file_access_override WHERE project_id = ? AND path = ?").run(a,b):this.db.prepare(`INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
584
+ VALUES (:id, :projectId, :path, :access, :now, :now)
585
+ ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`).run({id:(0,H.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)
586
+ VALUES (:id, :assetId, :trust, :now, :now)
587
+ ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`).run({id:(0,H.randomUUID)(),assetId:a,trust:b,now:Date.now()}),this.configRowsCache=void 0,"ok"):"not_found"}fetchHarnessRows(){return ad(this.db.prepare(`SELECT id, title, attributes, harness_version AS harnessVersion
588
+ FROM inventory
589
+ WHERE object_type = 'harness'
590
+ 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 (${V(a.length)})`;if(b){let a=W(b);e+=` AND ${X(["a.name","a.sub"])}`,d.push(a,a)}for(let a of ad(this.db.prepare(`SELECT ha.harness_id AS harnessInvId, a.id, a.asset_type AS assetType, a.name, a.sub,
591
+ a.description, a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
592
+ a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
593
+ FROM harness_asset ha
594
+ JOIN inventory_asset a ON a.id = ha.asset_id
595
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
596
+ WHERE ${e}
597
+ 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 (${V(a.length)})`),d.push(...a)),b){let a=W(b);c.push(X(["a.name","a.sub"])),d.push(a,a)}let e=c.length?`WHERE ${c.join(" AND ")}`:"",f=this.mapAssetRows(ad(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
598
+ a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
599
+ a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
600
+ FROM inventory_asset a
601
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
602
+ ${e}
603
+ 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(ad(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
604
+ a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
605
+ a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
606
+ FROM inventory_asset a
607
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
608
+ 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??bP(this.fetchHarnessRows())))return[];let b=this.latestConfigScanId();if(null===b)return[];if(this.configRowsCache?.scanId===b)return this.configRowsCache.rows;let c=new aZ(this.db).report(),d=[...c.skills.map(bR),...c.hooks.map(bS),...c.mcpServers.map(bT),...c.configFiles.map(bU)].sort((a,b)=>a.name.localeCompare(b.name));return this.configRowsCache={scanId:b,rows:d},d}latestConfigScanId(){return aY(this.db)?.id??null}fetchProjects(a){let b=`SELECT id, url, name, attributes, last_seen AS lastSeen FROM source_project
609
+ WHERE ${bJ}`,c=[];if(a){let d=W(a);b+=` AND ${X(["name","url"])}`,c.push(d,d)}return b+=" ORDER BY name ASC",ad(this.db.prepare(b),c)}fetchProjectById(a){return ae(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 ad(this.db.prepare(`SELECT id, url, name, attributes, last_seen AS lastSeen
610
+ FROM source_project WHERE id IN (${V(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 ad(this.db.prepare(`SELECT f.project_id AS projectId,
611
+ coalesce(o.access, f.default_access) AS eff,
612
+ count(*) AS n,
613
+ coalesce(sum(f.findings_count), 0) AS findings
614
+ FROM project_file f
615
+ LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
616
+ WHERE f.project_id IN (${V(a.length)})
617
+ 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,
618
+ f.findings_count AS findingsCount, f.blocked_at AS blockedAtMs, f.note,
619
+ coalesce(o.access, f.default_access) AS effectiveAccess,
620
+ o.access AS overrideAccess
621
+ FROM project_file f
622
+ LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
623
+ 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(ad(this.db.prepare(this.fileSelect("f.project_id = ? ORDER BY f.path ASC")),[a])):this.mapFileRows(ad(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path LIKE ? ESCAPE '\\' ORDER BY f.path ASC")),[a,`${U(b)}/%`]))}fetchProjectFilesSearch(a,b){let c=W(b);return this.mapFileRows(ad(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(ad(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(ad(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path = ?")),[a,b]))[0]??null}}class bZ{constructor(a){this.db=a}readPolicies(){return Promise.resolve(aj(ad(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 j.PEm.parse({id:a.id,scope:a.scope,target:b,action:a.action,enabled:af(a.enabled),customKeywords:c})}))}seedDefaults(){if(ah(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)
624
+ VALUES (:id, 'global', :target, :action, 1, :now, :now)`);$(this.db,()=>{for(let[b,c]of Object.entries(j.unw))a.run({id:(0,H.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)
625
+ VALUES (:id, 'global', :target, :action, 1, :now, :now)
626
+ ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`).run({id:(0,H.randomUUID)(),target:JSON.stringify({category:a}),action:b,now:c})}capCategoryActions(){return Number(this.db.prepare(`UPDATE policies SET action='warn', updated_at=:now
627
+ WHERE scope='global' AND action IN ('block','redact')
628
+ 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 b${constructor(a){this.packs=a}getPolicyList(a){if("custom"===a)return Promise.resolve({items:[]});let b=this.packs.countsByPolicyId();return Promise.resolve({items:j.RRF.map(a=>({id:a,kind:"builtin",name:j.ZpU[a].name,enabled:!0,usedByCount:b.get(a)??0}))})}getPolicyStats(){let a=this.packs.countsByPolicyId(),b=j.V0H.reduce((b,c)=>b+(a.get(c)??0),0),c=j.V0H.length;return Promise.resolve({policies:c,builtin:c,custom:0,detectionsGoverned:b})}getPolicyDetail(a){let b=j.V0H.find(b=>b===a);if(void 0===b)return Promise.resolve(null);let c=j.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 b_{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
629
+ (id, project_id, path, name, origin, default_access, findings_count, blocked_at, note, created_at, updated_at)
630
+ VALUES
631
+ (:id, :projectId, :path, :name, :origin, :defaultAccess, 0, NULL, NULL, :now, :now)
632
+ ON CONFLICT (project_id, path) DO UPDATE SET
633
+ name = excluded.name,
634
+ origin = excluded.origin,
635
+ default_access = excluded.default_access,
636
+ updated_at = excluded.updated_at`),this.pruneStmt=a.prepare("DELETE FROM project_file WHERE project_id = :projectId AND updated_at < :now")}replaceForProject(a,b,c){let d=Math.max(c,(ae(this.maxStampStmt,{projectId:a})?.maxStamp??0)+1);for(let c of b.files)this.upsertStmt.run({id:(0,H.randomUUID)(),projectId:a,path:c.path,name:c.name,origin:c.origin,defaultAccess:c.defaultAccess,now:d});b.truncated||this.pruneStmt.run({projectId:a,now:d})}}class b0{constructor(a,b=()=>Date.now(),c=()=>(0,H.randomUUID)()){this.db=a,this.now=b,this.newId=c,this.insertStmt=a.prepare(`INSERT INTO finding_resolution (id, finding_key, status, method, resolved_at, evidence, created_at)
637
+ VALUES (:id, :findingKey, :status, :method, :resolvedAt, :evidence, :createdAt)`),this.latestStmt=a.prepare(`SELECT status, method, resolved_at, evidence
638
+ FROM finding_resolution
639
+ WHERE finding_key = :findingKey
640
+ ORDER BY created_at DESC, rowid DESC
641
+ LIMIT 1`),this.openAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
642
+ FROM inspection_findings f
643
+ JOIN audit_events e ON e.id = f.audit_event_id
644
+ WHERE e.event_type = 'code_change'
645
+ AND json_extract(e.attributes, '$.file_path') = :path
646
+ AND f.finding_key IS NOT NULL
647
+ AND ${ba("f")} IS NOT 'resolved'`),this.resolvedAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
648
+ FROM inspection_findings f
649
+ JOIN audit_events e ON e.id = f.audit_event_id
650
+ WHERE e.event_type = 'code_change'
651
+ AND json_extract(e.attributes, '$.file_path') = :path
652
+ AND f.finding_key IS NOT NULL
653
+ AND ${ba("f")} = 'resolved'`)}insertResolution(a){this.insertStmt.run({id:this.newId(),findingKey:a.findingKey,status:j.GCf.parse(a.status),method:j.cqq.parse(a.method),resolvedAt:a.resolvedAt,evidence:a.evidence,createdAt:this.now()})}latestByKey(a){let b=ae(this.latestStmt,{findingKey:a});if(b)return{status:b.status,method:b.method,resolvedAt:b.resolved_at,evidence:b.evidence??""}}openAtRestKeysForPath(a){return ad(this.openAtRestStmt,{path:a}).map(a=>a.finding_key)}resolvedAtRestKeysForPath(a){return ad(this.resolvedAtRestStmt,{path:a}).map(a=>a.finding_key)}}class b1{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO rule_probe_cache (rule_key, verdict, worst_probe_ms, checked_at)
654
+ VALUES (:ruleKey, :verdict, :worstProbeMs, :checkedAt)
655
+ ON CONFLICT (rule_key) DO UPDATE SET
656
+ verdict = excluded.verdict,
657
+ worst_probe_ms = excluded.worst_probe_ms,
658
+ checked_at = excluded.checked_at`),this.readStmt=a.prepare("SELECT verdict, worst_probe_ms AS worstProbeMs FROM rule_probe_cache WHERE rule_key = :ruleKey"),this.countQuarantinedStmt=a.prepare("SELECT COUNT(*) AS n FROM rule_probe_cache WHERE verdict = 'quarantined'"),this.clearQuarantinedStmt=a.prepare("DELETE FROM rule_probe_cache WHERE verdict = 'quarantined'")}getVerdict(a){return ae(this.readStmt,{ruleKey:a})}countQuarantined(){return ae(this.countQuarantinedStmt,{})?.n??0}clearQuarantined(){let a=this.countQuarantined();return{refused:!$(this.db,()=>{this.clearQuarantinedStmt.run()}),cleared:a-this.countQuarantined()}}setVerdict(a,b,c){$(this.db,()=>{this.upsertStmt.run({ruleKey:a,verdict:b,worstProbeMs:c,checkedAt:Date.now()})})}}class b2{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
659
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
660
+ ON CONFLICT (path) DO UPDATE SET
661
+ mtime = excluded.mtime,
662
+ content_hash = excluded.content_hash,
663
+ ruleset_hash = excluded.ruleset_hash,
664
+ scanned_at = excluded.scanned_at`),this.readStmt=a.prepare(`SELECT path, mtime, content_hash AS contentHash
665
+ FROM scan_ledger WHERE ruleset_hash = :rulesetHash`)}entriesForRuleset(a){return new Map(ad(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();$(this.db,()=>{for(let c of a)this.upsertStmt.run({path:c.path,mtime:c.mtime,contentHash:c.contentHash,rulesetHash:c.rulesetHash,scannedAt:b})})}}function b3(a,b){return void 0===a?b:Math.min(Math.max(1,Math.trunc(a)),j.u8Q)}let b4=`(v.occurrence_count > 1
666
+ OR (SELECT count(*) FROM secret_vault_sighting s WHERE s.pointer_id = v.pointer_id) > 1)`,b5=`v.pointer_id, v.category, v.rule_id, v.masked_match, v.provider,
667
+ v.occurrence_count, v.first_seen, v.last_seen`,b6=`
668
+ pointer_id AS pointerId,
669
+ value_fingerprint AS valueFingerprint,
670
+ fingerprint_key_version AS fingerprintKeyVersion,
671
+ key_version AS keyVersion,
672
+ format_version AS formatVersion,
673
+ category,
674
+ rule_id AS ruleId,
675
+ masked_match AS maskedMatch,
676
+ provider,
677
+ ciphertext,
678
+ nonce,
679
+ auth_tag AS authTag,
680
+ user_authorized AS userAuthorized,
681
+ occurrence_count AS occurrenceCount,
682
+ first_seen AS firstSeen,
683
+ last_seen AS lastSeen`;function b7(a){let{provider:b,userAuthorized:c,...d}=a,e={...d,userAuthorized:0!==c};return null===b?e:{...e,provider:b}}class b8{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO secret_vault (
684
+ pointer_id, value_fingerprint, fingerprint_key_version, key_version,
685
+ format_version, category, rule_id, masked_match, provider,
686
+ ciphertext, nonce, auth_tag,
687
+ user_authorized, occurrence_count, first_seen, last_seen
688
+ ) VALUES (
689
+ :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
690
+ :formatVersion, :category, :ruleId, :maskedMatch, :provider,
691
+ :ciphertext, :nonce, :authTag,
692
+ :userAuthorized, 1, :now, :now
693
+ )`),this.bumpStmt=a.prepare(`UPDATE secret_vault
694
+ SET occurrence_count = occurrence_count + 1, last_seen = :now,
695
+ user_authorized = max(user_authorized, :userAuthorized)
696
+ WHERE value_fingerprint = :valueFingerprint`),this.byPointerStmt=a.prepare(`SELECT ${b6} FROM secret_vault WHERE pointer_id = :pointerId`),this.byFingerprintStmt=a.prepare(`SELECT ${b6} FROM secret_vault WHERE value_fingerprint = :valueFingerprint`),this.listStmt=a.prepare(`SELECT ${b6} FROM secret_vault ORDER BY first_seen`),this.replaceCiphertextStmt=a.prepare(`UPDATE secret_vault
697
+ SET key_version = :keyVersion, ciphertext = :ciphertext, nonce = :nonce, auth_tag = :authTag
698
+ WHERE pointer_id = :pointerId`),this.refreshFingerprintStmt=a.prepare(`UPDATE secret_vault
699
+ SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
700
+ WHERE pointer_id = :pointerId`),this.deleteByPointerStmt=a.prepare("DELETE FROM secret_vault WHERE pointer_id = :pointerId"),this.derefStmt=a.prepare(`INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
701
+ VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`)}upsert(a,b){let c=!1;Z(this.db,()=>{if(void 0===ae(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint})){this.insertStmt.run(ag({pointerId:a.pointerId,valueFingerprint:a.valueFingerprint,fingerprintKeyVersion:a.fingerprintKeyVersion,keyVersion:a.keyVersion,formatVersion:a.formatVersion??j.viY,category:a.category,ruleId:a.ruleId,maskedMatch:a.maskedMatch,provider:a.provider,ciphertext:a.ciphertext,nonce:a.nonce,authTag:a.authTag,userAuthorized:+(!0===a.userAuthorized),now:b})),c=!0;return}this.bumpStmt.run({valueFingerprint:a.valueFingerprint,userAuthorized:+(!0===a.userAuthorized),now:b})},"IMMEDIATE");let d=ae(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint});if(void 0===d)throw Error("vault: row vanished immediately after write");return{row:b7(d),minted:c}}byPointerId(a){let b=ae(this.byPointerStmt,{pointerId:a});return void 0===b?null:b7(b)}byValueFingerprint(a){let b=ae(this.byFingerprintStmt,{valueFingerprint:a});return void 0===b?null:b7(b)}recordDeref(a){this.derefStmt.run(ag({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 ad(this.listStmt).map(b7)}replaceCiphertext(a,b){this.replaceCiphertextStmt.run({pointerId:a,...b})}refreshFingerprint(a,b){this.refreshFingerprintStmt.run({pointerId:a,...b})}purgeAll(){let a=0;return Z(this.db,()=>{a=this.countEntries(),this.db.exec("DELETE FROM secret_vault")},"IMMEDIATE"),a}deleteByPointerIds(a){if(0===a.length)return[];let b=[];return Z(this.db,()=>{for(let c of a)Number(this.deleteByPointerStmt.run({pointerId:c}).changes)>0&&b.push(c)},"IMMEDIATE"),b}recordSighting(a,b){this.db.prepare(`INSERT INTO secret_vault_sighting (id, pointer_id, location, kind, first_seen, last_seen)
702
+ VALUES (:id, :pointerId, :location, :kind, :now, :now)
703
+ ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`).run({id:(0,H.randomUUID)(),pointerId:a.pointerId,location:a.location,kind:a.kind,now:b})}sightingsFor(a){let b=new Map(a.map(a=>[a,[]]));if(0===a.length)return b;for(let c of ad(this.db.prepare(`SELECT pointer_id, location, kind, first_seen, last_seen
704
+ FROM secret_vault_sighting
705
+ WHERE pointer_id IN (${V(a.length)})
706
+ ORDER BY last_seen DESC`),a))b.get(c.pointer_id)?.push({location:c.location,kind:c.kind,firstSeen:new Date(c.first_seen).toISOString(),lastSeen:new Date(c.last_seen).toISOString()});return b}toInventoryEntries(a){let b=this.sightingsFor(a.map(a=>a.pointer_id));return a.map(a=>({pointerId:a.pointer_id,category:a.category,...null===a.provider?{}:{provider:a.provider},maskedMatch:a.masked_match,occurrences:a.occurrence_count,firstSeen:new Date(a.first_seen).toISOString(),lastSeen:new Date(a.last_seen).toISOString(),revealGrantId:a.grant_id,sightings:b.get(a.pointer_id)??[]}))}listInventory(a={},b=Date.now()){let c=b3(a.limit,j.mBk),d=void 0===a.cursor?null:aE(a.cursor),e=null===d?"":"WHERE (v.last_seen < :cursorLastSeen OR (v.last_seen = :cursorLastSeen AND v.pointer_id < :cursorPointerId))",f=ad(this.db.prepare(`SELECT ${b5},
707
+ (SELECT e.id FROM exceptions e
708
+ WHERE e.rule_id = v.rule_id
709
+ AND e.value_fingerprint = v.value_fingerprint
710
+ AND e.key_version = v.fingerprint_key_version
711
+ AND ${a7}
712
+ LIMIT 1) AS grant_id
713
+ FROM secret_vault v
714
+ ${e}
715
+ ORDER BY v.last_seen DESC, v.pointer_id DESC
716
+ LIMIT :limit`),ag({now:b,limit:c+1,...null===d?{}:{cursorLastSeen:d.startedAtMs,cursorPointerId:d.id}})),g=f.length>c,h=g?f.slice(0,c):f,i=h[h.length-1];return{totals:{values:this.countEntries()},items:this.toInventoryEntries(h),nextCursor:g&&i?aD({startedAtMs:i.last_seen,id:i.pointer_id}):null}}listReuse(a={},b=Date.now()){var c;let d=b3(a.limit,j.mBk),e=void 0===a.cursor?null:function(a){let b=aC(Buffer.from(a,"base64url").toString("utf8"));return void 0!==b&&Number.isInteger(b.occurrences)&&"string"==typeof b.pointerId?{occurrences:b.occurrences,pointerId:b.pointerId}:null}(a.cursor),f=null===e?"":`AND (v.occurrence_count < :cursorOccurrences
717
+ OR (v.occurrence_count = :cursorOccurrences AND v.pointer_id < :cursorPointerId))`,g=ad(this.db.prepare(`SELECT ${b5},
718
+ (SELECT e.id FROM exceptions e
719
+ WHERE e.rule_id = v.rule_id
720
+ AND e.value_fingerprint = v.value_fingerprint
721
+ AND e.key_version = v.fingerprint_key_version
722
+ AND ${a7}
723
+ LIMIT 1) AS grant_id
724
+ FROM secret_vault v
725
+ WHERE ${b4} ${f}
726
+ ORDER BY v.occurrence_count DESC, v.pointer_id DESC
727
+ LIMIT :limit`),ag({now:b,limit:d+1,...null===e?{}:{cursorOccurrences:e.occurrences,cursorPointerId:e.pointerId}})),h=g.length>d,i=h?g.slice(0,d):g,k=i[i.length-1];return{totals:{reused:this.countReused()},items:this.toInventoryEntries(i),nextCursor:h&&k?(c={occurrences:k.occurrence_count,pointerId:k.pointer_id},Buffer.from(JSON.stringify(c)).toString("base64url")):null}}listDerefs(a={}){let b=b3(a.limit,j.hdu),c=void 0===a.cursor?null:aE(a.cursor),d=[];!0!==a.includeBatched&&d.push("reason NOT IN ('display', 'view-render')"),null!==c&&d.push("(at < :cursorAt OR (at = :cursorAt AND id < :cursorId))");let e=0===d.length?"":`WHERE ${d.join(" AND ")}`,f=ad(this.db.prepare(`SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
728
+ FROM secret_vault_deref ${e}
729
+ ORDER BY at DESC, id DESC LIMIT :limit`),ag({limit:b+1,...null===c?{}:{cursorAt:c.startedAtMs,cursorId:c.id}})),g=f.length>b,h=g?f.slice(0,b):f,i=h[h.length-1],k=!0===a.includeBatched?0:ah(this.db,"SELECT count(*) AS n FROM secret_vault_deref WHERE reason IN ('display', 'view-render')");return{items:h.map(a=>({id:a.id,pointerId:a.pointer_id,at:new Date(a.at).toISOString(),target:a.target,reason:a.reason,outcome:a.outcome,...null===a.grant_id?{}:{grantId:a.grant_id},pointerCount:a.pointer_count})),nextCursor:g&&i?aD({startedAtMs:i.at,id:i.id}):null,hiddenBatched:k}}countEntries(){return ah(this.db,"SELECT COUNT(*) AS n FROM secret_vault")}countReused(){return ah(this.db,`SELECT COUNT(*) AS n FROM secret_vault v WHERE ${b4}`)}}let b9=["critical","high","medium","low"],ca={block:"blocked",redact:"redacted",warn:"warned"},cb=["blocked","redacted","warned"],cc={[j.tLs.Antigravity]:{coverage:60,supported:!0},[j.tLs.Api]:{coverage:0,supported:!1},[j.tLs.ChatGpt]:{coverage:40,supported:!0},[j.tLs.ClaudeAi]:{coverage:40,supported:!0},[j.tLs.ClaudeCode]:{coverage:100,supported:!0},[j.tLs.Codex]:{coverage:80,supported:!0},[j.tLs.Copilot]:{coverage:0,supported:!1},[j.tLs.Cursor]:{coverage:0,supported:!1}},cd={"7d":"day","30d":"day","3m":"week","6m":"week"};function ce(a){return 864e5*Math.floor(a/864e5)}function cf(a){return new Date(a).toISOString().slice(0,10)}class cg{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}severitySummary(){let a=new Map(ad(this.db.prepare(`SELECT d.severity AS severity,
730
+ COUNT(*) AS count,
731
+ SUM(CASE
732
+ WHEN e.event_type != 'code_change' THEN 1
733
+ WHEN f.finding_key IS NULL THEN 0
734
+ WHEN latest.status = 'resolved' THEN 1
735
+ ELSE 0
736
+ END) AS caught,
737
+ SUM(CASE
738
+ WHEN e.event_type = 'code_change'
739
+ AND f.finding_key IS NOT NULL
740
+ AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
741
+ ELSE 0
742
+ END) AS open_at_rest
743
+ FROM inspection_findings f
744
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
745
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
746
+ LEFT JOIN ${bb} latest
747
+ ON latest.finding_key = f.finding_key
748
+ WHERE e.event_type IN (${j.hfB})
749
+ GROUP BY d.severity`)).map(a=>[a.severity,a])),b=b9.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:j.KqW.options.map(a=>({provider:a,...cc[a]}))})}enforcementActions(a){let b=864e5*j.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=ca[a.actionTaken];b&&(a.occurredAt>=d?f[b]++:g[b]++)}let h=cb.map(a=>({kind:a,count:f[a],delta:f[a]-g[a]}));return Promise.resolve({range:a,total:h.reduce((a,b)=>a+b.count,0),actions:h})}findingsTimeseries(a){let b=cd[a],c=("day"===b?1:7)*864e5,d=j.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),g=ce(f)-(d-1)*864e5,h=this.findingsInRange(g,f),i=Array.from({length:e},(a,b)=>({timestamp:cf(g+b*c),critical:0,high:0,medium:0,low:0}));for(let a of h){let b=i[Math.floor((a.occurredAt-g)/c)];if(b){var k;("critical"===(k=a.severity)||"high"===k||"medium"===k||"low"===k)&&b[a.severity]++}}return Promise.resolve({range:a,granularity:b,points:i})}mttrTrend(a){let b=cd[a],c=("day"===b?1:7)*864e5,d=j.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),g=ce(f)-(d-1)*864e5,h=ad(this.db.prepare(`SELECT DISTINCT f.finding_key AS finding_key,
750
+ COALESCE(f.first_detected_at, e.started_at) AS first_detected_at, d.severity AS severity,
751
+ latest.status AS latest_status,
752
+ latest.method AS latest_method,
753
+ latest.resolved_at AS latest_resolved_at
754
+ FROM finding_resolution fr
755
+ CROSS JOIN inspection_findings f ON f.finding_key = fr.finding_key
756
+ CROSS JOIN audit_events e ON e.id = f.audit_event_id
757
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
758
+ LEFT JOIN ${bb} latest
759
+ ON latest.finding_key = f.finding_key
760
+ WHERE fr.resolved_at >= :windowStart
761
+ AND e.event_type IN (${j.hfB})`),{windowStart:g}),i=new Map,k=new Map;for(let a of h){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);i.set(d,(i.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 b9){let c=`${String(b)}:${a}`,e=k.get(c)??0;d[a]=e>0?(i.get(c)??0)/e:null}return{timestamp:cf(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*j.eI7[a];return Promise.resolve({range:a,items:ad(this.db.prepare(`SELECT e.repo AS repo, count(*) AS c
762
+ FROM inspection_findings f
763
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
764
+ WHERE e.started_at >= :from AND e.started_at < :to
765
+ AND e.event_type IN (${j.hfB})
766
+ AND e.repo IS NOT NULL
767
+ AND e.repo != ''
768
+ GROUP BY e.repo
769
+ ORDER BY c DESC, e.repo
770
+ 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:ad(this.db.prepare(`SELECT f.finding_key AS finding_key,
771
+ d.rule_id AS rule_id,
772
+ d.severity AS severity,
773
+ e.repo AS repo,
774
+ e.file_path AS path,
775
+ COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
776
+ latest.resolved_at AS latest_resolved_at
777
+ FROM ${bb} latest
778
+ CROSS JOIN inspection_findings f ON f.finding_key = latest.finding_key
779
+ CROSS JOIN audit_events e ON e.id = f.audit_event_id
780
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
781
+ WHERE latest.status = 'resolved'
782
+ AND latest.method = 'fixed-at-source'
783
+ AND latest.resolved_at IS NOT NULL
784
+ AND e.event_type = 'code_change'
785
+ ORDER BY latest.resolved_at DESC
786
+ LIMIT :limit`),{limit:a}).map(a=>({findingKey:a.finding_key,ruleId:a.rule_id,repo:a.repo??"",severity:a.severity,path:a.path??"",resolvedAt:new Date(a.latest_resolved_at).toISOString(),detectedAt:new Date(a.first_detected_at).toISOString()}))})}recommendationInputs(){return Promise.resolve(ad(this.db.prepare(`SELECT d.rule_id AS rule_id,
787
+ d.category AS category,
788
+ d.severity AS severity,
789
+ COUNT(*) AS count
790
+ FROM inspection_findings f
791
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
792
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
793
+ LEFT JOIN ${bb} latest
794
+ ON latest.finding_key = f.finding_key
795
+ WHERE e.event_type IN (${j.hfB})
796
+ AND e.event_type = 'code_change'
797
+ AND (
798
+ f.finding_key IS NULL
799
+ OR latest.status IS NULL
800
+ OR latest.status NOT IN ('resolved', 'dismissed')
801
+ )
802
+ GROUP BY d.rule_id, d.category, d.severity`)).map(a=>({ruleId:a.rule_id,category:a.category,severity:a.severity,count:a.count})))}findingsInRange(a,b){return ad(this.db.prepare(`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
803
+ d.rule_id AS rule_id, d.category AS category
804
+ FROM inspection_findings f
805
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
806
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
807
+ WHERE e.started_at >= :from AND e.started_at < :to
808
+ AND e.event_type IN (${j.hfB})
809
+ ORDER BY e.started_at`),{from:a,to:b}).map(a=>({occurredAt:a.occurred_at,severity:a.severity,actionTaken:a.action_taken,ruleId:a.rule_id,category:a.category}))}}let ch=["provider","internal","external","ip"],ci="('http', 'ws')",cj=`LEFT JOIN egress_decision_override oh ON oh.host = d.host
810
+ LEFT JOIN egress_decision_override ol ON ol.destination_id = d.id AND ol.host IS NULL`;function ck(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}}function cl(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))}}function cm(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 cn(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,j.Gw9)(a.trust,a.overrideDecision),isCustom:(0,j.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(f).toISOString(),endpointCount:b.length,callSiteCount:e,transports:(0,j.by7)(c),dataClasses:(0,j.hzO)(d),review:(0,j.Fnc)(a.trust,c,null!==a.overrideDecision),network:"provider"===a.kind?null:aB(a.networkJson,null),endpoints:b.map(cm)}}class co{constructor(a){this.db=a}stats(){let a=ah(this.db,"SELECT count(*) AS n FROM share_destination"),b=ah(this.db,"SELECT count(*) AS n FROM share_endpoint"),c=ah(this.db,"SELECT count(*) AS n FROM share_call_site"),d=ah(this.db,`SELECT count(DISTINCT destination_id) AS n FROM share_endpoint
811
+ WHERE transport IN ${ci}`),e=ah(this.db,`SELECT count(DISTINCT d.id) AS n
812
+ FROM share_destination d
813
+ LEFT JOIN share_endpoint e ON e.destination_id = d.id
814
+ AND e.transport IN ${ci}
815
+ WHERE (d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL)
816
+ AND NOT EXISTS (
817
+ SELECT 1 FROM egress_decision_override o
818
+ WHERE o.host = d.host OR (o.destination_id = d.id AND o.host IS NULL)
819
+ )`),f=ai(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=ai(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=>cn(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:ch.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:cn(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,j.C05)(b.map(a=>a.dataClass)),callSiteCount:a.callSiteCount,lastSeen:a.lastSeen})).sort((a,b)=>{let c=(0,j.WSs)(a.review.reasons)-(0,j.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,j.Gw9)(a.trust,a.overrideDecision),isCustom:(0,j.y_0)(a.trust,a.overrideDecision),lastSeen:new Date(e).toISOString(),transports:(0,j.by7)(d),dataClasses:(0,j.hzO)(b.map(a=>a.dataClass)),review:(0,j.Fnc)(a.trust,d,null!==a.overrideDecision),network:"provider"===a.kind?null:aB(a.networkJson,null),note:a.note,endpoints:b.map(a=>({...cm(a),sites:f.get(a.id)??[]}))}}(b,c,d))}setEgressDecision(a,b){let c=!1;return Z(this.db,()=>{let d=this.db.prepare("SELECT host FROM share_destination WHERE id = ?").get(a);void 0!==d&&(c=!0,this.db.prepare(`DELETE FROM egress_decision_override
820
+ WHERE host = :host OR (destination_id = :destinationId AND host IS NULL)`).run({host:d.host,destinationId:a}),null!==b&&this.db.prepare(`INSERT INTO egress_decision_override
821
+ (id, destination_id, host, decision, created_at, updated_at)
822
+ VALUES (:id, :destinationId, :host, :decision, :now, :now)`).run({id:(0,H.randomUUID)(),destinationId:a,host:d.host,decision:b,now:Date.now()}))},"IMMEDIATE"),c}recordProjectEgress(a){let{hits:b,droppedFiles:c,truncated:d}=ck(a.hits,a.reconcile.mode),e=cl(a.reconcile,c),f=Date.now(),g={destinations:0,endpoints:0,callSites:0,truncated:d,droppedFiles:c};return Z(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
823
+ WHERE project_key = :key
824
+ AND (:prefix = '' OR file = :prefix OR file LIKE :subtree ESCAPE '\\')
825
+ AND file NOT LIKE '.%'
826
+ AND file NOT LIKE '%/.%'`).run({key:a,prefix:c,subtree:`${U(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
827
+ WHERE project_key = ? AND file IN (${V(d.length)})`).run(a,...d)}}upsertHits(a,b,c,d){if(0===b.length)return;let e=this.db.prepare(`INSERT INTO share_destination
828
+ (id, kind, name, host, category, trust, network_json, last_seen, provenance,
829
+ created_at, updated_at)
830
+ VALUES (:id, :kind, :name, :host, :category, :trust, :networkJson, :now, 'scan', :now, :now)
831
+ ON CONFLICT (host) DO UPDATE SET
832
+ kind = excluded.kind,
833
+ name = excluded.name,
834
+ category = excluded.category,
835
+ trust = excluded.trust,
836
+ network_json = excluded.network_json,
837
+ last_seen = excluded.last_seen,
838
+ updated_at = excluded.updated_at`),f=this.db.prepare("SELECT id FROM share_destination WHERE host = ?"),g=this.db.prepare(`INSERT INTO share_endpoint
839
+ (id, destination_id, method, transport, url, template, data_class, last_seen,
840
+ created_at, updated_at)
841
+ VALUES (:id, :destinationId, :method, :transport, :url, :template, :dataClass, :now,
842
+ :now, :now)
843
+ ON CONFLICT (destination_id, method, url) DO UPDATE SET
844
+ transport = excluded.transport,
845
+ template = excluded.template,
846
+ data_class = excluded.data_class,
847
+ last_seen = excluded.last_seen,
848
+ updated_at = excluded.updated_at`),h=this.db.prepare("SELECT id FROM share_endpoint WHERE destination_id = ? AND method = ? AND url = ?"),i=this.db.prepare(`INSERT INTO share_call_site
849
+ (id, endpoint_id, project, project_key, file, line, snippet, dynamic, vendored,
850
+ project_id, created_at, updated_at)
851
+ VALUES (:id, :endpointId, :project, :projectKey, :file, :line, :snippet, :dynamic,
852
+ :vendored, :projectId, :now, :now)
853
+ ON CONFLICT (endpoint_id, project_key, file, line) DO UPDATE SET
854
+ snippet = excluded.snippet,
855
+ dynamic = excluded.dynamic,
856
+ vendored = excluded.vendored,
857
+ project = excluded.project,
858
+ project_id = COALESCE(excluded.project_id, share_call_site.project_id),
859
+ updated_at = excluded.updated_at`),j=new Map,k=new Map;for(let l of b){let b=j.get(l.host);void 0===b&&(e.run({id:(0,H.randomUUID)(),kind:l.kind,name:l.name,host:l.host,category:l.category,trust:l.trust,networkJson:null===l.network?null:JSON.stringify(l.network),now:d}),b=ae(f,[l.host])?.id??"",j.set(l.host,b));let m=`${b}\0${l.method}\0${l.url}`,n=k.get(m);void 0===n&&(g.run({id:(0,H.randomUUID)(),destinationId:b,method:l.method,transport:l.transport,url:l.url,template:+!!l.template,dataClass:l.dataClass,now:d}),n=ae(h,[b,l.method,l.url])?.id??"",k.set(m,n)),i.run({id:(0,H.randomUUID)(),endpointId:n,project:a.project,projectKey:a.projectKey,file:l.site.file,line:l.site.line,snippet:l.site.snippet,dynamic:+!!l.site.dynamic,vendored:+!!l.site.vendored,projectId:c,now:d})}}knownProjectId(a){return ae(this.db.prepare(`SELECT project_id AS projectId FROM share_call_site
860
+ 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
861
+ 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
862
+ WHERE id IN (SELECT DISTINCT e.destination_id
863
+ FROM share_endpoint e
864
+ JOIN share_call_site c ON c.endpoint_id = e.id
865
+ WHERE c.project_key = :key)`).run({now:b,key:a})}pruneOrphans(){this.db.exec(`DELETE FROM share_endpoint
866
+ 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
867
+ WHERE host IS NULL
868
+ AND destination_id IN (
869
+ SELECT d.id FROM share_destination d
870
+ WHERE NOT EXISTS (SELECT 1 FROM share_endpoint e WHERE e.destination_id = d.id))`),this.db.exec(`DELETE FROM share_destination
871
+ WHERE NOT EXISTS (
872
+ SELECT 1 FROM share_endpoint e WHERE e.destination_id = share_destination.id)`)}projectTotals(a){return{destinations:ah(this.db,`SELECT count(DISTINCT e.destination_id) AS n
873
+ FROM share_endpoint e
874
+ JOIN share_call_site c ON c.endpoint_id = e.id
875
+ WHERE c.project_key = ?`,[a]),endpoints:ah(this.db,"SELECT count(DISTINCT endpoint_id) AS n FROM share_call_site WHERE project_key = ?",[a]),callSites:ah(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,
876
+ d.network_json AS networkJson, d.last_seen AS lastSeenMs,
877
+ d.created_at AS createdAt,
878
+ COALESCE(oh.decision, ol.decision) AS overrideDecision`,f=[],g=[];if(b&&b.length>0&&(f.push(`d.kind IN (${V(b.length)})`),g.push(...b)),c&&f.push(`(d.trust IN ('unverified', 'ip')
879
+ OR EXISTS (SELECT 1 FROM share_endpoint re
880
+ WHERE re.destination_id = d.id
881
+ AND re.transport IN ${ci}))`),a){let b=W(a);f.push(`(d.name LIKE ? ESCAPE '\\' OR d.category LIKE ? ESCAPE '\\' OR e.url LIKE ? ESCAPE '\\'
882
+ OR c.project LIKE ? ESCAPE '\\' OR c.file LIKE ? ESCAPE '\\')`),g.push(b,b,b,b,b),d=`SELECT DISTINCT ${e}
883
+ FROM share_destination d
884
+ ${cj}
885
+ LEFT JOIN share_endpoint e ON e.destination_id = d.id
886
+ LEFT JOIN share_call_site c ON c.endpoint_id = e.id
887
+ ${f.length?`WHERE ${f.join(" AND ")}`:""}
888
+ ORDER BY d.created_at ASC, d.id ASC`}else d=`SELECT ${e}
889
+ FROM share_destination d
890
+ ${cj}
891
+ ${f.length?`WHERE ${f.join(" AND ")}`:""}
892
+ ORDER BY d.created_at ASC, d.id ASC`;return ad(this.db.prepare(d),g).map(a=>this.mapDestRow(a))}fetchDestinationById(a){let b=ae(this.db.prepare(`SELECT d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
893
+ d.network_json AS networkJson, d.last_seen AS lastSeenMs,
894
+ COALESCE(oh.decision, ol.decision) AS overrideDecision
895
+ FROM share_destination d
896
+ ${cj}
897
+ WHERE d.id = ?`),[a]);return b?this.mapDestRow(b):null}fetchEndpoints(a){return 0===a.length?[]:ad(this.db.prepare(`SELECT e.id, e.destination_id AS destinationId, e.method, e.transport, e.url,
898
+ e.template, e.data_class AS dataClass, e.last_seen AS lastSeenMs,
899
+ count(c.id) AS callSiteCount
900
+ FROM share_endpoint e
901
+ LEFT JOIN share_call_site c ON c.endpoint_id = e.id
902
+ WHERE e.destination_id IN (${V(a.length)})
903
+ GROUP BY e.id
904
+ 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?[]:ad(this.db.prepare(`SELECT id, endpoint_id AS endpointId, project, file, line, snippet, dynamic, vendored,
905
+ project_id AS projectId
906
+ FROM share_call_site
907
+ WHERE endpoint_id IN (${V(a.length)})
908
+ 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 cp{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO source_project
909
+ (id, url, name, attributes, first_seen, last_seen)
910
+ VALUES
911
+ (:id, :url, :name, :attributes, :firstSeen, :lastSeen)
912
+ ON CONFLICT(id) DO UPDATE SET
913
+ url = excluded.url,
914
+ name = excluded.name,
915
+ attributes = excluded.attributes,
916
+ last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){let c=K(a.url),d=(0,j.QCA)(a,c,b);return this.upsertStmt.run(ag({id:d.id,url:d.url,name:d.name,attributes:d.attributes,firstSeen:d.firstSeen,lastSeen:d.lastSeen})),c}findById(a){return ae(this.db.prepare("SELECT * FROM source_project WHERE id = :id"),{id:a})}distinctNames(){return ad(this.db.prepare(`SELECT DISTINCT name FROM source_project
917
+ WHERE name IS NOT NULL
918
+ ORDER BY name`)).map(a=>a.name)}}let cq=new Set(j.ZYZ.options),cr=Symbol("aka.persistence.unsafeTestOnlyRawHandle");function cs(a,b){return b?{...a,hostId:b}:a}function ct(a){try{a.close()}catch{}}function cu(a){let b=new I.DatabaseSync(a);try{b.exec("PRAGMA journal_mode = WAL"),b.exec("PRAGMA busy_timeout = 2000"),b.exec("PRAGMA foreign_keys = ON"),b.function("aka_lower",{deterministic:!0,directOnly:!0,useBigIntArguments:!0},T)}catch(a){throw ct(b),a}return b}let cv=new Set(j.vog);function cw(a,b={}){p(a);let c=(0,e.join)(a,l);Q(c);let{db:f,events:g,findings:h,policies:i,installedPacks:k,scanLedger:m,historySync:n,bodyRetention:o,secretVault:r,exceptions:t,resolutions:u,ruleProbeCache:v,security:w,detections:x,shares:y,policyCatalog:z,inventory:A,inventoryAssets:B,projectFiles:C,activity:D,sourceProject:E,auditEvents:F,classifiedData:G,inspectionDefinitions:I,inspectionFindings:N,configInventory:O}=function(a,b,c){let e=cu(a);try{var f;if(f=e,aa(f,"table","tenants")||ac(f,"events").includes("tenant_id")){let b=function(a,b){let c;Q(b);let e=M(b,"legacy"),f=!1;try{R(a,e),f=!0}catch(a){c=a}finally{a.close()}if(!f){_(`Could not snapshot the incompatible ${l} (${String(c)}); moving the store aside with its sidecars instead.`);let a=[];(0,d.renameSync)(b,e),a.push([e,b]);try{for(let c of q(b)){let f=`${e}${c.slice(b.length)}`;try{(0,d.renameSync)(c,f),a.push([f,c])}catch{(0,d.rmSync)(c,{force:!0})}}}catch(b){for(let[b,c]of a.reverse())try{(0,d.renameSync)(b,c)}catch{}throw b}return s(e),e}try{for(let a of((0,d.rmSync)(b,{force:!0}),q(b)))(0,d.rmSync)(a,{force:!0})}catch(a){if((0,d.existsSync)(b))try{(0,d.rmSync)(e,{force:!0})}catch{}throw a}return e}(e,a);e=cu(a),_(`Detected an older, incompatible (tenant-bearing) ${l}; backed it up to ${b} and created a fresh store.`)}!function(a,b,c={}){var 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)),h=0===g.size&&f>0,i=a.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)");for(let[b,d]of j.lFU.entries()){if(g.has(d.tag)||c.skipTags?.has(d.tag)===!0||d.tag===ax)continue;let e=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}(d.sql),j=e.filter(b=>"column"===b.kind?ac(a,b.table,{includeGenerated:!0}).includes(b.name):aa(a,"table",b.name));if(j.length>0&&j.length<e.length){let a=e.filter(a=>!j.includes(a)),b=`sqlite migration ${d.tag} has no ledger row, but the store already has ${j.map(av).join(", ")} while missing ${a.map(av).join(", ")} — the schema diverged from the migration history; refusing to replay or skip.`;throw _(b),Error(`[aka] ${b}`)}let k=e.length>0?j.length===e.length:h&&b<f,l=/PRAGMA foreign_keys\s*=\s*OFF/i.test(d.sql),m=aw(d.sql);l&&a.exec("PRAGMA foreign_keys = OFF");try{Z(a,()=>{for(let b of m){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(k)continue}else if(ab(a,c))continue;a.exec(b)}if(l&&!k){let b=a.prepare("PRAGMA foreign_key_check").all();if(b.length>0)throw Error(`[aka] sqlite migration ${d.tag} left ${String(b.length)} foreign-key violation(s); rolling back.`)}i.run(d.tag,Date.now())},"IMMEDIATE")}finally{l&&a.exec("PRAGMA foreign_keys = ON")}}f<j.lFU.length&&a.exec(`PRAGMA user_version = ${String(j.lFU.length)}`),function(a,b){var c;if(!aa(a,"table",b))return;let d=ac(a,b);d.includes("synced_at")||a.exec(`ALTER TABLE ${b} ADD COLUMN synced_at integer`),d.includes("sync_claimed_at")||a.exec(`ALTER TABLE ${b} ADD COLUMN sync_claimed_at integer`),d.includes("outbox_owed")||a.exec(`ALTER TABLE ${b} ADD COLUMN outbox_owed integer`),d.includes("sync_failed_at")||a.exec(`ALTER TABLE ${b} ADD COLUMN sync_failed_at integer`),d.includes("sync_failure")||Z(a,()=>{a.exec(`ALTER TABLE ${b} ADD COLUMN sync_failure text`),a.exec(`UPDATE ${b} SET synced_at = NULL
919
+ WHERE synced_at = -1
920
+ AND event_type IN (${ao.map(a=>`'${a}'`).join(", ")})`)},"IMMEDIATE"),a.exec(`CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
921
+ BEFORE UPDATE OF sync_failure ON ${b}
922
+ WHEN ${function(a="sync_failure"){let b=au.map(a=>`'${a}'`).join(", ");return`NEW.${a} IS NOT NULL AND NEW.${a} NOT IN (${b})`}()}
923
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`);let e=["event_type","synced_at","sync_claimed_at","started_at","sync_failure"],f=(c="idx_audit_events_sync",ab(a,c)?a.prepare(`PRAGMA index_info(${c})`).all().map(a=>a.name).filter(a=>null!==a):[]);f.length===e.length&&f.every((a,b)=>a===e[b])||(a.exec("DROP INDEX IF EXISTS idx_audit_events_sync"),a.exec(`CREATE INDEX idx_audit_events_sync
924
+ ON audit_events (${e.join(", ")})`)),a.exec(`CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
925
+ ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`),a.exec(`CREATE INDEX IF NOT EXISTS idx_audit_claimed
926
+ ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`)}(a,"audit_events"),a.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
927
+ path TEXT PRIMARY KEY,
928
+ mtime TEXT NOT NULL,
929
+ content_hash TEXT NOT NULL,
930
+ ruleset_hash TEXT NOT NULL,
931
+ scanned_at INTEGER NOT NULL
932
+ )`),(d=a).exec(`CREATE TABLE IF NOT EXISTS history_sync (
933
+ id INTEGER PRIMARY KEY CHECK (id = 1),
934
+ endpoint_fingerprint TEXT,
935
+ backlog_before INTEGER,
936
+ owner_pid INTEGER,
937
+ owner_host TEXT,
938
+ acquired_at INTEGER,
939
+ heartbeat_at INTEGER
940
+ )`),ac(d,"history_sync").includes("backlog_before")||d.exec("ALTER TABLE history_sync ADD COLUMN backlog_before integer"),a.exec(`CREATE TABLE IF NOT EXISTS blocked_detections (
941
+ reference TEXT PRIMARY KEY,
942
+ rule_id TEXT NOT NULL,
943
+ category TEXT NOT NULL,
944
+ value_fingerprint TEXT NOT NULL,
945
+ key_version INTEGER NOT NULL,
946
+ masked_value TEXT NOT NULL,
947
+ session_id TEXT,
948
+ repo TEXT,
949
+ blocked_at INTEGER NOT NULL
950
+ )`),a.exec(`CREATE TABLE IF NOT EXISTS rule_probe_cache (
951
+ rule_key TEXT PRIMARY KEY,
952
+ verdict TEXT NOT NULL,
953
+ worst_probe_ms REAL NOT NULL,
954
+ checked_at INTEGER NOT NULL
955
+ )`),(e=a).exec(`CREATE TABLE IF NOT EXISTS \`_pack_write_gate\` (
956
+ \`id\` integer PRIMARY KEY NOT NULL,
957
+ \`open\` integer DEFAULT 0 NOT NULL,
958
+ CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)
959
+ )`),e.exec("INSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0)"),aa(e,"table","installed_packs")&&e.exec(`CREATE TRIGGER IF NOT EXISTS trg_installed_packs_write_gate
960
+ BEFORE UPDATE OF version, name, rules_json ON installed_packs
961
+ WHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1
962
+ BEGIN SELECT RAISE(IGNORE); END`),function(a){if(!aa(a,"table","audit_events"))return;let b=new Set(ac(a,"audit_events",{includeGenerated:!0}));for(let c of az)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
963
+ FROM source_project
964
+ WHERE url IS NOT NULL AND id NOT LIKE 'sample:%'
965
+ ORDER BY last_seen DESC, id`).all().map(a=>({row:a,canonicalId:K(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)
966
+ VALUES (?, ?, ?, ?, ?, ?)
967
+ ON CONFLICT(id) DO UPDATE SET
968
+ first_seen = min(first_seen, excluded.first_seen),
969
+ 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 = ?
970
+ 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 = ?");Z(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){_(`source_project id reconcile failed: ${String(a)}`)}}(a),!g.has(ax)&&function(a){try{if(!function(a){let b=a.prepare(`SELECT rowid AS rowid, id, source_tool AS sourceTool, kind, occurred_at AS occurredAt,
971
+ content_hash AS contentHash, content, metadata
972
+ FROM events WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO audit_events
973
+ (id, parent_id, root_session_id, event_type, started_at, content, content_hash, attributes)
974
+ VALUES (:id, :parentId, :rootSessionId, :eventType, :startedAt, :content, :contentHash, :attributes)`),d=a.prepare("INSERT OR IGNORE INTO audit_events (id, event_type, started_at) VALUES (?, 'session', ?)");return aA(a,"events",b,a=>{for(let e of a){var b;let a=function(a){if(null!==a)try{return JSON.parse(a)}catch{return}}(e.metadata),f=a?.sessionId??null;null!==f&&d.run(f,e.occurredAt),c.run(ag({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,j.$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,
975
+ span_start AS spanStart, span_end AS spanEnd, masked_match AS maskedMatch,
976
+ action_taken AS actionTaken, confidence, finding_key AS findingKey,
977
+ first_detected_at AS firstDetectedAt
978
+ FROM findings WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
979
+ (id, rule_id, name, category, severity, definition, version)
980
+ VALUES (:id, :ruleId, :name, :category, :severity, :definition, :version)`),d=a.prepare(`INSERT INTO inspection_findings
981
+ (id, audit_event_id, inspection_definition_id, classified_data_id,
982
+ span_start, span_end, masked_match, action_taken, confidence,
983
+ finding_key, first_detected_at)
984
+ VALUES
985
+ (:id, :auditEventId, :inspectionDefinitionId, NULL,
986
+ :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
987
+ :findingKey, :firstDetectedAt)
988
+ ON CONFLICT(id) DO NOTHING
989
+ ON CONFLICT (finding_key) DO UPDATE SET
990
+ first_detected_at = CASE
991
+ WHEN first_detected_at IS NULL THEN excluded.first_detected_at
992
+ WHEN excluded.first_detected_at IS NULL THEN first_detected_at
993
+ ELSE min(first_detected_at, excluded.first_detected_at)
994
+ END`);return aA(a,"findings",b,a=>{let b=new Map;for(let e of a){let a=JSON.stringify([e.ruleId,e.category,e.severity]),f=b.get(a);if(void 0===f){let d=`unmigrated/${e.category}/${e.severity}`;f=L(e.ruleId,d),c.run(ag({id:f,ruleId:e.ruleId,name:e.ruleId,category:e.category,severity:e.severity,definition:"",version:d})),b.set(a,f)}d.run(ag({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 _(`legacy history backfill failed: ${String(a)}`),!1}}(a)&&function(a,b){let c=j.lFU.find(a=>a.tag===ax);if(!c)return;let d=void 0===b?void 0:ay(a);if(void 0!==b&&d?.holdsRows===!0)try{var e=a,f=b;Q(f);let c=M(f,"pre-drop");R(e,c)}catch(a){_(`legacy events/findings backup failed; deferring the drop: ${String(a)}`);return}try{Z(a,()=>{if(!a.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(c.tag)){if(void 0!==d&&ay(a).mark!==d.mark)return void _("legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first.");for(let b of aw(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){_(`legacy events/findings drop failed; deferring: ${String(a)}`)}}(a,b)}(e,a,{skipTags:c}),s(a);let g=new bZ(e),h=new bF(e,b),i={events:new a2(e),findings:new bf(e),policies:g,installedPacks:h,scanLedger:new b2(e),historySync:new at(e),secretVault:new b8(e),exceptions:new a8(e),resolutions:new b0(e),ruleProbeCache:new b1(e),bodyRetention:new aW(e),security:new cg(e),detections:new a1(e),shares:new co(e),policyCatalog:new b$(h),inventory:new bG(e),inventoryAssets:new bY(e),projectFiles:new b_(e),activity:new aU(e),sourceProject:new cp(e),auditEvents:new aV(e),classifiedData:new aX(e),inspectionDefinitions:new bg(e),inspectionFindings:new bh(e),configInventory:new aZ(e)};return g.seedDefaults(),{db:e,...i}}catch(a){throw ct(e),a}}(c,(0,e.dirname)(a),!0===b.applyDeferredMigrations?void 0:cv);function P(a){return function(a,b,c=null){return J((0,j.tTV)(["capture",a??"no_session",b,c??"no_path"]))}(a.metadata?.sessionId??null,a.contentHash,a.metadata?.filePath??null)}return{events:g,findings:h,policies:i,installedPacks:k,scanLedger:m,historySync:n,bodyRetention:o,secretVault:r,exceptions:t,resolutions:u,ruleProbeCache:v,security:w,detections:x,shares:y,policyCatalog:z,inventory:A,inventoryAssets:B,activity:D,sourceProject:E,auditEvents:F,classifiedData:G,inspectionDefinitions:I,inspectionFindings:N,recordCapture:function(a,b){$(f,()=>{let c=a.metadata?.sessionId;c&&F.ensureSessionRoot(c,a.occurredAt);let d=P(a);F.insertAuditEvent({id:d,eventType:a.kind,startedAt:a.occurredAt,parentId:c,rootSessionId:c,content:a.content,contentHash:a.contentHash,attributes:(0,j.$w9)(a)});let e=new Map;for(let a of b){if(c&&N.isSessionDuplicate(a.ruleId,a.maskedMatch,c)||N.isEventDuplicate(d,a.ruleId,a.maskedMatch,a.span.start,a.span.end))continue;let b=`${a.ruleId}@${(0,j.qmP)(a)}`,f=e.get(b);f||(f=I.upsert((0,j.jTf)(a)),e.set(b,f)),N.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})}})},markCaptureDelivered:function(a,b){$(f,()=>{n.markSynced([P(a)],b)})},markCaptureOwed:function(a){$(f,()=>{n.markCaptureOwed(P(a))})},markAuditEventsDelivered:function(a,b){let c=a.filter(a=>!cq.has(a.eventType));0!==c.length&&$(f,()=>{n.markSynced(c.map(a=>a.id),b)})},ensureInventory:function(a){let b={};return $(f,()=>{let c=Date.now();a.host&&(b.hostId=A.upsert(a.host,c)),a.harness&&(b.harnessId=A.upsert(cs(a.harness,b.hostId),c)),b.accountId=A.upsert(cs({objectType:"user",identityKey:"local",attributes:{source:"local"}},b.hostId),c),a.project&&(b.sourceProjectId=E.upsert(a.project,c))})?b:{}},recordConfigScan:function(a){$(f,()=>{let b=(0,j.I8t)(a.scanEvent.startedAt);for(let c of a.items)A.upsert(c,b);F.insertAuditEvent(a.scanEvent);let c=new Map;for(let b of a.definitions??[])c.set(`${b.ruleId}@${b.version}`,I.upsert(b));for(let b of a.findings??[]){let d=c.get(`${b.ruleId}@${b.version}`);d&&N.insertFinding({id:(0,H.randomUUID)(),auditEventId:a.scanEvent.id,inspectionDefinitionId:d,span:b.span,maskedMatch:b.maskedMatch,actionTaken:b.actionTaken,confidence:b.confidence})}})},recordProjectFiles:function(a,b){0!==b.files.length&&$(f,()=>{C.replaceForProject(a,b,Date.now())})},reconcileWorktreeProjects:function(a,b,c){try{let d=b.split(e.sep).join("/"),g=c.split(e.sep).join("/"),h=c===b?"":"url IN (:worktreePosix, :worktreeWin) OR ",i=f.prepare(`SELECT id FROM source_project
995
+ WHERE id <> :canonicalId
996
+ AND (${h}url LIKE :pattern ESCAPE '\\' OR url LIKE :patternWin ESCAPE '\\')`).all({canonicalId:a,...c===b?{}:{worktreePosix:g,worktreeWin:g.split("/").join("\\")},pattern:`${U(d)}/.claude/worktrees/%`,patternWin:`${U(d.split("/").join("\\"))}\\\\.claude\\\\worktrees\\\\%`});if(0===i.length)return;Z(f,()=>{for(let{id:b}of i)f.prepare("UPDATE audit_events SET source_project_id = :canonicalId WHERE source_project_id = :id").run({canonicalId:a,id:b}),f.prepare("UPDATE OR IGNORE file_access_override SET project_id = :canonicalId WHERE project_id = :id").run({canonicalId:a,id:b}),f.prepare("DELETE FROM file_access_override WHERE project_id = :id").run({id:b}),f.prepare("DELETE FROM project_file WHERE project_id = :id").run({id:b}),f.prepare("DELETE FROM source_project WHERE id = :id").run({id:b})})}catch{}},configInventoryReport:()=>O.report(),facets:function(){return{hosts:A.distinctTitles("host"),harnesses:A.distinctTitles("harness"),osVersions:A.osVersions(),projects:E.distinctNames()}},purgeSampleData:()=>{!function(a){try{if(!a.prepare(`SELECT (
997
+ EXISTS(SELECT 1 FROM share_destination WHERE provenance = 'sample')
998
+ OR EXISTS(SELECT 1 FROM audit_events WHERE id LIKE 'sample:activity:%')
999
+ OR EXISTS(SELECT 1 FROM inventory_asset WHERE provenance = 'sample')
1000
+ ) AS n`).get().n)return;Z(a,()=>{a.exec(`DELETE FROM share_call_site WHERE endpoint_id IN (
1001
+ SELECT e.id FROM share_endpoint e
1002
+ JOIN share_destination d ON d.id = e.destination_id
1003
+ WHERE d.provenance = 'sample')`),a.exec(`DELETE FROM egress_decision_override WHERE destination_id IN (
1004
+ SELECT id FROM share_destination WHERE provenance = 'sample')`),a.exec(`DELETE FROM share_endpoint WHERE destination_id IN (
1005
+ 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')
1006
+ 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 (
1007
+ key TEXT PRIMARY KEY,
1008
+ value TEXT NOT NULL
1009
+ )`),a.exec("DELETE FROM app_meta WHERE key LIKE 'sample_seeded:%'")})}catch{}}(f)},transaction:async function a(a){f.exec("BEGIN");try{let b=await a();return f.exec("COMMIT"),b}catch(a){try{f.exec("ROLLBACK")}catch{}throw a}},close:()=>{f.close()},[cr]:f}}let cx=/^(?:[^@/]+@)?([^/:]+):(.+)$/,cy=/^[A-Za-z]:[\\/]/,cz=/^file:\/\//i,cA=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i,cB=".git";function cC(a){return{host:a.host,kind:a.kind,name:a.name,category:a.category,trust:a.trust,network:a.network,method:a.method,transport:a.transport,url:a.url,template:a.template,dataClass:a.dataClass,site:{file:a.site.file,line:a.site.line,dynamic:a.site.dynamic,vendored:a.site.vendored}}}function cD(a){let{hits:b,droppedFiles:c}=ck(a.hits,a.reconcile.mode),d=cl(a.reconcile,c);return{projectKey:function(a){let b=a.startsWith("git:")?`git:${function(a){let b=a.trim();if(cy.test(b)||cz.test(b))return b;let c=cA.exec(b),d=null===c?cx.exec(b):null,e=(c?.[1]??d?.[1])?.toLowerCase();if(void 0===e)return b;let f=function(a){let b=0,c=a.length;for(;b<c&&47===a.charCodeAt(b);)b+=1;for(;c>b&&47===a.charCodeAt(c-1);)c-=1;return a.slice(b,c)}((null===c?d?.[2]:c[2])??""),g=f.endsWith(cB)?f.slice(0,-cB.length):f;return""===g?e:`${e}/${g}`}(a.slice(4))}`:a;return(0,H.createHash)("sha256").update(`v2:${b}`,"utf8").digest("hex")}(a.projectKey),project:a.project,reconcile:d,hits:b.map(cC)}}function cE(a){let b=a.filePath.replaceAll("\\","/");return(0,H.createHash)("sha256").update(`${a.ruleId}\0${b}\0${a.valueFingerprint}`).digest("hex")}function cF(a){return(0,e.join)(a,"exception.key")}let cG={exceptions:"key_version",blocked_detections:"key_version",secret_vault:"fingerprint_key_version"};class cH 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 cI(a){let b,c=(0,e.join)(a,l);if(!(0,d.existsSync)(c))return 0;try{(b=new I.DatabaseSync(c,{readOnly:!0})).exec(`PRAGMA busy_timeout = ${String(250)}`);let a=0;for(let[c,d]of Object.entries(cG))try{let e=ae(b.prepare(`SELECT MAX(${d}) AS v FROM ${c}`));a=Math.max(a,e?.v??0)}catch(a){if(1!==a.errcode)throw new cH(a)}return a}catch(a){throw a instanceof cH?a:new cH(a)}finally{b?.close()}}function cJ(a){return JSON.stringify({version:a.version,material:a.material.toString("base64")})}function cK(a){let b;try{b=(0,d.readFileSync)(cF(a),"utf8")}catch(a){if("ENOENT"===a.code)return null;throw a instanceof Error?a:Error(String(a))}let c=JSON.parse(b);if("object"!=typeof c||null===c)throw Error("exception key file is corrupt: not a JSON object");let{version:e,material:f}=c;if("number"!=typeof e||!Number.isInteger(e)||e<1)throw Error("exception key file is corrupt: bad version");if("string"!=typeof f)throw Error("exception key file is corrupt: bad material");let g=Buffer.from(f,"base64");if(32!==g.length)throw Error("exception key file is corrupt: bad material length");return{version:e,material:g}}function cL(a){let b=cK(a);return b?(r(cF(a)),b):function(a,b){p(a);let c=cF(a);if(x(c,`${cJ(b)}
1010
+ `))return b;let d=cK(a);if(d)return r(c),d;let e=v(c);throw new w(function(a,b){switch(b){case"symlink":return`exception key file is a symlink (${a}); remove it so a key can be created`;case"gone":return"exception key file was removed while it was being created";case"unknown":return`exception key file (${a}) is occupied but cannot be inspected; check the permissions on its directory`}}(c,e.kind),e.cause)}(a,{version:cI(a)+1,material:(0,H.randomBytes)(32)})}function cM(a){var b;let c=cK(a);return b={version:Math.max(c?.version??0,cI(a))+1,material:(0,H.randomBytes)(32)},p(a),u(cF(a),`${cJ(b)}
1011
+ `),b}function cN(a,b){return(0,H.createHmac)("sha256",a.material).update(b,"utf8").digest("hex")}function cO(a,b){var c;return(0,j.qEQ)(b,null===(c=a)?{status:"absent"}:{status:"present",version:c.version})}let cP=new Set(["unauthorized","forbidden","unreachable"]);function cQ(a,b=Date.now()){try{return function(a,b){try{let c=JSON.parse(a);if("object"!=typeof c||null===c)return null;let d="number"==typeof c.consecutiveFailures&&c.consecutiveFailures>=0?c.consecutiveFailures:0,e="number"==typeof c.openedAtMs&&Number.isFinite(c.openedAtMs)&&c.openedAtMs<=b?c.openedAtMs:null,f="string"==typeof c.lastFailure&&cP.has(c.lastFailure)?c.lastFailure:null;return{consecutiveFailures:d,openedAtMs:e,lastFailure:f}}catch{return null}}((0,d.readFileSync)((0,e.join)(a,g),"utf8"),b)}catch{return null}}function cR(a,b){let c=a?.openedAtMs??null;return null!==c&&b-c<3e4}function cS(a,b){if((0,d.existsSync)((0,e.join)(a,l)))try{let c=cw(a);try{c.historySync.markCaptureBacklogOwed(b)}finally{c.close()}}catch{}}let cT="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function cU(a){let b="",c=0,d=0;for(let e of a)for(c=c<<8|e,d+=8;d>=5;)b+=cT.charAt(c>>>d-5&31),d-=5;return d>0&&(b+=cT.charAt(c<<5-d&31)),b}function cV(a){let b=[],c=0,d=0;for(let e of a){let a=cT.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 cW(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 cU(Uint8Array.from(b))}function cX(a){let b=b=>Buffer.from((0,H.hkdfSync)("sha256",a,"aka:vault:v1",b,32));return{enc:b("aka:vault:enc:v1"),sign:b("aka:vault:sign:v1")}}function cY(a,b,c,d=j.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 cZ(a,b,c,d){let e=(0,H.createCipheriv)("aes-256-gcm",a,d);return e.setAAD(c),{ciphertext:Buffer.concat([e.update(b,"utf8"),e.final()]),nonce:d,authTag:e.getAuthTag()}}function c$(a,b,c){try{let d=(0,H.createDecipheriv)("aes-256-gcm",a,b.nonce);return d.setAAD(c),d.setAuthTag(b.authTag),Buffer.concat([d.update(b.ciphertext),d.final()]).toString("utf8")}catch{return null}}function c_(a,b,c,d){return(0,H.createHmac)("sha256",a).update(cY(b,c,d,j.viY)).digest().subarray(0,10)}function c0(a,b,c,d,e){if(10!==e.length)return!1;let f=c_(a,b,c,d);return(0,H.timingSafeEqual)(f,Buffer.from(e))}var c1=c(31421);let c2={symlink:"the path is a symlink; remove it so a keyring can be created",gone:"the path was occupied but holds no keyring (removed while it was being created)",unknown:"the path is occupied but cannot be inspected; check the permissions on its directory"};class c3 extends Error{constructor(a){super(`vault: key epoch ${String(a)} is not present in the keyring`),this.name="VaultKeyEpochMissingError",this.version=a}}let c4="vault.key",c5="aka-vault",c6="keyring";function c7(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 c8(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 c9(){return{current:1,keys:new Map([[1,(0,H.randomBytes)(32)]])}}function da(a){let b=Math.max(...a.keys.keys())+1,c=new Map(a.keys);return c.set(b,(0,H.randomBytes)(32)),{current:b,keys:c}}function db(a){let b=a.keys.get(a.current);if(!b)throw new c3(a.current);return{material:b,version:a.current}}function dc(a,b){let c=a.keys.get(b);if(!c)throw new c3(b);return{material:c,version:b}}function dd(a){try{return Promise.resolve(a())}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}function de(a){return a instanceof Error?a:Error(String(a))}let df="owner",dg="vault: a key rotation is already in progress";function dh(a,b){try{o(a),n(a)}catch(a){if("EEXIST"===a.code)return!1;throw de(a)}try{return(0,d.writeFileSync)((0,e.join)(a,df),`${b}
1012
+ `,{mode:384}),!0}catch(b){throw(0,d.rmSync)(a,{recursive:!0,force:!0}),de(b)}}function di(a,b){p(a);let c=function(a){let b,c=(0,e.join)(a,`${c4}.lock`),f=(0,H.randomBytes)(16).toString("hex");if(dh(c,f))return{lock:c,owner:f};try{b=(0,d.statSync)(c)}catch{throw Error(dg)}if(Date.now()-b.mtimeMs<6e4)throw Error(dg);let g=`${c}.stale.${f}`;try{let a=(0,d.statSync)(c);if(a.ino!==b.ino||a.mtimeMs!==b.mtimeMs)throw Error(dg);(0,d.renameSync)(c,g)}catch(a){if(a instanceof Error&&a.message===dg)throw a;throw Error(dg,{cause:a})}if((0,d.rmSync)(g,{recursive:!0,force:!0}),!dh(c,f))throw Error(dg);return{lock:c,owner:f}}(a);try{return b()}finally{!function(a){try{if((0,d.readFileSync)((0,e.join)(a.lock,df),"utf8").trim()!==a.owner)return}catch{return}(0,d.rmSync)(a.lock,{recursive:!0,force:!0})}(c)}}class dj{#a;constructor(a){this.#a=a}get filePath(){return(0,e.join)(this.#a,c4)}loadOrCreate(){return dd(()=>{let a=this.#b();return a?(dk(this.filePath),db(a)):db(this.#c())})}rotate(){return dd(()=>di(this.#a,()=>{let a=this.#b();return a?db(this.#d(da(a))):db(this.#c())}))}materialFor(a){return dd(()=>{let b=this.#b();if(!b)throw new c3(a);return dc(b,a)})}#b(){let a;try{a=(0,d.readFileSync)(this.filePath,"utf8")}catch(a){if("ENOENT"===a.code)return null;throw a instanceof Error?a:Error(String(a))}return c7(a)}#c(){p(this.#a);let a=c9();if(x(this.filePath,`${c8(a)}
1013
+ `))return a;let b=this.#b();if(!b){let a=v(this.filePath);throw new w(`vault: cannot create a key file at ${this.filePath} — ${c2[a.kind]}`,a.cause)}return dk(this.filePath),b}#d(a){return p(this.#a),u(this.filePath,`${c8(a)}
1014
+ `),a}}function dk(a){try{(0,d.chmodSync)(a,384)}catch{}}let dl=(a,b)=>(0,c1.execFileSync)("/usr/bin/security",a,{encoding:"utf8",input:b,timeout:5e3,stdio:[void 0===b?"ignore":"pipe","pipe","ignore"]});function dm(a){let b=[];return"number"==typeof a.status&&b.push(`exit ${String(a.status)}`),"string"==typeof a.signal&&a.signal&&b.push(`signal ${a.signal}`),"string"==typeof a.code&&a.code&&b.push(a.code),b.length>0?b.join(", "):"unknown error"}function dn(a,b,c){let d=["add-generic-password",...b?["-U"]:[],"-s",c5,"-a",c6,"-X",Buffer.from(c8(a),"utf8").toString("hex")];if(void 0!==c){if(/['\\\n\r\0]/.test(c))throw Error("vault: keychain path contains a quote, backslash, line break or NUL, which security -i cannot carry intact");d.push(`'${c}'`)}return`${d.join(" ")}
1015
+ `}class dp{#a;#e;#f;#g;constructor(a,b=dl,c){if(b===dl&&"darwin"!==process.platform)throw Error(`keychain custody is not available on this platform (${process.platform}); use file custody`);this.#a=a,this.#e=b,this.#f=c,this.#g=void 0===c?[]:[c]}get keysDir(){return this.#a}loadOrCreate(){return dd(()=>{let a=this.#b();return a?db(a):db(this.#h(c9()))})}rotate(){return dd(()=>di(this.#a,()=>{let a=this.#b();return a?db(this.#i(da(a))):db(this.#h(c9()))}))}materialFor(a){return dd(()=>{let b=this.#b();if(!b)throw new c3(a);return dc(b,a)})}#b(){let a;try{a=this.#e(["find-generic-password","-s",c5,"-a",c6,"-w",...this.#g])}catch(a){if(44===a.status)return null;throw Error(`vault: keychain read failed (${dm(a)}); refusing to treat the failure as an absent keyring`)}let b=a.trim();if(0===b.length)return null;try{return c7(b)}catch(a){throw Error(`vault: keychain item is not a usable keyring (${a instanceof SyntaxError?"malformed JSON":a instanceof Error?a.message:"unknown"})`)}}#h(a){let b=dn(a,!1,this.#f);try{this.#e(["-i"],b)}catch(b){let a=this.#b();if(a)return a;throw Error(`vault: keychain write failed (${dm(b)})`)}return a}#i(a){let b=dn(a,!0,this.#f);try{this.#e(["-i"],b)}catch(a){throw Error(`vault: keychain write failed (${dm(a)})`)}return a}}function dq(a,b){return"keychain"===a?new dp(b):new dj(b)}let dr=Symbol("aka.vault.consentAbsent"),ds=Symbol("aka.vault.unavailable");function dt(a){if(!j.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=cV(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=cV(f),c=cV(g);if(cW(a)!==e||cU(b)!==f||cU(c)!==g)return null;return{category:d,keyVersion:a,pointerId:b,tag:c}}catch{return null}}class du{#j;#k;#l;#m;#n;constructor(a){this.#j=a.repo,this.#k=a.keys,this.#l=a.isConsented,this.#m=a.verifyGrant,this.#n=a.now??(()=>Date.now())}async tokenize(a,b,c){if(!this.#l())return dr;let d=c(),e=cN(d,a),f=this.#j.byValueFingerprint(e),g=this.#n();if(f)return this.#j.upsert({...f,provider:f.provider??void 0,userAuthorized:!0===b.userAuthorized},g),await this.#o(f.keyVersion,f.pointerId,f.category);let{material:h,version:i}=await this.#k.loadOrCreate(),k=cX(h),l=(0,H.randomBytes)(16),m=cY(i,l,b.category,j.viY),n=cZ(k.enc,a,m,(0,H.randomBytes)(12)),{row:o}=this.#j.upsert({pointerId:cU(l),valueFingerprint:e,fingerprintKeyVersion:d.version,keyVersion:i,formatVersion:j.viY,category:b.category,ruleId:b.ruleId,maskedMatch:b.maskedMatch,provider:b.provider,userAuthorized:!0===b.userAuthorized,ciphertext:n.ciphertext.toString("base64"),nonce:n.nonce.toString("base64"),authTag:n.authTag.toString("base64")},g);return await this.#o(o.keyVersion,o.pointerId,o.category)}async detokenize(a,b){let c,d,e=dt(a);if(!e)return ds;try{let a=await this.#k.materialFor(e.keyVersion);c=cX(a.material).sign}catch{return ds}if(!c0(c,e.keyVersion,e.pointerId,e.category,e.tag))return ds;let f=cU(e.pointerId),g=this.#j.byPointerId(f);if(!g)return this.#p(f,b,"unavailable"),ds;if(g.category!==e.category)return ds;if("model"===b.target){let a,c=b.grantId,d=this.#m;if(void 0===d||void 0===c||""===c)return this.#p(f,b,"refused"),ds;try{a=await d(c,{ruleId:g.ruleId,valueFingerprint:g.valueFingerprint,fingerprintKeyVersion:g.fingerprintKeyVersion})}catch{a=!1}if(!a)return this.#p(f,b,"refused"),ds}try{let a=await this.#k.materialFor(g.keyVersion);d=c$(cX(a.material).enc,{ciphertext:Buffer.from(g.ciphertext,"base64"),nonce:Buffer.from(g.nonce,"base64"),authTag:Buffer.from(g.authTag,"base64")},cY(g.keyVersion,e.pointerId,g.category,g.formatVersion))}catch{d=null}return null===d?(this.#p(f,b,"unavailable"),ds):(this.#p(f,b,"revealed"),d)}async revealEntry(a,b){let c=this.#j.byPointerId(a);if(!c)return this.#p(a,{target:"human",reason:b.reason},"unavailable"),ds;let d=await this.#q(c);return null===d?(this.#p(a,{target:"human",reason:b.reason},"unavailable"),ds):(this.#p(a,{target:"human",reason:b.reason},"revealed"),d)}async describePointer(a){let b=await this.#r(a);return b?{category:b.category,...void 0===b.provider?{}:{provider:b.provider},maskedMatch:b.maskedMatch,occurrences:b.occurrenceCount,firstSeen:new Date(b.firstSeen).toISOString(),lastSeen:new Date(b.lastSeen).toISOString()}:null}async resolvePointerIdentity(a){let b=await this.#r(a);return b?{ruleId:b.ruleId,valueFingerprint:b.valueFingerprint,fingerprintKeyVersion:b.fingerprintKeyVersion}:null}async rotateVaultKey(){let a=await this.#k.rotate(),b=cX(a.material).enc,c=0;for(let d of this.#j.listAll()){let e;if(d.keyVersion===a.version)continue;let f=cV(d.pointerId);try{let a=await this.#k.materialFor(d.keyVersion);e=c$(cX(a.material).enc,{ciphertext:Buffer.from(d.ciphertext,"base64"),nonce:Buffer.from(d.nonce,"base64"),authTag:Buffer.from(d.authTag,"base64")},cY(d.keyVersion,f,d.category,d.formatVersion))}catch{e=null}if(null===e)continue;let g=cZ(b,e,cY(a.version,f,d.category,d.formatVersion),(0,H.randomBytes)(12));this.#j.replaceCiphertext(d.pointerId,{keyVersion:a.version,ciphertext:g.ciphertext.toString("base64"),nonce:g.nonce.toString("base64"),authTag:g.authTag.toString("base64")}),c+=1}return{version:a.version,reEncrypted:c}}async refreshFingerprints(a){let b=0;for(let c of this.#j.listAll())try{let d=await this.#q(c);if(null===d)continue;this.#j.refreshFingerprint(c.pointerId,{valueFingerprint:cN(a,d),fingerprintKeyVersion:a.version}),b+=1}catch{continue}return b}purgeVault(){let a=this.#j.purgeAll();return this.#j.recordDeref({id:(0,H.randomUUID)(),pointerId:"*",at:this.#n(),target:"human",reason:"purge",outcome:"unavailable",pointerCount:Math.max(a,1)}),a}async #o(a,b,c){var d;let e=cV(b),f=cX((await this.#k.materialFor(a)).material).sign;return d=c_(f,a,e,c),`[[aka:${c}:${cW(a)}.${cU(e)}.${cU(d)}]]`}async #q(a){try{let b=await this.#k.materialFor(a.keyVersion);return c$(cX(b.material).enc,{ciphertext:Buffer.from(a.ciphertext,"base64"),nonce:Buffer.from(a.nonce,"base64"),authTag:Buffer.from(a.authTag,"base64")},cY(a.keyVersion,cV(a.pointerId),a.category,a.formatVersion))}catch{return null}}async #r(a){let b=dt(a);if(!b)return null;try{let a=await this.#k.materialFor(b.keyVersion),c=cX(a.material).sign;if(!c0(c,b.keyVersion,b.pointerId,b.category,b.tag))return null}catch{return null}let c=this.#j.byPointerId(cU(b.pointerId));return c?.category!==b.category?null:c}#p(a,b,c){this.#j.recordDeref({id:(0,H.randomUUID)(),pointerId:a,at:this.#n(),target:b.target,reason:b.reason,outcome:c,...void 0===b.grantId?{}:{grantId:b.grantId},pointerCount:(0,j.kqf)(b.reason)?b.pointerCount??1:1})}}},75046:(a,b,c)=>{c.d(b,{S8C:()=>al,leE:()=>bP,hxQ:()=>bc,Itg:()=>a0,Nh0:()=>cS,QcD:()=>cR,qeh:()=>fk,yi_:()=>bQ,t8P:()=>b$,RRF:()=>dF,ZpU:()=>dS,fDu:()=>ev,HUb:()=>dz,hfB:()=>cH,unw:()=>dR,p$t:()=>aK,IYX:()=>aE,b2L:()=>aH,Jr:()=>dT,hdu:()=>eb,mBk:()=>ea,vog:()=>d,gbA:()=>ai,V8B:()=>cN,B0R:()=>cb,CPm:()=>b9,IgC:()=>dD,aIg:()=>bz,BZd:()=>bY,ZYZ:()=>cG,iRC:()=>cO,GCf:()=>aq,agn:()=>cT,tLs:()=>ad,xIP:()=>em,TUN:()=>ae,SHn:()=>bi,rov:()=>eq,kg1:()=>bZ,V0H:()=>dy,mzG:()=>aI,OXN:()=>aL,VEg:()=>aF,OVs:()=>ef,LsM:()=>ed,bm0:()=>ee,WRR:()=>eK,u8Q:()=>ec,kxf:()=>el,ZXz:()=>eN,MhX:()=>eO,viY:()=>dX,XZo:()=>d$,NtJ:()=>b1,jUf:()=>d0,PEm:()=>dx,vap:()=>dB,KqW:()=>e9,eI7:()=>eS,lBn:()=>bW,qhM:()=>bV,suk:()=>dA,cqq:()=>au,PUD:()=>aW,eYL:()=>cU,JJC:()=>cV,jON:()=>cp,Zdp:()=>af,lFU:()=>e,N3u:()=>fj,PhW:()=>a$,AJV:()=>ar,BIx:()=>be,DzG:()=>ei,NFD:()=>eh,hd_:()=>ew,_5V:()=>dn,tXp:()=>da,plk:()=>cF,Ple:()=>c4,Fnc:()=>fA,ryv:()=>aa,fhc:()=>dH,tTV:()=>aZ,qmP:()=>eH,_6W:()=>dc,hml:()=>dp,rG:()=>de,F$B:()=>ez,Bfj:()=>c9,fj8:()=>dk,q_t:()=>$,i1j:()=>ex,xHz:()=>cY,xog:()=>c3,hzO:()=>fC,by7:()=>fB,Gw9:()=>fy,ZoN:()=>dq,q11:()=>W,U7X:()=>aj,JB8:()=>c2,T2I:()=>dL,lgf:()=>ey,kqf:()=>d5,y_0:()=>fz,EL9:()=>eu,qEQ:()=>cP,DLF:()=>es,hds:()=>ek,I8t:()=>V,am1:()=>dh,SSj:()=>dm,K7s:()=>cW,jwX:()=>d_,TdZ:()=>dQ,DhA:()=>dU,WSs:()=>fF,a45:()=>cD,N6N:()=>g,X0p:()=>dd,pnU:()=>cE,Lq6:()=>dM,V9M:()=>eC,$w9:()=>eG,jTf:()=>eI,$BP:()=>eD,JAl:()=>eE,$3l:()=>eF,MgS:()=>dl,gzP:()=>eA,QCA:()=>eB,C05:()=>fD,GWi:()=>dN});let d=["0031_audit_capture_by_time_index","0032_audit_capture_by_id_index","0033_audit_capture_location_index","0034_findings_read_indexes"],e=[{tag:"0000_acoustic_felicia_hardy",sql:"CREATE TABLE `audit_events` (\n `id` text PRIMARY KEY NOT NULL,\n `parent_id` text,\n `root_session_id` text,\n `event_type` text NOT NULL,\n `host_id` text,\n `harness_id` text,\n `source_project_id` text,\n `started_at` integer NOT NULL,\n `ended_at` integer,\n `severity` text,\n `priority` text,\n `content` text,\n `content_hash` text,\n `attributes` text,\n FOREIGN KEY (`parent_id`) REFERENCES `audit_events`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`root_session_id`) REFERENCES `audit_events`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`host_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`harness_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`source_project_id`) REFERENCES `source_project`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_parent` ON `audit_events` (`parent_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_session` ON `audit_events` (`root_session_id`,`started_at`);--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_harness_t` ON `audit_events` (`harness_id`,`started_at`);--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_project_t` ON `audit_events` (`source_project_id`,`started_at`);--\x3e statement-breakpoint\nCREATE TABLE `classified_data` (\n `id` text PRIMARY KEY NOT NULL,\n `class` text NOT NULL,\n `label` text,\n `attributes` text\n);\n--\x3e statement-breakpoint\nCREATE TABLE `events` (\n `id` text PRIMARY KEY NOT NULL,\n `source_tool` text NOT NULL,\n `kind` text NOT NULL,\n `occurred_at` integer NOT NULL,\n `content_hash` text NOT NULL,\n `content` text NOT NULL,\n `metadata` text\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_events_occurred` ON `events` (`occurred_at`);--\x3e statement-breakpoint\nCREATE TABLE `findings` (\n `id` text PRIMARY KEY NOT NULL,\n `event_id` text NOT NULL,\n `rule_id` text NOT NULL,\n `category` text NOT NULL,\n `severity` text NOT NULL,\n `span_start` integer NOT NULL,\n `span_end` integer NOT NULL,\n `masked_match` text NOT NULL,\n `action_taken` text NOT NULL,\n `confidence` real NOT NULL,\n FOREIGN KEY (`event_id`) REFERENCES `events`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_findings_event` ON `findings` (`event_id`);--\x3e statement-breakpoint\nCREATE TABLE `inspection_definitions` (\n `id` text PRIMARY KEY NOT NULL,\n `rule_id` text NOT NULL,\n `name` text NOT NULL,\n `category` text NOT NULL,\n `severity` text NOT NULL,\n `definition` text NOT NULL,\n `version` text NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE TABLE `inspection_findings` (\n `id` text PRIMARY KEY NOT NULL,\n `audit_event_id` text NOT NULL,\n `inspection_definition_id` text NOT NULL,\n `classified_data_id` text,\n `span_start` integer NOT NULL,\n `span_end` integer NOT NULL,\n `masked_match` text NOT NULL,\n `action_taken` text NOT NULL,\n `confidence` real NOT NULL,\n FOREIGN KEY (`audit_event_id`) REFERENCES `audit_events`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`inspection_definition_id`) REFERENCES `inspection_definitions`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`classified_data_id`) REFERENCES `classified_data`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event` ON `inspection_findings` (`audit_event_id`);--\x3e statement-breakpoint\nCREATE TABLE `installed_packs` (\n `id` text PRIMARY KEY NOT NULL,\n `namespace` text NOT NULL,\n `pack_id` text NOT NULL,\n `version` text NOT NULL,\n `name` text NOT NULL,\n `rules_json` text NOT NULL,\n `enabled` integer DEFAULT true NOT NULL,\n `policy_id` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_installed_packs_pack` ON `installed_packs` (`namespace`,`pack_id`);--\x3e statement-breakpoint\nCREATE TABLE `inventory` (\n `id` text PRIMARY KEY NOT NULL,\n `object_type` text NOT NULL,\n `location` text,\n `title` text,\n `host_id` text,\n `attributes` text NOT NULL,\n `os_version` text GENERATED ALWAYS AS (json_extract(attributes, '$.os_version')) VIRTUAL,\n `harness_version` text GENERATED ALWAYS AS (json_extract(attributes, '$.harness_version')) VIRTUAL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL,\n FOREIGN KEY (`host_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_type` ON `inventory` (`object_type`);--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_type_osver` ON `inventory` (`object_type`,`os_version`);--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_type_harnessver` ON `inventory` (`object_type`,`harness_version`);--\x3e statement-breakpoint\nCREATE TABLE `policies` (\n `id` text PRIMARY KEY NOT NULL,\n `scope` text DEFAULT 'global' NOT NULL,\n `target` text NOT NULL,\n `action` text NOT NULL,\n `enabled` integer DEFAULT true NOT NULL,\n `custom_keywords` text,\n `name` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_policies_scope_target` ON `policies` (`scope`,`target`);--\x3e statement-breakpoint\nCREATE TABLE `source_project` (\n `id` text PRIMARY KEY NOT NULL,\n `url` text,\n `name` text,\n `attributes` text NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n"},{tag:"0001_adorable_marten_broadcloak",sql:"ALTER TABLE `audit_events` ADD `input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `output_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `cache_creation_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `cache_read_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `model` text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `provider` text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL;--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_session_type` ON `audit_events` (`root_session_id`,`started_at`) WHERE event_type = 'llm_call';"},{tag:"0002_groovy_big_bertha",sql:"CREATE TABLE `exceptions` (\n `id` text PRIMARY KEY NOT NULL,\n `rule_id` text NOT NULL,\n `category` text NOT NULL,\n `value_fingerprint` text NOT NULL,\n `key_version` integer NOT NULL,\n `masked_value` text NOT NULL,\n `scope` text NOT NULL,\n `expires_at` integer,\n `max_uses` integer,\n `use_count` integer DEFAULT 0 NOT NULL,\n `last_used_at` integer,\n `justification` text NOT NULL,\n `conditions` text,\n `created_by` text NOT NULL,\n `created_via` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n `revoked_at` integer,\n `revoked_by` text,\n `revoke_reason` text\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_exceptions_active` ON `exceptions` (`rule_id`,`value_fingerprint`,`key_version`) WHERE revoked_at IS NULL;"},{tag:"0003_rich_sage",sql:"CREATE TABLE `egress_decision_override` (\n `id` text PRIMARY KEY NOT NULL,\n `destination_id` text NOT NULL,\n `decision` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`destination_id`) REFERENCES `share_destination`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override` ON `egress_decision_override` (`destination_id`);--\x3e statement-breakpoint\nCREATE TABLE `file_access_override` (\n `id` text PRIMARY KEY NOT NULL,\n `project_id` text NOT NULL,\n `path` text NOT NULL,\n `access` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`project_id`) REFERENCES `source_project`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_file_access_override_project` ON `file_access_override` (`project_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_file_access_override` ON `file_access_override` (`project_id`,`path`);--\x3e statement-breakpoint\nCREATE TABLE `harness_asset` (\n `id` text PRIMARY KEY NOT NULL,\n `harness_id` text NOT NULL,\n `asset_id` text NOT NULL,\n `created_at` integer NOT NULL,\n FOREIGN KEY (`harness_id`) REFERENCES `inventory`(`id`) ON UPDATE no action ON DELETE no action,\n FOREIGN KEY (`asset_id`) REFERENCES `inventory_asset`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_harness_asset_harness` ON `harness_asset` (`harness_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_harness_asset` ON `harness_asset` (`harness_id`,`asset_id`);--\x3e statement-breakpoint\nCREATE TABLE `inventory_asset` (\n `id` text PRIMARY KEY NOT NULL,\n `asset_type` text NOT NULL,\n `name` text NOT NULL,\n `sub` text,\n `description` text,\n `flags_json` text DEFAULT '[]' NOT NULL,\n `meta_json` text DEFAULT '{}' NOT NULL,\n `trust` text,\n `tools_json` text,\n `provenance` text DEFAULT 'scan' NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_inventory_asset_type` ON `inventory_asset` (`asset_type`);--\x3e statement-breakpoint\nCREATE TABLE `mcp_trust_override` (\n `id` text PRIMARY KEY NOT NULL,\n `asset_id` text NOT NULL,\n `trust` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`asset_id`) REFERENCES `inventory_asset`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_mcp_trust_override` ON `mcp_trust_override` (`asset_id`);--\x3e statement-breakpoint\nCREATE TABLE `project_file` (\n `id` text PRIMARY KEY NOT NULL,\n `project_id` text NOT NULL,\n `path` text NOT NULL,\n `name` text NOT NULL,\n `origin` text NOT NULL,\n `default_access` text NOT NULL,\n `findings_count` integer DEFAULT 0 NOT NULL,\n `blocked_at` integer,\n `note` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`project_id`) REFERENCES `source_project`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_project_file_project` ON `project_file` (`project_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_project_file` ON `project_file` (`project_id`,`path`);--\x3e statement-breakpoint\nCREATE TABLE `share_call_site` (\n `id` text PRIMARY KEY NOT NULL,\n `endpoint_id` text NOT NULL,\n `project` text NOT NULL,\n `file` text NOT NULL,\n `line` integer NOT NULL,\n `snippet` text NOT NULL,\n `dynamic` integer DEFAULT false NOT NULL,\n `vendored` integer DEFAULT false NOT NULL,\n `project_id` text,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`endpoint_id`) REFERENCES `share_endpoint`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_share_call_site_endpoint` ON `share_call_site` (`endpoint_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_call_site` ON `share_call_site` (`endpoint_id`,`project`,`file`,`line`);--\x3e statement-breakpoint\nCREATE TABLE `share_destination` (\n `id` text PRIMARY KEY NOT NULL,\n `kind` text NOT NULL,\n `name` text NOT NULL,\n `host` text NOT NULL,\n `category` text NOT NULL,\n `trust` text NOT NULL,\n `note` text,\n `network_json` text,\n `last_seen` integer NOT NULL,\n `provenance` text DEFAULT 'scan' NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_share_destination_kind` ON `share_destination` (`kind`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_destination_host` ON `share_destination` (`host`);--\x3e statement-breakpoint\nCREATE TABLE `share_endpoint` (\n `id` text PRIMARY KEY NOT NULL,\n `destination_id` text NOT NULL,\n `method` text NOT NULL,\n `transport` text NOT NULL,\n `url` text NOT NULL,\n `template` integer DEFAULT false NOT NULL,\n `data_class` text NOT NULL,\n `last_seen` integer NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`destination_id`) REFERENCES `share_destination`(`id`) ON UPDATE no action ON DELETE no action\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_share_endpoint_dest` ON `share_endpoint` (`destination_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_endpoint` ON `share_endpoint` (`destination_id`,`method`,`url`);"},{tag:"0004_glorious_mindworm",sql:"CREATE TABLE `available_packs` (\n `id` text PRIMARY KEY NOT NULL,\n `namespace` text NOT NULL,\n `pack_id` text NOT NULL,\n `version` text NOT NULL,\n `name` text NOT NULL,\n `rules_json` text NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_available_packs_pack` ON `available_packs` (`namespace`,`pack_id`);"},{tag:"0005_fast_vindicator",sql:'PRAGMA foreign_keys=OFF;--\x3e statement-breakpoint\nCREATE TABLE `__new_mcp_trust_override` (\n `id` text PRIMARY KEY NOT NULL,\n `asset_id` text NOT NULL,\n `trust` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nINSERT INTO `__new_mcp_trust_override`("id", "asset_id", "trust", "created_at", "updated_at") SELECT "id", "asset_id", "trust", "created_at", "updated_at" FROM `mcp_trust_override`;--\x3e statement-breakpoint\nDROP TABLE `mcp_trust_override`;--\x3e statement-breakpoint\nALTER TABLE `__new_mcp_trust_override` RENAME TO `mcp_trust_override`;--\x3e statement-breakpoint\nPRAGMA foreign_keys=ON;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_mcp_trust_override` ON `mcp_trust_override` (`asset_id`);'},{tag:"0006_magenta_flatman",sql:'CREATE TABLE `_pack_write_gate` (\n `id` integer PRIMARY KEY NOT NULL,\n `open` integer DEFAULT 0 NOT NULL,\n CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)\n);\n--\x3e statement-breakpoint\nALTER TABLE `available_packs` ADD `recorded_by` text;--\x3e statement-breakpoint\nINSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0);\n--\x3e statement-breakpoint\nCREATE TRIGGER trg_installed_packs_write_gate\nBEFORE UPDATE OF version, name, rules_json ON installed_packs\nWHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1\nBEGIN SELECT RAISE(IGNORE); END;'},{tag:"0007_thick_stick",sql:"CREATE TABLE `finding_resolution` (\n `id` text PRIMARY KEY NOT NULL,\n `finding_key` text NOT NULL,\n `status` text NOT NULL,\n `method` text NOT NULL,\n `resolved_at` integer NOT NULL,\n `evidence` text,\n `created_at` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_finding_resolution_key` ON `finding_resolution` (`finding_key`);--\x3e statement-breakpoint\nALTER TABLE `findings` ADD `finding_key` text;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_findings_key` ON `findings` (`finding_key`);"},{tag:"0008_freezing_selene",sql:"ALTER TABLE `findings` ADD `first_detected_at` integer;--\x3e statement-breakpoint\nUPDATE `findings` SET `first_detected_at` = (SELECT `occurred_at` FROM `events` WHERE `events`.`id` = `findings`.`event_id`) WHERE `first_detected_at` IS NULL;"},{tag:"0009_findings_path_expression_index",sql:"-- Custom migration: partial expression index for the resolver's per-path reads.\n--\n-- openAtRestKeysForPath / resolvedAtRestKeysForPath (and the scanner's tier-3\n-- open-key probe) filter at-rest events by\n-- e.kind = 'code_change' AND json_extract(e.metadata, '$.filePath') = :path\n-- once per changed/deleted file on every scan — previously a full events scan\n-- per file. json_extract is deterministic, so SQLite allows it in an index;\n-- the WHERE kind = 'code_change' keeps the index to exactly the rows those\n-- queries can match (in-flight events are never path-addressed).\nCREATE INDEX `idx_events_code_change_path` ON `events` (json_extract(`metadata`, '$.filePath')) WHERE `kind` = 'code_change';\n"},{tag:"0010_events_session_expression_index",sql:"-- Custom migration: partial expression index for session-scoped finding reads.\n--\n-- sessionFindingsCount, the session-scoped listGroupedFindings paths, and the\n-- insert-time session dedup all filter live-capture events by\n-- json_extract(e.metadata, '$.sessionId') = :sessionId\n-- — previously a full findings-join scan with a JSON parse per row. The\n-- IS NOT NULL predicate keeps the index to session-stamped events only (an\n-- equality probe implies non-null, so SQLite still uses it).\nCREATE INDEX `idx_events_session_id` ON `events` (json_extract(`metadata`, '$.sessionId')) WHERE json_extract(`metadata`, '$.sessionId') IS NOT NULL;\n"},{tag:"0011_egress_writer",sql:'-- Stable per-project reconcile key for egress call sites, plus a host-keyed\n-- egress decision override that survives destination pruning.\n--\n-- DROP INDEX IF EXISTS, not a bare DROP: the applier replays a pending\n-- migration\'s non-index statements verbatim, so a store that lost\n-- uq_share_call_site out of band would throw here — and on the plugin hook path\n-- that throw is swallowed fail-open, silently stopping capture.\n--\n-- Existing rows carry the old key\'s discriminator into project_key\n-- (\'legacy:\' || project), so the new unique index is a re-encoding of the old\n-- one and cannot collide on rows the old one allowed. Leaving them on the\n-- column default would collapse two projects\' identical file/line hits onto\n-- one key and abort the whole migration. Writer keys are \'git:\'/\'path:\'-\n-- prefixed, so a backfilled row never collides with a captured one either.\n--\n-- egress_decision_override.destination_id becomes nullable with ON DELETE SET\n-- NULL, which SQLite can only do by rebuilding the table. `host` is ADDed\n-- before the rebuild so the copy has a column to read and so the migration\n-- still presents two probeable columns to the applier\'s evidence check.\nALTER TABLE `share_call_site` ADD `project_key` text DEFAULT \'\' NOT NULL;--\x3e statement-breakpoint\nUPDATE `share_call_site` SET `project_key` = \'legacy:\' || `project`;--\x3e statement-breakpoint\nDROP INDEX IF EXISTS `uq_share_call_site`;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_call_site` ON `share_call_site` (`endpoint_id`,`project_key`,`file`,`line`);--\x3e statement-breakpoint\nCREATE INDEX `idx_share_call_site_project` ON `share_call_site` (`project_key`,`endpoint_id`);--\x3e statement-breakpoint\nALTER TABLE `egress_decision_override` ADD `host` text;--\x3e statement-breakpoint\nPRAGMA foreign_keys=OFF;--\x3e statement-breakpoint\nCREATE TABLE `__new_egress_decision_override` (\n `id` text PRIMARY KEY NOT NULL,\n `destination_id` text,\n `host` text,\n `decision` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`destination_id`) REFERENCES `share_destination`(`id`) ON UPDATE no action ON DELETE set null\n);\n--\x3e statement-breakpoint\nINSERT INTO `__new_egress_decision_override`("id", "destination_id", "host", "decision", "created_at", "updated_at") SELECT "id", "destination_id", "host", "decision", "created_at", "updated_at" FROM `egress_decision_override`;--\x3e statement-breakpoint\nDROP TABLE `egress_decision_override`;--\x3e statement-breakpoint\nALTER TABLE `__new_egress_decision_override` RENAME TO `egress_decision_override`;--\x3e statement-breakpoint\nPRAGMA foreign_keys=ON;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override` ON `egress_decision_override` (`destination_id`);--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override_host` ON `egress_decision_override` (`host`) WHERE `host` IS NOT NULL;\n'},{tag:"0012_handy_the_captain",sql:"ALTER TABLE `inspection_findings` ADD `finding_key` text;--\x3e statement-breakpoint\nALTER TABLE `inspection_findings` ADD `first_detected_at` integer;--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_inspection_findings_key` ON `inspection_findings` (`finding_key`);"},{tag:"0013_legacy_history_backfill_support",sql:"-- Legacy-to-generalized backfill support: the schema the resumable\n-- events/findings -> audit_events/inspection_findings copy needs (the row\n-- copy itself runs as a batched post-migration installer, not here — see\n-- @akasecurity/persistence's migrations.ts), plus the audit_events read-path\n-- indexes replacing the ones the legacy events table carried (0009/0010).\n\n-- Tracks how far the batched, resumable copy has advanced through each legacy\n-- table, by rowid, so a copy interrupted mid-run resumes instead of\n-- restarting, and a completed copy is a cheap no-op on every later open.\nCREATE TABLE `legacy_copy_watermark` (\n `source` text PRIMARY KEY NOT NULL,\n `last_rowid` integer DEFAULT 0 NOT NULL\n);\n--\x3e statement-breakpoint\n-- Serves the time-range read family that scans a single event_type across a\n-- start/end window (e.g. the Activity timeline) without a full-table scan.\nCREATE INDEX `idx_audit_type_t` ON `audit_events` (`event_type`,`started_at`);\n--\x3e statement-breakpoint\n-- Partial expression index mirroring `idx_events_code_change_path` (0009) for\n-- the generalized audit_events/attributes pair: file-path reads filter\n-- `event_type = 'code_change' AND json_extract(attributes, '$.file_path') = :path`.\nCREATE INDEX `idx_audit_code_change_path` ON `audit_events` (json_extract(`attributes`, '$.file_path')) WHERE `event_type` = 'code_change';\n--\x3e statement-breakpoint\n-- Synthesizes a stub session root (event_type = 'session', no attributes) for\n-- every legacy `events.metadata.sessionId` that has no audit_events row yet.\n-- audit_events.root_session_id is a self-FK, enforced with foreign-key\n-- checking on, and INSERT OR IGNORE does not suppress a foreign-key violation\n-- (only UNIQUE/PK/NOT NULL/CHECK) — so this must run before the events copy\n-- resolves root_session_id, or every session-scoped row's insert fails.\n-- started_at takes the earliest legacy occurred_at recorded under that\n-- session, so the stub root's own timeline position is never later than\n-- anything it will end up parenting.\nINSERT INTO audit_events (id, event_type, root_session_id, started_at)\nSELECT\n json_extract(metadata, '$.sessionId'),\n 'session',\n NULL,\n min(occurred_at)\nFROM events\nWHERE json_valid(metadata)\n AND json_extract(metadata, '$.sessionId') IS NOT NULL\n AND json_extract(metadata, '$.sessionId') NOT IN (SELECT id FROM audit_events)\nGROUP BY json_extract(metadata, '$.sessionId');\n"},{tag:"0014_drop_legacy_events_findings",sql:"-- Custom migration: drops the frozen legacy `events`/`findings` tables\n-- (superseded by audit_events/inspection_definitions/inspection_findings) and\n-- replaces them with read-only views of the same name.\n--\n-- persistence's migrations.ts applies this migration ONLY once the batched\n-- history backfill (see runLegacyHistoryBackfill) has fully drained both\n-- tables, and only after copying the live file aside — see\n-- backupBeforeLegacyDrop in packages/persistence/src/migrations.ts. A store\n-- still mid-copy keeps its real tables and this migration stays pending.\n--\n-- The views exist for skew: the `aka` CLI and the Claude Code plugin update\n-- independently against one shared store, so an older, already-installed\n-- binary can open a store a newer binary already dropped these tables on.\n-- Every already-shipped repository constructor prepares its SQL eagerly at\n-- open time, so a bare \"table not found\" would fail the WHOLE open, not just\n-- a findings-specific read — these views keep `prepare()` succeeding so an\n-- old binary's unrelated features keep working; its own reads stay truthful,\n-- and its rare (already fail-open) writes fail at run time instead.\n--\n-- The 0009/0010 expression indexes existed only over the legacy `events`\n-- table; DROP TABLE below would remove them implicitly, but they are\n-- dropped explicitly first so the intent reads clearly. IF EXISTS so a store\n-- that reached here with an index missing out of band (an adopted-tag store\n-- whose physical index was never built) does not throw a deterministic \"no\n-- such index\" out of the fail-open drop path.\nDROP INDEX IF EXISTS `idx_events_code_change_path`;\n--\x3e statement-breakpoint\nDROP INDEX IF EXISTS `idx_events_session_id`;\n--\x3e statement-breakpoint\n-- `findings.event_id` references `events.id` — drop the child first.\nDROP TABLE `findings`;\n--\x3e statement-breakpoint\nDROP TABLE `events`;\n--\x3e statement-breakpoint\n-- Legacy `events` shape, projected from audit_events: `kind`/`occurred_at`/\n-- `source_tool` become real columns again (source_tool round-trips through\n-- the attributes bag, the only place a capture-typed audit row keeps it);\n-- `metadata` is reconstructed as the old camelCase JSON object from the new\n-- snake_case attributes bag, with `root_session_id` folded back in as\n-- `sessionId` (the one legacy metadata key that became a column, never an\n-- attribute, on the new table). Constrained to the four capture kinds so\n-- structural rows (session/run/tool_call/llm_call/source_lookup/config_scan)\n-- never leak into a legacy reader's result set — the old `events` table\n-- never held them either.\nCREATE VIEW `events` AS\nSELECT\n id,\n json_extract(attributes, '$.source_tool') AS source_tool,\n event_type AS kind,\n started_at AS occurred_at,\n content_hash,\n content,\n -- Plugin-local bookkeeping column that `ensureSyncedAtColumn` adds to the\n -- real `events` table at open time. A pre-cutover binary runs that probe on\n -- EVERY open; without this projection its `columnNames('events')` check\n -- misses `synced_at` and issues `ALTER TABLE events ADD COLUMN` against this\n -- view, which SQLite rejects (\"Cannot add a column to a view\") — a hard,\n -- non-fail-open crash of the whole open, the exact skew failure these views\n -- exist to prevent. Projecting it (always NULL; no reader consumes it)\n -- short-circuits that ALTER.\n NULL AS synced_at,\n json_object(\n 'sessionId', root_session_id,\n 'repo', json_extract(attributes, '$.repo'),\n 'filePath', json_extract(attributes, '$.file_path'),\n 'toolName', json_extract(attributes, '$.tool_name'),\n 'gitignored', json_extract(attributes, '$.gitignored'),\n 'wholeFile', json_extract(attributes, '$.whole_file'),\n 'model', json_extract(attributes, '$.model'),\n 'turnIndex', json_extract(attributes, '$.turn_index'),\n 'correlationId', json_extract(attributes, '$.correlation_id'),\n 'traceId', json_extract(attributes, '$.trace_id'),\n 'exceptionIds', json_extract(attributes, '$.exception_ids')\n ) AS metadata\nFROM audit_events\nWHERE event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--\x3e statement-breakpoint\n-- A plain single-row INSERT (the old writer's shape — no ON CONFLICT) is\n-- accepted by prepare() against a view once an INSTEAD OF INSERT trigger\n-- exists, so it fails at run time instead of at open — landing in the same\n-- fail-open path the caller already wraps its write in.\nCREATE TRIGGER `trg_events_ro`\nINSTEAD OF INSERT ON `events`\nBEGIN SELECT RAISE(ABORT, 'events is read-only; write to audit_events instead'); END;\n--\x3e statement-breakpoint\n-- Legacy `findings` shape: rule_id/category/severity come from the joined\n-- inspection_definitions row (the legacy table inlined them per-row; the\n-- generalized schema normalizes them out into the shared definition). A view\n-- has no rowid of its own, so the underlying table's rowid is re-exposed\n-- explicitly under that name — a legacy reader ordering by `f.rowid` would\n-- otherwise fail to resolve the column at all. Joined to audit_events for the\n-- same four-capture-kind constraint as the events view above (a finding\n-- attached to a tool_call/config_scan row never existed in the legacy table\n-- either — see the persistence findings repository's identical predicate).\nCREATE VIEW `findings` AS\nSELECT\n f.id AS id,\n f.rowid AS rowid,\n f.audit_event_id AS event_id,\n d.rule_id AS rule_id,\n d.category AS category,\n d.severity AS severity,\n f.span_start AS span_start,\n f.span_end AS span_end,\n f.masked_match AS masked_match,\n f.action_taken AS action_taken,\n f.confidence AS confidence,\n f.finding_key AS finding_key,\n f.first_detected_at AS first_detected_at\nFROM inspection_findings f\nJOIN audit_events e ON e.id = f.audit_event_id\nJOIN inspection_definitions d ON d.id = f.inspection_definition_id\nWHERE e.event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--\x3e statement-breakpoint\n-- Defense in depth only: SQLite refuses to plan ANY upsert against a view\n-- (\"cannot UPSERT a view\") no matter what trigger exists, so this can never\n-- rescue the real legacy writer, which always used\n-- `ON CONFLICT (finding_key) DO UPDATE` — that statement still fails at\n-- prepare() on an old binary, same as it would with no trigger at all. This\n-- only covers a plain-INSERT shape, should one ever exist.\nCREATE TRIGGER `trg_findings_ro`\nINSTEAD OF INSERT ON `findings`\nBEGIN SELECT RAISE(ABORT, 'findings is read-only; write to inspection_findings instead'); END;\n"},{tag:"0015_busy_vengeance",sql:"CREATE TABLE `secret_vault` (\n `pointer_id` text PRIMARY KEY NOT NULL,\n `value_fingerprint` text NOT NULL,\n `fingerprint_key_version` integer NOT NULL,\n `key_version` integer NOT NULL,\n `category` text NOT NULL,\n `rule_id` text NOT NULL,\n `masked_match` text NOT NULL,\n `provider` text,\n `ciphertext` text NOT NULL,\n `nonce` text NOT NULL,\n `auth_tag` text NOT NULL,\n `occurrence_count` integer DEFAULT 1 NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_value` ON `secret_vault` (`value_fingerprint`);--\x3e statement-breakpoint\nCREATE TABLE `secret_vault_deref` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `at` integer NOT NULL,\n `target` text NOT NULL,\n `reason` text NOT NULL,\n `outcome` text NOT NULL,\n `grant_id` text,\n `pointer_count` integer DEFAULT 1 NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_pointer` ON `secret_vault_deref` (`pointer_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_reason_at` ON `secret_vault_deref` (`reason`,`at`);"},{tag:"0016_breezy_zodiak",sql:"ALTER TABLE `exceptions` ADD `capability` text DEFAULT 'suppress' NOT NULL;"},{tag:"0017_rainy_kat_farrell",sql:"CREATE TABLE `secret_vault_sighting` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `location` text NOT NULL,\n `kind` text NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--\x3e statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_sighting` ON `secret_vault_sighting` (`pointer_id`,`location`);"},{tag:"0018_serious_tana_nile",sql:"ALTER TABLE `secret_vault` ADD `format_version` integer DEFAULT 2 NOT NULL;"},{tag:"0019_audit_started_at_index",sql:"CREATE INDEX `idx_audit_started_at` ON `audit_events` (`started_at`);"},{tag:"0020_secret_vault_pagination_indexes",sql:"CREATE INDEX `idx_secret_vault_last_seen` ON `secret_vault` (`last_seen`,`pointer_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_reuse` ON `secret_vault` (`occurrence_count`,`pointer_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_at` ON `secret_vault_deref` (`at`,`id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_signal` ON `secret_vault_deref` (`at`,`id`) WHERE `reason` NOT IN ('display', 'view-render');"},{tag:"0021_finding_resolution_resolved_at_index",sql:"CREATE INDEX `idx_finding_resolution_resolved_at` ON `finding_resolution` (`resolved_at`);\n"},{tag:"0022_audit_inspection_ms",sql:"ALTER TABLE `audit_events` ADD `inspection_ms` integer GENERATED ALWAYS AS (json_extract(attributes, '$.inspection_ms')) VIRTUAL;"},{tag:"0023_secret_vault_user_authorized",sql:"ALTER TABLE `secret_vault` ADD `user_authorized` integer DEFAULT 0 NOT NULL;"},{tag:"0024_finding_resolution_key_created_index",sql:"DROP INDEX IF EXISTS `idx_finding_resolution_key`;--\x3e statement-breakpoint\nCREATE INDEX `idx_finding_resolution_key_created` ON `finding_resolution` (`finding_key`,`created_at`);"},{tag:"0025_audit_capture_attribute_columns",sql:"ALTER TABLE `audit_events` ADD `source_tool` text GENERATED ALWAYS AS (json_extract(attributes, '$.source_tool')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `repo` text GENERATED ALWAYS AS (json_extract(attributes, '$.repo')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `file_path` text GENERATED ALWAYS AS (json_extract(attributes, '$.file_path')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `tool_name` text GENERATED ALWAYS AS (json_extract(attributes, '$.tool_name')) VIRTUAL;"},{tag:"0026_audit_llm_call_usage_columns",sql:"ALTER TABLE `audit_events` ADD `service_tier` text GENERATED ALWAYS AS (json_extract(attributes, '$.service_tier')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_1h_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_1h_input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_5m_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_5m_input_tokens')) VIRTUAL;--\x3e statement-breakpoint\nALTER TABLE `audit_events` ADD `web_search_requests` integer GENERATED ALWAYS AS (json_extract(attributes, '$.web_search_requests')) VIRTUAL;"},{tag:"0027_audit_llm_usage_index",sql:"CREATE INDEX `idx_audit_llm_usage` ON `audit_events` (`started_at`,`root_session_id`,`provider`,`model`,`service_tier`,`input_tokens`,`output_tokens`,`cache_creation_input_tokens`,`cache_read_input_tokens`,`ephemeral_1h_input_tokens`,`ephemeral_5m_input_tokens`,`web_search_requests`) WHERE event_type = 'llm_call' AND attributes IS NOT NULL;"},{tag:"0028_activity_session_probe_indexes",sql:"CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--\x3e statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"},{tag:"0029_audit_capture_rollup_index",sql:"CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"},{tag:"0030_audit_content_expiry",sql:"ALTER TABLE `audit_events` ADD `content_expired_at` integer;--\x3e statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"},{tag:"0031_audit_capture_by_time_index",sql:"CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"},{tag:"0032_audit_capture_by_id_index",sql:"CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"},{tag:"0033_audit_capture_location_index",sql:"CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"},{tag:"0034_findings_read_indexes",sql:"CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--\x3e statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--\x3e statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"}],f=/^(\d+)([mh])$/;function g(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=f.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}}var h=c(86879);let i=h.Ik({thresholdInputTokens:h.ai().int().positive(),input:h.ai().nonnegative().nullable(),output:h.ai().nonnegative().nullable()});function j(a,b,c){return Object.freeze({input:a,output:b,longContext:null,cacheWrite5m:1.25*a,cacheWrite1h:2*a,cacheRead:c,webSearch:.01})}function k(a,b,c={}){return Object.freeze({input:a,output:b,longContext:void 0===c.longContext?null:Object.freeze(c.longContext),cacheWrite5m:null,cacheWrite1h:null,cacheRead:c.cacheRead??null,webSearch:null})}h.Ik({input:h.ai().nonnegative(),output:h.ai().nonnegative(),longContext:i.nullable(),cacheWrite5m:h.ai().nonnegative().nullable(),cacheWrite1h:h.ai().nonnegative().nullable(),cacheRead:h.ai().nonnegative().nullable(),webSearch:h.ai().nonnegative().nullable()});let l=Object.freeze({input:0,output:0,longContext:null,cacheWrite5m:0,cacheWrite1h:0,cacheRead:0,webSearch:0}),m=new Map([["standard",1],["batch",.5],["priority",1.5]]);h.k5(["anthropic","openai","google","meta","mistral","deepseek","alibaba","xai","amazon","cohere","unknown"]),h.k5(["anthropic","openai","google-ai","mistral","deepseek","xai","cohere","bedrock","vertex","azure","foundry","together","fireworks","groq","openrouter","ollama","local"]),h.k5(["api","gateway","local"]);let n=new Map([["anthropic","api"],["openai","api"],["google-ai","api"],["mistral","api"],["deepseek","api"],["xai","api"],["cohere","api"],["bedrock","api"],["vertex","api"],["azure","api"],["foundry","api"],["together","gateway"],["fireworks","gateway"],["groq","gateway"],["openrouter","gateway"],["ollama","local"],["local","local"]]);function o(a){return n.get(a)??"api"}let p=new Map([["anthropic","anthropic"],["openai","openai"],["google","google-ai"],["mistral","mistral"],["deepseek","deepseek"],["xai","xai"],["cohere","cohere"]]),q=Object.freeze(["anthropic","amazon","meta","mistral","deepseek","qwen","cohere","ai21","writer","luma","stability"]),r=Object.freeze(["us","eu","apac","au","jp","global"]);class s{constructor(a,b={}){this.entries=[],this.vendor=a,this.defaults=b}model(a,b){var c,d;let e=b.family??this.defaults.family??{id:a,name:b.name},f=!1===b.firstParty?null:(c=this.vendor,p.get(c)??null),g=b.openWeights??this.defaults.openWeights??!1,h=b.region??this.defaults.region??null,i=b.retention??this.defaults.retention??"unknown",j=new Map;for(let a of(null!==f&&j.set(f,Object.freeze({platform:f,hosting:o(f),firstParty:!0,price:b.price??null,retention:i,region:h})),b.on??[])){let{platform:c,price:e,retention:f,region:g}="string"==typeof a?{platform:a}:a,k=(d=this.vendor,p.get(d)===c),m=o(c),n="local"===m;j.set(c,Object.freeze({platform:c,hosting:m,firstParty:k,price:e??(n?l:k?b.price??null:null),retention:f??(n?"on_infrastructure":k?i:"unknown"),region:void 0===g?k?h:null:g}))}let k=b.defaultHosting??this.defaults.defaultHosting??(null===f?"gateway":o(f));if(void 0!==b.price&&![...j.values()].some(a=>a.price===b.price))throw Error(`${a}: a first-party price was declared but no platform can carry it — vendor '${this.vendor}' has no first-party endpoint. Price the serving platform explicitly via the object form of \`on\`.`);let m={id:a,vendor:this.vendor,displayName:b.name,familyId:e.id,familyName:e.name,capability:b.capability??null,contextWindow:b.ctx??null,maxOutputTokens:b.maxOut??null,openWeights:g,aliases:Object.freeze([...b.aliases??[]]),training:this.defaults.training??null,platforms:j,defaultHosting:k,seen:b.seen??"managed"};return Object.freeze(m),Object.freeze(m.aliases),this.entries.push(m),m}models(){return this.entries}}function t(a,b={}){return new s(a,b)}let u=RegExp(`^(?:${r.join("|")})\\.`,"u"),v=RegExp(`^(?:${q.join("|")})\\.`,"u"),w=RegExp(`^(?:${q.join("|")})/`,"iu"),x=/^[a-z0-9][\w.-]*\//iu,y=/-v\d+:\d+$/u,z=/:\d+$/u,A=/@[\w-]+$/u,B=/-\d{8}$/u;function C(a,b){let c,d,e=b.byId.get(a);if(void 0!==e)return{entry:e,canonicalId:a,platform:null,raw:a};let{id:f,platform:g}=(c=a.trim(),d=null,u.test(c)&&(c=c.replace(u,""),d="bedrock"),v.test(c)&&(c=c.replace(v,""),d??="bedrock"),y.test(c)?(c=c.replace(y,""),d??="bedrock"):z.test(c)&&(c=c.replace(z,""),d??="bedrock"),A.test(c)&&(c=c.replace(A,""),d??="vertex"),w.test(c)?c=c.replace(w,""):x.test(c)&&(c=c.replace(x,"")),{id:c,platform:d}),h=b.byId.get(f);if(void 0!==h)return{entry:h,canonicalId:f,platform:g,raw:a};if(B.test(f)){let c=f.replace(B,""),d=b.byId.get(c);if(void 0!==d)return{entry:d,canonicalId:c,platform:g,raw:a}}return{entry:null,canonicalId:a,platform:g,raw:a}}let D=t("anthropic",{family:{id:"claude",name:"Claude"},region:"us",retention:"zero_retention",training:{apiDefault:"no",consumerDefault:"no",consumerControl:"opt-in",source:"https://privacy.claude.com/en/articles/7996868-is-my-data-used-for-model-training"}}),E=["bedrock","vertex","foundry"];D.model("claude-fable-5-1",{name:"Claude Fable 5.1",ctx:1e6,maxOut:128e3,capability:"reasoning",price:j(10,50,.25),on:[...E]}),D.model("claude-fable-5",{name:"Claude Fable 5",capability:"reasoning",price:j(10,50,1),on:[...E]}),D.model("claude-opus-5",{name:"Claude Opus 5",ctx:1e6,maxOut:128e3,capability:"reasoning",price:j(5,25,.5),on:[...E]}),D.model("claude-opus-4-8",{name:"Claude Opus 4.8",capability:"reasoning",price:j(5,25,.5),on:[...E]}),D.model("claude-opus-4-7",{name:"Claude Opus 4.7",capability:"reasoning",price:j(5,25,.5),on:[...E]}),D.model("claude-opus-4-6",{name:"Claude Opus 4.6",capability:"reasoning",price:j(5,25,.5),on:[...E]}),D.model("claude-opus-4-5",{name:"Claude Opus 4.5",capability:"reasoning",price:j(5,25,.5),on:[...E]}),D.model("claude-opus-4-1",{name:"Claude Opus 4.1",capability:"reasoning",price:j(15,75,1.5),on:[...E]}),D.model("claude-sonnet-5",{name:"Claude Sonnet 5",ctx:1e6,maxOut:128e3,capability:"reasoning",price:j(2,10,.2),on:[...E]}),D.model("claude-sonnet-4-6",{name:"Claude Sonnet 4.6",capability:"reasoning",price:j(3,15,.3),on:[...E]}),D.model("claude-sonnet-4-5",{name:"Claude Sonnet 4.5",capability:"reasoning",price:j(3,15,.3),on:[...E]}),D.model("claude-haiku-4-5",{name:"Claude Haiku 4.5",ctx:2e5,maxOut:64e3,capability:null,price:j(1,5,.1),aliases:["claude-haiku-4-5-20251001"],on:[...E]}),D.model("claude-sonnet-3-7",{name:"Claude Sonnet 3.7",on:[...E]});let F={thresholdInputTokens:272e3,input:null,output:null},G=t("openai",{family:{id:"gpt",name:"GPT"},region:"us",retention:"configurable",training:{apiDefault:"no",consumerDefault:"yes",consumerControl:"opt-out",source:"https://developers.openai.com/api/docs/guides/your-data"}}),H=["azure","foundry"];G.model("gpt-5.6-sol",{name:"GPT-5.6 Sol",ctx:105e4,maxOut:128e3,capability:"reasoning",price:k(4,20,{cacheRead:.4,longContext:F}),on:[...H]}),G.model("gpt-5.6-terra",{name:"GPT-5.6 Terra",ctx:105e4,maxOut:128e3,capability:"reasoning",price:k(2,12,{cacheRead:.2,longContext:F}),on:[...H]}),G.model("gpt-5.6-luna",{name:"GPT-5.6 Luna",ctx:105e4,maxOut:128e3,capability:null,price:k(.2,1.2,{cacheRead:.02,longContext:F}),on:[...H]}),G.model("gpt-5.5",{name:"GPT-5.5",ctx:105e4,maxOut:128e3,capability:"reasoning",price:k(5,30,{cacheRead:.5,longContext:F}),on:[...H]}),G.model("gpt-5.4",{name:"GPT-5.4",ctx:105e4,maxOut:128e3,capability:"reasoning",price:k(2.5,15,{cacheRead:.25,longContext:F}),on:[...H]}),G.model("gpt-5.4-mini",{name:"GPT-5.4 mini",ctx:4e5,maxOut:128e3,capability:null,price:k(.75,4.5,{cacheRead:.075}),on:[...H]}),G.model("gpt-5.4-nano",{name:"GPT-5.4 nano",ctx:4e5,maxOut:128e3,capability:null,price:k(.2,1.25,{cacheRead:.02}),on:[...H]}),G.model("gpt-5.3-codex",{name:"GPT-5.3 Codex",ctx:4e5,maxOut:128e3,capability:"code",price:k(1.75,14,{cacheRead:.175}),on:[...H]}),G.model("gpt-5.1",{name:"GPT-5.1",ctx:4e5,maxOut:128e3,capability:"reasoning",price:k(1.25,10,{cacheRead:.125}),on:[...H]}),G.model("gpt-5",{name:"GPT-5",ctx:4e5,maxOut:128e3,capability:"reasoning",price:k(1.25,10,{cacheRead:.125}),on:[...H]}),G.model("gpt-5-mini",{name:"GPT-5 mini",ctx:4e5,capability:null,price:k(.25,2,{cacheRead:.025}),on:[...H]}),G.model("gpt-5-nano",{name:"GPT-5 nano",ctx:4e5,maxOut:128e3,capability:null,price:k(.05,.4,{cacheRead:.005}),on:[...H]}),G.model("gpt-4.1",{name:"GPT-4.1",price:k(2,8,{cacheRead:.5}),on:[...H]}),G.model("gpt-4o",{name:"GPT-4o",price:k(2.5,10,{cacheRead:1.25}),on:[...H]}),G.model("gpt-4o-mini",{name:"GPT-4o mini",price:k(.15,.6,{cacheRead:.075}),on:[...H]}),G.model("gpt-4-turbo",{name:"GPT-4 Turbo",seen:"discovered",price:k(10,30),aliases:["gpt-4-turbo-2024-04-09"],on:[...H]}),G.model("o3",{name:"o3",capability:"reasoning",price:k(2,8,{cacheRead:.5}),on:[...H]}),G.model("gpt-oss-120b",{name:"GPT-OSS 120B",openWeights:!0,firstParty:!1,retention:"unknown",defaultHosting:"local",on:["together","fireworks","groq","openrouter","bedrock","ollama","local"]}),G.model("gpt-oss-20b",{name:"GPT-OSS 20B",openWeights:!0,firstParty:!1,retention:"unknown",defaultHosting:"local",on:["together","fireworks","groq","openrouter","ollama","local"]});let I=t("google",{family:{id:"gemini",name:"Gemini"},region:"us",retention:"configurable",training:{apiDefault:"no",consumerDefault:"yes",consumerControl:"none",source:"https://ai.google.dev/gemini-api/terms"}});I.model("gemini-3.7-flash",{name:"Gemini 3.7 Flash",capability:null,price:k(.75,3.75),on:["vertex"]}),I.model("gemini-3.6-flash",{name:"Gemini 3.6 Flash",capability:null,price:k(.75,3.75),on:["vertex"]}),I.model("gemini-3.5-flash",{name:"Gemini 3.5 Flash",capability:null,price:k(1.5,9),on:["vertex"]}),I.model("gemini-3.5-flash-lite",{name:"Gemini 3.5 Flash Lite",capability:null,price:k(.3,2.5),on:["vertex"]}),I.model("gemini-3.1-pro-preview",{name:"Gemini 3.1 Pro Preview",capability:"reasoning",price:k(2,12,{longContext:{thresholdInputTokens:2e5,input:4,output:18}}),on:["vertex"]}),I.model("gemini-2.5-pro",{name:"Gemini 2.5 Pro",capability:"reasoning",price:k(1.25,10,{longContext:{thresholdInputTokens:2e5,input:2.5,output:15}}),on:["vertex"]}),I.model("gemini-2.5-flash",{name:"Gemini 2.5 Flash",capability:null,price:k(.3,2.5),on:["vertex"]}),I.model("gemini-2.5-flash-lite",{name:"Gemini 2.5 Flash Lite",capability:null,price:k(.1,.4),on:["vertex"]}),I.model("gemini-1-5-pro",{name:"Gemini 1.5 Pro",on:["vertex"]}),I.model("gemini-1-5-flash",{name:"Gemini 1.5 Flash",on:["vertex"]});let J=t("xai",{family:{id:"grok",name:"Grok"},region:"us",retention:"configurable",training:{apiDefault:"no",consumerDefault:"unknown",consumerControl:"unknown",source:"https://docs.x.ai/developers/faq/security"}});J.model("grok-4.6",{name:"Grok 4.6",ctx:5e5,capability:"reasoning",price:k(2,6,{cacheRead:.5,longContext:{thresholdInputTokens:2e5,input:4,output:12}}),on:["bedrock"]}),J.model("grok-4.5",{name:"Grok 4.5",ctx:5e5,capability:"reasoning",price:k(2,6,{cacheRead:.3,longContext:{thresholdInputTokens:2e5,input:4,output:12}})}),J.model("grok-4.3",{name:"Grok 4.3",ctx:1e6,capability:"reasoning",price:k(1.25,2.5,{cacheRead:.2,longContext:{thresholdInputTokens:2e5,input:2.5,output:5}}),on:["bedrock"]}),J.model("grok-build-0.1",{name:"Grok Build 0.1",ctx:256e3,capability:"code",price:k(1,2,{cacheRead:.2,longContext:{thresholdInputTokens:2e5,input:2,output:4}})});let K=t("deepseek",{family:{id:"deepseek",name:"DeepSeek"},region:"cn",retention:"configurable",training:{apiDefault:"yes",consumerDefault:"yes",consumerControl:"opt-out",source:"https://cdn.deepseek.com/policies/en-US/deepseek-privacy-policy.html"}});K.model("deepseek-v4-flash",{name:"DeepSeek V4 Flash",ctx:1e6,capability:null,price:k(.44,1.32,{cacheRead:.014}),on:["bedrock","together","fireworks","openrouter","ollama","local"]}),K.model("deepseek-v4-pro",{name:"DeepSeek V4 Pro",ctx:1e6,capability:"reasoning",price:k(1.32,3.96,{cacheRead:.044}),on:["bedrock","together","fireworks","openrouter"]}),K.model("deepseek-r1",{name:"DeepSeek R1",seen:"discovered",capability:"reasoning",openWeights:!0,defaultHosting:"local",on:["bedrock","together","fireworks","openrouter","ollama","local"]});let L=t("cohere",{family:{id:"command",name:"Command"},region:"us",retention:"configurable",training:{apiDefault:"unknown",consumerDefault:"unknown",consumerControl:"opt-out",source:"https://cohere.com/security"}});L.model("command-a-plus-05-2026",{name:"Command A+",ctx:128e3,maxOut:64e3,on:["bedrock"]}),L.model("command-a-03-2025",{name:"Command A",ctx:256e3,maxOut:8e3,on:["bedrock"]}),L.model("command-a-reasoning-08-2025",{name:"Command A Reasoning",ctx:256e3,maxOut:32e3,capability:"reasoning"}),L.model("command-r-plus-08-2024",{name:"Command R+",ctx:128e3,maxOut:4e3,price:k(2.5,10),aliases:["command-r-plus"],on:["bedrock"]});let M=t("meta",{family:{id:"llama",name:"Llama"},openWeights:!0,retention:"unknown",defaultHosting:"local"}),N=["bedrock","together","fireworks","groq","openrouter","ollama","local"];M.model("llama-3-3-70b",{name:"Llama 3.3 70B",ctx:128e3,on:[...N]}),M.model("llama-3-1-70b",{name:"Llama 3.1 70B",ctx:128e3,on:[...N]}),M.model("llama-3-1-8b",{name:"Llama 3.1 8B",ctx:128e3,on:[...N]});let O=t("alibaba",{family:{id:"qwen",name:"Qwen"},openWeights:!0,retention:"unknown",defaultHosting:"local"});O.model("qwen-3-235b",{name:"Qwen 3 235B",on:[...N]}),O.model("qwen-3-coder-480b",{name:"Qwen 3 Coder 480B",capability:"code",on:[...N]});let P=t("amazon",{family:{id:"nova",name:"Nova"},retention:"configurable"});P.model("nova-2-lite",{name:"Nova 2 Lite",ctx:1e6,maxOut:64e3,aliases:["nova-2-lite-v1:0"],on:["bedrock"]});let Q=t("mistral",{family:{id:"mistral",name:"Mistral"},openWeights:!0,retention:"unknown",defaultHosting:"local"});Q.model("mixtral-8x7b",{name:"Mixtral 8x7B",seen:"discovered",on:[...N]});let R=function(a){let b=new Map;for(let c of a)b.set(c.id,c);for(let c of a)for(let a of c.aliases)b.has(a)||b.set(a,c);return{byId:b,entries:Object.freeze([...a])}}(Object.freeze([...D.models(),...G.models(),...I.models(),...J.models(),...K.models(),...L.models(),...Q.models(),...M.models(),...O.models(),...P.models()]));h.k5(["reasoning","code"]),h.k5(["zero_retention","no_storage","configurable","on_device","on_infrastructure","unknown"]),h.k5(["managed","discovered"]);let S=h.k5(["yes","no","unknown"]),T=h.k5(["opt-in","opt-out","none","unknown"]);h.Ik({apiDefault:S,consumerDefault:S,consumerControl:T,source:h.Yj().nullable()});let U=h.k5(["api","consumer","enterprise","unknown"]);function V(a){return new Date(a).getTime()}function W(a){return new Date(a).toISOString()}h.Ik({tier:U,controlExercised:h.zM().nullable()}),Object.freeze({tier:"unknown",controlExercised:null});let X=new Map([["anthropic","anthropic"],["openai","openai"],["google","google-ai"],["google-ai","google-ai"],["bedrock","bedrock"],["vertex","vertex"],["azure","azure"],["foundry","foundry"],["mistral","mistral"],["deepseek","deepseek"],["xai","xai"],["cohere","cohere"],["together","together"],["fireworks","fireworks"],["groq","groq"],["openrouter","openrouter"],["ollama","ollama"],["local","local"]]);function Y(a){return X.get(a.trim().toLowerCase())??null}function Z(a){let b=Y(a);return null!==b&&"local"===o(b)}Object.freeze(["gateway","unknown","cli","api"]);let $={normalizeModelId(a,b){let c=a.trim().toLowerCase();if(Z(c))return{provider:c,model:"*"};let d=C(b,R);return{provider:c,model:d.entry?.id??b}},costFor({provider:a,model:b,usage:c}){let d=function(a,b){if(Z(a))return l;let c=C(b,R);if(null===c.entry)return null;let d=c.platform??Y(a);return null===d?null:c.entry.platforms.get(d)?.price??null}(a,b);return null===d?null:function(a,b){var c;let d=[[b.cacheWrite1hTokens??0,a.cacheWrite1h],[b.cacheWrite5mTokens??0,a.cacheWrite5m],[b.cacheReadTokens??0,a.cacheRead]],e=null!==a.longContext&&(b.inputTokens??0)>a.longContext.thresholdInputTokens?a.longContext:null;if(null!==e&&(null===e.input||null===e.output))return null;let f=e?.input??a.input,g=e?.output??a.output,h=(b.inputTokens??0)*f+(b.outputTokens??0)*g;for(let[a,b]of d)if(0!==a){if(null===b)return null;h+=a*b}let i=h/1e6*(void 0===(c=b.serviceTier)?1:m.get(c)??1),j=b.webSearchRequests??0;return j>0&&null===a.webSearch?null:i+j*(a.webSearch??0)}(d,c)}};new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1});let _=a=>a??0;function aa(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+=_(e.input_tokens),i.output+=_(e.output_tokens),i.cacheCreation+=_(e.cache_creation_input_tokens),i.cacheRead+=_(e.cache_read_input_tokens);let j=b.costFor({provider:a,model:f,usage:function(a){let b={inputTokens:_(a.input_tokens),outputTokens:_(a.output_tokens),cacheWrite1hTokens:_(a.ephemeral_1h_input_tokens),cacheWrite5mTokens:_(a.ephemeral_5m_input_tokens),cacheReadTokens:_(a.cache_read_input_tokens),webSearchRequests:_(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 ab=c(81852),ac=c(31518);let ad={ClaudeCode:"claudecode",Cursor:"cursor",Copilot:"copilot",Codex:"codex",Antigravity:"antigravity",Windsurf:"windsurf",ClaudeDesktop:"claudedesktop",ChatGpt:"chatgpt",ClaudeAi:"claudeai",Api:"api"},ae=h.k5(ad).meta({id:"Harness"}),af={ClaudeCode:"claude-code",ClaudeDesktop:"claude-desktop",Cursor:"cursor",ChatGpt:"chatgpt",ClaudeAi:"claude-ai",Copilot:"github-copilot",Codex:"codex",Antigravity:"antigravity",Cli:"cli",Unknown:"unknown"},ag=h.k5(af).meta({id:"SourceTool"}),ah={[af.ClaudeCode]:ad.ClaudeCode,[af.ClaudeDesktop]:ad.ClaudeDesktop,[af.Copilot]:ad.Copilot,[af.Cursor]:ad.Cursor,[af.ChatGpt]:ad.ChatGpt,[af.Codex]:ad.Codex,[af.Antigravity]:ad.Antigravity,[af.ClaudeAi]:ad.ClaudeAi},ai=h.k5(["pii","financial","secret","phi","code_context","code_flaw","custom","config"]).meta({id:"DetectionCategory"}),aj=h.k5(["critical","high","medium","low"]).meta({id:"Severity"}),ak=h.k5(["warn","redact","block","allow","log"]).meta({id:"ActionTaken"}),al=ak.options,am=h.Ik({start:h.ai().int().nonnegative(),end:h.ai().int().nonnegative()}).meta({id:"Span"});h.Ik({id:h.Os(),eventId:h.Os(),ruleId:h.Yj(),category:ai,severity:aj,span:am,maskedMatch:h.Yj(),actionTaken:ak,confidence:h.ai().min(0).max(1)}).meta({id:"Finding"}).meta({id:"DetectedFinding"});let an=h.k5(["blocked","redacted","warned","allowed","quarantined","monitored"]).meta({id:"FindingAction"}),ao=ae.extract(["ClaudeCode","ClaudeDesktop","Cursor","Copilot","ChatGpt","ClaudeAi","Codex","Antigravity","Api"]).meta({id:"FindingProvider"}),ap=h.k5(["secret","pii","source_code","code_flaw","external_share","mcp_server","customer_data","financial","phi","custom"]).meta({id:"FindingCategory"});h.k5(["in-flight","at-rest"]).meta({id:"FindingOrigin"});let aq=h.k5(["open","handled","resolved","dismissed"]).meta({id:"FindingStatus"}),ar=h.k5(["deployment_refused","payload_invalid","detached_undelivered"]).meta({id:"SyncFailureReason"}),as=h.k5(["sent","queued","not_sent","never_offered","local_scan"]).meta({id:"FindingDeliveryState"}),at=h.Ik({state:as,at:ab.w$().optional(),reason:ar.optional()}).meta({id:"FindingDelivery"}),au=h.k5(["enforced-in-flight","fixed-at-source","exception","acknowledged","false-positive","redetected"]).meta({id:"ResolutionMethod"}),av=h.Ik({maskedValue:h.Yj(),contextPrefix:h.Yj()}).meta({id:"FindingMatch"}),aw=h.Ik({id:h.Yj(),name:h.Yj().nullable()}).meta({id:"FindingDetectionRef"}),ax=h.Ik({id:h.Yj(),name:h.Yj()}).meta({id:"FindingPolicyRef"}),ay=h.Ik({id:h.Yj(),name:h.Yj()}).meta({id:"FindingUser"}),az=h.Ik({id:h.Yj(),provider:ao,repo:h.Yj(),file:h.Yj(),user:ay.optional(),toolName:h.Yj().optional(),action:an,detectedAt:ab.w$(),confidence:h.ai().min(0).max(1),status:aq.optional(),eventId:h.Yj().optional(),sessionId:h.Yj().optional(),delivery:at.optional()}).meta({id:"FindingInstance"}),aA=h.Ik({id:h.Yj(),category:ap,subtype:h.Yj(),severity:aj,match:av,detection:aw,policy:ax,instanceCount:h.ai().int().nonnegative(),providers:h.YO(ao),aggregateAction:an.nullable(),latestDetectedAt:ab.w$(),instances:h.YO(az),status:aq.optional(),users:h.YO(ay).optional()}).meta({id:"FindingGroup"});h.Ik({findings:h.ai().int().nonnegative(),groups:h.ai().int().nonnegative(),bySeverity:h.Ik({critical:h.ai().int().nonnegative(),high:h.ai().int().nonnegative(),medium:h.ai().int().nonnegative(),low:h.ai().int().nonnegative()})}).meta({id:"FindingStats"});let aB=h.Ik({value:h.Yj(),count:h.ai().int().nonnegative()}).meta({id:"FindingFacetItem"}),aC=h.Ik({severity:h.YO(aB),subtype:h.YO(aB),provider:h.YO(aB),action:h.YO(aB),status:h.YO(aB),tool:h.YO(aB).optional(),deployment:h.YO(aB).optional()}).meta({id:"FindingFacets"}),aD=aA.omit({instances:!0,match:!0}).meta({id:"FindingTypeSummary"}),aE=50,aF=h.Ik({severity:h.YO(aj).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ao).optional(),action:h.YO(an).optional(),status:h.YO(aq).optional(),q:h.Yj().optional(),sessionId:h.Yj().optional(),from:ab.w$().optional(),includeId:h.Yj().optional(),limit:ac.ai().int().min(1).max(100).optional(),cursor:h.Yj().optional()});h.Ik({totals:h.Ik({findings:h.ai().int().nonnegative(),types:h.ai().int().nonnegative()}),facets:aC,items:h.YO(aD),nextCursor:h.Yj().nullable(),sessionFirings:h.g1(h.Yj(),h.ai().int().nonnegative()).optional()}).meta({id:"ListFindingTypesResponse"}),h.Ik({action:an.exclude(["quarantined"]),instanceId:h.Yj().optional()}).meta({id:"ApplyFindingActionRequest"}),aA.meta({id:"ApplyFindingActionResponse"}),h.Ik({severity:h.YO(aj).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ao).optional(),action:h.YO(an).optional(),q:h.Yj().optional(),format:h.k5(["csv","json"]).optional()});let aG=az.extend({groupId:h.Yj(),category:ap,subtype:h.Yj(),severity:aj,match:av,detection:aw,policy:ax}).meta({id:"FindingInstanceDetail"}),aH=50,aI=h.Ik({severity:h.YO(aj).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ao).optional(),action:h.YO(an).optional(),status:h.YO(aq).optional(),tool:h.YO(h.Yj()).optional(),deployment:h.YO(as).optional(),repo:h.Yj().optional(),file:h.Yj().optional(),q:h.Yj().optional(),sessionId:h.Yj().optional(),from:ab.w$().optional(),limit:ac.ai().int().min(1).max(200).optional(),cursor:h.Yj().optional()});h.Ik({totals:h.Ik({findings:h.ai().int().nonnegative()}),facets:aC,items:h.YO(aG),nextCursor:h.Yj().nullable()}).meta({id:"ListFindingInstancesResponse"}),h.Ik({items:h.YO(aG),nextCursor:h.Yj().nullable()}).meta({id:"ListFindingInstancesPage"});let aJ=h.Ik({id:h.Yj(),repo:h.Yj(),file:h.Yj(),instanceCount:h.ai().int().nonnegative(),maxSeverity:aj,latestDetectedAt:ab.w$(),status:aq.optional(),ruleIds:h.YO(h.Yj())}).meta({id:"FindingLocationSummary"}),aK=50,aL=h.Ik({severity:h.YO(aj).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ao).optional(),action:h.YO(an).optional(),status:h.YO(aq).optional(),tool:h.YO(h.Yj()).optional(),deployment:h.YO(as).optional(),q:h.Yj().optional(),sessionId:h.Yj().optional(),from:ab.w$().optional(),includeId:h.Yj().optional(),limit:ac.ai().int().min(1).max(100).optional(),cursor:h.Yj().optional()});h.Ik({totals:h.Ik({findings:h.ai().int().nonnegative(),locations:h.ai().int().nonnegative()}),facets:aC,items:h.YO(aJ),nextCursor:h.Yj().nullable()}).meta({id:"ListFindingLocationsResponse"});let aM=h.k5(["host","harness","user","skill","hook","mcp_server","config_file"]).meta({id:"InventoryObjectType"}),aN=h.k5(["session","run","tool_call","llm_call","source_lookup","prompt","response","code_change","tool_use","model_refusal","config_scan"]).meta({id:"AuditEventType"}),aO=h.g1(h.Yj(),h.L5());h.Ik({host_name:h.Yj().optional(),os:h.Yj().optional(),os_version:h.Yj().optional(),arch:h.Yj().optional()}).catchall(h.L5()),h.Ik({harness_version:h.Yj().optional(),interface:h.Yj().optional()}).catchall(h.L5()),h.Ik({display_name:h.Yj().optional(),email:h.Yj().optional()}).catchall(h.L5()),h.Ik({source:h.Yj().optional(),version:h.Yj().optional(),description:h.Yj().optional(),updated_at:h.Yj().optional(),scope:h.Yj().optional(),plugin_name:h.Yj().optional()}).catchall(h.L5()),h.Ik({event:h.Yj().optional(),matcher:h.Yj().optional(),command:h.Yj().optional(),scope:h.Yj().optional(),plugin_name:h.Yj().optional(),timeout:h.ai().optional()}).catchall(h.L5()),h.Ik({scope:h.Yj().optional(),transport:h.Yj().optional(),command:h.Yj().optional(),url:h.Yj().optional(),env_keys:h.YO(h.Yj()).optional(),plugin_name:h.Yj().optional(),marketplace:h.Yj().optional(),project:h.Yj().optional()}).catchall(h.L5()),h.Ik({kind:h.Yj().optional(),detail:h.Yj().optional(),scope:h.Yj().optional(),updated_at:h.Yj().optional(),entry_count:h.ai().optional()}).catchall(h.L5());let aP=h.Ik({model:h.Yj().optional(),provider:h.Yj().optional(),input_tokens:h.ai().int().nonnegative().optional(),output_tokens:h.ai().int().nonnegative().optional(),cache_creation_input_tokens:h.ai().int().nonnegative().optional(),cache_read_input_tokens:h.ai().int().nonnegative().optional(),ephemeral_1h_input_tokens:h.ai().int().nonnegative().optional(),ephemeral_5m_input_tokens:h.ai().int().nonnegative().optional(),web_search_requests:h.ai().int().nonnegative().optional(),web_fetch_requests:h.ai().int().nonnegative().optional(),service_tier:h.Yj().optional(),stop_reason:h.Yj().optional(),message_id:h.Yj().optional(),uuid:h.Yj().optional(),parent_uuid:h.Yj().optional(),run_key:h.Yj().optional()}).catchall(h.L5());h.Ik({sessionId:h.Yj().min(1),messageId:h.Yj().min(1),parentId:h.Yj().min(1),rootSessionId:h.Yj().min(1),startedAt:ab.w$(),attributes:aP});let aQ=h.Ik({tool_name:h.Yj().optional(),tool_use_id:h.Yj().optional(),target:h.Yj().optional(),is_error:h.zM().optional(),input_size:h.ai().int().nonnegative().optional(),output_size:h.ai().int().nonnegative().optional(),uuid:h.Yj().optional(),parent_uuid:h.Yj().optional(),run_key:h.Yj().optional()}).catchall(h.L5());h.Ik({source_tool:h.Yj().optional(),file_path:h.Yj().optional(),repo:h.Yj().optional(),tool_name:h.Yj().optional(),gitignored:h.zM().optional(),whole_file:h.zM().optional(),correlation_id:h.uR().optional(),trace_id:h.Yj().regex(/^[0-9a-f]{32}$/).optional(),exception_ids:h.YO(h.Os()).optional(),message_id:h.Yj().optional(),conversation_id:h.Yj().optional(),inspection_ms:h.ai().int().nonnegative().optional(),redact_degraded_to:ak.optional()}).catchall(h.L5());let aR=h.Ik({ruleId:h.Yj().min(1),ruleName:h.Yj(),ruleVersion:h.Yj().min(1),category:ai,severity:aj,span:am,maskedMatch:h.Yj(),actionTaken:ak,confidence:h.ai().min(0).max(1)});h.Ik({sessionId:h.Yj().min(1),toolUseId:h.Yj().min(1),parentId:h.Yj().min(1),rootSessionId:h.Yj().min(1),startedAt:ab.w$(),attributes:aQ,inspections:h.YO(aR).default([])});let aS=h.Ik({objectType:aM,identityKey:h.Yj().min(1),location:h.Yj().optional(),title:h.Yj().optional(),hostId:h.Yj().optional(),attributes:aO.default({})}).meta({id:"InventoryInput"}),aT=h.Ik({url:h.Yj().min(1),name:h.Yj().optional(),attributes:aO.default({})}).meta({id:"SourceProjectInput"}),aU=h.Ik({id:h.Yj().min(1),eventType:aN,startedAt:ab.w$(),endedAt:ab.w$().optional(),parentId:h.Yj().optional(),rootSessionId:h.Yj().optional(),hostId:h.Yj().optional(),harnessId:h.Yj().optional(),sourceProjectId:h.Yj().optional(),severity:aj.optional(),priority:h.Yj().optional(),content:h.Yj().optional(),contentHash:h.Yj().optional(),attributes:aO.optional()}).meta({id:"AuditEventInput"});h.Ik({class:h.Yj().min(1),label:h.Yj().optional(),attributes:aO.optional()});let aV=h.Ik({ruleId:h.Yj().min(1),version:h.Yj().min(1),name:h.Yj(),category:ai,severity:aj,definition:h.Yj()});h.Ik({id:h.Yj().min(1),auditEventId:h.Yj().min(1),inspectionDefinitionId:h.Yj().min(1),classifiedDataId:h.Yj().optional(),span:am,maskedMatch:h.Yj(),actionTaken:ak,confidence:h.ai().min(0).max(1),findingKey:h.Yj().optional(),firstDetectedAt:ab.w$().optional()}),h.Ik({host:aS.optional(),harness:aS.optional(),project:aT.optional()}).meta({id:"InventoryContext"});let aW=h.Ik({hostId:h.Yj().optional(),harnessId:h.Yj().optional(),accountId:h.Yj().optional(),sourceProjectId:h.Yj().optional()}).meta({id:"ResolvedInventory"});h.Ik({hosts:h.YO(h.Yj()),harnesses:h.YO(h.Yj()),osVersions:h.YO(h.Yj()),projects:h.YO(h.Yj())}).meta({id:"InventoryFacets"});let aX=h.Ik({sessionId:h.Yj(),model:h.Yj(),provider:h.Yj(),inputTokens:h.ai().int().nonnegative(),outputTokens:h.ai().int().nonnegative(),cacheCreation:h.ai().int().nonnegative(),cacheRead:h.ai().int().nonnegative(),totalTokens:h.ai().int().nonnegative(),estimatedCostUsd:h.ai().nullable()}).meta({id:"TokenRollup"});h.Ik({sessionId:h.Yj(),rollups:h.YO(aX),totalTokens:h.ai().int().nonnegative(),estimatedCostUsd:h.ai().nullable(),costIsPartial:h.zM()});let aY=h.Ik({provider:h.Yj(),model:h.Yj(),inputTokens:h.ai().int().nonnegative(),outputTokens:h.ai().int().nonnegative(),cacheTokens:h.ai().int().nonnegative(),totalTokens:h.ai().int().nonnegative(),estimatedCostUsd:h.ai().nullable()});function aZ(a){return JSON.stringify(a)}h.Ik({models:h.YO(aY),sessionCount:h.ai().int().nonnegative(),totalTokens:h.ai().int().nonnegative(),estimatedCostUsd:h.ai(),costIsPartial:h.zM()});let a$=h.k5(["active","completed","interrupted","error"]),a_=h.k5(["session","prompt","response","tool","hook","detection","share","permission","commit","error","active"]),a0=h.k5(["detections","shares","inventory"]),a1=h.Ik({id:h.Yj(),occurredAt:ab.w$(),kind:a_,title:h.Yj(),detail:h.Yj(),tool:h.Yj().nullable(),severity:aj.nullable(),link:a0.nullable(),targetId:h.Yj().nullable(),internal:h.zM(),flagged:h.zM(),bodyExpired:h.zM().default(!1)}).meta({id:"ActivityAuditEvent"}),a2=h.Ik({id:h.Yj(),harness:ae,title:h.Yj(),project:h.Yj(),repo:h.Yj(),branches:h.YO(h.Yj()),startedAt:ab.w$(),endedAt:ab.w$().nullable(),status:a$,turns:h.ai().int().nonnegative(),findings:h.ai().int().nonnegative(),shares:h.ai().int().nonnegative()}).meta({id:"ActivitySessionSummary"});a2.extend({host:h.Yj(),cwd:h.Yj(),models:h.YO(h.Yj()),version:h.Yj(),tokens:aX,tools:h.g1(h.Yj(),h.ai().int().nonnegative()),files:h.YO(h.Yj()),commits:h.ai().int().nonnegative(),events:h.YO(a1)}).meta({id:"ActivitySession"}),h.Ik({tz:h.Yj().optional()});let a3=h.Ik({sessionsToday:h.ai().int().nonnegative(),liveNow:h.ai().int().nonnegative(),toolCallsToday:h.ai().int().nonnegative(),findingsToday:h.ai().int().nonnegative(),egressToday:h.ai().int().nonnegative()}).meta({id:"GetActivityStatsResponse"});h.Ik({q:h.Yj().optional(),harness:h.YO(ae).optional(),from:h.KC([ab.p6(),ab.w$()]).optional(),to:h.KC([ab.p6(),ab.w$()]).optional(),excludeEmpty:h.uE().optional(),limit:ac.ai().int().min(1).max(100).default(50),cursor:h.Yj().optional()});let a4=h.Ik({items:h.YO(a2),nextCursor:h.Yj().nullable(),emptyCount:h.ai().int().nonnegative()}).meta({id:"ListActivitySessionsResponse"});h.Ik({limit:ac.ai().int().min(1).max(500).default(100),cursor:h.Yj().optional(),order:h.k5(["asc","desc"]).default("asc")}),h.Ik({items:h.YO(a1),nextCursor:h.Yj().nullable()}).meta({id:"ListSessionEventsResponse"}),h.Ik({format:h.k5(["ndjson","json"]).default("ndjson")}),h.Ik({format:h.k5(["csv","json"]).default("csv"),q:h.Yj().optional(),harness:h.YO(ae).optional(),from:h.KC([ab.p6(),ab.w$()]).optional(),to:h.KC([ab.p6(),ab.w$()]).optional()}),h.Ik({stats:a3,sessions:a4}).meta({id:"ActivityOverviewResponse"});let a5=h.k5(["user","project","local","plugin"]),a6=h.Ik({name:h.Yj().min(1),source:h.Yj().min(1),scope:a5,pluginName:h.Yj().optional(),version:h.Yj().optional(),description:h.Yj().optional(),updatedAt:ab.w$().optional(),location:h.Yj().optional()}),a7=h.Ik({event:h.Yj().min(1),matcher:h.Yj().optional(),command:h.Yj().min(1),timeout:h.ai().optional(),scope:a5,pluginName:h.Yj().optional(),location:h.Yj().optional()}),a8=h.Ik({name:h.Yj().min(1),scope:a5,pluginName:h.Yj().optional(),marketplace:h.Yj().optional(),project:h.Yj().optional(),transport:h.Yj().min(1),command:h.Yj().optional(),url:h.Yj().optional(),envKeys:h.YO(h.Yj()).optional(),location:h.Yj().optional()}),a9=h.Ik({name:h.Yj().min(1),path:h.Yj().min(1),scope:a5,kind:h.Yj().min(1),detail:h.Yj().optional(),entryCount:h.ai().optional(),updatedAt:ab.w$().optional()});h.Ik({scannedAt:ab.w$(),skills:h.YO(a6),hooks:h.YO(a7),mcpServers:h.YO(a8),configFiles:h.YO(a9),errors:h.YO(h.Ik({source:h.Yj(),reason:h.Yj()}))});let ba=h.Ik({ruleId:h.Yj().min(1),version:h.Yj().min(1),span:am,maskedMatch:h.Yj(),actionTaken:ak,confidence:h.ai().min(0).max(1)});h.Ik({items:h.YO(aS),scanEvent:aU,definitions:h.YO(aV).optional(),findings:h.YO(ba).optional()});let bb=h.k5(["project","skill","mcp","hook","config"]).meta({id:"AssetType"}),bc=h.k5(["open","approved","blocked"]).meta({id:"AccessLevel"}),bd=h.k5(["source","public-dep","vendored","config","data","docs","generated"]).meta({id:"Origin"}),be=h.k5(["known-good","risky","unapproved"]).meta({id:"TrustLevel"}),bf=h.k5(["update","stale","conflict","unknown","change","untracked","risk","findings"]).meta({id:"Flag"}),bg=h.k5(["public","private"]).meta({id:"Visibility"}),bh=h.k5(["block","redact","warn"]).meta({id:"HarnessEventKind"}),bi=ae.extract(["ClaudeCode","Cursor","Codex","Antigravity"]).meta({id:"HarnessId"}),bj=h.Ik({open:h.ai().int().nonnegative(),approved:h.ai().int().nonnegative(),blocked:h.ai().int().nonnegative(),total:h.ai().int().nonnegative()}).meta({id:"AccessCounts"}),bk=h.Ik({id:h.Yj(),type:bb,name:h.Yj(),sub:h.Yj(),flags:h.YO(bf),trust:be.optional()}).meta({id:"AssetSummary"}),bl=h.Ik({id:h.Yj(),name:h.Yj(),repo:h.Yj(),visibility:bg,language:h.Yj(),policyDefault:bc,updatedAt:ab.w$(),accessCounts:bj,findingsCount:h.ai().int().nonnegative()}).meta({id:"ProjectSummary"}),bm=h.Ik({type:bb,assets:h.YO(bk)}),bn=h.Ik({id:bi,label:h.Yj(),kind:h.Yj(),version:h.Yj(),sessions:h.ai().int().nonnegative(),assetCount:h.ai().int().nonnegative(),flagCount:h.ai().int().nonnegative(),projects:h.YO(bl),categories:h.YO(bm)}).meta({id:"HarnessSummary"});h.Ik({items:h.YO(bn)}).meta({id:"ListHarnessesResponse"});let bo=h.Ik({type:bb,total:h.ai().int().nonnegative(),trustRollup:h.Ik({"known-good":h.ai().int().nonnegative(),risky:h.ai().int().nonnegative(),unapproved:h.ai().int().nonnegative()}).partial().strict().optional(),flagRollup:h.Ik({update:h.ai().int().nonnegative(),stale:h.ai().int().nonnegative(),conflict:h.ai().int().nonnegative(),unknown:h.ai().int().nonnegative(),change:h.ai().int().nonnegative(),untracked:h.ai().int().nonnegative(),risk:h.ai().int().nonnegative(),findings:h.ai().int().nonnegative()}).partial().strict(),items:h.YO(bk)}).meta({id:"AssetGroup"});h.Ik({groups:h.YO(bo)}).meta({id:"ListAssetsResponse"});let bp=h.Ik({name:h.Yj(),signature:h.Yj(),description:h.Yj(),write:h.zM(),risk:h.Yj().nullable()}).meta({id:"McpTool"}),bq=h.Ik({id:h.Yj(),title:h.Yj(),note:h.Yj()});bk.extend({description:h.Yj().nullable(),trust:be.nullable(),meta:h.g1(h.Yj(),h.L5()),finding:bq.nullable(),tools:h.YO(bp).optional()}).meta({id:"AssetDetail"}),h.Ik({items:h.YO(bl)}).meta({id:"ListProjectsResponse"}),h.Ik({attention:h.ai().int().nonnegative(),byType:h.Ik({project:h.ai().int().nonnegative(),skill:h.ai().int().nonnegative(),mcp:h.ai().int().nonnegative(),hook:h.ai().int().nonnegative(),config:h.ai().int().nonnegative()}),harnesses:h.ai().int().nonnegative(),mcpTrust:h.Ik({"known-good":h.ai().int().nonnegative(),risky:h.ai().int().nonnegative(),unapproved:h.ai().int().nonnegative()})}).meta({id:"InventoryStats"});let br=h.Ik({path:h.Yj(),name:h.Yj(),origin:bd,access:bc,isCustom:h.zM(),findings:h.ai().int().nonnegative(),blockedAt:ab.w$().nullable().optional(),note:h.Yj().nullable().optional()}).meta({id:"FileSummary"}),bs=h.Ik({name:h.Yj(),path:h.Yj(),accessCounts:bj}).meta({id:"FolderSummary"});h.Ik({project:h.Ik({id:h.Yj(),repo:h.Yj(),visibility:bg}),path:h.Yj(),folders:h.YO(bs).optional(),files:h.YO(br)}).meta({id:"ProjectTreeResponse"}),br.extend({project:h.Ik({repo:h.Yj(),visibility:bg,language:h.Yj(),policyDefault:bc,updatedAt:ab.w$()}),findingsRefs:h.YO(h.Ik({id:h.Yj(),title:h.Yj()}))}).meta({id:"FileDetail"}),h.Ik({path:h.Yj(),access:bc}).meta({id:"SetFileAccessBody"}),h.Ik({file:br,accessCounts:bj}).meta({id:"SetFileAccessResponse"}),h.Ik({trust:be}).meta({id:"SetMcpTrustBody"});let bt=h.Ik({kind:bh,title:h.Yj(),detail:h.Yj(),occurredAt:ab.w$(),findingId:h.Yj().nullable().optional()}).meta({id:"HarnessEventItem"});h.Ik({counts:h.Ik({block:h.ai().int().nonnegative(),redact:h.ai().int().nonnegative(),warn:h.ai().int().nonnegative()}),items:h.YO(bt)}).meta({id:"HarnessEventsResponse"}),h.Ik({jobId:h.Yj(),startedAt:ab.w$()}).meta({id:"RescanResponse"}),h.Ik({repo:h.Yj()}).meta({id:"ConnectProjectBody"}),h.Ik({type:h.YO(bb).optional(),q:h.Yj().optional()}),h.Ik({path:h.Yj().optional(),q:h.Yj().optional(),filter:h.k5(["blocked"]).optional()}),h.Ik({path:h.Yj()}),h.Ik({limit:ac.ai().int().min(1).max(50).default(7)});let bu=h.k5(["provider","internal","external","ip"]).meta({id:"DestinationKind"}),bv=h.k5(["https","http","sftp","grpc","smtp","ws","wss"]).meta({id:"Transport"}),bw=h.k5(["secrets","pii","customer","source","telemetry","logs","metrics","none"]).meta({id:"DataClass"}),bx=bw.options,by=h.k5(["recognized","internal","unverified","ip"]).meta({id:"ShareTrustLevel"}),bz=h.k5(["allow","block"]).meta({id:"EgressDecision"}),bA=h.k5(["allowed","blocked","review"]).meta({id:"EgressStatus"}),bB=h.k5(["raw_ip","unverified_domain","plaintext_transport"]).meta({id:"ReviewReason"}),bC=h.k5(["GET","POST","PUT","DELETE","SDK","REF"]).meta({id:"HttpMethod"}),bD=h.Ik({needsReview:h.zM(),reasons:h.YO(bB)}).meta({id:"ReviewInfo"}),bE=h.Ik({port:h.ai().int().nullable(),geo:h.Yj().nullable(),ptr:h.Yj().nullable()}).meta({id:"DestinationNetwork"}),bF=h.Ik({id:h.Yj(),method:bC,transport:bv,url:h.Yj(),template:h.zM(),dataClass:bw,lastSeen:ab.w$(),callSiteCount:h.ai().int().nonnegative()}).meta({id:"EndpointSummary"}),bG=h.Ik({id:h.Yj(),project:h.Yj(),file:h.Yj(),line:h.ai().int().nonnegative(),snippet:h.Yj(),dynamic:h.zM(),vendored:h.zM(),projectId:h.Yj().nullable()}).meta({id:"CallSite"}),bH=bF.extend({sites:h.YO(bG)}).meta({id:"EndpointWithSites"}),bI=h.Ik({id:h.Yj(),kind:bu,name:h.Yj(),host:h.Yj(),category:h.Yj(),trust:by,status:bA,isCustom:h.zM(),lastSeen:ab.w$(),endpointCount:h.ai().int().nonnegative(),callSiteCount:h.ai().int().nonnegative(),transports:h.YO(bv),dataClasses:h.YO(bw),review:bD,network:bE.nullable(),endpoints:h.YO(bF)}).meta({id:"ShareDestinationSummary"});bI.omit({endpointCount:!0,callSiteCount:!0,endpoints:!0}).extend({note:h.Yj().nullable(),endpoints:h.YO(bH)}).meta({id:"ShareDestinationDetail"});let bJ=h.Ik({id:h.Yj(),kind:bu,name:h.Yj(),host:h.Yj(),trust:by,status:bA,review:bD,topDataClass:bw,callSiteCount:h.ai().int().nonnegative(),lastSeen:ab.w$()}).meta({id:"ReviewDestination"}),bK=h.Ik({kind:bu,total:h.ai().int().nonnegative(),items:h.YO(bI)}).meta({id:"ShareDestinationGroup"});h.Ik({groups:h.YO(bK)}).meta({id:"ListShareDestinationsResponse"}),h.Ik({items:h.YO(bJ)}).meta({id:"NeedsReviewResponse"}),h.Ik({destinations:h.ai().int().nonnegative(),endpoints:h.ai().int().nonnegative(),callSites:h.ai().int().nonnegative(),needsReview:h.ai().int().nonnegative(),insecure:h.ai().int().nonnegative(),byKind:h.Ik({provider:h.ai().int().nonnegative(),internal:h.ai().int().nonnegative(),external:h.ai().int().nonnegative(),ip:h.ai().int().nonnegative()}),byTrust:h.Ik({recognized:h.ai().int().nonnegative(),internal:h.ai().int().nonnegative(),unverified:h.ai().int().nonnegative(),ip:h.ai().int().nonnegative()})}).meta({id:"SharesStats"}),h.Ik({decision:bz.nullable()}).meta({id:"SetEgressDecisionBody"}),h.Ik({destination:bI}).meta({id:"SetEgressDecisionResponse"}),h.Ik({q:h.Yj().optional(),kind:h.YO(bu).optional(),groupBy:h.k5(["destination"]).default("destination"),review:h.uE().default(!1)}),h.Ik({format:h.k5(["csv","json"]).default("csv"),q:h.Yj().optional(),kind:h.YO(bu).optional()});let bL=h.k5(["npm","pypi","go","maven","rubygems","cargo","composer","nuget"]).meta({id:"EgressEcosystem"});h.Ik({id:h.Yj(),name:h.Yj(),category:h.Yj(),hostSuffixes:h.YO(h.Yj()).min(1),apiBase:h.Yj(),defaultDataClasses:h.YO(bw).min(1),sdks:h.jg(bL,h.YO(h.Yj()))}).meta({id:"ProviderRegistryEntry"});let bM=h.Ik({file:h.Yj(),line:h.ai().int().positive(),snippet:h.Yj(),dynamic:h.zM(),vendored:h.zM()}).meta({id:"EgressCallSiteHit"}),bN=h.Ik({host:h.Yj(),kind:bu,name:h.Yj(),category:h.Yj(),trust:by,network:bE.nullable(),method:bC,transport:bv,url:h.Yj(),template:h.zM(),dataClass:bw,site:bM}).meta({id:"ResolvedEgressHit"}),bO=h.gM("mode",[h.Ik({mode:h.eu("walk"),walkedPrefix:h.Yj()}),h.Ik({mode:h.eu("ledger"),scannedFiles:h.YO(h.Yj()),deletedFiles:h.YO(h.Yj())})]).meta({id:"EgressReconcile"});h.Ik({projectKey:h.Yj().min(1),project:h.Yj(),projectId:h.Yj().nullable(),reconcile:bO,hits:h.YO(bN)}).meta({id:"RecordProjectEgressInput"}),h.Ik({destinations:h.ai().int().nonnegative(),endpoints:h.ai().int().nonnegative(),callSites:h.ai().int().nonnegative(),truncated:h.zM(),droppedFiles:h.YO(h.Yj()).default([])}).meta({id:"EgressWriteSummary"});let bP="control-plane-credential.json",bQ=h.Ik({specVersion:h.eu(1),endpoint:h.Yj().min(1),apiKey:h.Yj().min(1),keyPrefix:h.Yj().min(1).max(16).optional(),mintedAt:ab.w$().optional()}),bR=h.Ik({packId:h.Yj().min(1),version:h.Yj().min(1),enabled:h.zM(),updatedAt:h.Yj().nullable()}).meta({id:"StorePosturePack"}),bS=h.Ik({total:h.ai().int().min(0),disabled:h.ai().int().min(0),byAction:h.Ik({warn:h.ai().int().min(0),redact:h.ai().int().min(0),block:h.ai().int().min(0),allow:h.ai().int().min(0),log:h.ai().int().min(0)}).strict()}).meta({id:"StorePosturePolicyCounts"}),bT=h.Ik({package:h.Yj().min(1).max(200),version:h.Yj().min(1).max(64),ossVersion:h.Yj().max(64).nullable(),policyBundleVersion:h.Yj().max(200).nullable(),policyFetchedAt:h.ai().int().min(0).max(0xe677d21fdbff).nullable()}).meta({id:"StorePosturePlugin"});h.Ik({deviceId:h.Os(),hostname:h.Yj().min(1).max(253),capturedAt:h.ai().int().min(0).max(0xe677d21fdbff),storePresent:h.zM(),schemaVersion:h.ai().int().min(0).max(0x7fffffff).nullable(),findingsTotal:h.ai().int().min(0).max(0x7fffffff),findingsFirstAt:h.ai().int().min(0).max(0xe677d21fdbff).nullable(),findingsLastAt:h.ai().int().min(0).max(0xe677d21fdbff).nullable(),packs:h.YO(bR).max(500),policyCounts:bS,plugin:bT.optional()}).meta({id:"StorePostureSnapshot"});let bU="capture/",bV=aU.extend({inspections:h.YO(aR).default([])}).refine(a=>a.inspections.every(a=>!a.ruleVersion.startsWith(bU)),{message:`inspections[].ruleVersion must not start with \`${bU}\` — that namespace is reserved for capture definitions the control plane mints itself`,path:["inspections"]}).meta({id:"RecordAuditEventRequest"}),bW=h.Ik({events:h.YO(bV).min(1).max(50)}).meta({id:"RecordAuditEventBatch"}),bX=h.Ik({host:h.Yj(),kind:bu,name:h.Yj(),category:h.Yj(),trust:by,network:bE.nullable(),method:bC,transport:bv,url:h.Yj(),template:h.zM(),dataClass:bw,site:h.Ik({file:h.Yj(),line:h.ai().int().positive(),dynamic:h.zM(),vendored:h.zM()})}).meta({id:"EgressIngestHit"}),bY=h.Ik({projectKey:h.Yj().regex(/^[0-9a-f]{64}$/,"projectKey must be a 64-character lowercase hex digest"),project:h.Yj(),reconcile:bO,hits:h.YO(bX)}).meta({id:"EgressIngestRequest"}),bZ=h.Ik({accepted:h.ai().int().nonnegative(),duplicates:h.ai().int().nonnegative()}),b$=h.Ik({accepted:h.ai().int().nonnegative()}),b_=/^[^\p{Cc}\p{Cf}]*$/u,b0=a=>h.Yj().max(a).regex(b_,"must not contain control characters"),b1=h.Ik({tenantName:b0(200),userEmail:b0(320),role:b0(64),keyKind:b0(64),serverTime:b0(64)});h.Ik({error:h.Ik({code:h.Yj().optional(),message:h.Yj().optional()}).optional()}),h.k5(["unauthorized","forbidden","route-absent","invalid-request","rejected","unreachable"]),h.Ik({deviceId:b0(128).min(1),hostname:b0(255).min(1),os:b0(64).min(1),cliVersion:b0(64).min(1),label:b0(200).optional()}).meta({id:"AttachDeviceRequest"}),h.Ik({deviceCode:b0(128).min(1)}).meta({id:"AttachTokenRequest"}),h.Ik({deviceCode:b0(128),userCode:b0(32),verificationUri:b0(512),verificationUriComplete:b0(512).optional(),expiresIn:h.ai().int().positive(),interval:h.ai().int().positive()});let b2=h.Ik({status:h.eu("pending")}),b3=h.Ik({status:h.eu("slow_down"),interval:h.ai().int().positive()}),b4=h.Ik({status:h.eu("denied"),message:b0(500).optional()}),b5=h.Ik({status:h.eu("expired")}),b6=h.Ik({status:h.eu("issued"),apiKey:h.Yj().min(1).max(512),endpoint:b0(512),tenantName:b0(200).optional(),userEmail:b0(320).optional()});h.KC([b6,b2,b3,b4,b5,h.Ik({status:b0(64)})]);let b7=h.k5(["shares_rescan"]),b8=h.Ik({id:b0(128).min(1),kind:b7,issuedAt:b0(64).min(1),expiresAt:b0(64).min(1)}).strict(),b9=h.Ik({command:b8.nullable()}),ca=h.k5(["scan_failed","no_projects","expired"]),cb=h.gM("outcome",[h.Ik({outcome:h.eu("reported"),projectsScanned:h.ai().int().nonnegative()}).strict(),h.Ik({outcome:h.eu("failed"),reason:ca,projectsScanned:h.ai().int().nonnegative()}).strict()]),cc=h.Yj().regex(/^[a-z][a-z0-9-]*$/),cd=h.Yj().regex(/^[a-z][a-z0-9-]*$/),ce=h.Yj().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/),cf=h.k5(["labs","user","org"]),cg=h.k5(["keyword","regex"]).meta({id:"MatcherType"});h.k5(["safe","quarantined"]).meta({id:"RuleProbeVerdict"});let ch=h.re({type:h.eu("keyword"),keywords:h.YO(h.Yj().min(1)).min(1),caseSensitive:h.zM().default(!1)});function ci(a){return a.replace(/[gy]/g,"")}let cj=h.re({type:h.eu("regex"),pattern:h.Yj().min(1).max(2e3),flags:h.Yj().default("gi"),captureGroup:h.ai().int().nonnegative().optional()}).refine(a=>(function(a,b){try{return new RegExp(a,b),!0}catch{return!1}})(a.pattern,a.flags),{message:"pattern/flags do not form a valid JavaScript regular expression",path:["pattern"]}).refine(a=>!function(a){return void 0===a||0===a}(a.captureGroup)||!function(a,b){try{let c=new RegExp(a,ci(b));return c.exec("")?.[0].length===0}catch{return!1}}(a.pattern,a.flags),{message:'a whole-match regex that can match the empty string (e.g. "\\d*", "a?", "(?:)") can hang the matcher — scope the quantifier to a captureGroup, or require at least one character',path:["pattern"]}).superRefine((a,b)=>{if(void 0===a.captureGroup)return;let c=function(a,b){try{let c=RegExp(`${a}|`,ci(b)).exec("");return c?c.length-1:void 0}catch{return}}(a.pattern,a.flags);void 0===c||a.captureGroup<=c||b.addIssue({code:"custom",path:["captureGroup"],message:`captureGroup ${String(a.captureGroup)} is out of range — the pattern declares ${String(c)} capture group(s), so valid values are 0-${String(c)}. An out-of-range group never matches, which would make the rule silently never fire.`})}),ck=h.gM("type",[ch,cj]).meta({id:"Matcher"});cg.options;let cl=h.re({extensions:h.YO(h.Yj().regex(/^\.[A-Za-z0-9]+$/)).min(1)}).meta({id:"AppliesTo"}),cm=h.k5(["entropy","luhn"]).meta({id:"PostValidatorName"}),cn=h.KC([cm,h.re({name:cm,config:h.g1(h.Yj(),h.L5()).optional()})],{error:()=>`not a valid post-validator: use a bare name (${cm.options.map(a=>JSON.stringify(a)).join(" or ")}) or { "name": ..., "config": { ... } }. An unrecognized name would be a false-positive guard that never runs.`}).meta({id:"PostValidatorRef"}),co=h.re({categories:h.YO(ai).min(1).optional(),ruleIds:h.YO(h.Yj().min(1)).min(1).optional(),labels:h.YO(h.Yj().min(1)).min(1).optional(),windowChars:h.ai().int().positive().default(160),confidenceBoost:h.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"});h.re({label:h.Yj(),text:h.Yj().max(5e4),shouldMatch:h.zM(),filePath:h.Yj().optional(),expectedSpans:h.YO(h.re({start:h.ai(),end:h.ai()})).optional()}).meta({id:"RuleFixture"});let cp=h.re({specVersion:h.eu(1),id:h.Yj().regex(/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/),name:h.Yj(),category:ai,severity:aj,matcher:ck,appliesTo:cl.optional(),postValidators:h.YO(cn).optional(),requiresNearby:co.optional(),examples:h.YO(h.Yj()).optional()}).meta({id:"Rule"}),cq=h.Ik({name:h.Yj(),email:h.Rp().optional(),url:h.OZ().optional()}).meta({id:"Author"});h.Ik({specVersion:h.eu(1),id:h.Yj(),name:h.Yj(),version:h.Yj(),rules:h.YO(h.Yj()),description:h.Yj().optional(),author:cq.optional(),license:h.Yj().optional(),sourceUrl:h.OZ().optional()}).meta({id:"PackManifest"});let cr=h.k5(["library","custom"]).meta({id:"OriginEnum"}),cs=h.k5(["all","library","custom","customized","updates"]),ct=h.k5(["new","imported","update"]).meta({id:"LibraryStateEnum"}),cu=h.Ik({all:h.ai().int().nonnegative(),library:h.ai().int().nonnegative(),custom:h.ai().int().nonnegative(),customized:h.ai().int().nonnegative(),updates:h.ai().int().nonnegative()}).meta({id:"DetectionCounts"}),cv=h.Ik({id:h.Yj(),name:h.Yj(),version:ce,enabled:h.zM(),origin:cr,publisher:cc.optional(),publisherKind:cf.optional(),ruleCount:h.ai().int().nonnegative(),namespace:cc,packId:cd,policyId:h.Yj().optional(),latestVersion:ce.optional()}).meta({id:"DetectionListItem"});h.Ik({counts:cu,items:h.YO(cv)}).meta({id:"ListDetectionsResponse"}),h.Ik({filter:cs.optional().default("all"),q:h.Yj().optional()}),h.Ik({detections:h.ai().int().nonnegative(),rules:h.ai().int().nonnegative(),active:h.ai().int().nonnegative(),findingsLast30d:h.ai().int().nonnegative()}).meta({id:"DetectionStats"});let cw=h.Ik({id:h.Yj(),name:h.Yj(),category:ai,severity:aj,matcher:ck,appliesTo:cl.optional(),postValidators:h.YO(cn).optional(),requiresNearby:co.optional(),examples:h.YO(h.Yj()).optional()}).meta({id:"DetectionRule"}),cx=h.Ik({available:h.zM(),latestVersion:ce,latestRuleCount:h.ai().int().nonnegative().optional()}).nullable().meta({id:"DetectionUpdate"});h.Ik({id:h.Yj(),name:h.Yj(),version:ce,enabled:h.zM(),origin:cr,publisher:cc.optional(),publisherKind:cf.optional(),ruleCount:h.ai().int().nonnegative(),namespace:cc,packId:cd,description:h.Yj().optional(),editedAt:ab.w$(),findingsLast30d:h.ai().int().nonnegative(),latestVersion:ce.nullable().optional(),update:cx,rules:h.YO(cw),modified:h.zM(),policyId:h.Yj().optional()}).meta({id:"DetectionDetail"});let cy=h.Ik({id:h.Yj(),name:h.Yj(),publisher:cc,publisherKind:cf.optional(),category:ai.optional(),version:ce,ruleCount:h.ai().int().nonnegative(),description:h.Yj().optional(),updatedAt:ab.w$(),state:ct,importedAs:h.Yj().nullable()}).meta({id:"LibraryItem"});function cz(a,b,c){return void 0!==c&&b.success&&void 0!==b.data?{[a]:b.data}:{}}h.Ik({categories:h.YO(ai),items:h.YO(cy)}).meta({id:"ListLibraryResponse"}),h.Ik({libraryId:h.Yj().refine(a=>/^[^/]+\/[^/]+$/.test(a),{message:"libraryId must be in namespace/packId format"})}).meta({id:"ImportDetectionRequest"});let cA={library:!0,custom:!0};function cB(a){return null!=a&&Object.hasOwn(cA,a)?a:"library"}function cC(a){return{id:`${a.namespace}/${a.packId}`,name:a.name,version:a.version,enabled:a.enabled,origin:cB(a.origin),namespace:a.namespace,packId:a.packId,ruleCount:a.ruleCount,...null!=a.policyId?{policyId:a.policyId}:{},...null!=a.latestVersion?{latestVersion:a.latestVersion}:{}}}function cD(a,b,c){let d=a.rules.flatMap(a=>{var b;let c=ck.safeParse(a.matcher);return c.success?[{id:a.id,name:a.name,category:a.category,severity:a.severity,matcher:c.data,...cz("appliesTo",cl.safeParse(a.appliesTo),a.appliesTo),...cz("postValidators",cn.array().safeParse(a.postValidators),a.postValidators),...cz("requiresNearby",co.safeParse(a.requiresNearby),a.requiresNearby),...cz("examples",{success:Array.isArray(b=a.examples)&&b.every(a=>"string"==typeof a),data:a.examples},a.examples)}]:[]});return{id:`${a.namespace}/${a.packId}`,name:a.name,version:a.version,enabled:a.enabled,origin:cB(a.origin),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 cE(a){let b=a.indexOf("/");return b<1||b===a.length-1?null:{namespace:a.slice(0,b),packId:a.slice(b+1)}}function cF(a,b){let c=a.filter(a=>null!=a.latestVersion),d=a=>cB(a.origin),e={all:a.length,library:a.filter(a=>"library"===d(a)).length,custom:a.filter(a=>"custom"===d(a)).length,customized:0,updates:c.length},f=b.filter,g="customized"===f?[]:"custom"===f?a.filter(a=>"custom"===d(a)):"library"===f?a.filter(a=>"library"===d(a)):"updates"===f?[...c]:[...a];if(b.q){let a=b.q.toLowerCase();g=g.filter(b=>b.name.toLowerCase().includes(a)||b.packId.toLowerCase().includes(a)||b.namespace.toLowerCase().includes(a))}return g.sort((a,b)=>a.enabled!==b.enabled?a.enabled?-1:1:a.name.localeCompare(b.name)),{counts:e,items:g.map(cC)}}let cG=h.k5(["prompt","response","code_change","tool_use"]).meta({id:"EventKind"}),cH=cG.options.map(a=>`'${a}'`).join(","),cI=h.Ik({sessionId:h.Yj().optional(),repo:h.Yj().optional(),filePath:h.Yj().optional(),toolName:h.Yj().optional(),gitignored:h.zM().optional(),wholeFile:h.zM().optional(),model:h.Yj().optional(),turnIndex:h.ai().int().nonnegative().optional(),correlationId:h.uR().optional(),traceId:h.Yj().regex(/^[0-9a-f]{32}$/).optional(),exceptionIds:h.YO(h.Os()).optional(),messageId:h.Yj().optional(),conversationId:h.Yj().optional(),inspectionMs:h.ai().int().nonnegative().optional(),redactDegradedTo:ak.optional()}).meta({id:"EventMetadata"}),cJ=h.Ik({id:h.Os(),sourceTool:ag,kind:cG,occurredAt:ab.w$(),contentHash:h.Yj(),content:h.Yj(),metadata:cI.optional()}).meta({id:"Event"}).meta({id:"IngestEvent"});h.Ik({events:h.YO(cJ).min(1).max(100),dedupe:h.eu("content-hash").optional()}).meta({id:"IngestBatch"});let cK=h.k5(["once","temporary","permanent"]),cL=h.Ik({repo:h.Yj().optional(),sourceTool:h.Yj().optional(),provider:h.Yj().optional()}).strict(),cM=h.k5(["suppress","reveal_to_model"]),cN=h.Ik({id:h.Os(),ruleId:h.Yj(),category:ai,valueFingerprint:h.Yj().regex(/^[0-9a-f]{64}$/),keyVersion:h.ai().int().positive(),maskedValue:h.Yj(),capability:cM.default("suppress"),scope:cK,expiresAt:ab.w$().nullable(),maxUses:h.ai().int().positive().nullable(),useCount:h.ai().int().nonnegative(),lastUsedAt:ab.w$().nullable(),justification:h.Yj().min(1),conditions:cL.nullable(),createdBy:h.Yj(),createdVia:h.k5(["cli-approve","cli-add","web-approve","web-add","api","setup-triage"]),createdAt:ab.w$(),updatedAt:ab.w$(),revokedAt:ab.w$().nullable(),revokedBy:h.Yj().nullable(),revokeReason:h.Yj().nullable()}),cO=cN.pick({id:!0,ruleId:!0,valueFingerprint:!0,keyVersion:!0,capability:!0,expiresAt:!0,maxUses:!0,useCount:!0,conditions:!0});function cP(a,b){return"present"===b.status&&b.version===a}cN.omit({valueFingerprint:!0});let cQ=h.Yj().optional(),cR=h.Ik({reference:h.Yj(),scope:h.Yj(),reason:h.Yj(),confirmation:cQ}),cS=h.Ik({ruleId:h.Yj(),value:h.Yj(),scope:h.Yj(),reason:h.Yj(),confirmation:cQ}),cT=h.Ik({pointer:h.Yj(),scope:h.Yj(),justification:h.Yj(),confirmation:cQ}),cU=h.Ik({id:h.Yj(),reason:h.Yj()}),cV=h.Ik({confirmation:h.Yj()});function cW(a,b){let c=a.safeParse(b);if(c.success)return{ok:!0,data:c.data};for(let a of c.error.issues){let[b]=a.path;if("string"==typeof b)return{ok:!1,field:b,wrongType:"invalid_type"===a.code}}return{ok:!1,field:null,wrongType:!1}}let cX=ar.options;function cY(a){if("code_change"===a.kind)return{state:"local_scan"};if(null!==a.syncedAt&&a.syncedAt>0)return{state:"sent",at:W(a.syncedAt)};if(null!==a.syncedAt){var b;let c=null!==(b=a.syncFailure)&&cX.includes(b)?b:void 0;return{state:"not_sent",...null===a.syncFailedAt?{}:{at:W(a.syncFailedAt)},...void 0===c?{}:{reason:c}}}return 1===a.outboxOwed||null!==a.syncClaimedAt?{state:"queued"}:{state:"never_offered"}}function cZ(a,b){return Object.hasOwn(a,b)?a[b]:void 0}function c$(a){return cZ({log:"monitored",block:"blocked",redact:"redacted",warn:"warned",allow:"allowed"},a)??"allowed"}function c_(a){if("code_context"===a)return"source_code";let b=ap.safeParse(a);return b.success?b.data:"custom"}function c0(a){return cZ(ah,a)??ad.Api}let c1=["open","handled","dismissed","resolved"];function c2(a){let b=new Set(a.filter(a=>void 0!==a));if(0!==b.size){for(let a of c1)if(b.has(a))return a}}function c3(a){return"code_change"!==a.kind?"handled":null===a.findingKey?"open":"resolved"===a.latestResolutionStatus?"resolved":"dismissed"===a.latestResolutionStatus?"dismissed":"open"}function c4(a,b={}){let c=b.packNames,d=[];for(let[b,e]of a){let a=[...e.users??[]].sort((a,b)=>a.name.localeCompare(b.name)||a.id.localeCompare(b.id)),f=[...new Set(e.sourceTools.map(c0))].sort(),g=new Set(e.actionsTaken.map(c$)),h=1===g.size?[...g][0]??null:null,i=c_(e.category??"custom"),j={id:b,category:i,subtype:b,severity:e.severity??"low",detection:{id:b,name:c?.get(b)??null},policy:{id:`category:${i}`,name:i},instanceCount:e.instanceCount,providers:f,aggregateAction:h,latestDetectedAt:e.latestDetectedAt,status:c2(e.statusInputs.map(c3)),...a.length>0?{users:a}:{}};c7.set(j,[...g]),void 0!==e.searchText&&c5.set(j,c6(j,e.searchText)),d.push(j)}return d}let c5=new WeakMap;function c6(a,b){return[a.subtype,a.category,a.policy.name,a.id,...(a.users??[]).map(a=>a.name),...void 0===b?[]:[b]].join(" ").toLowerCase()}let c7=new WeakMap;function c8(a){return c7.get(a)??[]}function c9(a,b){let c=new Set(b),d=0;for(let b of a){if(void 0===b.count)return null;c.has(c3(b))&&(d+=b.count)}return d}function da(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=>c8(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=c5.get(a);if(void 0!==b)return b;let c=c6(a);return c5.set(a,c),c})(b).includes(a))}return c}let db=Object.fromEntries(aj.options.map((a,b)=>[a,b]));function dc(a,b){let c=(cZ(db,a.severity)??-1)-(cZ(db,b.severity)??-1);if(0!==c)return c;let d=b.latestDetectedAt.localeCompare(a.latestDetectedAt);return 0!==d?d:a.id.localeCompare(b.id)}function dd(a){return[...a].sort(dc)}function de(a,b){let c=da(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=da(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=da(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 c8(a))h.set(b,(h.get(b)??0)+1);let i=da(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=da(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)}}function df(a,b){let c=a[Symbol.iterator](),d=b[Symbol.iterator]();for(;;){let a=c.next(),b=d.next();if(a.done&&b.done)return 0;if(a.done)return -1;if(b.done)return 1;let e=a.value.codePointAt(0)??0,f=b.value.codePointAt(0)??0;if(e!==f)return e-f}}let dg=["severity","subtype","providers","actions","statuses","deliveries","tools","repo","file","q"];function dh(a,b,c){for(let d of dg)if(d!==c&&!function(a,b,c){switch(c){case"severity":return!b.severity?.length||b.severity.includes(a.severity);case"subtype":return!b.subtype?.length||b.subtype.includes(a.ruleId);case"providers":return!b.providers?.length||b.providers.includes(c0(a.sourceTool));case"actions":return!b.actions?.length||b.actions.includes(c$(a.actionTaken));case"statuses":return!b.statuses?.length||void 0!==a.status&&b.statuses.includes(a.status);case"deliveries":return!b.deliveries?.length||void 0!==a.delivery&&b.deliveries.includes(a.delivery.state);case"tools":return!b.tools?.length||void 0!==a.toolName&&b.tools.includes(a.toolName);case"repo":return void 0===b.repo||a.repo===b.repo;case"file":return void 0===b.file||a.file===b.file;case"q":return!b.q||[a.ruleId,a.category,a.maskedMatch,a.repo,a.file,a.toolName?`via ${a.toolName}`:"",a.id,a.user?.name??""].join(" ").toLowerCase().includes(b.q.toLowerCase())}}(a,b,d))return!1;return!0}function di(a){return[...a.entries()].map(([a,b])=>({value:a,count:b})).sort((a,b)=>b.count-a.count||a.value.localeCompare(b.value)||df(a.value,b.value))}function dj(a,b,c=1){a.set(b,(a.get(b)??0)+c)}function dk(a){let b=new Map,c=new Map,d=new Map,e=new Map,f=new Map,g=new Map,h=new Map;return{add(i){dh(i,a,"severity")&&dj(b,i.severity),dh(i,a,"subtype")&&dj(c,i.ruleId),dh(i,a,"providers")&&dj(d,c0(i.sourceTool)),dh(i,a,"actions")&&dj(e,c$(i.actionTaken)),void 0!==i.status&&dh(i,a,"statuses")&&dj(f,i.status),void 0!==i.toolName&&dh(i,a,"tools")&&dj(g,i.toolName),void 0!==i.delivery&&dh(i,a,"deliveries")&&dj(h,i.delivery.state)},facets:()=>({severity:di(b),subtype:di(c),provider:di(d),action:di(e),status:di(f),tool:di(g),deployment:di(h)})}}function dl(a){let b=c_(a.category);return{id:a.id,provider:c0(a.sourceTool),repo:a.repo,file:a.file,...void 0===a.toolName?{}:{toolName:a.toolName},eventId:a.eventId,...void 0===a.sessionId?{}:{sessionId:a.sessionId},...void 0===a.delivery?{}:{delivery:a.delivery},...void 0===a.user?{}:{user:a.user},action:c$(a.actionTaken),detectedAt:a.occurredAt,confidence:a.confidence,...void 0===a.status?{}:{status:a.status},groupId:a.ruleId,category:b,subtype:a.ruleId,severity:a.severity,match:{maskedValue:a.maskedMatch,contextPrefix:""},detection:{id:a.ruleId,name:null},policy:{id:`category:${b}`,name:b}}}function dm(){return{instanceCount:0,maxSeverityRank:Number.MAX_SAFE_INTEGER,maxSeverity:"low",latestDetectedAt:"",statuses:[],ruleIds:new Set}}function dn(a,b){a.instanceCount+=1;let c=cZ(db,b.severity)??Number.MAX_SAFE_INTEGER-1;c<a.maxSeverityRank&&(a.maxSeverityRank=c,a.maxSeverity=b.severity),b.occurredAt>a.latestDetectedAt&&(a.latestDetectedAt=b.occurredAt),a.statuses.push(b.status),a.ruleIds.add(b.ruleId)}function dp(a,b){let c=cZ(db,a.maxSeverity)??-1,d=cZ(db,b.maxSeverity)??-1;if(c!==d)return c-d;if(a.latestDetectedAt!==b.latestDetectedAt)return a.latestDetectedAt<b.latestDetectedAt?1:-1;let e=df(a.repo,b.repo);return 0!==e?e:df(a.file,b.file)}function dq(a,b){return`${dr(a)}/${dr(b)}`}function dr(a){return encodeURIComponent(a.replace(/[\uD800-\uDFFF]/gu,"�"))}let ds=h.Ik({id:h.Os(),namespace:cc,packId:cd,version:ce,name:h.Yj(),enabled:h.zM().default(!0),policyId:h.Yj().optional()}).meta({id:"InstalledPack"});h.Ik({namespace:cc,packId:cd,version:ce}).meta({id:"InstallPackRequest"}),h.Ik({items:h.YO(ds)}).meta({id:"ListInstalledPacksResponse"}),h.Ik({enabled:h.zM().optional(),policyId:h.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 dt=h.k5(["global","repo","user"]).meta({id:"PolicyScope"}),du=h.KC([h.Ik({ruleId:h.Yj()}),h.Ik({category:ai})]).meta({id:"PolicyTarget"}),dv=h.k5(["builtin","custom"]).meta({id:"PolicyKind"}),dw=h.k5(["builtin","authored"]).meta({id:"PolicyProvenance"}),dx=h.Ik({id:h.Os(),scope:dt,target:du,action:ak,enabled:h.zM().default(!0),customKeywords:h.YO(h.Yj()).optional(),name:h.Yj().optional(),provenance:dw.optional()}).meta({id:"Policy"}),dy=["monitor","warn","redact","vault","block"],dz=h.k5(dy).meta({id:"BuiltinPolicyId"}),dA=dz.extract(["monitor","warn","block"]).meta({id:"RedactFallback"}),dB=h.Ik({version:h.Yj(),policies:h.YO(dx),rules:h.YO(cp).optional(),rulesComplete:h.zM().optional(),exceptions:h.YO(cO).optional(),reversibleRuleIds:h.YO(h.Yj()).optional(),ruleVersions:h.g1(h.Yj(),h.Yj()).optional(),prohibitedModels:h.YO(h.Yj()).optional(),redactFallback:dA.optional(),customKeywords:h.YO(h.Yj()),fetchedAt:ab.w$()}).meta({id:"PolicyBundle"});[...Object.keys(dB.shape),...Object.keys(dx.shape).map(a=>`policies.${a}`),...du.options.flatMap(a=>"shape"in a?Object.keys(a.shape):[]).map(a=>`policies.target.${a}`),...Object.keys(cO.shape).map(a=>`exceptions.${a}`)].sort().join(",");let dC=["config"],dD=ai.options.filter(a=>!dC.includes(a)),dE={secret:"critical",financial:"critical",code_flaw:"critical",pii:"high",phi:"high",custom:"high",code_context:"low",config:"low"},dF=dy,dG={monitor:{name:"Monitor",action:"log",reversible:!1,description:"Log every match for audit. The request is allowed through untouched."},warn:{name:"Warn",action:"warn",reversible:!1,description:"Allow the request, but warn the user inline before it is sent."},redact:{name:"Redact",action:"redact",reversible:!1,description:"Strip the matched value from the request and destroy it, then continue. What was removed cannot be recovered."},vault:{name:"Redact & Vault",action:"redact",reversible:!0,description:"Strip the matched value from the request and keep an encrypted, recoverable copy in the local vault, leaving a pointer in its place. Needs the vault consent granted under Settings; without it this behaves as Redact."},block:{name:"Block",action:"block",reversible:!1,description:"Refuse the request entirely whenever any rule in this detection matches."}};function dH(a){return dG[a].action}let dI=[...new Set(dy.map(dH))],dJ=[...al.filter(a=>!dI.includes(a)),...dI];function dK(a){return dJ.indexOf(a)}function dL(a,b){return dK(a)>=dK(b)}function dM(a,b){return dK(a)>=dK(b)?a:b}function dN(a){return dy.find(b=>dL(dH(b),a))??"block"}h.Ik({floor:dz,locked:h.zM()}).describe("PackPolicyFloor");let dO=dy.filter(a=>!dG[a].reversible);dy.filter(a=>dG[a].reversible);let dP=h.k5(dO).meta({id:"CategoryPolicyId"});function dQ(a){let b=dz.safeParse(a??dT);return dG[b.success?b.data:dT].reversible}let dR=Object.fromEntries(ai.options.map(a=>[a,dH(function(a){if(dC.includes(a))return"monitor";let b=dE[a];return"critical"===b||"high"===b?"warn":"monitor"}(a))])),dS=Object.fromEntries(dy.map(a=>[a,{id:a,...dG[a]}])),dT="monitor";function dU(a){let b=dz.safeParse(a??dT);return dS[b.success?b.data:dT].action}let dV=h.Ik({id:h.Yj(),name:h.Yj(),ruleCount:h.ai().int().nonnegative(),enabled:h.zM()}).meta({id:"UsedByItem"}),dW=h.Ik({id:h.Yj(),kind:dv,name:h.Yj(),enabled:h.zM(),usedByCount:h.ai().int().nonnegative()}).meta({id:"PolicyListItem"});h.Ik({items:h.YO(dW)}).meta({id:"ListPoliciesResponse"}),h.Ik({specVersion:h.eu(1),id:h.Yj(),kind:dv,name:h.Yj(),enabled:h.zM(),description:h.Yj(),usedBy:h.YO(dV)}).meta({id:"PolicyDetail"}),h.Ik({policies:h.ai().int().nonnegative(),builtin:h.ai().int().nonnegative(),custom:h.ai().int().nonnegative(),detectionsGoverned:h.ai().int().nonnegative()}).meta({id:"PolicyStatsResponse"});let dX=2,dY=ai.options.join("|"),dZ=RegExp(`\\[\\[aka:(?:${dY}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`),d$=RegExp(`^${dZ.source}$`);function d_(){return RegExp(dZ.source,"g")}let d0=h.Yj().regex(d$);h.Ik({category:ai,keyVersion:h.ai().int().positive(),pointerId:h.Yj(),tag:h.Yj()}),h.Ik({pointerId:h.Yj(),valueFingerprint:h.Yj().regex(/^[0-9a-f]{64}$/),fingerprintKeyVersion:h.ai().int().positive(),keyVersion:h.ai().int().positive(),category:ai,ruleId:h.Yj(),maskedMatch:h.Yj(),provider:h.Yj().optional(),ciphertext:h.Yj(),nonce:h.Yj(),authTag:h.Yj(),occurrenceCount:h.ai().int().nonnegative(),userAuthorized:h.zM(),firstSeen:h.Yj(),lastSeen:h.Yj()}),h.Ik({category:ai,provider:h.Yj().optional(),maskedMatch:h.Yj(),occurrences:h.ai().int().nonnegative(),firstSeen:h.Yj(),lastSeen:h.Yj()}),h.Ik({ruleId:h.Yj(),valueFingerprint:h.Yj().regex(/^[0-9a-f]{64}$/),fingerprintKeyVersion:h.ai().int().positive()});let d1=h.k5(["human","model"]),d2=h.k5(["display","explicit-reveal","view-render","model-input","remediation","purge"]),d3=h.k5(["revealed","refused","unavailable"]),d4=["display","view-render"];function d5(a){return d4.includes(a)}let d6=h.Ik({id:h.Os(),pointerId:h.Yj(),at:h.Yj(),target:d1,reason:d2,outcome:d3,grantId:h.Yj().optional(),pointerCount:h.ai().int().positive().default(1)}),d7=h.k5(["prompt","tool-input","tool-output","file","transcript"]),d8=h.Ik({location:h.Yj(),kind:d7,firstSeen:h.Yj(),lastSeen:h.Yj()}),d9=h.Ik({pointerId:h.Yj(),category:ai,provider:h.Yj().optional(),maskedMatch:h.Yj(),occurrences:h.ai().int().nonnegative(),firstSeen:h.Yj(),lastSeen:h.Yj(),revealGrantId:h.Yj().nullable(),sightings:h.YO(d8)}),ea=50,eb=50,ec=200,ed=h.Ik({limit:ac.ai().int().min(1).max(ec).optional(),cursor:h.Yj().optional()});h.Ik({totals:h.Ik({values:h.ai().int().nonnegative()}),items:h.YO(d9),nextCursor:h.Yj().nullable()});let ee=h.Ik({limit:ac.ai().int().min(1).max(ec).optional(),cursor:h.Yj().optional()});h.Ik({totals:h.Ik({reused:h.ai().int().nonnegative()}),items:h.YO(d9),nextCursor:h.Yj().nullable()});let ef=h.Ik({includeBatched:h.zM().optional(),limit:ac.ai().int().min(1).max(ec).optional(),cursor:h.Yj().optional()});h.Ik({items:h.YO(d6),nextCursor:h.Yj().nullable(),hiddenBatched:h.ai().int().nonnegative()});let eg=h.Yj(),eh=h.k5(["masked","full","off"]),ei=1,ej=h.Ik({acknowledgedAt:ab.w$(),version:h.ai().int().positive()});function ek(a){return a?.version===ei}let el=1,em=3,en=h.k5(["standalone","attached"]),eo=h.Ik({endpoint:h.Yj().min(1),label:h.Yj().min(1).optional(),attachedAt:ab.w$()}).meta({id:"ControlPlaneConnection"}),ep=h.k5(["redact","warn"]),eq=h.k5(["full","session-only"]),er=h.Ik({acknowledgedAt:ab.w$(),payloadVersion:h.ai().int().positive()});function es(a){return a?.payloadVersion===el}let et=h.Ik({acknowledgedAt:ab.w$(),payloadVersion:h.ai().int().positive(),endpoint:h.Yj()});function eu(a,b){return void 0!==a&&void 0!==b&&a.payloadVersion===em&&a.endpoint===b}let ev=h.Ik({enabled:h.zM().default(!1),retainDays:h.ai().int().min(1).max(3650).default(30)}).meta({id:"BodyRetention"}),ew=h.Ik({specVersion:h.ai().int().positive().default(8),runMode:en.default("standalone"),controlPlane:eo.optional(),policy:ep.default("redact"),historicalAccess:eq.default("session-only"),dataSharesInPlace:h.zM().default(!0),vaultConsent:ej.optional(),vaultKeyCustody:eg.default("file"),vaultInlineReveal:eh.default("masked"),redactFallback:dA.default("warn"),onboardedAt:ab.w$().optional(),modelJudgeConsent:er.optional(),historySyncConsent:et.optional(),bodyRetention:ev.default({enabled:!1,retainDays:30})});function ex(){return ew.parse({})}function ey(a){return"attached"===a.runMode&&void 0!==a.controlPlane}function ez(a){return a.label??a.endpoint}function eA(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 eB(a,b,c){return{id:b,url:a.url,name:a.name??null,attributes:JSON.stringify(a.attributes),firstSeen:c,lastSeen:c}}function eC(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:V(a.startedAt),endedAt:a.endedAt?V(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 eD(a,b){return{id:b,class:a.class,label:a.label??null,attributes:a.attributes?JSON.stringify(a.attributes):null}}function eE(a,b){return{id:b,ruleId:a.ruleId,name:a.name,category:a.category,severity:a.severity,definition:a.definition,version:a.version}}function eF(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?V(a.firstDetectedAt):null}}function eG(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?.inspectionMs!==void 0?{inspection_ms:b.inspectionMs}:{},...b?.redactDegradedTo!==void 0?{redact_degraded_to:b.redactDegradedTo}:{},...b?.model!==void 0?{model:b.model}:{},...b?.turnIndex!==void 0?{turn_index:b.turnIndex}:{},...b?.messageId!==void 0?{message_id:b.messageId}:{},...b?.conversationId!==void 0?{conversation_id:b.conversationId}:{}}}function eH(a){return`capture/${a.category}/${a.severity}`}function eI(a){return{ruleId:a.ruleId,version:eH(a),name:a.ruleId,category:a.category,severity:a.severity,definition:JSON.stringify({ruleId:a.ruleId})}}var eJ=c(10539);let eK="managed-settings.json",eL=h.k5(["runMode","historicalAccess","vaultConsent","vaultKeyCustody","vaultInlineReveal","modelJudgeConsent","dataSharesInPlace","redactFallback","bodyRetention"]).meta({id:"ManagedSettingKey"}),eM=h.Ik({runMode:h.k5(["standalone","attached"]).optional(),controlPlane:h.Ik({endpoint:h.Yj().min(1),label:h.Yj().min(1).optional()}).optional(),historicalAccess:h.k5(["full","session-only"]).optional(),vaultConsent:h.zM().optional(),vaultKeyCustody:h.k5(["file","keychain"]).optional(),vaultInlineReveal:h.k5(["masked","full","off"]).optional(),modelJudgeConsent:h.zM().optional(),dataSharesInPlace:h.zM().optional(),redactFallback:dA.optional(),bodyRetention:ev.optional()}).meta({id:"ManagedSettingsValues"}),eN=h.Ik({specVersion:h.ai().int().positive().default(1),organization:h.Yj().min(1).optional(),values:h.g1(h.Yj(),h.L5()).default({}),lockedFields:h.YO(h.Yj()).default([])}).transform(({lockedFields:a,values:b,...c},d)=>{let e=[],f=[];for(let b of a)eL.safeParse(b).success?e.push(b):f.push(b);let g=Object.create(null),h=[];for(let[a,c]of Object.entries(b))Object.hasOwn(eM.shape,a)?g[a]=c:h.push(a);let i=eM.safeParse(g);if(!i.success){for(let a of i.error.issues)d.addIssue({...a,path:["values",...a.path]});return eJ.tm}return{...c,values:i.data,lockedFields:e,...f.length>0?{unknownLockedFields:f}:{},...h.length>0?{unknownValueFields:h}:{}}}).meta({id:"ManagedSettings"}),eO={present:!1,lockedFields:[]},eP=h.Ik({path:h.Yj().min(1),name:h.Yj().min(1),origin:bd,defaultAccess:bc});h.Ik({files:h.YO(eP),truncated:h.zM(),scannedAt:h.Yj()});let eQ=["7d","30d","3m","6m"],eR=h.k5(eQ).meta({id:"TimeRange"}),eS={"7d":7,"30d":30,"3m":90,"6m":180};eR.catch("7d");let eT=h.k5(["still-valid","unknown","invalid"]),eU=h.Ik({filePath:h.Yj(),span:am.optional()}).strict(),eV=h.Ik({provider:h.Yj(),maskedToken:h.Yj(),where:eU,state:eT,observedAt:ab.w$().optional()}).strict();h.Ik({provider:h.Yj(),maskedToken:h.Yj(),consolePath:h.Yj(),occurrenceSpread:h.ai().int().positive()}).strict();let eW=h.k5(["redact-rotation-checklist","redact-only","set-secret-redact","leave"]),eX=h.k5(["first-run","pre-push","secret-scan"]);h.Ik({entrySource:eX}).strict();let eY=h.Ik({id:eW,label:h.Yj()}),eZ=h.Ik({kind:h.eu("decision"),entrySource:eX,secretCount:h.ai().int().positive(),prompt:h.Yj(),options:h.PV([eY.extend({id:h.eu("redact-rotation-checklist")}),eY.extend({id:h.eu("redact-only")}),eY.extend({id:h.eu("set-secret-redact")}),eY.extend({id:h.eu("leave")})])}),e$=h.Ik({kind:h.eu("no-decision")});h.gM("kind",[eZ,e$]);let e_=h.Ik({severity:aj,count:h.ai().int().nonnegative(),caught:h.ai().int().nonnegative().optional(),openAtRest:h.ai().int().nonnegative().optional()}).meta({id:"SeveritySummaryItem"});h.Ik({total:h.ai().int().nonnegative(),needsRemediation:h.ai().int().nonnegative().optional(),bySeverity:h.YO(e_)}).meta({id:"SeveritySummaryResponse"}),h.Ik({range:h.k5(eQ).default("7d")});let e0=h.k5(["blocked","redacted","warned"]).meta({id:"EnforcementActionKind"}),e1=h.Ik({kind:e0,count:h.ai().int().nonnegative(),delta:h.ai().int()}).meta({id:"EnforcementAction"});h.Ik({range:eR,total:h.ai().int().nonnegative(),actions:h.YO(e1)}).meta({id:"EnforcementActionsResponse"});let e2=h.k5(["day","week"]).meta({id:"TimeseriesGranularity"}),e3=h.Ik({timestamp:ab.p6(),critical:h.ai().int().nonnegative(),high:h.ai().int().nonnegative(),medium:h.ai().int().nonnegative(),low:h.ai().int().nonnegative().optional()}).meta({id:"FindingsTimeseriesPoint"});h.Ik({range:eR,granularity:e2,points:h.YO(e3)}).meta({id:"FindingsTimeseriesResponse"});let e4=h.Ik({timestamp:ab.p6(),bySeverity:h.Ik({critical:h.ai().nonnegative().nullable(),high:h.ai().nonnegative().nullable(),medium:h.ai().nonnegative().nullable(),low:h.ai().nonnegative().nullable()})}).meta({id:"MttrTrendPoint"});h.Ik({range:eR,granularity:e2,points:h.YO(e4)}).meta({id:"MttrTrendResponse"});let e5=h.Ik({findingKey:h.Yj(),ruleId:h.Yj(),severity:aj,repo:h.Yj().optional(),path:h.Yj(),resolvedAt:ab.w$(),detectedAt:ab.w$()}).meta({id:"ResolvedFeedItem"});h.Ik({items:h.YO(e5)}).meta({id:"RecentlyResolvedResponse"});let e6=["repo","user"],e7=h.k5(e6).meta({id:"SourceKind"}),e8=h.Ik({id:h.Yj(),name:h.Yj(),kind:e7,findingsCount:h.ai().int().nonnegative()}).meta({id:"TopSource"});h.Ik({range:eR,items:h.YO(e8)}).meta({id:"TopSourcesResponse"}),h.Ik({range:h.k5(eQ).default("7d"),limit:ac.ai().int().min(1).max(50).default(5),kind:h.k5(e6).optional()});let e9=ae.extract(["ClaudeCode","Cursor","Codex","Antigravity","ClaudeAi","ChatGpt","Copilot","Api"]).meta({id:"Provider"}),fa=h.Ik({provider:e9,coverage:h.ai().int().min(0).max(100),supported:h.zM()}).meta({id:"ScanCoverageProvider"});h.Ik({range:eR,providers:h.YO(fa)}).meta({id:"ScanCoverageResponse"});let fb=h.k5(["repo","user","team","policy","share","rule"]).meta({id:"SubjectType"}),fc=h.Ik({type:fb,id:h.Yj(),label:h.Yj()}).meta({id:"RecommendationSubject"}),fd=h.k5(["apply","navigate"]).meta({id:"RecommendationActionMode"}),fe=h.Ik({mode:fd,type:h.Yj(),label:h.Yj(),href:h.Yj().optional(),policyId:h.Yj().optional(),teamId:h.Yj().optional()}).meta({id:"RecommendationAction"}),ff=h.Ik({id:h.Yj(),category:h.Yj(),severity:aj,title:h.Yj(),description:h.Yj(),subjects:h.YO(fc),action:fe}).meta({id:"RecommendedAction"});h.Ik({items:h.YO(ff)}).meta({id:"RecommendedActionsResponse"}),h.Ik({limit:ac.ai().int().min(1).max(20).default(3)});let fg=h.Ik({type:h.Yj(),policyId:h.Yj().optional(),teamId:h.Yj().optional()}).meta({id:"AppliedAction"});h.Ik({id:h.Yj(),status:h.eu("applied"),appliedAction:fg}).meta({id:"ApplyRecommendedActionResponse"}),h.Ik({id:h.Yj(),status:h.eu("dismissed")}).meta({id:"DismissRecommendedActionResponse"}),h.Ik({id:h.Yj()});let fh=h.k5(["granted","revoked","unchanged"]).meta({id:"HistorySyncConsentChoice"}),fi=h.k5(["granted","revoked","unchanged"]).meta({id:"ModelJudgeConsentChoice"}),fj=h.Ik({historicalAccess:h.Yj(),modelJudgeConsent:fi,historySyncConsent:fh,vaultConsent:h.Yj(),vaultInlineReveal:h.Yj(),redactFallback:h.Yj(),bodyRetention:h.Ik({enabled:h.zM(),retainDays:h.ai()})}),fk=h.Ik({endpoint:h.Yj(),label:b0(200).optional(),accessKey:h.Yj()});h.Ik({ruleId:h.Yj(),category:ai,severity:aj,maskedMatch:h.Yj(),rawMatch:h.Yj(),context:h.Yj(),filePath:h.Yj().optional(),confidence:h.ai().min(0).max(1),id:h.Yj().optional(),valueFingerprint:h.Yj().optional(),keyVersion:h.ai().int().nonnegative().optional()});let fl=h.Ik({category:ai,action:dP,reasoning:h.Yj(),genuineCount:h.ai().int().nonnegative(),fpCount:h.ai().int().nonnegative(),fpIds:h.YO(h.Yj())});h.Ik({perCategory:h.YO(fl),notes:h.Yj()});let fm=h.Ik({total:h.ai().int().nonnegative(),important:h.ai().int().nonnegative(),routine:h.ai().int().nonnegative()}).refine(a=>a.total===a.important+a.routine,{message:"total must equal important + routine",path:["total"]}),fn=h.Ik({ruleId:h.Yj(),category:ai,valueFingerprint:h.Yj(),keyVersion:h.ai().int().nonnegative()}),fo=h.Ik({pattern:h.Yj(),count:h.ai().int().nonnegative(),values:h.YO(fn).min(1)}),fp=h.Ik({category:ai,count:h.ai().int().nonnegative(),egress:h.zM()}),fq=h.Ik({counts:fm,routineCategories:h.YO(ai),surfacedCategories:h.YO(ai),findingKinds:h.YO(fp),posture:h.g1(ai,dz),maskedFindings:h.YO(eV).optional(),falsePositivePatterns:h.YO(fo).optional()}),fr=fl.pick({category:!0,genuineCount:!0,fpCount:!0}).extend({egress:h.zM()});h.Ik({categories:h.YO(fr),posture:h.g1(ai,dz)}),h.Ik({frame:fq,copy:h.Yj()}),h.k5(["scan","floor"]);let fs=h.Ik({id:h.k5(["enter-remediation","open-dashboard","not-now"]),label:h.Yj()}),ft=h.PV([fs.extend({id:h.eu("open-dashboard")}),fs.extend({id:h.eu("not-now")})]),fu=h.PV([fs.extend({id:h.eu("enter-remediation")}),fs.extend({id:h.eu("open-dashboard")}),fs.extend({id:h.eu("not-now")})]);h.Ik({worthALook:h.ai().int().nonnegative(),liveKeys:h.ai().int().nonnegative().optional(),options:h.KC([ft,fu])}).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 fv=new Set(["recognized","internal"]);function fw(a){return fv.has(a)?"allowed":"review"}function fx(a){return"block"===a?"blocked":"allowed"}function fy(a,b){return null===b?fw(a):fx(b)}function fz(a,b){return null!==b&&fx(b)!==fw(a)}function fA(a,b,c){let d=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:d.length>0&&!c,reasons:d}}function fB(a){return Array.from(new Set(a))}function fC(a){let b=new Set(a);return bx.filter(a=>b.has(a))}function fD(a){return fC(a)[0]??"none"}let fE={raw_ip:0,unverified_domain:1,plaintext_transport:2};function fF(a){return 0===a.length?1/0:Math.min(...a.map(a=>fE[a]))}let fG=h.k5(["site","estimated","none"]),fH=h.Ik({inputTokens:h.ai().int().nonnegative().optional(),outputTokens:h.ai().int().nonnegative().optional(),cacheReadInputTokens:h.ai().int().nonnegative().optional(),cacheCreationInputTokens:h.ai().int().nonnegative().optional()}),fI=h.Ik({toolUseId:h.Yj().min(1),toolName:h.Yj().min(1),target:h.Yj().optional(),isError:h.zM().optional(),inputSize:h.ai().int().nonnegative().optional(),outputSize:h.ai().int().nonnegative().optional()});h.Ik({messageId:h.Yj().min(1),startedAt:ab.w$(),model:h.Yj().optional(),usage:fH.optional(),usageSource:fG,stopReason:h.Yj().optional(),conversationId:h.Yj().optional(),turnIndex:h.ai().int().nonnegative().optional(),toolCalls:h.YO(fI).default([]),responseText:h.Yj().optional(),truncated:h.zM().default(!1)}),h.Ik({patched:h.zM(),live:h.zM(),blind:h.zM(),sendsSeenDom:h.ai().int().nonnegative(),exchangesSeenNet:h.ai().int().nonnegative(),parseFailures:h.ai().int().nonnegative(),unparsedBodies:h.ai().int().nonnegative(),shapeMisses:h.YO(h.Yj()).default([])})}};