@akasecurity/cli 0.9.12 → 0.9.13

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 (113) hide show
  1. package/dist/cli.js +553 -82
  2. package/extension/background.js +1 -1
  3. package/extension/bridge.js +1 -0
  4. package/extension/content.js +1 -1
  5. package/extension/manifest.json +24 -1
  6. package/extension/popup.html +9 -0
  7. package/extension/popup.js +1 -1
  8. package/extension/tap.js +1 -0
  9. package/native-host/host.js +919 -142
  10. package/native-host/scan-worker.js +209 -17
  11. package/native-host/sync.js +250 -32
  12. package/package.json +6 -6
  13. package/web-ui/web-ui/.next/BUILD_ID +1 -1
  14. package/web-ui/web-ui/.next/app-build-manifest.json +72 -72
  15. package/web-ui/web-ui/.next/app-path-routes-manifest.json +7 -7
  16. package/web-ui/web-ui/.next/build-manifest.json +2 -2
  17. package/web-ui/web-ui/.next/prerender-manifest.json +18 -18
  18. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js +2 -2
  19. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js.nft.json +1 -1
  20. package/web-ui/web-ui/.next/server/app/(app)/activity/page_client-reference-manifest.js +1 -1
  21. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js +2 -2
  22. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js.nft.json +1 -1
  23. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page_client-reference-manifest.js +1 -1
  24. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js +2 -2
  25. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js.nft.json +1 -1
  26. package/web-ui/web-ui/.next/server/app/(app)/detections/page_client-reference-manifest.js +1 -1
  27. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js +2 -2
  28. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js.nft.json +1 -1
  29. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page_client-reference-manifest.js +1 -1
  30. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js +1 -1
  31. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js.nft.json +1 -1
  32. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page_client-reference-manifest.js +1 -1
  33. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js +1 -1
  34. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js.nft.json +1 -1
  35. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page_client-reference-manifest.js +1 -1
  36. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js +2 -2
  37. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js.nft.json +1 -1
  38. package/web-ui/web-ui/.next/server/app/(app)/findings/page_client-reference-manifest.js +1 -1
  39. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js +2 -2
  40. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js.nft.json +1 -1
  41. package/web-ui/web-ui/.next/server/app/(app)/inventory/page_client-reference-manifest.js +1 -1
  42. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js +2 -2
  43. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js.nft.json +1 -1
  44. package/web-ui/web-ui/.next/server/app/(app)/policies/page_client-reference-manifest.js +1 -1
  45. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js +3 -3
  46. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js.nft.json +1 -1
  47. package/web-ui/web-ui/.next/server/app/(app)/scan/page_client-reference-manifest.js +1 -1
  48. package/web-ui/web-ui/.next/server/app/(app)/security/page.js +1 -1
  49. package/web-ui/web-ui/.next/server/app/(app)/security/page.js.nft.json +1 -1
  50. package/web-ui/web-ui/.next/server/app/(app)/security/page_client-reference-manifest.js +1 -1
  51. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js +2 -2
  52. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js.nft.json +1 -1
  53. package/web-ui/web-ui/.next/server/app/(app)/settings/page_client-reference-manifest.js +1 -1
  54. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js +2 -2
  55. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js.nft.json +1 -1
  56. package/web-ui/web-ui/.next/server/app/(app)/updates/page_client-reference-manifest.js +1 -1
  57. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js +2 -2
  58. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js.nft.json +1 -1
  59. package/web-ui/web-ui/.next/server/app/(app)/vault/page_client-reference-manifest.js +1 -1
  60. package/web-ui/web-ui/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  61. package/web-ui/web-ui/.next/server/app/_not-found.html +1 -1
  62. package/web-ui/web-ui/.next/server/app/_not-found.rsc +2 -2
  63. package/web-ui/web-ui/.next/server/app/index.html +1 -1
  64. package/web-ui/web-ui/.next/server/app/index.rsc +2 -2
  65. package/web-ui/web-ui/.next/server/app/page_client-reference-manifest.js +1 -1
  66. package/web-ui/web-ui/.next/server/app-paths-manifest.json +7 -7
  67. package/web-ui/web-ui/.next/server/chunks/121.js +1 -1
  68. package/web-ui/web-ui/.next/server/chunks/130.js +1026 -0
  69. package/web-ui/web-ui/.next/server/chunks/290.js +1 -1
  70. package/web-ui/web-ui/.next/server/chunks/3.js +1017 -0
  71. package/web-ui/web-ui/.next/server/chunks/300.js +1 -0
  72. package/web-ui/web-ui/.next/server/chunks/475.js +1 -1
  73. package/web-ui/web-ui/.next/server/chunks/662.js +1 -0
  74. package/web-ui/web-ui/.next/server/chunks/70.js +1 -0
  75. package/web-ui/web-ui/.next/server/functions-config-manifest.json +6 -6
  76. package/web-ui/web-ui/.next/server/middleware-manifest.json +5 -5
  77. package/web-ui/web-ui/.next/server/pages/404.html +1 -1
  78. package/web-ui/web-ui/.next/server/pages/500.html +1 -1
  79. package/web-ui/web-ui/.next/server/server-reference-manifest.js +1 -1
  80. package/web-ui/web-ui/.next/server/server-reference-manifest.json +1 -1
  81. package/web-ui/web-ui/.next/static/chunks/421-cc967c01935826d1.js +1 -0
  82. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/{page-a27c8937989448e4.js → page-41fba0354cc950be.js} +1 -1
  83. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/{page-2b805f9e1f995092.js → page-d2e03c3ab61af01a.js} +1 -1
  84. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/{page-a87cfee370c4e0f4.js → page-566036afcc87e4c9.js} +1 -1
  85. package/web-ui/web-ui/.next/static/chunks/app/(app)/{error-190085728a856072.js → error-4baae46bcee63009.js} +1 -1
  86. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/{page-4e214491c7be8d43.js → page-73dbcf0078b82ec4.js} +1 -1
  87. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-8051503193da1baf.js +1 -0
  88. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/{page-f16ba40d88e414b1.js → page-32c8a853bc8b5d34.js} +1 -1
  89. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-dc8fadb56d6d1e77.js +1 -0
  90. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-9b49ef42350ea7bd.js +1 -0
  91. package/web-ui/web-ui/.next/static/chunks/app/(app)/{layout-cb3c8c7b6b33414c.js → layout-f5f361f817f90ac9.js} +1 -1
  92. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/{page-ab639e48f60ad7ee.js → page-01b303adf3c8ee56.js} +1 -1
  93. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-8db3b62245c333a3.js +1 -0
  94. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/{page-a3095119b3e87341.js → page-7a4ba61626e0d130.js} +1 -1
  95. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-0930b49f6ab951bc.js +1 -0
  96. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/{page-5b32bd569c9569d9.js → page-9b04f3441a1a3f96.js} +1 -1
  97. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-911a76e75f5a1419.js +1 -0
  98. package/web-ui/web-ui/.next/static/css/298a651f6af38209.css +2 -0
  99. package/web-ui/web-ui/dist/scan-worker.js +209 -17
  100. package/web-ui/web-ui/.next/server/chunks/611.js +0 -1015
  101. package/web-ui/web-ui/.next/server/chunks/7.js +0 -1
  102. package/web-ui/web-ui/.next/server/chunks/816.js +0 -1
  103. package/web-ui/web-ui/.next/server/chunks/968.js +0 -1006
  104. package/web-ui/web-ui/.next/static/chunks/674-d8237c5d0faa4a53.js +0 -1
  105. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-c1bb992ee1f12566.js +0 -1
  106. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-59c76da638f22b0e.js +0 -1
  107. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-c37447caf89a86e1.js +0 -1
  108. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-494614fccc8c62cc.js +0 -1
  109. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-469613d499e41093.js +0 -1
  110. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-3152ceb31f024b8d.js +0 -1
  111. package/web-ui/web-ui/.next/static/css/6e72259eccdf4435.css +0 -2
  112. /package/web-ui/web-ui/.next/static/{PMeePXfXsQ2xxrXppySG_ → pkVZ1_T311YNkJgZOLTx5}/_buildManifest.js +0 -0
  113. /package/web-ui/web-ui/.next/static/{PMeePXfXsQ2xxrXppySG_ → pkVZ1_T311YNkJgZOLTx5}/_ssgManifest.js +0 -0
@@ -0,0 +1,1026 @@
1
+ "use strict";exports.id=130,exports.ids=[130],exports.modules={23130:(a,b,c)=>{c.d(b,{WR:()=>a2,qA:()=>a3,qk:()=>bw,Pi:()=>ds,o8:()=>bx,zd:()=>i,Qo:()=>cD,Ru:()=>dn,KS:()=>bk,tI:()=>bi,_2:()=>cM,Dg:()=>cN,gt:()=>cP,lG:()=>j.lGs,Wo:()=>bl,Rd:()=>cK,Ji:()=>cv,R8:()=>C,Hg:()=>B,XK:()=>A,y9:()=>cJ,cn:()=>cO,xR:()=>bu,Zu:()=>E,v5:()=>cL,Cn:()=>cQ,VL:()=>bj,Yf:()=>cC,sF:()=>D,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)}function A(a,b){let c=B(a,b);return c.usable?{usable:!0}:c}function B(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?(0,j.lGs)(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 C(a,b){let c=B(a,b);return c.usable?c.credential:null}function D(a,b){let c=(0,j.AaX)(b.endpoint);if(null!==c)throw Error(`refusing to store a control-plane credential for ${(0,j.Vgn)(b.endpoint)}: `+function(a){switch(a){case"unparseable":return"that does not look like a web address.";case"userinfo":return"the address carries a username or password, which must not be stored alongside the credential.";case"query-or-fragment":return"the address must be an origin, optionally with a path, not a query string or fragment.";case"insecure":return"an access key must not be stored for a non-HTTPS endpoint (http is accepted only for a loopback deployment)."}}(c));p(a),u(z(a),`${JSON.stringify(b,null,2)}
2
+ `)}function E(a){let b=z(a),c=void 0!==(0,d.lstatSync)(b,{throwIfNoEntry:!1});return(0,d.rmSync)(b,{force:!0}),c}var F=c(77598),G=c(79868);function H(a){return(0,F.createHash)("sha256").update(a).digest("hex")}function I(a){return H((0,j.tTV)(["source_project",a]))}function J(a,b){return H((0,j.tTV)(["inspection_definition",a,b]))}function K(a,b){return`${a}.${b}.${String(Date.now())}.${(0,F.randomUUID)().slice(0,8)}.bak`}let L=".partial",M=`.bak${L}`,N="copy";function O(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(M))continue;let b=(0,e.join)(c,a);try{let a=function(a){for(let b of[(0,e.join)(a,N),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 P(a,b){let{stage:c,copy:f}=function(a){let b=`${a}${L}`;return(0,d.rmSync)(b,{recursive:!0,force:!0}),o(b),n(b),{stage:b,copy:(0,e.join)(b,N)}}(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 Q=new TextDecoder;function R(a){return null===a?null:"string"==typeof a?a.toLowerCase():"number"==typeof a||"bigint"==typeof a?String(a).toLowerCase():Q.decode(a).toLowerCase()}function S(a){return a.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function T(a){return Array.from({length:a},()=>"?").join(", ")}function U(a){return`%${S(a)}%`}function V(a){return`(${a.map(a=>`${a} LIKE ? ESCAPE '\\'`).join(" OR ")})`}let W=0;function X(a,b,c="DEFERRED"){if(a.isTransaction){let c=`aka_sp_${String(W+=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 Y(a,b,c="DEFERRED"){let d=a.isTransaction;try{return X(a,b,c),!0}catch(b){if(!a.isTransaction&&d)throw b;return!1}}function Z(a){process.stderr.write(`[aka] ${a}
3
+ `)}function $(a,b,c){return void 0!==a.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ? LIMIT 1").get(b,c)}function _(a,b){return $(a,"index",b)}function aa(a,b,c){let d=c?.includeGenerated?"table_xinfo":"table_info";return a.prepare(`PRAGMA ${d}(${b})`).all().map(a=>a.name)}function ab(a,b){return void 0===b?a.all():Array.isArray(b)?a.all(...b):a.all(b)}function ac(a,b){return void 0===b?a.get():Array.isArray(b)?a.get(...b):a.get(b)}function ad(a){return 1===a||!0===a}function ae(a){let b={};for(let[c,d]of Object.entries(a))b[c]=void 0===d?null:d;return b}function af(a,b,c){return ac(a.prepare(b),c)?.n??0}function ag(a,b,c){let d=new Map;for(let e of ab(a.prepare(b),c))d.set(e.k,e.n);return d}function ah(a,b){let c=[];for(let d of a)try{c.push(b(d))}catch{}return c}let ai=["prompt","response","tool_use"],aj=ai.map(a=>`'${a}'`).join(", "),ak=["session","llm_call","tool_call"],al=ak.map(a=>`'${a}'`).join(", "),am=[...ak,...ai],an=am.map(a=>`'${a}'`).join(", "),ao=`
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`,ap=`
18
+ WHERE event_type IN (${an})
19
+ AND (
20
+ event_type IN (${al})
21
+ OR synced_at IS NOT NULL
22
+ OR outbox_owed = 1
23
+ )`,aq=`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 ar{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 (${al})
40
+ AND started_at < :before
41
+ GROUP BY sessionId
42
+ ORDER BY earliest
43
+ LIMIT :limit`),this.rowsStmt=a.prepare(`SELECT ${aq}
44
+ FROM audit_events
45
+ WHERE synced_at IS NULL
46
+ AND event_type IN (${al})
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 ${aq}
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 (${aj})
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 (${aj})
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${ao}
68
+ FROM audit_events${ap}`),this.partitionByKindStmt=a.prepare(`SELECT event_type AS kind,${ao}
69
+ FROM audit_events INDEXED BY idx_audit_events_sync${ap}
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 (${al})`),this.captureSkipCountStmt=a.prepare(`SELECT COUNT(*) AS skipped
82
+ FROM audit_events
83
+ WHERE synced_at = ${String(-1)}
84
+ AND event_type IN (${aj})`),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 (${aj})
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 (${al})`),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 (${al})
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 ab(this.inspectionsStmt,{auditEventId:a})}pendingSessions(a,b){return ab(this.sessionsStmt,{limit:a,before:b}).map(a=>a.sessionId)}pendingRows(a,b,c){return ab(this.rowsStmt,{sessionId:a,limit:b,before:c})}pendingCaptureRows(a,b){return ab(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&&X(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;X(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 ab(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=ac(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=ac(this.countsStmt,{before:a}),c=ac(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=ac(this.fingerprintStmt);return{fingerprint:a?.fingerprint??void 0,backlogBefore:a?.backlogBefore??void 0}}rearmFor(a,b,c){this.ensureRowStmt.run(),X(this.db,()=>{let d=ac(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(),X(this.db,()=>{let c=ac(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 X(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 ac(this.leaseStmt)}}let as=j.AJV.options;function at(a){return"column"===a.kind?`column ${a.table}.${a.name}`:`table ${a.name}`}function au(a){return a.split(/-->\s*statement-breakpoint/).map(a=>a.trim()).filter(a=>a.length>0)}let av="0014_drop_legacy_events_findings";function aw(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 ax=[{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 ay(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||(X(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 az(a,b){if(null==a)return b;try{return JSON.parse(a)}catch{return b}}function aA(a){if(null!=a)try{let b=JSON.parse(a);if("object"==typeof b&&null!==b)return b}catch{}}function aB(a){return Buffer.from(JSON.stringify(a)).toString("base64url")}function aC(a){let b=aA(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 aD(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}let aE={session:"session",prompt:"prompt",response:"response",tool_call:"tool",hook:"hook",detection:"detection",share:"share",permission:"permission",commit:"commit",error:"error",active:"active"},aF=Object.keys(aE).map(a=>`'${a}'`).join(", ");function aG(a){if(!a)return[];let b=az(a,null);return Array.isArray(b)?b:[]}let aH=j.tLs.ClaudeCode;function aI(a){let b=j.TUN.safeParse(a);return b.success?b.data:aH}function aJ(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:aI(a.harness),title:a.title||a.project||a.repo||`Session ${a.id.slice(0,8)}`,project:a.project??"",repo:a.repo??"",branches:aG(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 aK(a){let b=aE[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:ad(a.internal),flagged:ad(a.flagged),bodyExpired:null!==a.content_expired_at&&(a.title??"")===""}}let aL=`
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`,aM=`
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`,aN="event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL",aO="GROUP BY root_session_id, provider, model, service_tier";function aP(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 aQ="event_type = 'session'",aR=`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', 'capture_status'))`;class aS{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=aD();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??aD(),this.now()),d=af(this.db,`SELECT count(*) AS n FROM audit_events
151
+ WHERE ${aQ} AND started_at >= ? AND started_at < ?
152
+ AND ${aR}`,[b,c]),e=this.now()-18e5,f=af(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 >= ? AND event_type <> 'capture_status'
159
+ UNION
160
+ SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
161
+ WHERE ended_at >= ? AND event_type <> 'capture_status')`,[e,e,e]),g=af(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:af(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:af(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?aC(a.cursor):null,c=a.to?(0,j.I8t)(a.to):this.now(),d=a.from?(0,j.I8t)(a.from):void 0,e=[aQ],f=[];if(a.harness&&a.harness.length>0&&(e.push(`coalesce(json_extract(attributes, '$.harness'), '${aH}') IN (${T(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=U(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=af(this.db,`SELECT count(*) AS n FROM audit_events
176
+ WHERE ${[...e,`NOT ${aR}`].join(" AND ")}`,f);a.excludeEmpty&&e.push(aR),b&&(e.push("(started_at < ? OR (started_at = ? AND id < ?))"),f.push(b.startedAtMs,b.startedAtMs,b.id));let h=a.limit,i=ab(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=>aJ(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?aB({startedAtMs:p.started_at,id:p.id}):null,emptyCount:g})}getSession(a){let b=ac(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=ab(this.db.prepare(`SELECT ${aL}
205
+ FROM audit_events
206
+ WHERE (id = ? OR root_session_id = ?) AND event_type IN (${aF})
207
+ ORDER BY started_at ASC, id ASC`),[a,a]).map(aK).filter(a=>null!==a),d=ac(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=ac(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=ab(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=ab(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=af(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({...aJ(b,i,this.now()),host:b.host??"",cwd:b.cwd??"",models:g.length>0?g:aG(b.models),version:b.version??"",tokens:j,tools:Object.fromEntries(f.flatMap(a=>a.tool?[[a.tool,a.n]]:[])),files:aG(b.files),commits:h,events:c})}tokenReports(a){let b=ab(this.db.prepare(`${aM}
224
+ FROM audit_events INDEXED BY idx_audit_llm_usage
225
+ WHERE ${aN}${void 0===a?"":" AND started_at >= ?"}
226
+ ${aO}`),void 0===a?void 0:[a]);return Promise.resolve((0,j.ryv)(aP(b),j.q_t))}tokenReportForSession(a){let b=ab(this.db.prepare(`${aM}
227
+ FROM audit_events
228
+ WHERE ${aN} AND root_session_id = ?
229
+ ${aO}`),[a]);return Promise.resolve((0,j.ryv)(aP(b),j.q_t)[0]??null)}harnessFacets(a){let b=ab(this.db.prepare(`SELECT DISTINCT coalesce(json_extract(attributes, '$.harness'), '${aH}') AS harness
230
+ FROM audit_events WHERE ${aQ}${void 0===a?"":" AND started_at >= ?"}`),void 0===a?void 0:[a]),c=new Set;for(let a of b)c.add(aI(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=T(a.length);for(let c of ab(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 ab(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 ab(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 ab(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 ab(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 aT{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)
269
+ OR (json_extract(excluded.attributes, '$.usage_source') IS NOT NULL
270
+ AND json_extract(excluded.attributes, '$.output_tokens') IS NULL
271
+ AND excluded.attributes <> audit_events.attributes)`),this.upsertSessionRootStmt=a.prepare(`INSERT OR IGNORE INTO audit_events
272
+ (id, parent_id, root_session_id, event_type,
273
+ host_id, harness_id, source_project_id, started_at, ended_at,
274
+ severity, priority, content, content_hash, attributes)
275
+ VALUES
276
+ (:id, :parentId, :rootSessionId, :eventType,
277
+ :hostId, :harnessId, :sourceProjectId, :startedAt, :endedAt,
278
+ :severity, :priority, :content, :contentHash, :attributes)
279
+ ON CONFLICT(id) DO UPDATE SET
280
+ parent_id = excluded.parent_id,
281
+ root_session_id = excluded.root_session_id,
282
+ host_id = excluded.host_id,
283
+ harness_id = excluded.harness_id,
284
+ source_project_id = excluded.source_project_id,
285
+ started_at = min(audit_events.started_at, excluded.started_at),
286
+ ended_at = excluded.ended_at,
287
+ severity = excluded.severity,
288
+ priority = excluded.priority,
289
+ content = excluded.content,
290
+ content_hash = excluded.content_hash,
291
+ attributes = excluded.attributes
292
+ WHERE audit_events.attributes IS NULL AND excluded.attributes IS NOT NULL`)}runInTransaction(a){X(this.db,a)}insertAuditEvent(a){let b=(0,j.V9M)(a);Number.isFinite(b.startedAt)&&("session"===b.eventType?this.upsertSessionRootStmt:this.insertStmt).run(ae({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,H((0,j.tTV)(["audit_event_llm_call",b,c])));this.upsertLlmCallStmt.run(ae({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,H((0,j.tTV)(["audit_event_tool_call",b,c])));this.insertStmt.run(ae({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 ac(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=aA(b.attributes)?.provider;if("string"==typeof c)return c}llmCallLeaves(){return ab(this.db.prepare(`SELECT root_session_id AS sessionId, attributes
293
+ FROM audit_events
294
+ WHERE event_type = 'llm_call' AND attributes IS NOT NULL`))}}class aU{constructor(a){this.db=a;let b=a=>`
295
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
296
+ FROM audit_events
297
+ WHERE content IS NOT NULL
298
+ AND started_at < :cutoff
299
+ AND event_type IN (${j.hfB})
300
+ ${a}
301
+ ORDER BY started_at
302
+ LIMIT :limit`;this.candidatesStmt=this.db.prepare(b("")),this.candidatesSyncSafeStmt=this.db.prepare(b(`AND (event_type NOT IN (${aj}) OR synced_at IS NOT NULL)`)),this.heldBySyncStmt=this.db.prepare(`
303
+ SELECT COUNT(*) AS n
304
+ FROM audit_events
305
+ WHERE content IS NOT NULL
306
+ AND started_at < :cutoff
307
+ AND event_type IN (${aj})
308
+ 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||(X(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 aV{constructor(a){this.db=a,this.recentStmt=a.prepare(`SELECT a.started_at AS startedAt,
309
+ a.attributes AS attributes,
310
+ a.root_session_id AS rootSessionId
311
+ FROM audit_events a
312
+ WHERE a.event_type = 'capture_status'
313
+ AND a.source_tool = ?
314
+ AND a.started_at >= ?
315
+ ORDER BY a.started_at DESC, a.id DESC
316
+ LIMIT ?`)}latest(a){let b=a-j.Rf1,c=[];for(let a of j.AKh.options){let d=new Map,e=new Map;for(let c of ab(this.recentStmt,[a,b,128])){let b=(0,j.GVg)(aA(c.attributes));if(null===b)continue;let f={tool:a,observedAt:(0,j.q11)(c.startedAt),status:b},g=d.get(c.rootSessionId);void 0===g?(d.set(c.rootSessionId,[f]),e.set(c.rootSessionId,{at:f.observedAt,closed:b.closed})):g.push(f)}for(let[a,b]of d){let d=(0,j.Pv3)(b),f=e.get(a);void 0!==d&&void 0!==f&&c.push({...d,...null===a?{}:{rootSessionId:a},lastReportAt:f.at,closed:f.closed})}}return c}}class aW{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO classified_data (id, class, label, attributes)
317
+ VALUES (:id, :class, :label, :attributes)`)}upsert(a){var b;let c=(b=a.class,H((0,j.tTV)(["classified_data",b]))),d=(0,j.$BP)(a,c);return this.insertStmt.run(ae({id:d.id,class:d.class,label:d.label,attributes:d.attributes})),c}}function aX(a){return ac(a.prepare(`SELECT id, started_at, attributes FROM audit_events
318
+ WHERE event_type = 'config_scan'
319
+ ORDER BY started_at DESC, id DESC LIMIT 1`))}class aY{constructor(a){this.db=a}report(){let a=aX(this.db);if(!a)return{scannedAt:null,skills:[],hooks:[],mcpServers:[],configFiles:[],topics:[]};let b=ab(this.db.prepare(`SELECT id, object_type AS objectType, title, location, attributes FROM inventory
320
+ WHERE object_type IN ('skill', 'hook', 'mcp_server', 'config_file') AND last_seen >= :startedAt
321
+ ORDER BY object_type, title`),{startedAt:a.started_at}),c=ab(this.db.prepare(`SELECT f.masked_match AS maskedMatch, d.rule_id AS ruleId, d.name AS name
322
+ FROM inspection_findings f
323
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
324
+ WHERE f.audit_event_id = :scanId`),{scanId:a.id}),d=[],e=[],f=[],g=[],h=this.trustOverrides();for(let a of b){let b=aA(a.attributes);b&&("skill"===a.objectType?d.push(function(a,b){let c={id:a.id,name:a.title??"(unnamed)",source:aZ(b.source)??"unknown",scope:aZ(b.scope)??"unknown",status:"unknown"},d=aZ(b.description);void 0!==d&&(c.description=d);let e=aZ(b.version);void 0!==e&&(c.installedVersion=e);let f=aZ(b.updated_at);return void 0!==f&&(c.updatedAt=f),c}(a,b)):"hook"===a.objectType?e.push(function(a,b,c){let d=aZ(b.command)??"",e=c.filter(a=>a.maskedMatch===d),f={id:a.id,event:aZ(b.event)??"unknown",command:d,scope:aZ(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=aZ(b.matcher);void 0!==g&&(f.matcher=g);let h=aZ(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:aZ(b.scope)??"unknown",transport:aZ(b.transport)??"unknown",trust:c.get(a.id)??"unapproved"},e=aZ(b.command);void 0!==e&&(d.command=e);let f=aZ(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=aZ(b.plugin_name);void 0!==g&&(d.pluginName=g);let h=aZ(b.marketplace);void 0!==h&&(d.marketplace=h);let i=aZ(b.project);return void 0!==i&&(d.project=i),d}(a,b,h)):g.push(function(a,b){let c=aZ(b.scope)??"unknown",d={id:a.id,name:a.title??"(unnamed)",path:a.location??"",scope:c,kind:aZ(b.kind)??"Configuration file",untracked:"local"===c},e=aZ(b.detail);void 0!==e&&(d.detail=e),"number"==typeof b.entry_count&&(d.entryCount=b.entry_count);let f=aZ(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=aA(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=ab(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 aZ(a){return"string"==typeof a?a:void 0}function a$(a){let b=az(a,[]);if(!Array.isArray(b))return[];let c=[];for(let a of b)a&&"object"==typeof a&&c.push(a);return c}function a_(a,b){return a.version!==b.version||a.rulesJson!==b.rulesJson}class a0{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}listDetections(a){let b=ab(this.db.prepare(`SELECT namespace, pack_id AS packId, version, name, enabled, policy_id AS policyId,
325
+ rules_json AS rulesJson
326
+ 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:ad(a.enabled),ruleCount:a$(a.rulesJson).length,policyId:a.policyId,...b&&a_(a,b)?{latestVersion:b.version}:{}}});return Promise.resolve((0,j.plk)(d,a))}availableByPack(){return new Map(ab(this.db.prepare(`SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson
327
+ FROM available_packs`)).map(a=>[`${a.namespace}/${a.packId}`,a]))}getDetectionStats(){let a=ab(this.db.prepare("SELECT enabled, rules_json AS rulesJson FROM installed_packs")),b=0,c=0,d=new Set;for(let e of a){ad(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=ac(this.db.prepare(`SELECT namespace, pack_id AS packId, version, name, enabled, policy_id AS policyId,
328
+ rules_json AS rulesJson, updated_at AS updatedAt
329
+ FROM installed_packs
330
+ 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?a_(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:ad(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=T(a.length);return af(this.db,`SELECT count(*) AS n
331
+ FROM inspection_findings f
332
+ JOIN audit_events e ON e.id = f.audit_event_id
333
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
334
+ WHERE e.started_at >= ?
335
+ AND e.event_type IN (${j.hfB})
336
+ AND d.rule_id IN (${c})`,[b,...a])}}class a1{constructor(a){this.db=a}contentHashes(){return Promise.resolve(new Set(ab(this.db.prepare(`SELECT content_hash FROM audit_events
337
+ WHERE event_type IN (${j.hfB})`)).map(a=>a.content_hash)))}}let a2=864e5;class a3 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 a4 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 a5=`revoked_at IS NULL
338
+ AND (expires_at IS NULL OR expires_at > :now)
339
+ AND (max_uses IS NULL OR use_count < max_uses)`,a6=`capability = 'reveal_to_model'
340
+ AND conditions IS NULL
341
+ AND ${a5}`;class a7{constructor(a,b=()=>Date.now()){this.db=a,this.now=b,this.consumeStmt=a.prepare(`UPDATE exceptions
342
+ SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
343
+ WHERE id = :id AND ${a5}`),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)
344
+ 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,F.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;X(this.db,()=>{if(1!==Number(this.db.prepare(`UPDATE exceptions
345
+ SET revoked_at = :now, revoked_by = :revokedBy,
346
+ revoke_reason = 'superseded by a new grant for the same value',
347
+ updated_at = :now
348
+ WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
349
+ AND key_version = :keyVersion AND revoked_at IS NULL
350
+ AND ((expires_at IS NOT NULL AND expires_at <= :now)
351
+ 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 a3(a.ruleId);this.insertExceptionRow(b,a,c)},"IMMEDIATE")}let d=ac(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 a8(d)}insertExceptionRow(a,b,c){this.db.prepare(`INSERT INTO exceptions (
352
+ id, rule_id, category, value_fingerprint, key_version, masked_value,
353
+ capability, scope, expires_at, max_uses, use_count, last_used_at,
354
+ justification, conditions, created_by, created_via, created_at, updated_at
355
+ ) VALUES (
356
+ :id, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue,
357
+ :capability, :scope, :expiresAt, :maxUses, 0, NULL, :justification,
358
+ :conditions, :createdBy, :createdVia, :now, :now
359
+ )`).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 ${a5}`;return Promise.resolve(ah(ab(this.db.prepare(`SELECT * FROM exceptions ${b} ORDER BY created_at DESC, rowid DESC`),a?.includeTerminal?{}:{now:this.now()}),a8))}getByIdPrefix(a){if(0===a.length)return Promise.resolve(void 0);let b=ab(this.db.prepare(String.raw`SELECT * FROM exceptions WHERE id LIKE :pattern ESCAPE '\' LIMIT 2`),{pattern:`${S(a)}%`});if(b.length>1)return Promise.reject(new a4(a));let c=b[0];if(!c)return Promise.resolve(void 0);try{return Promise.resolve(a8(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
360
+ SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
361
+ 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(ah(ab(this.db.prepare(`SELECT * FROM exceptions
362
+ WHERE key_version = :keyVersion AND ${a5}
363
+ 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-a2}),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(ab(this.db.prepare(`SELECT * FROM blocked_detections
364
+ WHERE blocked_at > :cutoff
365
+ 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=ac(this.db.prepare(`SELECT id FROM exceptions
366
+ WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
367
+ AND key_version = :keyVersion
368
+ AND ${a6}
369
+ 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
370
+ WHERE updated_at < :cutoff
371
+ AND (revoked_at IS NOT NULL
372
+ OR (expires_at IS NOT NULL AND expires_at <= :now)
373
+ OR (max_uses IS NOT NULL AND use_count >= max_uses))`).run({cutoff:b-a,now:b}).changes))}}function a8(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 a9(a){return`(
374
+ SELECT fr.status FROM finding_resolution fr
375
+ WHERE fr.finding_key = ${a}.finding_key
376
+ ORDER BY fr.created_at DESC, fr.rowid DESC
377
+ LIMIT 1
378
+ )`}let ba=`(
379
+ SELECT finding_key, status, method, resolved_at FROM (
380
+ SELECT fr.finding_key, fr.status, fr.method, fr.resolved_at,
381
+ ROW_NUMBER() OVER (
382
+ PARTITION BY fr.finding_key
383
+ ORDER BY fr.created_at DESC, fr.rowid DESC
384
+ ) AS rn
385
+ FROM finding_resolution fr
386
+ ) WHERE rn = 1
387
+ )`;function bb(a){return null===a||""===a?[]:a.split(",")}function bc(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 bd=`f.id AS id, d.rule_id AS rule_id, d.category AS category,
388
+ d.severity AS severity, f.masked_match AS masked_match,
389
+ f.action_taken AS action_taken, f.confidence AS confidence,
390
+ e.started_at AS occurred_at,
391
+ e.source_tool AS source_tool,
392
+ e.repo AS repo,
393
+ e.file_path AS file,
394
+ e.tool_name AS tool_name,
395
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
396
+ e.event_type AS kind, f.finding_key AS finding_key,
397
+ ${a9("f")} AS latest_status,
398
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
399
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
400
+ e.outbox_owed AS outbox_owed`;class be{constructor(a){this.db=a}recentFindings(a){let b=a?.limit??50;return Promise.resolve(ab(this.db.prepare(`SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
401
+ f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
402
+ e.source_tool AS source_tool,
403
+ e.event_type AS kind
404
+ FROM audit_events e
405
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
406
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
407
+ WHERE +e.event_type IN (${j.hfB})
408
+ ORDER BY e.started_at DESC, f.rowid DESC
409
+ 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(af(this.db,`SELECT count(*) AS n FROM inspection_findings f
410
+ JOIN audit_events e ON e.id = f.audit_event_id
411
+ WHERE e.root_session_id = :sessionId
412
+ AND e.event_type IN (${j.hfB})`,{sessionId:a})):Promise.resolve(0)}sessionFirings(a){return Object.fromEntries(ag(this.db,`SELECT d.rule_id AS k, count(*) AS n
413
+ FROM inspection_findings f
414
+ JOIN audit_events e ON e.id = f.audit_event_id
415
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
416
+ WHERE e.root_session_id = :sessionId
417
+ AND e.event_type NOT IN (${j.hfB})
418
+ 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=aA(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:aC(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?aB({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=aA(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 bc(a)}findingInstance(a){let b=this.db.prepare(`SELECT ${bd}
419
+ FROM inspection_findings f
420
+ JOIN audit_events e ON e.id = f.audit_event_id
421
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
422
+ WHERE f.id = ?`).get(a);return Promise.resolve(void 0===b?null:(0,j.MgS)(bc(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 ${bd}
423
+ FROM audit_events e
424
+ CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
425
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
426
+ WHERE ${b.join(" AND ")}
427
+ ORDER BY e.started_at DESC, f.id DESC`,params:c}}groupAggregates(a,b){let c=a?`, group_concat(DISTINCT e.repo) AS repos,
428
+ group_concat(DISTINCT e.file_path) AS files,
429
+ 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,
430
+ -- BARE columns beside max(latest_at), which is deliberate and
431
+ -- is SQLite's documented behaviour: with a single min()/max()
432
+ -- in an aggregate query, every bare column takes its value from
433
+ -- the row that produced the extremum. So these are the severity
434
+ -- and category of the definition whose finding is NEWEST, which
435
+ -- is what the row-based build they replaced read off its first
436
+ -- (newest-first) row.
437
+ --
438
+ -- min() is WRONG here and was the defect: inspection_definitions
439
+ -- holds one row per rule VERSION (see its writer — a version bump
440
+ -- mints a new row), so a rule whose severity moved between
441
+ -- versions has several, and min() picks the ALPHABETICALLY
442
+ -- smallest — 'low' over 'medium', but 'critical' over 'high'.
443
+ -- That is arbitrary in direction, and it feeds the badge, the
444
+ -- filter, the facet counts and the primary sort key.
445
+ --
446
+ -- Adding a second min()/max() aggregate here would make these
447
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
448
+ severity,
449
+ category,
450
+ sum(tuple_count) AS instance_count,
451
+ max(latest_at) AS latest_at,
452
+ group_concat(source_tools) AS source_tools,
453
+ group_concat(actions_taken) AS actions_taken,
454
+ group_concat(status_tuple || '|' || tuple_count) AS status_inputs,
455
+ group_concat(repos) AS repos,
456
+ group_concat(files) AS files,
457
+ group_concat(tool_names) AS tool_names
458
+ FROM (
459
+ SELECT d.rule_id AS rule_id,
460
+ -- Severity and category are columns of the DEFINITION, and
461
+ -- a rule can have SEVERAL definitions (one per version), so
462
+ -- these are grouped on below and resolved to the newest
463
+ -- firing version by the outer query's bare-column select.
464
+ -- They ride the aggregate because the type build has no rows
465
+ -- to read them off — see buildFindingTypes.
466
+ d.severity AS severity,
467
+ d.category AS category,
468
+ e.event_type || '|' ||
469
+ (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '|' ||
470
+ coalesce(latest.status, '') AS status_tuple,
471
+ count(*) AS tuple_count,
472
+ max(e.started_at) AS latest_at,
473
+ group_concat(DISTINCT e.source_tool) AS source_tools,
474
+ group_concat(DISTINCT f.action_taken) AS actions_taken
475
+ ${c}
476
+ FROM inspection_findings f
477
+ JOIN audit_events e ON e.id = f.audit_event_id
478
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
479
+ LEFT JOIN ${ba} latest
480
+ ON latest.finding_key = f.finding_key
481
+ ${b.predicate}
482
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
483
+ )
484
+ GROUP BY rule_id`).all(b.params).map(b=>[b.rule_id,{instanceCount:b.instance_count,severity:b.severity,category:b.category,sourceTools:bb(b.source_tools),actionsTaken:bb(b.actions_taken),statusInputs:bb(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=af(this.db,`SELECT count(*) AS n FROM inspection_findings f
485
+ JOIN audit_events e ON e.id = f.audit_event_id
486
+ WHERE e.event_type IN (${j.hfB})`),b=Object.fromEntries(j.S8C.map(a=>[a,0]));for(let a of ab(this.db.prepare(`SELECT f.action_taken AS action_taken, count(*) AS c
487
+ FROM inspection_findings f
488
+ JOIN audit_events e ON e.id = f.audit_event_id
489
+ WHERE e.event_type IN (${j.hfB})
490
+ 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 ab(this.db.prepare(`SELECT d.severity AS severity, count(*) AS c
491
+ FROM inspection_findings f
492
+ JOIN audit_events e ON e.id = f.audit_event_id
493
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
494
+ LEFT JOIN ${ba} latest
495
+ ON latest.finding_key = f.finding_key
496
+ WHERE e.event_type IN (${j.hfB})
497
+ AND (latest.status IS NULL OR latest.status != 'resolved')
498
+ GROUP BY d.severity`)))Object.hasOwn(c,a.severity)&&(c[a.severity]=a.c);let d=j.IgC,e=new Set(ab(this.db.prepare(`SELECT DISTINCT json_extract(target, '$.category') AS category
499
+ 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=ab(this.db.prepare(`SELECT date(e.started_at / 1000, 'unixepoch') AS day, f.action_taken AS action, count(*) AS c
500
+ FROM inspection_findings f
501
+ JOIN audit_events e ON e.id = f.audit_event_id
502
+ WHERE e.started_at >= :since
503
+ AND e.event_type IN (${j.hfB})
504
+ 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 bf{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
505
+ (id, rule_id, name, category, severity, definition, version)
506
+ VALUES
507
+ (:id, :ruleId, :name, :category, :severity, :definition, :version)`)}upsert(a){let b=J(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 bg{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO inspection_findings
508
+ (id, audit_event_id, inspection_definition_id, classified_data_id,
509
+ span_start, span_end, masked_match, action_taken, confidence,
510
+ finding_key, first_detected_at)
511
+ VALUES
512
+ (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
513
+ :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
514
+ :findingKey,
515
+ COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
516
+ ON CONFLICT(id) DO UPDATE SET
517
+ inspection_definition_id = excluded.inspection_definition_id
518
+ ON CONFLICT (finding_key) DO UPDATE SET
519
+ audit_event_id = excluded.audit_event_id,
520
+ inspection_definition_id = excluded.inspection_definition_id,
521
+ classified_data_id = excluded.classified_data_id,
522
+ span_start = excluded.span_start,
523
+ span_end = excluded.span_end,
524
+ masked_match = excluded.masked_match,
525
+ action_taken = excluded.action_taken,
526
+ confidence = excluded.confidence`),this.sessionDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
527
+ JOIN audit_events e ON e.id = f.audit_event_id
528
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
529
+ WHERE d.rule_id = :ruleId AND f.masked_match = :maskedMatch
530
+ AND e.root_session_id = :sessionId
531
+ AND e.event_type IN (${j.hfB})
532
+ LIMIT 1`),this.eventDupStmt=a.prepare(`SELECT 1 FROM inspection_findings f
533
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
534
+ WHERE f.audit_event_id = :auditEventId AND d.rule_id = :ruleId
535
+ AND f.masked_match = :maskedMatch
536
+ AND f.span_start = :spanStart AND f.span_end = :spanEnd
537
+ 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(ae({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 bh=c(48161);function bi(){return(0,e.join)((0,bh.homedir)(),".aka")}function bj(a=bi()){return(0,e.join)(a,"settings")}function bk(a=bi()){return(0,e.join)(a,"data")}function bl(a=bi()){return(0,e.join)(a,"keys")}let bm=new Set(["EEXIST","EACCES","EPERM","EBUSY"]),bn=new Int32Array(new SharedArrayBuffer(4));class bo 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 bp(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 bq(a,b){let c,e=(0,F.randomUUID)();try{c=(0,d.openSync)(a,"wx",384)}catch(e){let c=e.code??"";if("EEXIST"===c||bm.has(c)&&((0,d.existsSync)(a)||function(a){let b=`${a}.probe-${(0,F.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 bo("unavailable",b,e instanceof Error?e.message:String(e),void 0,{cause:e})}let f={pid:process.pid,token:e,at:Date.now(),host:(0,bh.hostname)()};try{(0,d.writeFileSync)(c,`${JSON.stringify(f)}
538
+ `)}catch{try{(0,d.closeSync)(c)}catch{}return(0,d.rmSync)(a,{force:!0}),null}try{(0,d.closeSync)(c)}catch{}return e}function br(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=aA(a);if(!c)continue;let e=j.ZXz.safeParse(c);if(e.success)return e.data}return null}function bs(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 bt="settings.json";function bu(a=bi()){return bs(bv(a),br())}function bv(a){let b=function(a){let b;try{b=(0,d.readFileSync)(a,"utf8")}catch{return null}return aA(b)??null}((0,e.join)(bj(a),bt));if(!b)return(0,j.i1j)();try{return j.hd_.parse(b)}catch{return(0,j.i1j)()}}class bw extends Error{constructor(a){super(`refusing to write administratively locked settings: ${a.join(", ")}`),this.name="ManagedFieldError",this.fields=a}}function bx(a,b=bi(),c){let f=bj(b);p(f);let g=(0,e.join)(f,bt),h=void 0===c?br():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=bq(g,a);for(;null===i;){if(function(a,b){let c,e=`${a}.break`;try{c=(0,d.openSync)(e,"wx",384)}catch{return function(a){try{Date.now()-(0,d.statSync)(a).mtimeMs>=1e4&&(0,d.rmSync)(a,{force:!0})}catch{}}(e),!1}try{(0,d.closeSync)(c)}catch{}try{if(!(0,d.existsSync)(a)||!function(a,b,c){var e;if(!a)try{return Date.now()-(0,d.statSync)(b).mtimeMs>=c}catch{return!1}return!(Date.now()-a.at<c)&&(!(a.host===(0,bh.hostname)()&&function(a){if(!Number.isInteger(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"ESRCH"!==a.code}}(a.pid))||Date.now()-a.at>=(e=c,Math.max(30*e,6e4)))}(bp(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=bq(g,a);continue}if(Date.now()>=h)throw new bo("timeout",a,`still held after ${String(e)}ms`,bp(g)?.pid);Atomics.wait(bn,0,0,5),i=bq(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(bp(a)?.token!==b)return;(0,d.rmSync)(a,{force:!0})}catch{}}(g,i)}}(g,()=>{let c=bv(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}(bs(c,h),d),f=i.present?e.filter(a=>i.lockedFields.includes(a)):[];if(f.length>0)throw new bw(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)}
539
+ `),k})}class by 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 bz(a=bi()){if(!(0,j.lgf)(bu(a)))return null;let b=function(a=bi()){try{let b=(0,d.readFileSync)((0,e.join)(bk(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 bA(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 bB=j.Jr;function bC(a){return a.map(a=>{var b;return`${a.namespace}/${a.packId}@${a.version}#${b=a.rulesJson,(0,F.createHash)("sha256").update(b).digest("hex")}`}).sort().join(",")}function bD(a){let b=/^(\d+)\.(\d+)\.(\d+)/.exec(a);return b?[Number(b[1]),Number(b[2]),Number(b[3])]:null}class bE{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)
540
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
541
+ 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)
542
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, :recordedBy, :now)
543
+ ON CONFLICT (namespace, pack_id) DO UPDATE SET
544
+ version = excluded.version,
545
+ name = excluded.name,
546
+ rules_json = excluded.rules_json,
547
+ recorded_by = excluded.recorded_by,
548
+ updated_at = excluded.updated_at
549
+ WHERE available_packs.version <> excluded.version
550
+ OR available_packs.name <> excluded.name
551
+ 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
552
+ 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()===bC(c))return;let d=Date.now();X(this.db,()=>{let a=this.mirrorState(),e=!1;for(let f of c){let c={id:(0,F.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=bD(a.version);if(null===c)return!0;let d=bD(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,F.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(ab(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=az(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=ab(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 X(this.db,()=>{this.db.exec("UPDATE _pack_write_gate SET open = 1 WHERE id = 1");let d=this.db.prepare(`UPDATE installed_packs SET
553
+ version = (SELECT a.version FROM available_packs a
554
+ WHERE a.namespace = :namespace AND a.pack_id = :packId),
555
+ name = (SELECT a.name FROM available_packs a
556
+ WHERE a.namespace = :namespace AND a.pack_id = :packId),
557
+ rules_json = (SELECT a.rules_json FROM available_packs a
558
+ WHERE a.namespace = :namespace AND a.pack_id = :packId),
559
+ updated_at = :now
560
+ WHERE namespace = :namespace AND pack_id = :packId
561
+ AND EXISTS (SELECT 1 FROM available_packs a
562
+ 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=ab(this.db.prepare(`SELECT enabled, policy_id AS policyId, rules_json AS rulesJson, version,
563
+ namespace, pack_id AS packId
564
+ FROM installed_packs
565
+ 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(!ad(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=ab(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!==bA(e)&&(null===b||function(a,b){let c=bA(a),d=bA(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(ac(this.db.prepare(`SELECT count(*) AS packs,
566
+ coalesce(sum(json_array_length(rules_json)), 0) AS rules,
567
+ coalesce(sum(enabled), 0) AS enabled
568
+ FROM installed_packs`))??{packs:0,rules:0,enabled:0})}countsByPolicyId(){return ag(this.db,`SELECT coalesce(policy_id, '${bB}') AS k, count(*) AS n
569
+ FROM installed_packs
570
+ GROUP BY k`)}listByPolicyId(a){return ab(this.db.prepare(`SELECT namespace, pack_id AS packId, name, enabled, rules_json AS rulesJson
571
+ FROM installed_packs
572
+ WHERE coalesce(policy_id, '${bB}') = ?
573
+ ORDER BY name ASC`),[a]).map(a=>({id:`${a.namespace}/${a.packId}`,name:a.name,ruleCount:a$(a.rulesJson).length,enabled:ad(a.enabled)}))}packFloorRules(a,b){let c=ac(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=bi()){let c=bz(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=bz(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 by(`${a}/${b}`,c,d.floor,e)}return Number(this.db.prepare(`UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
574
+ 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 by(`${a}/${b}`,null,d.floor,e)}return Number(this.db.prepare(`UPDATE installed_packs SET enabled = :enabled, updated_at = :now
575
+ WHERE namespace = :namespace AND pack_id = :packId`).run({enabled:+!!c,now:Date.now(),namespace:a,packId:b}).changes)>0}storedSignature(){return bC(ab(this.signatureStmt))}}class bF{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO inventory
576
+ (id, object_type, location, title, host_id, attributes, first_seen, last_seen)
577
+ VALUES
578
+ (:id, :objectType, :location, :title, :hostId, :attributes, :firstSeen, :lastSeen)
579
+ ON CONFLICT(id) DO UPDATE SET
580
+ location = excluded.location,
581
+ title = excluded.title,
582
+ host_id = excluded.host_id,
583
+ attributes = excluded.attributes,
584
+ last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){var c,d;let e=(c=a.objectType,d=a.identityKey,H((0,j.tTV)(["inventory",c,d]))),f=(0,j.gzP)(a,e,b);return this.upsertStmt.run(ae({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 ac(this.db.prepare("SELECT * FROM inventory WHERE id = :id"),{id:a})}distinctTitles(a){return ab(this.db.prepare(`SELECT DISTINCT title FROM inventory
585
+ WHERE object_type = :objectType AND title IS NOT NULL
586
+ ORDER BY title`),{objectType:a}).map(a=>a.title)}osVersions(){return ab(this.db.prepare(`SELECT DISTINCT os_version AS value FROM inventory
587
+ WHERE object_type = 'host' AND os_version IS NOT NULL
588
+ ORDER BY value`)).map(a=>a.value)}}let bG=["config","skill","mcp","hook"],bH=new Set(j.SHn.options),bI="(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))",bJ={[j.tLs.ClaudeCode]:"Claude Code",[j.tLs.Cursor]:"Cursor",[j.tLs.Codex]:"Codex",[j.tLs.Antigravity]:"Antigravity"},bK={accessCounts:{open:0,approved:0,blocked:0,total:0},findingsCount:0},bL=a=>a.toLowerCase().replace(/[\s-]/g,""),bM={ClaudeCode:bL(j.Zdp.ClaudeCode),Cursor:bL(j.Zdp.Cursor),Codex:bL(j.Zdp.Codex),Antigravity:bL(j.Zdp.Antigravity)};function bN(a,b){if(a.provider&&bH.has(a.provider))return a.provider;let c=bL(b.title??"");return c.includes(bM.ClaudeCode)||"claude"===c?j.tLs.ClaudeCode:c.includes(bM.Cursor)?j.tLs.Cursor:c.includes(bM.Codex)?j.tLs.Codex:c.includes(bM.Antigravity)?j.tLs.Antigravity:null}function bO(a){return a.some(a=>{let b=az(a.attributes,{});return"sample"!==b.provenance&&bN(b,a)===j.tLs.ClaudeCode})}function bP(a){let b={id:a.id,type:a.assetType,name:a.name,sub:a.sub??"",flags:az(a.flagsJson,[])};return"mcp"===a.assetType&&a.effectiveTrust&&(b.trust=a.effectiveTrust),b}function bQ(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 bR(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:bU(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 bS(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 ${bU(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 bT(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 bU(a,b){return a.length>b?`${a.slice(0,b-1)}…`:a}function bV(a,b,c){let d=az(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 bW(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 bX{constructor(a){this.db=a}getInventoryStats(){let a=ag(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=af(this.db,`SELECT count(*) AS n FROM source_project WHERE ${bI}`);let c=ag(this.db,`SELECT coalesce(o.trust, a.trust) AS k, count(*) AS n
589
+ FROM inventory_asset a
590
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
591
+ WHERE a.asset_type = 'mcp' AND coalesce(o.trust, a.trust) IS NOT NULL
592
+ 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=af(this.db,`SELECT count(*) AS n FROM inventory
593
+ WHERE object_type = 'harness'
594
+ AND (last_seen >= :liveSince OR json_extract(attributes, '$.provenance') = 'sample')`,{liveSince:Date.now()-2592e6}),f=af(this.db,"SELECT count(*) AS n FROM inventory_asset WHERE flags_json <> '[]'"),g=af(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=bN(az(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=>az(a.attributes,{}).projectIds??[]))],f=this.fetchProjectsByIds(e),g=this.projectAggregates(e),h=this.configAssetRows(a,bO(b)),i=[];for(let[b,e]of c){let c=e.flatMap(a=>d.get(a.id)??[]),k=e.some(a=>"sample"!==az(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=az(l.attributes,{}),n=[...new Set(e.flatMap(a=>az(a.attributes,{}).projectIds??[]))].map(a=>f.get(a)).filter(a=>void 0!==a).map(a=>{let b=g.get(a.id)??bK;return bV(a,b.accessCounts,b.findingsCount)}),o=e.reduce((a,b)=>a+(az(b.attributes,{}).sessions??0),0),p=k.reduce((a,b)=>a+az(b.flagsJson,[]).length,0),q=new Map;for(let a of k){let b=q.get(a.assetType);b?b.push(bP(a)):q.set(a.assetType,[bP(a)])}let r=bG.filter(a=>q.has(a)).map(a=>({type:a,assets:q.get(a)??[]}));i.push({id:b,label:m.label??bJ[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 az(a.flagsJson,[]))c.set(b,(c.get(b)??0)+1);let d={type:a,total:b.length,flagRollup:Object.fromEntries(c),items:b.map(bP)};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)=>bG.indexOf(a.type)-bG.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:az(a.flagsJson,[]),description:a.description??null,trust:"mcp"===a.assetType?a.effectiveTrust??null:null,meta:az(a.metaJson,{}),finding:null};if("mcp"===a.assetType&&null!==a.toolsJson){let c=az(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)??bK;return bV(a,b.accessCounts,b.findingsCount)})})}getProjectTree(a,b){let c=this.fetchProjectById(a);if(!c)return Promise.resolve(null);let d=az(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(bW)})}if(void 0!==b.q&&""!==b.q)return Promise.resolve({project:e,path:f,files:this.fetchProjectFilesSearch(a,b.q).map(bW)});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(bW)})}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=az(c.attributes,{});return Promise.resolve({...bW(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)
595
+ VALUES (:id, :projectId, :path, :access, :now, :now)
596
+ ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`).run({id:(0,F.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)
597
+ VALUES (:id, :assetId, :trust, :now, :now)
598
+ ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`).run({id:(0,F.randomUUID)(),assetId:a,trust:b,now:Date.now()}),this.configRowsCache=void 0,"ok"):"not_found"}fetchHarnessRows(){return ab(this.db.prepare(`SELECT id, title, attributes, harness_version AS harnessVersion
599
+ FROM inventory
600
+ WHERE object_type = 'harness'
601
+ 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 (${T(a.length)})`;if(b){let a=U(b);e+=` AND ${V(["a.name","a.sub"])}`,d.push(a,a)}for(let a of ab(this.db.prepare(`SELECT ha.harness_id AS harnessInvId, a.id, a.asset_type AS assetType, a.name, a.sub,
602
+ a.description, a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
603
+ a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
604
+ FROM harness_asset ha
605
+ JOIN inventory_asset a ON a.id = ha.asset_id
606
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
607
+ WHERE ${e}
608
+ 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 (${T(a.length)})`),d.push(...a)),b){let a=U(b);c.push(V(["a.name","a.sub"])),d.push(a,a)}let e=c.length?`WHERE ${c.join(" AND ")}`:"",f=this.mapAssetRows(ab(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
609
+ a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
610
+ a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
611
+ FROM inventory_asset a
612
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
613
+ ${e}
614
+ 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(ab(this.db.prepare(`SELECT a.id, a.asset_type AS assetType, a.name, a.sub, a.description,
615
+ a.flags_json AS flagsJson, a.meta_json AS metaJson, a.trust,
616
+ a.tools_json AS toolsJson, coalesce(o.trust, a.trust) AS effectiveTrust
617
+ FROM inventory_asset a
618
+ LEFT JOIN mcp_trust_override o ON o.asset_id = a.id
619
+ 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??bO(this.fetchHarnessRows())))return[];let b=this.latestConfigScanId();if(null===b)return[];if(this.configRowsCache?.scanId===b)return this.configRowsCache.rows;let c=new aY(this.db).report(),d=[...c.skills.map(bQ),...c.hooks.map(bR),...c.mcpServers.map(bS),...c.configFiles.map(bT)].sort((a,b)=>a.name.localeCompare(b.name));return this.configRowsCache={scanId:b,rows:d},d}latestConfigScanId(){return aX(this.db)?.id??null}fetchProjects(a){let b=`SELECT id, url, name, attributes, last_seen AS lastSeen FROM source_project
620
+ WHERE ${bI}`,c=[];if(a){let d=U(a);b+=` AND ${V(["name","url"])}`,c.push(d,d)}return b+=" ORDER BY name ASC",ab(this.db.prepare(b),c)}fetchProjectById(a){return ac(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 ab(this.db.prepare(`SELECT id, url, name, attributes, last_seen AS lastSeen
621
+ FROM source_project WHERE id IN (${T(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 ab(this.db.prepare(`SELECT f.project_id AS projectId,
622
+ coalesce(o.access, f.default_access) AS eff,
623
+ count(*) AS n,
624
+ coalesce(sum(f.findings_count), 0) AS findings
625
+ FROM project_file f
626
+ LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
627
+ WHERE f.project_id IN (${T(a.length)})
628
+ 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,
629
+ f.findings_count AS findingsCount, f.blocked_at AS blockedAtMs, f.note,
630
+ coalesce(o.access, f.default_access) AS effectiveAccess,
631
+ o.access AS overrideAccess
632
+ FROM project_file f
633
+ LEFT JOIN file_access_override o ON o.project_id = f.project_id AND o.path = f.path
634
+ 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(ab(this.db.prepare(this.fileSelect("f.project_id = ? ORDER BY f.path ASC")),[a])):this.mapFileRows(ab(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path LIKE ? ESCAPE '\\' ORDER BY f.path ASC")),[a,`${S(b)}/%`]))}fetchProjectFilesSearch(a,b){let c=U(b);return this.mapFileRows(ab(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(ab(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(ab(this.db.prepare(this.fileSelect("f.project_id = ? AND f.path = ?")),[a,b]))[0]??null}}class bY{constructor(a){this.db=a}readPolicies(){return Promise.resolve(ah(ab(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:ad(a.enabled),customKeywords:c})}))}seedDefaults(){if(af(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)
635
+ VALUES (:id, 'global', :target, :action, 1, :now, :now)`);Y(this.db,()=>{for(let[b,c]of Object.entries(j.unw))a.run({id:(0,F.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)
636
+ VALUES (:id, 'global', :target, :action, 1, :now, :now)
637
+ ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`).run({id:(0,F.randomUUID)(),target:JSON.stringify({category:a}),action:b,now:c})}capCategoryActions(){return Number(this.db.prepare(`UPDATE policies SET action='warn', updated_at=:now
638
+ WHERE scope='global' AND action IN ('block','redact')
639
+ 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 bZ{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
640
+ (id, project_id, path, name, origin, default_access, findings_count, blocked_at, note, created_at, updated_at)
641
+ VALUES
642
+ (:id, :projectId, :path, :name, :origin, :defaultAccess, 0, NULL, NULL, :now, :now)
643
+ ON CONFLICT (project_id, path) DO UPDATE SET
644
+ name = excluded.name,
645
+ origin = excluded.origin,
646
+ default_access = excluded.default_access,
647
+ 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,(ac(this.maxStampStmt,{projectId:a})?.maxStamp??0)+1);for(let c of b.files)this.upsertStmt.run({id:(0,F.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 b_{constructor(a,b=()=>Date.now(),c=()=>(0,F.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)
648
+ VALUES (:id, :findingKey, :status, :method, :resolvedAt, :evidence, :createdAt)`),this.latestStmt=a.prepare(`SELECT status, method, resolved_at, evidence
649
+ FROM finding_resolution
650
+ WHERE finding_key = :findingKey
651
+ ORDER BY created_at DESC, rowid DESC
652
+ LIMIT 1`),this.openAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
653
+ FROM inspection_findings f
654
+ JOIN audit_events e ON e.id = f.audit_event_id
655
+ WHERE e.event_type = 'code_change'
656
+ AND json_extract(e.attributes, '$.file_path') = :path
657
+ AND f.finding_key IS NOT NULL
658
+ AND ${a9("f")} IS NOT 'resolved'`),this.resolvedAtRestStmt=a.prepare(`SELECT DISTINCT f.finding_key AS finding_key
659
+ FROM inspection_findings f
660
+ JOIN audit_events e ON e.id = f.audit_event_id
661
+ WHERE e.event_type = 'code_change'
662
+ AND json_extract(e.attributes, '$.file_path') = :path
663
+ AND f.finding_key IS NOT NULL
664
+ AND ${a9("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=ac(this.latestStmt,{findingKey:a});if(b)return{status:b.status,method:b.method,resolvedAt:b.resolved_at,evidence:b.evidence??""}}openAtRestKeysForPath(a){return ab(this.openAtRestStmt,{path:a}).map(a=>a.finding_key)}resolvedAtRestKeysForPath(a){return ab(this.resolvedAtRestStmt,{path:a}).map(a=>a.finding_key)}}class b0{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO rule_probe_cache (rule_key, verdict, worst_probe_ms, checked_at)
665
+ VALUES (:ruleKey, :verdict, :worstProbeMs, :checkedAt)
666
+ ON CONFLICT (rule_key) DO UPDATE SET
667
+ verdict = excluded.verdict,
668
+ worst_probe_ms = excluded.worst_probe_ms,
669
+ 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 ac(this.readStmt,{ruleKey:a})}countQuarantined(){return ac(this.countQuarantinedStmt,{})?.n??0}clearQuarantined(){let a=this.countQuarantined();return{refused:!Y(this.db,()=>{this.clearQuarantinedStmt.run()}),cleared:a-this.countQuarantined()}}setVerdict(a,b,c){Y(this.db,()=>{this.upsertStmt.run({ruleKey:a,verdict:b,worstProbeMs:c,checkedAt:Date.now()})})}}class b1{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
670
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
671
+ ON CONFLICT (path) DO UPDATE SET
672
+ mtime = excluded.mtime,
673
+ content_hash = excluded.content_hash,
674
+ ruleset_hash = excluded.ruleset_hash,
675
+ scanned_at = excluded.scanned_at`),this.readStmt=a.prepare(`SELECT path, mtime, content_hash AS contentHash
676
+ FROM scan_ledger WHERE ruleset_hash = :rulesetHash`)}entriesForRuleset(a){return new Map(ab(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();Y(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 b2(a,b){return void 0===a?b:Math.min(Math.max(1,Math.trunc(a)),j.u8Q)}let b3=`(v.occurrence_count > 1
677
+ OR (SELECT count(*) FROM secret_vault_sighting s WHERE s.pointer_id = v.pointer_id) > 1)`,b4=`v.pointer_id, v.category, v.rule_id, v.masked_match, v.provider,
678
+ v.occurrence_count, v.first_seen, v.last_seen`,b5=`
679
+ pointer_id AS pointerId,
680
+ value_fingerprint AS valueFingerprint,
681
+ fingerprint_key_version AS fingerprintKeyVersion,
682
+ key_version AS keyVersion,
683
+ format_version AS formatVersion,
684
+ category,
685
+ rule_id AS ruleId,
686
+ masked_match AS maskedMatch,
687
+ provider,
688
+ ciphertext,
689
+ nonce,
690
+ auth_tag AS authTag,
691
+ user_authorized AS userAuthorized,
692
+ occurrence_count AS occurrenceCount,
693
+ first_seen AS firstSeen,
694
+ last_seen AS lastSeen`;function b6(a){let{provider:b,userAuthorized:c,...d}=a,e={...d,userAuthorized:0!==c};return null===b?e:{...e,provider:b}}class b7{constructor(a){this.db=a,this.insertStmt=a.prepare(`INSERT INTO secret_vault (
695
+ pointer_id, value_fingerprint, fingerprint_key_version, key_version,
696
+ format_version, category, rule_id, masked_match, provider,
697
+ ciphertext, nonce, auth_tag,
698
+ user_authorized, occurrence_count, first_seen, last_seen
699
+ ) VALUES (
700
+ :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
701
+ :formatVersion, :category, :ruleId, :maskedMatch, :provider,
702
+ :ciphertext, :nonce, :authTag,
703
+ :userAuthorized, 1, :now, :now
704
+ )`),this.bumpStmt=a.prepare(`UPDATE secret_vault
705
+ SET occurrence_count = occurrence_count + 1, last_seen = :now,
706
+ user_authorized = max(user_authorized, :userAuthorized)
707
+ WHERE value_fingerprint = :valueFingerprint`),this.byPointerStmt=a.prepare(`SELECT ${b5} FROM secret_vault WHERE pointer_id = :pointerId`),this.byFingerprintStmt=a.prepare(`SELECT ${b5} FROM secret_vault WHERE value_fingerprint = :valueFingerprint`),this.listStmt=a.prepare(`SELECT ${b5} FROM secret_vault ORDER BY first_seen`),this.replaceCiphertextStmt=a.prepare(`UPDATE secret_vault
708
+ SET key_version = :keyVersion, ciphertext = :ciphertext, nonce = :nonce, auth_tag = :authTag
709
+ WHERE pointer_id = :pointerId`),this.refreshFingerprintStmt=a.prepare(`UPDATE secret_vault
710
+ SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
711
+ 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)
712
+ VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`)}upsert(a,b){let c=!1;X(this.db,()=>{if(void 0===ac(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint})){this.insertStmt.run(ae({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=ac(this.byFingerprintStmt,{valueFingerprint:a.valueFingerprint});if(void 0===d)throw Error("vault: row vanished immediately after write");return{row:b6(d),minted:c}}byPointerId(a){let b=ac(this.byPointerStmt,{pointerId:a});return void 0===b?null:b6(b)}byValueFingerprint(a){let b=ac(this.byFingerprintStmt,{valueFingerprint:a});return void 0===b?null:b6(b)}recordDeref(a){this.derefStmt.run(ae({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 ab(this.listStmt).map(b6)}replaceCiphertext(a,b){this.replaceCiphertextStmt.run({pointerId:a,...b})}refreshFingerprint(a,b){this.refreshFingerprintStmt.run({pointerId:a,...b})}purgeAll(){let a=0;return X(this.db,()=>{a=this.countEntries(),this.db.exec("DELETE FROM secret_vault")},"IMMEDIATE"),a}deleteByPointerIds(a){if(0===a.length)return[];let b=[];return X(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)
713
+ VALUES (:id, :pointerId, :location, :kind, :now, :now)
714
+ ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`).run({id:(0,F.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 ab(this.db.prepare(`SELECT pointer_id, location, kind, first_seen, last_seen
715
+ FROM secret_vault_sighting
716
+ WHERE pointer_id IN (${T(a.length)})
717
+ 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=b2(a.limit,j.mBk),d=void 0===a.cursor?null:aC(a.cursor),e=null===d?"":"WHERE (v.last_seen < :cursorLastSeen OR (v.last_seen = :cursorLastSeen AND v.pointer_id < :cursorPointerId))",f=ab(this.db.prepare(`SELECT ${b4},
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 ${a6}
723
+ LIMIT 1) AS grant_id
724
+ FROM secret_vault v
725
+ ${e}
726
+ ORDER BY v.last_seen DESC, v.pointer_id DESC
727
+ LIMIT :limit`),ae({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?aB({startedAtMs:i.last_seen,id:i.pointer_id}):null}}listReuse(a={},b=Date.now()){var c;let d=b2(a.limit,j.mBk),e=void 0===a.cursor?null:function(a){let b=aA(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
728
+ OR (v.occurrence_count = :cursorOccurrences AND v.pointer_id < :cursorPointerId))`,g=ab(this.db.prepare(`SELECT ${b4},
729
+ (SELECT e.id FROM exceptions e
730
+ WHERE e.rule_id = v.rule_id
731
+ AND e.value_fingerprint = v.value_fingerprint
732
+ AND e.key_version = v.fingerprint_key_version
733
+ AND ${a6}
734
+ LIMIT 1) AS grant_id
735
+ FROM secret_vault v
736
+ WHERE ${b3} ${f}
737
+ ORDER BY v.occurrence_count DESC, v.pointer_id DESC
738
+ LIMIT :limit`),ae({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=b2(a.limit,j.hdu),c=void 0===a.cursor?null:aC(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=ab(this.db.prepare(`SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
739
+ FROM secret_vault_deref ${e}
740
+ ORDER BY at DESC, id DESC LIMIT :limit`),ae({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:af(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?aB({startedAtMs:i.at,id:i.id}):null,hiddenBatched:k}}countEntries(){return af(this.db,"SELECT COUNT(*) AS n FROM secret_vault")}countReused(){return af(this.db,`SELECT COUNT(*) AS n FROM secret_vault v WHERE ${b3}`)}}let b8=["critical","high","medium","low"],b9={block:"blocked",redact:"redacted",warn:"warned"},ca=["blocked","redacted","warned"],cb={[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}},cc={"7d":"day","30d":"day","3m":"week","6m":"week"};function cd(a){return 864e5*Math.floor(a/864e5)}function ce(a){return new Date(a).toISOString().slice(0,10)}class cf{constructor(a,b=()=>Date.now()){this.db=a,this.now=b}severitySummary(){let a=new Map(ab(this.db.prepare(`SELECT d.severity AS severity,
741
+ COUNT(*) AS count,
742
+ SUM(CASE
743
+ WHEN e.event_type != 'code_change' THEN 1
744
+ WHEN f.finding_key IS NULL THEN 0
745
+ WHEN latest.status = 'resolved' THEN 1
746
+ ELSE 0
747
+ END) AS caught,
748
+ SUM(CASE
749
+ WHEN e.event_type = 'code_change'
750
+ AND f.finding_key IS NOT NULL
751
+ AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
752
+ ELSE 0
753
+ END) AS open_at_rest
754
+ FROM inspection_findings f
755
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
756
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
757
+ LEFT JOIN ${ba} latest
758
+ ON latest.finding_key = f.finding_key
759
+ WHERE e.event_type IN (${j.hfB})
760
+ GROUP BY d.severity`)).map(a=>[a.severity,a])),b=b8.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,...cb[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=b9[a.actionTaken];b&&(a.occurredAt>=d?f[b]++:g[b]++)}let h=ca.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=cc[a],c=("day"===b?1:7)*864e5,d=j.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),g=cd(f)-(d-1)*864e5,h=this.findingsInRange(g,f),i=Array.from({length:e},(a,b)=>({timestamp:ce(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=cc[a],c=("day"===b?1:7)*864e5,d=j.eI7[a],e="day"===b?d:Math.ceil(d/7),f=this.now(),g=cd(f)-(d-1)*864e5,h=ab(this.db.prepare(`SELECT DISTINCT f.finding_key AS finding_key,
761
+ COALESCE(f.first_detected_at, e.started_at) AS first_detected_at, d.severity AS severity,
762
+ latest.status AS latest_status,
763
+ latest.method AS latest_method,
764
+ latest.resolved_at AS latest_resolved_at
765
+ FROM finding_resolution fr
766
+ CROSS JOIN inspection_findings f ON f.finding_key = fr.finding_key
767
+ CROSS JOIN audit_events e ON e.id = f.audit_event_id
768
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
769
+ LEFT JOIN ${ba} latest
770
+ ON latest.finding_key = f.finding_key
771
+ WHERE fr.resolved_at >= :windowStart
772
+ 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 b8){let c=`${String(b)}:${a}`,e=k.get(c)??0;d[a]=e>0?(i.get(c)??0)/e:null}return{timestamp:ce(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:ab(this.db.prepare(`SELECT e.repo AS repo, count(*) AS c
773
+ FROM inspection_findings f
774
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
775
+ WHERE e.started_at >= :from AND e.started_at < :to
776
+ AND e.event_type IN (${j.hfB})
777
+ AND e.repo IS NOT NULL
778
+ AND e.repo != ''
779
+ GROUP BY e.repo
780
+ ORDER BY c DESC, e.repo
781
+ 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:ab(this.db.prepare(`SELECT f.finding_key AS finding_key,
782
+ d.rule_id AS rule_id,
783
+ d.severity AS severity,
784
+ e.repo AS repo,
785
+ e.file_path AS path,
786
+ COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
787
+ latest.resolved_at AS latest_resolved_at
788
+ FROM ${ba} latest
789
+ CROSS JOIN inspection_findings f ON f.finding_key = latest.finding_key
790
+ CROSS JOIN audit_events e ON e.id = f.audit_event_id
791
+ CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
792
+ WHERE latest.status = 'resolved'
793
+ AND latest.method = 'fixed-at-source'
794
+ AND latest.resolved_at IS NOT NULL
795
+ AND e.event_type = 'code_change'
796
+ ORDER BY latest.resolved_at DESC
797
+ 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(ab(this.db.prepare(`SELECT d.rule_id AS rule_id,
798
+ d.category AS category,
799
+ d.severity AS severity,
800
+ COUNT(*) AS count
801
+ FROM inspection_findings f
802
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
803
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
804
+ LEFT JOIN ${ba} latest
805
+ ON latest.finding_key = f.finding_key
806
+ WHERE e.event_type IN (${j.hfB})
807
+ AND e.event_type = 'code_change'
808
+ AND (
809
+ f.finding_key IS NULL
810
+ OR latest.status IS NULL
811
+ OR latest.status NOT IN ('resolved', 'dismissed')
812
+ )
813
+ 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 ab(this.db.prepare(`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
814
+ d.rule_id AS rule_id, d.category AS category
815
+ FROM inspection_findings f
816
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
817
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
818
+ WHERE e.started_at >= :from AND e.started_at < :to
819
+ AND e.event_type IN (${j.hfB})
820
+ 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 cg=["provider","internal","external","ip"],ch="('http', 'ws')",ci=`LEFT JOIN egress_decision_override oh ON oh.host = d.host
821
+ LEFT JOIN egress_decision_override ol ON ol.destination_id = d.id AND ol.host IS NULL`;function cj(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 ck(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 cl(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 cm(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:az(a.networkJson,null),endpoints:b.map(cl)}}class cn{constructor(a){this.db=a}stats(){let a=af(this.db,"SELECT count(*) AS n FROM share_destination"),b=af(this.db,"SELECT count(*) AS n FROM share_endpoint"),c=af(this.db,"SELECT count(*) AS n FROM share_call_site"),d=af(this.db,`SELECT count(DISTINCT destination_id) AS n FROM share_endpoint
822
+ WHERE transport IN ${ch}`),e=af(this.db,`SELECT count(DISTINCT d.id) AS n
823
+ FROM share_destination d
824
+ LEFT JOIN share_endpoint e ON e.destination_id = d.id
825
+ AND e.transport IN ${ch}
826
+ WHERE (d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL)
827
+ AND NOT EXISTS (
828
+ SELECT 1 FROM egress_decision_override o
829
+ WHERE o.host = d.host OR (o.destination_id = d.id AND o.host IS NULL)
830
+ )`),f=ag(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=ag(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=>cm(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:cg.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:cm(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:az(a.networkJson,null),note:a.note,endpoints:b.map(a=>({...cl(a),sites:f.get(a.id)??[]}))}}(b,c,d))}setEgressDecision(a,b){let c=!1;return X(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
831
+ 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
832
+ (id, destination_id, host, decision, created_at, updated_at)
833
+ VALUES (:id, :destinationId, :host, :decision, :now, :now)`).run({id:(0,F.randomUUID)(),destinationId:a,host:d.host,decision:b,now:Date.now()}))},"IMMEDIATE"),c}recordProjectEgress(a){let{hits:b,droppedFiles:c,truncated:d}=cj(a.hits,a.reconcile.mode),e=ck(a.reconcile,c),f=Date.now(),g={destinations:0,endpoints:0,callSites:0,truncated:d,droppedFiles:c};return X(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
834
+ WHERE project_key = :key
835
+ AND (:prefix = '' OR file = :prefix OR file LIKE :subtree ESCAPE '\\')
836
+ AND file NOT LIKE '.%'
837
+ AND file NOT LIKE '%/.%'`).run({key:a,prefix:c,subtree:`${S(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
838
+ WHERE project_key = ? AND file IN (${T(d.length)})`).run(a,...d)}}upsertHits(a,b,c,d){if(0===b.length)return;let e=this.db.prepare(`INSERT INTO share_destination
839
+ (id, kind, name, host, category, trust, network_json, last_seen, provenance,
840
+ created_at, updated_at)
841
+ VALUES (:id, :kind, :name, :host, :category, :trust, :networkJson, :now, 'scan', :now, :now)
842
+ ON CONFLICT (host) DO UPDATE SET
843
+ kind = excluded.kind,
844
+ name = excluded.name,
845
+ category = excluded.category,
846
+ trust = excluded.trust,
847
+ network_json = excluded.network_json,
848
+ last_seen = excluded.last_seen,
849
+ updated_at = excluded.updated_at`),f=this.db.prepare("SELECT id FROM share_destination WHERE host = ?"),g=this.db.prepare(`INSERT INTO share_endpoint
850
+ (id, destination_id, method, transport, url, template, data_class, last_seen,
851
+ created_at, updated_at)
852
+ VALUES (:id, :destinationId, :method, :transport, :url, :template, :dataClass, :now,
853
+ :now, :now)
854
+ ON CONFLICT (destination_id, method, url) DO UPDATE SET
855
+ transport = excluded.transport,
856
+ template = excluded.template,
857
+ data_class = excluded.data_class,
858
+ last_seen = excluded.last_seen,
859
+ 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
860
+ (id, endpoint_id, project, project_key, file, line, snippet, dynamic, vendored,
861
+ project_id, created_at, updated_at)
862
+ VALUES (:id, :endpointId, :project, :projectKey, :file, :line, :snippet, :dynamic,
863
+ :vendored, :projectId, :now, :now)
864
+ ON CONFLICT (endpoint_id, project_key, file, line) DO UPDATE SET
865
+ snippet = excluded.snippet,
866
+ dynamic = excluded.dynamic,
867
+ vendored = excluded.vendored,
868
+ project = excluded.project,
869
+ project_id = COALESCE(excluded.project_id, share_call_site.project_id),
870
+ 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,F.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=ac(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,F.randomUUID)(),destinationId:b,method:l.method,transport:l.transport,url:l.url,template:+!!l.template,dataClass:l.dataClass,now:d}),n=ac(h,[b,l.method,l.url])?.id??"",k.set(m,n)),i.run({id:(0,F.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 ac(this.db.prepare(`SELECT project_id AS projectId FROM share_call_site
871
+ 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
872
+ 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
873
+ WHERE id IN (SELECT DISTINCT e.destination_id
874
+ FROM share_endpoint e
875
+ JOIN share_call_site c ON c.endpoint_id = e.id
876
+ WHERE c.project_key = :key)`).run({now:b,key:a})}pruneOrphans(){this.db.exec(`DELETE FROM share_endpoint
877
+ 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
878
+ WHERE host IS NULL
879
+ AND destination_id IN (
880
+ SELECT d.id FROM share_destination d
881
+ WHERE NOT EXISTS (SELECT 1 FROM share_endpoint e WHERE e.destination_id = d.id))`),this.db.exec(`DELETE FROM share_destination
882
+ WHERE NOT EXISTS (
883
+ SELECT 1 FROM share_endpoint e WHERE e.destination_id = share_destination.id)`)}projectTotals(a){return{destinations:af(this.db,`SELECT count(DISTINCT e.destination_id) AS n
884
+ FROM share_endpoint e
885
+ JOIN share_call_site c ON c.endpoint_id = e.id
886
+ WHERE c.project_key = ?`,[a]),endpoints:af(this.db,"SELECT count(DISTINCT endpoint_id) AS n FROM share_call_site WHERE project_key = ?",[a]),callSites:af(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,
887
+ d.network_json AS networkJson, d.last_seen AS lastSeenMs,
888
+ d.created_at AS createdAt,
889
+ COALESCE(oh.decision, ol.decision) AS overrideDecision`,f=[],g=[];if(b&&b.length>0&&(f.push(`d.kind IN (${T(b.length)})`),g.push(...b)),c&&f.push(`(d.trust IN ('unverified', 'ip')
890
+ OR EXISTS (SELECT 1 FROM share_endpoint re
891
+ WHERE re.destination_id = d.id
892
+ AND re.transport IN ${ch}))`),a){let b=U(a);f.push(`(d.name LIKE ? ESCAPE '\\' OR d.category LIKE ? ESCAPE '\\' OR e.url LIKE ? ESCAPE '\\'
893
+ OR c.project LIKE ? ESCAPE '\\' OR c.file LIKE ? ESCAPE '\\')`),g.push(b,b,b,b,b),d=`SELECT DISTINCT ${e}
894
+ FROM share_destination d
895
+ ${ci}
896
+ LEFT JOIN share_endpoint e ON e.destination_id = d.id
897
+ LEFT JOIN share_call_site c ON c.endpoint_id = e.id
898
+ ${f.length?`WHERE ${f.join(" AND ")}`:""}
899
+ ORDER BY d.created_at ASC, d.id ASC`}else d=`SELECT ${e}
900
+ FROM share_destination d
901
+ ${ci}
902
+ ${f.length?`WHERE ${f.join(" AND ")}`:""}
903
+ ORDER BY d.created_at ASC, d.id ASC`;return ab(this.db.prepare(d),g).map(a=>this.mapDestRow(a))}fetchDestinationById(a){let b=ac(this.db.prepare(`SELECT d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
904
+ d.network_json AS networkJson, d.last_seen AS lastSeenMs,
905
+ COALESCE(oh.decision, ol.decision) AS overrideDecision
906
+ FROM share_destination d
907
+ ${ci}
908
+ WHERE d.id = ?`),[a]);return b?this.mapDestRow(b):null}fetchEndpoints(a){return 0===a.length?[]:ab(this.db.prepare(`SELECT e.id, e.destination_id AS destinationId, e.method, e.transport, e.url,
909
+ e.template, e.data_class AS dataClass, e.last_seen AS lastSeenMs,
910
+ count(c.id) AS callSiteCount
911
+ FROM share_endpoint e
912
+ LEFT JOIN share_call_site c ON c.endpoint_id = e.id
913
+ WHERE e.destination_id IN (${T(a.length)})
914
+ GROUP BY e.id
915
+ 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?[]:ab(this.db.prepare(`SELECT id, endpoint_id AS endpointId, project, file, line, snippet, dynamic, vendored,
916
+ project_id AS projectId
917
+ FROM share_call_site
918
+ WHERE endpoint_id IN (${T(a.length)})
919
+ 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 co{constructor(a){this.db=a,this.upsertStmt=a.prepare(`INSERT INTO source_project
920
+ (id, url, name, attributes, first_seen, last_seen)
921
+ VALUES
922
+ (:id, :url, :name, :attributes, :firstSeen, :lastSeen)
923
+ ON CONFLICT(id) DO UPDATE SET
924
+ url = excluded.url,
925
+ name = excluded.name,
926
+ attributes = excluded.attributes,
927
+ last_seen = excluded.last_seen`)}upsert(a,b=Date.now()){let c=I(a.url),d=(0,j.QCA)(a,c,b);return this.upsertStmt.run(ae({id:d.id,url:d.url,name:d.name,attributes:d.attributes,firstSeen:d.firstSeen,lastSeen:d.lastSeen})),c}findById(a){return ac(this.db.prepare("SELECT * FROM source_project WHERE id = :id"),{id:a})}distinctNames(){return ab(this.db.prepare(`SELECT DISTINCT name FROM source_project
928
+ WHERE name IS NOT NULL
929
+ ORDER BY name`)).map(a=>a.name)}}let cp=new Set(j.ZYZ.options),cq=Symbol("aka.persistence.unsafeTestOnlyRawHandle");function cr(a,b){return b?{...a,hostId:b}:a}function cs(a){try{a.close()}catch{}}function ct(a){let b=new G.DatabaseSync(a);try{b.exec("PRAGMA journal_mode = WAL"),b.exec("PRAGMA busy_timeout = 2000"),b.exec("PRAGMA foreign_keys = ON"),b.function("aka_lower",{deterministic:!0,directOnly:!0,useBigIntArguments:!0},R)}catch(a){throw cs(b),a}return b}let cu=new Set(j.vog);function cv(a,b={}){p(a);let c=(0,e.join)(a,l);O(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:G,captureStatus:L,classifiedData:M,inspectionDefinitions:N,inspectionFindings:Q,configInventory:R}=function(a,b,c){let e=ct(a);try{var f;if(f=e,$(f,"table","tenants")||aa(f,"events").includes("tenant_id")){let b=function(a,b){let c;O(b);let e=K(b,"legacy"),f=!1;try{P(a,e),f=!0}catch(a){c=a}finally{a.close()}if(!f){Z(`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=ct(a),Z(`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===av)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?aa(a,b.table,{includeGenerated:!0}).includes(b.name):$(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(at).join(", ")} while missing ${a.map(at).join(", ")} — the schema diverged from the migration history; refusing to replay or skip.`;throw Z(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=au(d.sql);l&&a.exec("PRAGMA foreign_keys = OFF");try{X(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(_(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(!$(a,"table",b))return;let d=aa(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")||X(a,()=>{a.exec(`ALTER TABLE ${b} ADD COLUMN sync_failure text`),a.exec(`UPDATE ${b} SET synced_at = NULL
930
+ WHERE synced_at = -1
931
+ AND event_type IN (${am.map(a=>`'${a}'`).join(", ")})`)},"IMMEDIATE"),a.exec(`CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
932
+ BEFORE UPDATE OF sync_failure ON ${b}
933
+ WHEN ${function(a="sync_failure"){let b=as.map(a=>`'${a}'`).join(", ");return`NEW.${a} IS NOT NULL AND NEW.${a} NOT IN (${b})`}()}
934
+ 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",_(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
935
+ ON audit_events (${e.join(", ")})`)),a.exec(`CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
936
+ 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
937
+ 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 (
938
+ path TEXT PRIMARY KEY,
939
+ mtime TEXT NOT NULL,
940
+ content_hash TEXT NOT NULL,
941
+ ruleset_hash TEXT NOT NULL,
942
+ scanned_at INTEGER NOT NULL
943
+ )`),(d=a).exec(`CREATE TABLE IF NOT EXISTS history_sync (
944
+ id INTEGER PRIMARY KEY CHECK (id = 1),
945
+ endpoint_fingerprint TEXT,
946
+ backlog_before INTEGER,
947
+ owner_pid INTEGER,
948
+ owner_host TEXT,
949
+ acquired_at INTEGER,
950
+ heartbeat_at INTEGER
951
+ )`),aa(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 (
952
+ reference TEXT PRIMARY KEY,
953
+ rule_id TEXT NOT NULL,
954
+ category TEXT NOT NULL,
955
+ value_fingerprint TEXT NOT NULL,
956
+ key_version INTEGER NOT NULL,
957
+ masked_value TEXT NOT NULL,
958
+ session_id TEXT,
959
+ repo TEXT,
960
+ blocked_at INTEGER NOT NULL
961
+ )`),a.exec(`CREATE TABLE IF NOT EXISTS rule_probe_cache (
962
+ rule_key TEXT PRIMARY KEY,
963
+ verdict TEXT NOT NULL,
964
+ worst_probe_ms REAL NOT NULL,
965
+ checked_at INTEGER NOT NULL
966
+ )`),(e=a).exec(`CREATE TABLE IF NOT EXISTS \`_pack_write_gate\` (
967
+ \`id\` integer PRIMARY KEY NOT NULL,
968
+ \`open\` integer DEFAULT 0 NOT NULL,
969
+ CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)
970
+ )`),e.exec("INSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0)"),$(e,"table","installed_packs")&&e.exec(`CREATE TRIGGER IF NOT EXISTS trg_installed_packs_write_gate
971
+ BEFORE UPDATE OF version, name, rules_json ON installed_packs
972
+ WHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1
973
+ BEGIN SELECT RAISE(IGNORE); END`),function(a){if(!$(a,"table","audit_events"))return;let b=new Set(aa(a,"audit_events",{includeGenerated:!0}));for(let c of ax)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
974
+ FROM source_project
975
+ WHERE url IS NOT NULL AND id NOT LIKE 'sample:%'
976
+ ORDER BY last_seen DESC, id`).all().map(a=>({row:a,canonicalId:I(a.url)})).filter(({row:a,canonicalId:b})=>a.id!==b);if(0===b.length)return;let c=a.prepare(`INSERT INTO source_project (id, url, name, attributes, first_seen, last_seen)
977
+ VALUES (?, ?, ?, ?, ?, ?)
978
+ ON CONFLICT(id) DO UPDATE SET
979
+ first_seen = min(first_seen, excluded.first_seen),
980
+ 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 = ?
981
+ 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 = ?");X(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){Z(`source_project id reconcile failed: ${String(a)}`)}}(a),!g.has(av)&&function(a){try{if(!function(a){let b=a.prepare(`SELECT rowid AS rowid, id, source_tool AS sourceTool, kind, occurred_at AS occurredAt,
982
+ content_hash AS contentHash, content, metadata
983
+ FROM events WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO audit_events
984
+ (id, parent_id, root_session_id, event_type, started_at, content, content_hash, attributes)
985
+ 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 ay(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(ae({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,
986
+ span_start AS spanStart, span_end AS spanEnd, masked_match AS maskedMatch,
987
+ action_taken AS actionTaken, confidence, finding_key AS findingKey,
988
+ first_detected_at AS firstDetectedAt
989
+ FROM findings WHERE rowid > ? ORDER BY rowid LIMIT ?`),c=a.prepare(`INSERT OR IGNORE INTO inspection_definitions
990
+ (id, rule_id, name, category, severity, definition, version)
991
+ VALUES (:id, :ruleId, :name, :category, :severity, :definition, :version)`),d=a.prepare(`INSERT INTO inspection_findings
992
+ (id, audit_event_id, inspection_definition_id, classified_data_id,
993
+ span_start, span_end, masked_match, action_taken, confidence,
994
+ finding_key, first_detected_at)
995
+ VALUES
996
+ (:id, :auditEventId, :inspectionDefinitionId, NULL,
997
+ :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
998
+ :findingKey, :firstDetectedAt)
999
+ ON CONFLICT(id) DO NOTHING
1000
+ ON CONFLICT (finding_key) DO UPDATE SET
1001
+ first_detected_at = CASE
1002
+ WHEN first_detected_at IS NULL THEN excluded.first_detected_at
1003
+ WHEN excluded.first_detected_at IS NULL THEN first_detected_at
1004
+ ELSE min(first_detected_at, excluded.first_detected_at)
1005
+ END`);return ay(a,"findings",b,a=>{let b=new Map;for(let e of a){let a=JSON.stringify([e.ruleId,e.category,e.severity]),f=b.get(a);if(void 0===f){let d=`unmigrated/${e.category}/${e.severity}`;f=J(e.ruleId,d),c.run(ae({id:f,ruleId:e.ruleId,name:e.ruleId,category:e.category,severity:e.severity,definition:"",version:d})),b.set(a,f)}d.run(ae({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 Z(`legacy history backfill failed: ${String(a)}`),!1}}(a)&&function(a,b){let c=j.lFU.find(a=>a.tag===av);if(!c)return;let d=void 0===b?void 0:aw(a);if(void 0!==b&&d?.holdsRows===!0)try{var e=a,f=b;O(f);let c=K(f,"pre-drop");P(e,c)}catch(a){Z(`legacy events/findings backup failed; deferring the drop: ${String(a)}`);return}try{X(a,()=>{if(!a.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(c.tag)){if(void 0!==d&&aw(a).mark!==d.mark)return void Z("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 au(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){Z(`legacy events/findings drop failed; deferring: ${String(a)}`)}}(a,b)}(e,a,{skipTags:c}),s(a);let g=new bY(e),h=new bE(e,b),i={events:new a1(e),findings:new be(e),policies:g,installedPacks:h,scanLedger:new b1(e),historySync:new ar(e),secretVault:new b7(e),exceptions:new a7(e),resolutions:new b_(e),ruleProbeCache:new b0(e),bodyRetention:new aU(e),security:new cf(e),detections:new a0(e),shares:new cn(e),policyCatalog:new bZ(h),inventory:new bF(e),inventoryAssets:new bX(e),projectFiles:new b$(e),activity:new aS(e),sourceProject:new co(e),auditEvents:new aT(e),captureStatus:new aV(e),classifiedData:new aW(e),inspectionDefinitions:new bf(e),inspectionFindings:new bg(e),configInventory:new aY(e)};return g.seedDefaults(),{db:e,...i}}catch(a){throw cs(e),a}}(c,(0,e.dirname)(a),!0===b.applyDeferredMigrations?void 0:cu);function T(a){return function(a,b,c=null){return H((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:G,captureStatus:L,classifiedData:M,inspectionDefinitions:N,inspectionFindings:Q,recordCapture:function(a,b){Y(f,()=>{let c=a.metadata?.sessionId;c&&G.ensureSessionRoot(c,a.occurredAt);let d=T(a);G.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&&Q.isSessionDuplicate(a.ruleId,a.maskedMatch,c)||Q.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=N.upsert((0,j.jTf)(a)),e.set(b,f)),Q.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){Y(f,()=>{n.markSynced([T(a)],b)})},markCaptureOwed:function(a){Y(f,()=>{n.markCaptureOwed(T(a))})},markAuditEventsDelivered:function(a,b){let c=a.filter(a=>!cp.has(a.eventType));0!==c.length&&Y(f,()=>{n.markSynced(c.map(a=>a.id),b)})},ensureInventory:function(a){let b={};return Y(f,()=>{let c=Date.now();a.host&&(b.hostId=A.upsert(a.host,c)),a.harness&&(b.harnessId=A.upsert(cr(a.harness,b.hostId),c)),b.accountId=A.upsert(cr({objectType:"user",identityKey:"local",attributes:{source:"local"}},b.hostId),c),a.project&&(b.sourceProjectId=E.upsert(a.project,c))})?b:{}},recordConfigScan:function(a){Y(f,()=>{let b=(0,j.I8t)(a.scanEvent.startedAt);for(let c of a.items)A.upsert(c,b);G.insertAuditEvent(a.scanEvent);let c=new Map;for(let b of a.definitions??[])c.set(`${b.ruleId}@${b.version}`,N.upsert(b));for(let b of a.findings??[]){let d=c.get(`${b.ruleId}@${b.version}`);d&&Q.insertFinding({id:(0,F.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&&Y(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
1006
+ WHERE id <> :canonicalId
1007
+ AND (${h}url LIKE :pattern ESCAPE '\\' OR url LIKE :patternWin ESCAPE '\\')`).all({canonicalId:a,...c===b?{}:{worktreePosix:g,worktreeWin:g.split("/").join("\\")},pattern:`${S(d)}/.claude/worktrees/%`,patternWin:`${S(d.split("/").join("\\"))}\\\\.claude\\\\worktrees\\\\%`});if(0===i.length)return;X(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:()=>R.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 (
1008
+ EXISTS(SELECT 1 FROM share_destination WHERE provenance = 'sample')
1009
+ OR EXISTS(SELECT 1 FROM audit_events WHERE id LIKE 'sample:activity:%')
1010
+ OR EXISTS(SELECT 1 FROM inventory_asset WHERE provenance = 'sample')
1011
+ ) AS n`).get().n)return;X(a,()=>{a.exec(`DELETE FROM share_call_site WHERE endpoint_id IN (
1012
+ SELECT e.id FROM share_endpoint e
1013
+ JOIN share_destination d ON d.id = e.destination_id
1014
+ WHERE d.provenance = 'sample')`),a.exec(`DELETE FROM egress_decision_override WHERE destination_id IN (
1015
+ SELECT id FROM share_destination WHERE provenance = 'sample')`),a.exec(`DELETE FROM share_endpoint WHERE destination_id IN (
1016
+ 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')
1017
+ 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 (
1018
+ key TEXT PRIMARY KEY,
1019
+ value TEXT NOT NULL
1020
+ )`),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()},[cq]:f}}let cw=/^(?:[^@/]+@)?([^/:]+):(.+)$/,cx=/^[A-Za-z]:[\\/]/,cy=/^file:\/\//i,cz=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i,cA=".git";function cB(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 cC(a){let{hits:b,droppedFiles:c}=cj(a.hits,a.reconcile.mode),d=ck(a.reconcile,c);return{projectKey:function(a){let b=a.startsWith("git:")?`git:${function(a){let b=a.trim();if(cx.test(b)||cy.test(b))return b;let c=cz.exec(b),d=null===c?cw.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(cA)?f.slice(0,-cA.length):f;return""===g?e:`${e}/${g}`}(a.slice(4))}`:a;return(0,F.createHash)("sha256").update(`v2:${b}`,"utf8").digest("hex")}(a.projectKey),project:a.project,reconcile:d,hits:b.map(cB)}}function cD(a){let b=a.filePath.replaceAll("\\","/");return(0,F.createHash)("sha256").update(`${a.ruleId}\0${b}\0${a.valueFingerprint}`).digest("hex")}function cE(a){return(0,e.join)(a,"exception.key")}let cF={exceptions:"key_version",blocked_detections:"key_version",secret_vault:"fingerprint_key_version"};class cG 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 cH(a){let b,c=(0,e.join)(a,l);if(!(0,d.existsSync)(c))return 0;try{(b=new G.DatabaseSync(c,{readOnly:!0})).exec(`PRAGMA busy_timeout = ${String(250)}`);let a=0;for(let[c,d]of Object.entries(cF))try{let e=ac(b.prepare(`SELECT MAX(${d}) AS v FROM ${c}`));a=Math.max(a,e?.v??0)}catch(a){if(1!==a.errcode)throw new cG(a)}return a}catch(a){throw a instanceof cG?a:new cG(a)}finally{b?.close()}}function cI(a){return JSON.stringify({version:a.version,material:a.material.toString("base64")})}function cJ(a){let b;try{b=(0,d.readFileSync)(cE(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 cK(a){let b=cJ(a);return b?(r(cE(a)),b):function(a,b){p(a);let c=cE(a);if(x(c,`${cI(b)}
1021
+ `))return b;let d=cJ(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:cH(a)+1,material:(0,F.randomBytes)(32)})}function cL(a){var b;let c=cJ(a);return b={version:Math.max(c?.version??0,cH(a))+1,material:(0,F.randomBytes)(32)},p(a),u(cE(a),`${cI(b)}
1022
+ `),b}function cM(a,b){return(0,F.createHmac)("sha256",a.material).update(b,"utf8").digest("hex")}function cN(a,b){var c;return(0,j.qEQ)(b,null===(c=a)?{status:"absent"}:{status:"present",version:c.version})}function cO(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=j.QA8.safeParse(c.lastFailure),g=f.success?f.data:null;return{consecutiveFailures:d,openedAtMs:e,lastFailure:g}}catch{return null}}((0,d.readFileSync)((0,e.join)(a,g),"utf8"),b)}catch{return null}}function cP(a,b){let c=a?.openedAtMs??null;return null!==c&&b-c<3e4}function cQ(a,b){if((0,d.existsSync)((0,e.join)(a,l)))try{let c=cv(a);try{c.historySync.markCaptureBacklogOwed(b)}finally{c.close()}}catch{}}let cR="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function cS(a){let b="",c=0,d=0;for(let e of a)for(c=c<<8|e,d+=8;d>=5;)b+=cR.charAt(c>>>d-5&31),d-=5;return d>0&&(b+=cR.charAt(c<<5-d&31)),b}function cT(a){let b=[],c=0,d=0;for(let e of a){let a=cR.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 cU(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 cS(Uint8Array.from(b))}function cV(a){let b=b=>Buffer.from((0,F.hkdfSync)("sha256",a,"aka:vault:v1",b,32));return{enc:b("aka:vault:enc:v1"),sign:b("aka:vault:sign:v1")}}function cW(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 cX(a,b,c,d){let e=(0,F.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 cY(a,b,c){try{let d=(0,F.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 cZ(a,b,c,d){return(0,F.createHmac)("sha256",a).update(cW(b,c,d,j.viY)).digest().subarray(0,10)}function c$(a,b,c,d,e){if(10!==e.length)return!1;let f=cZ(a,b,c,d);return(0,F.timingSafeEqual)(f,Buffer.from(e))}var c_=c(31421);let c0={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 c1 extends Error{constructor(a){super(`vault: key epoch ${String(a)} is not present in the keyring`),this.name="VaultKeyEpochMissingError",this.version=a}}let c2="vault.key",c3="aka-vault",c4="keyring";function c5(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 c6(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 c7(){return{current:1,keys:new Map([[1,(0,F.randomBytes)(32)]])}}function c8(a){let b=Math.max(...a.keys.keys())+1,c=new Map(a.keys);return c.set(b,(0,F.randomBytes)(32)),{current:b,keys:c}}function c9(a){let b=a.keys.get(a.current);if(!b)throw new c1(a.current);return{material:b,version:a.current}}function da(a,b){let c=a.keys.get(b);if(!c)throw new c1(b);return{material:c,version:b}}function db(a){try{return Promise.resolve(a())}catch(a){return Promise.reject(a instanceof Error?a:Error(String(a)))}}function dc(a){return a instanceof Error?a:Error(String(a))}let dd="owner",de="vault: a key rotation is already in progress";function df(a,b){try{o(a),n(a)}catch(a){if("EEXIST"===a.code)return!1;throw dc(a)}try{return(0,d.writeFileSync)((0,e.join)(a,dd),`${b}
1023
+ `,{mode:384}),!0}catch(b){throw(0,d.rmSync)(a,{recursive:!0,force:!0}),dc(b)}}function dg(a,b){p(a);let c=function(a){let b,c=(0,e.join)(a,`${c2}.lock`),f=(0,F.randomBytes)(16).toString("hex");if(df(c,f))return{lock:c,owner:f};try{b=(0,d.statSync)(c)}catch{throw Error(de)}if(Date.now()-b.mtimeMs<6e4)throw Error(de);let g=`${c}.stale.${f}`;try{let a=(0,d.statSync)(c);if(a.ino!==b.ino||a.mtimeMs!==b.mtimeMs)throw Error(de);(0,d.renameSync)(c,g)}catch(a){if(a instanceof Error&&a.message===de)throw a;throw Error(de,{cause:a})}if((0,d.rmSync)(g,{recursive:!0,force:!0}),!df(c,f))throw Error(de);return{lock:c,owner:f}}(a);try{return b()}finally{!function(a){try{if((0,d.readFileSync)((0,e.join)(a.lock,dd),"utf8").trim()!==a.owner)return}catch{return}(0,d.rmSync)(a.lock,{recursive:!0,force:!0})}(c)}}class dh{#a;constructor(a){this.#a=a}get filePath(){return(0,e.join)(this.#a,c2)}loadOrCreate(){return db(()=>{let a=this.#b();return a?(di(this.filePath),c9(a)):c9(this.#c())})}rotate(){return db(()=>dg(this.#a,()=>{let a=this.#b();return a?c9(this.#d(c8(a))):c9(this.#c())}))}materialFor(a){return db(()=>{let b=this.#b();if(!b)throw new c1(a);return da(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 c5(a)}#c(){p(this.#a);let a=c7();if(x(this.filePath,`${c6(a)}
1024
+ `))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} — ${c0[a.kind]}`,a.cause)}return di(this.filePath),b}#d(a){return p(this.#a),u(this.filePath,`${c6(a)}
1025
+ `),a}}function di(a){try{(0,d.chmodSync)(a,384)}catch{}}let dj=(a,b)=>(0,c_.execFileSync)("/usr/bin/security",a,{encoding:"utf8",input:b,timeout:5e3,stdio:[void 0===b?"ignore":"pipe","pipe","ignore"]});function dk(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 dl(a,b,c){let d=["add-generic-password",...b?["-U"]:[],"-s",c3,"-a",c4,"-X",Buffer.from(c6(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(" ")}
1026
+ `}class dm{#a;#e;#f;#g;constructor(a,b=dj,c){if(b===dj&&"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 db(()=>{let a=this.#b();return a?c9(a):c9(this.#h(c7()))})}rotate(){return db(()=>dg(this.#a,()=>{let a=this.#b();return a?c9(this.#i(c8(a))):c9(this.#h(c7()))}))}materialFor(a){return db(()=>{let b=this.#b();if(!b)throw new c1(a);return da(b,a)})}#b(){let a;try{a=this.#e(["find-generic-password","-s",c3,"-a",c4,"-w",...this.#g])}catch(a){if(44===a.status)return null;throw Error(`vault: keychain read failed (${dk(a)}); refusing to treat the failure as an absent keyring`)}let b=a.trim();if(0===b.length)return null;try{return c5(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=dl(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 (${dk(b)})`)}return a}#i(a){let b=dl(a,!0,this.#f);try{this.#e(["-i"],b)}catch(a){throw Error(`vault: keychain write failed (${dk(a)})`)}return a}}function dn(a,b){return"keychain"===a?new dm(b):new dh(b)}let dp=Symbol("aka.vault.consentAbsent"),dq=Symbol("aka.vault.unavailable");function dr(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=cT(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=cT(f),c=cT(g);if(cU(a)!==e||cS(b)!==f||cS(c)!==g)return null;return{category:d,keyVersion:a,pointerId:b,tag:c}}catch{return null}}class ds{#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 dp;let d=c(),e=cM(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=cV(h),l=(0,F.randomBytes)(16),m=cW(i,l,b.category,j.viY),n=cX(k.enc,a,m,(0,F.randomBytes)(12)),{row:o}=this.#j.upsert({pointerId:cS(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=dr(a);if(!e)return dq;try{let a=await this.#k.materialFor(e.keyVersion);c=cV(a.material).sign}catch{return dq}if(!c$(c,e.keyVersion,e.pointerId,e.category,e.tag))return dq;let f=cS(e.pointerId),g=this.#j.byPointerId(f);if(!g)return this.#p(f,b,"unavailable"),dq;if(g.category!==e.category)return dq;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"),dq;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"),dq}try{let a=await this.#k.materialFor(g.keyVersion);d=cY(cV(a.material).enc,{ciphertext:Buffer.from(g.ciphertext,"base64"),nonce:Buffer.from(g.nonce,"base64"),authTag:Buffer.from(g.authTag,"base64")},cW(g.keyVersion,e.pointerId,g.category,g.formatVersion))}catch{d=null}return null===d?(this.#p(f,b,"unavailable"),dq):(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"),dq;let d=await this.#q(c);return null===d?(this.#p(a,{target:"human",reason:b.reason},"unavailable"),dq):(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=cV(a.material).enc,c=0;for(let d of this.#j.listAll()){let e;if(d.keyVersion===a.version)continue;let f=cT(d.pointerId);try{let a=await this.#k.materialFor(d.keyVersion);e=cY(cV(a.material).enc,{ciphertext:Buffer.from(d.ciphertext,"base64"),nonce:Buffer.from(d.nonce,"base64"),authTag:Buffer.from(d.authTag,"base64")},cW(d.keyVersion,f,d.category,d.formatVersion))}catch{e=null}if(null===e)continue;let g=cX(b,e,cW(a.version,f,d.category,d.formatVersion),(0,F.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:cM(a,d),fingerprintKeyVersion:a.version}),b+=1}catch{continue}return b}purgeVault(){let a=this.#j.purgeAll();return this.#j.recordDeref({id:(0,F.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=cT(b),f=cV((await this.#k.materialFor(a)).material).sign;return d=cZ(f,a,e,c),`[[aka:${c}:${cU(a)}.${cS(e)}.${cS(d)}]]`}async #q(a){try{let b=await this.#k.materialFor(a.keyVersion);return cY(cV(b.material).enc,{ciphertext:Buffer.from(a.ciphertext,"base64"),nonce:Buffer.from(a.nonce,"base64"),authTag:Buffer.from(a.authTag,"base64")},cW(a.keyVersion,cT(a.pointerId),a.category,a.formatVersion))}catch{return null}}async #r(a){let b=dr(a);if(!b)return null;try{let a=await this.#k.materialFor(b.keyVersion),c=cV(a.material).sign;if(!c$(c,b.keyVersion,b.pointerId,b.category,b.tag))return null}catch{return null}let c=this.#j.byPointerId(cS(b.pointerId));return c?.category!==b.category?null:c}#p(a,b,c){this.#j.recordDeref({id:(0,F.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:()=>am,leE:()=>bR,hxQ:()=>be,Itg:()=>a2,Nh0:()=>cZ,QcD:()=>cY,qeh:()=>fy,yi_:()=>bS,t8P:()=>b4,RRF:()=>dM,ZpU:()=>dZ,fDu:()=>eH,HUb:()=>dG,hfB:()=>cO,oz:()=>f_,Rf1:()=>f$,QA8:()=>b8,unw:()=>dY,p$t:()=>aL,IYX:()=>aF,b2L:()=>aI,Jr:()=>d$,hdu:()=>ei,mBk:()=>eh,vog:()=>d,gbA:()=>aj,V8B:()=>cU,B0R:()=>ci,CPm:()=>cg,IgC:()=>dK,aIg:()=>bB,BZd:()=>b2,ZYZ:()=>cN,iRC:()=>cV,GCf:()=>ar,agn:()=>c$,tLs:()=>ad,xIP:()=>et,TUN:()=>ae,SHn:()=>bk,rov:()=>ex,kg1:()=>b3,V0H:()=>dF,mzG:()=>aJ,OXN:()=>aM,VEg:()=>aG,OVs:()=>em,LsM:()=>ek,bm0:()=>el,WRR:()=>eX,u8Q:()=>ej,kxf:()=>es,ZXz:()=>e$,MhX:()=>e_,viY:()=>d2,XZo:()=>d5,NtJ:()=>b7,jUf:()=>d7,PEm:()=>dE,vap:()=>dI,KqW:()=>fm,eI7:()=>e3,lBn:()=>b0,qhM:()=>b_,suk:()=>dH,cqq:()=>av,PUD:()=>aY,eYL:()=>c_,JJC:()=>c0,jON:()=>cw,Zdp:()=>af,lFU:()=>e,N3u:()=>fx,PhW:()=>a0,AJV:()=>as,BIx:()=>bg,DzG:()=>ep,NFD:()=>eo,Fz0:()=>eC,AKh:()=>ah,hd_:()=>eI,_5V:()=>dv,tXp:()=>dh,plk:()=>cM,Ple:()=>db,Fnc:()=>fO,ryv:()=>aa,fhc:()=>dO,tTV:()=>a_,qmP:()=>eU,_6W:()=>dj,hml:()=>dw,rG:()=>dl,F$B:()=>eM,Bfj:()=>dg,fj8:()=>ds,q_t:()=>$,i1j:()=>eJ,xHz:()=>c3,xog:()=>da,hzO:()=>fQ,by7:()=>fP,Gw9:()=>fM,ZoN:()=>dx,q11:()=>W,U7X:()=>ak,JB8:()=>c9,GVg:()=>f0,T2I:()=>dS,lgf:()=>eL,kqf:()=>ec,y_0:()=>fN,EL9:()=>eB,qEQ:()=>cW,DLF:()=>ez,lGs:()=>bV,hds:()=>er,dnP:()=>eG,I8t:()=>V,am1:()=>dp,SSj:()=>du,Vgn:()=>bW,K7s:()=>c1,Pv3:()=>fZ,jwX:()=>d6,TdZ:()=>dX,DhA:()=>d_,WSs:()=>fT,a45:()=>cK,N6N:()=>g,X0p:()=>dk,pnU:()=>cL,Lq6:()=>dT,V9M:()=>eP,$w9:()=>eT,jTf:()=>eV,$BP:()=>eQ,JAl:()=>eR,$3l:()=>eS,MgS:()=>dt,gzP:()=>eN,QCA:()=>eO,C05:()=>fR,AaX:()=>bU,GWi:()=>dU,Yc8:()=>eK});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","chatgpt","claude-ai"]);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",AiTcSdk:"ai-tc-sdk"},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",AiTcSdk:"ai-tc-sdk"},ag=h.k5(af).meta({id:"SourceTool"}),ah=ag.extract(["ChatGpt","ClaudeAi"]),ai={[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,[af.AiTcSdk]:ad.AiTcSdk},aj=h.k5(["pii","financial","secret","phi","code_context","code_flaw","custom","config"]).meta({id:"DetectionCategory"}),ak=h.k5(["critical","high","medium","low"]).meta({id:"Severity"}),al=h.k5(["warn","redact","block","allow","log"]).meta({id:"ActionTaken"}),am=al.options,an=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:aj,severity:ak,span:an,maskedMatch:h.Yj(),actionTaken:al,confidence:h.ai().min(0).max(1)}).meta({id:"Finding"}).meta({id:"DetectedFinding"});let ao=h.k5(["blocked","redacted","warned","allowed","quarantined","monitored"]).meta({id:"FindingAction"}),ap=ae.extract(["ClaudeCode","ClaudeDesktop","Cursor","Copilot","ChatGpt","ClaudeAi","Codex","Antigravity","Api","AiTcSdk"]).meta({id:"FindingProvider"}),aq=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 ar=h.k5(["open","handled","resolved","dismissed"]).meta({id:"FindingStatus"}),as=h.k5(["deployment_refused","payload_invalid","detached_undelivered"]).meta({id:"SyncFailureReason"}),at=h.k5(["sent","queued","not_sent","never_offered","local_scan"]).meta({id:"FindingDeliveryState"}),au=h.Ik({state:at,at:ab.w$().optional(),reason:as.optional()}).meta({id:"FindingDelivery"}),av=h.k5(["enforced-in-flight","fixed-at-source","exception","acknowledged","false-positive","redetected"]).meta({id:"ResolutionMethod"}),aw=h.Ik({maskedValue:h.Yj(),contextPrefix:h.Yj()}).meta({id:"FindingMatch"}),ax=h.Ik({id:h.Yj(),name:h.Yj().nullable()}).meta({id:"FindingDetectionRef"}),ay=h.Ik({id:h.Yj(),name:h.Yj()}).meta({id:"FindingPolicyRef"}),az=h.Ik({id:h.Yj(),name:h.Yj()}).meta({id:"FindingUser"}),aA=h.Ik({id:h.Yj(),provider:ap,repo:h.Yj(),file:h.Yj(),user:az.optional(),toolName:h.Yj().optional(),action:ao,detectedAt:ab.w$(),confidence:h.ai().min(0).max(1),status:ar.optional(),eventId:h.Yj().optional(),sessionId:h.Yj().optional(),delivery:au.optional()}).meta({id:"FindingInstance"}),aB=h.Ik({id:h.Yj(),category:aq,subtype:h.Yj(),severity:ak,match:aw,detection:ax,policy:ay,instanceCount:h.ai().int().nonnegative(),providers:h.YO(ap),aggregateAction:ao.nullable(),latestDetectedAt:ab.w$(),instances:h.YO(aA),status:ar.optional(),users:h.YO(az).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 aC=h.Ik({value:h.Yj(),count:h.ai().int().nonnegative()}).meta({id:"FindingFacetItem"}),aD=h.Ik({severity:h.YO(aC),subtype:h.YO(aC),provider:h.YO(aC),action:h.YO(aC),status:h.YO(aC),tool:h.YO(aC).optional(),deployment:h.YO(aC).optional()}).meta({id:"FindingFacets"}),aE=aB.omit({instances:!0,match:!0}).meta({id:"FindingTypeSummary"}),aF=50,aG=h.Ik({severity:h.YO(ak).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ap).optional(),action:h.YO(ao).optional(),status:h.YO(ar).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:aD,items:h.YO(aE),nextCursor:h.Yj().nullable(),sessionFirings:h.g1(h.Yj(),h.ai().int().nonnegative()).optional()}).meta({id:"ListFindingTypesResponse"}),h.Ik({action:ao.exclude(["quarantined"]),instanceId:h.Yj().optional()}).meta({id:"ApplyFindingActionRequest"}),aB.meta({id:"ApplyFindingActionResponse"}),h.Ik({severity:h.YO(ak).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ap).optional(),action:h.YO(ao).optional(),q:h.Yj().optional(),format:h.k5(["csv","json"]).optional()});let aH=aA.extend({groupId:h.Yj(),category:aq,subtype:h.Yj(),severity:ak,match:aw,detection:ax,policy:ay}).meta({id:"FindingInstanceDetail"}),aI=50,aJ=h.Ik({severity:h.YO(ak).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ap).optional(),action:h.YO(ao).optional(),status:h.YO(ar).optional(),tool:h.YO(h.Yj()).optional(),deployment:h.YO(at).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:aD,items:h.YO(aH),nextCursor:h.Yj().nullable()}).meta({id:"ListFindingInstancesResponse"}),h.Ik({items:h.YO(aH),nextCursor:h.Yj().nullable()}).meta({id:"ListFindingInstancesPage"});let aK=h.Ik({id:h.Yj(),repo:h.Yj(),file:h.Yj(),instanceCount:h.ai().int().nonnegative(),maxSeverity:ak,latestDetectedAt:ab.w$(),status:ar.optional(),ruleIds:h.YO(h.Yj())}).meta({id:"FindingLocationSummary"}),aL=50,aM=h.Ik({severity:h.YO(ak).optional(),subtype:h.YO(h.Yj()).optional(),provider:h.YO(ap).optional(),action:h.YO(ao).optional(),status:h.YO(ar).optional(),tool:h.YO(h.Yj()).optional(),deployment:h.YO(at).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:aD,items:h.YO(aK),nextCursor:h.Yj().nullable()}).meta({id:"ListFindingLocationsResponse"});let aN=h.k5(["host","harness","user","skill","hook","mcp_server","config_file"]).meta({id:"InventoryObjectType"}),aO=h.k5(["session","run","tool_call","llm_call","source_lookup","prompt","response","code_change","tool_use","model_refusal","request_decision","config_scan","capture_status"]).meta({id:"AuditEventType"}),aP=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 aQ=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:aQ});let aR=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:al.optional()}).catchall(h.L5());let aS=h.Ik({source_tool:h.Yj().optional(),patched:h.zM().optional(),live:h.zM().optional(),blind:h.zM().optional(),sends_seen_dom:h.ai().int().nonnegative().optional(),exchanges_seen_net:h.ai().int().nonnegative().optional(),parse_failures:h.ai().int().nonnegative().optional(),unparsed_bodies:h.ai().int().nonnegative().optional(),shape_misses:h.YO(h.Yj()).optional(),conversation_endpoints:h.ai().int().nonnegative().optional(),closed:h.zM().optional(),enforcement:h.Yj().optional()}).catchall(h.L5()),aT=h.Ik({ruleId:h.Yj().min(1),ruleName:h.Yj(),ruleVersion:h.Yj().min(1),category:aj,severity:ak,span:an,maskedMatch:h.Yj(),actionTaken:al,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:aR,inspections:h.YO(aT).default([])});let aU=h.Ik({objectType:aN,identityKey:h.Yj().min(1),location:h.Yj().optional(),title:h.Yj().optional(),hostId:h.Yj().optional(),attributes:aP.default({})}).meta({id:"InventoryInput"}),aV=h.Ik({url:h.Yj().min(1),name:h.Yj().optional(),attributes:aP.default({})}).meta({id:"SourceProjectInput"}),aW=h.Ik({id:h.Yj().min(1),eventType:aO,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:ak.optional(),priority:h.Yj().optional(),content:h.Yj().optional(),contentHash:h.Yj().optional(),attributes:aP.optional()}).meta({id:"AuditEventInput"});h.Ik({class:h.Yj().min(1),label:h.Yj().optional(),attributes:aP.optional()});let aX=h.Ik({ruleId:h.Yj().min(1),version:h.Yj().min(1),name:h.Yj(),category:aj,severity:ak,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:an,maskedMatch:h.Yj(),actionTaken:al,confidence:h.ai().min(0).max(1),findingKey:h.Yj().optional(),firstDetectedAt:ab.w$().optional()}),h.Ik({host:aU.optional(),harness:aU.optional(),project:aV.optional()}).meta({id:"InventoryContext"});let aY=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 aZ=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(aZ),totalTokens:h.ai().int().nonnegative(),estimatedCostUsd:h.ai().nullable(),costIsPartial:h.zM()});let a$=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 a_(a){return JSON.stringify(a)}h.Ik({models:h.YO(a$),sessionCount:h.ai().int().nonnegative(),totalTokens:h.ai().int().nonnegative(),estimatedCostUsd:h.ai(),costIsPartial:h.zM()});let a0=h.k5(["active","completed","interrupted","error"]),a1=h.k5(["session","prompt","response","tool","hook","detection","share","permission","commit","error","active"]),a2=h.k5(["detections","shares","inventory"]),a3=h.Ik({id:h.Yj(),occurredAt:ab.w$(),kind:a1,title:h.Yj(),detail:h.Yj(),tool:h.Yj().nullable(),severity:ak.nullable(),link:a2.nullable(),targetId:h.Yj().nullable(),internal:h.zM(),flagged:h.zM(),bodyExpired:h.zM().default(!1)}).meta({id:"ActivityAuditEvent"}),a4=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:a0,turns:h.ai().int().nonnegative(),findings:h.ai().int().nonnegative(),shares:h.ai().int().nonnegative()}).meta({id:"ActivitySessionSummary"});a4.extend({host:h.Yj(),cwd:h.Yj(),models:h.YO(h.Yj()),version:h.Yj(),tokens:aZ,tools:h.g1(h.Yj(),h.ai().int().nonnegative()),files:h.YO(h.Yj()),commits:h.ai().int().nonnegative(),events:h.YO(a3)}).meta({id:"ActivitySession"}),h.Ik({tz:h.Yj().optional()});let a5=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 a6=h.Ik({items:h.YO(a4),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(a3),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:a5,sessions:a6}).meta({id:"ActivityOverviewResponse"});let a7=h.k5(["user","project","local","plugin"]),a8=h.Ik({name:h.Yj().min(1),source:h.Yj().min(1),scope:a7,pluginName:h.Yj().optional(),version:h.Yj().optional(),description:h.Yj().optional(),updatedAt:ab.w$().optional(),location:h.Yj().optional()}),a9=h.Ik({event:h.Yj().min(1),matcher:h.Yj().optional(),command:h.Yj().min(1),timeout:h.ai().optional(),scope:a7,pluginName:h.Yj().optional(),location:h.Yj().optional()}),ba=h.Ik({name:h.Yj().min(1),scope:a7,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()}),bb=h.Ik({name:h.Yj().min(1),path:h.Yj().min(1),scope:a7,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(a8),hooks:h.YO(a9),mcpServers:h.YO(ba),configFiles:h.YO(bb),errors:h.YO(h.Ik({source:h.Yj(),reason:h.Yj()}))});let bc=h.Ik({ruleId:h.Yj().min(1),version:h.Yj().min(1),span:an,maskedMatch:h.Yj(),actionTaken:al,confidence:h.ai().min(0).max(1)});h.Ik({items:h.YO(aU),scanEvent:aW,definitions:h.YO(aX).optional(),findings:h.YO(bc).optional()});let bd=h.k5(["project","skill","mcp","hook","config"]).meta({id:"AssetType"}),be=h.k5(["open","approved","blocked"]).meta({id:"AccessLevel"}),bf=h.k5(["source","public-dep","vendored","config","data","docs","generated"]).meta({id:"Origin"}),bg=h.k5(["known-good","risky","unapproved"]).meta({id:"TrustLevel"}),bh=h.k5(["update","stale","conflict","unknown","change","untracked","risk","findings"]).meta({id:"Flag"}),bi=h.k5(["public","private"]).meta({id:"Visibility"}),bj=h.k5(["block","redact","warn"]).meta({id:"HarnessEventKind"}),bk=ae.extract(["ClaudeCode","Cursor","Codex","Antigravity"]).meta({id:"HarnessId"}),bl=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"}),bm=h.Ik({id:h.Yj(),type:bd,name:h.Yj(),sub:h.Yj(),flags:h.YO(bh),trust:bg.optional()}).meta({id:"AssetSummary"}),bn=h.Ik({id:h.Yj(),name:h.Yj(),repo:h.Yj(),visibility:bi,language:h.Yj(),policyDefault:be,updatedAt:ab.w$(),accessCounts:bl,findingsCount:h.ai().int().nonnegative()}).meta({id:"ProjectSummary"}),bo=h.Ik({type:bd,assets:h.YO(bm)}),bp=h.Ik({id:bk,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(bn),categories:h.YO(bo)}).meta({id:"HarnessSummary"});h.Ik({items:h.YO(bp)}).meta({id:"ListHarnessesResponse"});let bq=h.Ik({type:bd,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(bm)}).meta({id:"AssetGroup"});h.Ik({groups:h.YO(bq)}).meta({id:"ListAssetsResponse"});let br=h.Ik({name:h.Yj(),signature:h.Yj(),description:h.Yj(),write:h.zM(),risk:h.Yj().nullable()}).meta({id:"McpTool"}),bs=h.Ik({id:h.Yj(),title:h.Yj(),note:h.Yj()});bm.extend({description:h.Yj().nullable(),trust:bg.nullable(),meta:h.g1(h.Yj(),h.L5()),finding:bs.nullable(),tools:h.YO(br).optional()}).meta({id:"AssetDetail"}),h.Ik({items:h.YO(bn)}).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 bt=h.Ik({path:h.Yj(),name:h.Yj(),origin:bf,access:be,isCustom:h.zM(),findings:h.ai().int().nonnegative(),blockedAt:ab.w$().nullable().optional(),note:h.Yj().nullable().optional()}).meta({id:"FileSummary"}),bu=h.Ik({name:h.Yj(),path:h.Yj(),accessCounts:bl}).meta({id:"FolderSummary"});h.Ik({project:h.Ik({id:h.Yj(),repo:h.Yj(),visibility:bi}),path:h.Yj(),folders:h.YO(bu).optional(),files:h.YO(bt)}).meta({id:"ProjectTreeResponse"}),bt.extend({project:h.Ik({repo:h.Yj(),visibility:bi,language:h.Yj(),policyDefault:be,updatedAt:ab.w$()}),findingsRefs:h.YO(h.Ik({id:h.Yj(),title:h.Yj()}))}).meta({id:"FileDetail"}),h.Ik({path:h.Yj(),access:be}).meta({id:"SetFileAccessBody"}),h.Ik({file:bt,accessCounts:bl}).meta({id:"SetFileAccessResponse"}),h.Ik({trust:bg}).meta({id:"SetMcpTrustBody"});let bv=h.Ik({kind:bj,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(bv)}).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(bd).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 bw=h.k5(["provider","internal","external","ip"]).meta({id:"DestinationKind"}),bx=h.k5(["https","http","sftp","grpc","smtp","ws","wss"]).meta({id:"Transport"}),by=h.k5(["secrets","pii","customer","source","telemetry","logs","metrics","none"]).meta({id:"DataClass"}),bz=by.options,bA=h.k5(["recognized","internal","unverified","ip"]).meta({id:"ShareTrustLevel"}),bB=h.k5(["allow","block"]).meta({id:"EgressDecision"}),bC=h.k5(["allowed","blocked","review"]).meta({id:"EgressStatus"}),bD=h.k5(["raw_ip","unverified_domain","plaintext_transport"]).meta({id:"ReviewReason"}),bE=h.k5(["GET","POST","PUT","DELETE","SDK","REF"]).meta({id:"HttpMethod"}),bF=h.Ik({needsReview:h.zM(),reasons:h.YO(bD)}).meta({id:"ReviewInfo"}),bG=h.Ik({port:h.ai().int().nullable(),geo:h.Yj().nullable(),ptr:h.Yj().nullable()}).meta({id:"DestinationNetwork"}),bH=h.Ik({id:h.Yj(),method:bE,transport:bx,url:h.Yj(),template:h.zM(),dataClass:by,lastSeen:ab.w$(),callSiteCount:h.ai().int().nonnegative()}).meta({id:"EndpointSummary"}),bI=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"}),bJ=bH.extend({sites:h.YO(bI)}).meta({id:"EndpointWithSites"}),bK=h.Ik({id:h.Yj(),kind:bw,name:h.Yj(),host:h.Yj(),category:h.Yj(),trust:bA,status:bC,isCustom:h.zM(),lastSeen:ab.w$(),endpointCount:h.ai().int().nonnegative(),callSiteCount:h.ai().int().nonnegative(),transports:h.YO(bx),dataClasses:h.YO(by),review:bF,network:bG.nullable(),endpoints:h.YO(bH)}).meta({id:"ShareDestinationSummary"});bK.omit({endpointCount:!0,callSiteCount:!0,endpoints:!0}).extend({note:h.Yj().nullable(),endpoints:h.YO(bJ)}).meta({id:"ShareDestinationDetail"});let bL=h.Ik({id:h.Yj(),kind:bw,name:h.Yj(),host:h.Yj(),trust:bA,status:bC,review:bF,topDataClass:by,callSiteCount:h.ai().int().nonnegative(),lastSeen:ab.w$()}).meta({id:"ReviewDestination"}),bM=h.Ik({kind:bw,total:h.ai().int().nonnegative(),items:h.YO(bK)}).meta({id:"ShareDestinationGroup"});h.Ik({groups:h.YO(bM)}).meta({id:"ListShareDestinationsResponse"}),h.Ik({items:h.YO(bL)}).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:bB.nullable()}).meta({id:"SetEgressDecisionBody"}),h.Ik({destination:bK}).meta({id:"SetEgressDecisionResponse"}),h.Ik({q:h.Yj().optional(),kind:h.YO(bw).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(bw).optional()});let bN=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(by).min(1),sdks:h.jg(bN,h.YO(h.Yj()))}).meta({id:"ProviderRegistryEntry"});let bO=h.Ik({file:h.Yj(),line:h.ai().int().positive(),snippet:h.Yj(),dynamic:h.zM(),vendored:h.zM()}).meta({id:"EgressCallSiteHit"}),bP=h.Ik({host:h.Yj(),kind:bw,name:h.Yj(),category:h.Yj(),trust:bA,network:bG.nullable(),method:bE,transport:bx,url:h.Yj(),template:h.zM(),dataClass:by,site:bO}).meta({id:"ResolvedEgressHit"}),bQ=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:bQ,hits:h.YO(bP)}).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 bR="control-plane-credential.json",bS=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()}),bT=new Set(["localhost","127.0.0.1","::1","[::1]"]);function bU(a){let b;try{b=new URL(a)}catch{return"unparseable"}return""!==b.username||""!==b.password?"userinfo":""!==b.search||""!==b.hash?"query-or-fragment":"https:"===b.protocol||"http:"===b.protocol&&bT.has(b.hostname)?null:"insecure"}function bV(a){return null===bU(a)}function bW(a){try{let b=new URL(a);return`${b.protocol}//${b.host}`}catch{return"(unparseable endpoint)"}}let bX=h.Ik({packId:h.Yj().min(1),version:h.Yj().min(1),enabled:h.zM(),updatedAt:h.Yj().nullable()}).meta({id:"StorePosturePack"}),bY=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"}),bZ=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(bX).max(500),policyCounts:bY,plugin:bZ.optional()}).meta({id:"StorePostureSnapshot"});let b$="capture/",b_=aW.extend({inspections:h.YO(aT).default([])}).refine(a=>a.inspections.every(a=>!a.ruleVersion.startsWith(b$)),{message:`inspections[].ruleVersion must not start with \`${b$}\` — that namespace is reserved for capture definitions the control plane mints itself`,path:["inspections"]}).meta({id:"RecordAuditEventRequest"}),b0=h.Ik({events:h.YO(b_).min(1).max(50)}).meta({id:"RecordAuditEventBatch"}),b1=h.Ik({host:h.Yj(),kind:bw,name:h.Yj(),category:h.Yj(),trust:bA,network:bG.nullable(),method:bE,transport:bx,url:h.Yj(),template:h.zM(),dataClass:by,site:h.Ik({file:h.Yj(),line:h.ai().int().positive(),dynamic:h.zM(),vendored:h.zM()})}).meta({id:"EgressIngestHit"}),b2=h.Ik({projectKey:h.Yj().regex(/^[0-9a-f]{64}$/,"projectKey must be a 64-character lowercase hex digest"),project:h.Yj(),reconcile:bQ,hits:h.YO(b1)}).meta({id:"EgressIngestRequest"}),b3=h.Ik({accepted:h.ai().int().nonnegative(),duplicates:h.ai().int().nonnegative()}),b4=h.Ik({accepted:h.ai().int().nonnegative()}),b5=/^[^\p{Cc}\p{Cf}]*$/u,b6=a=>h.Yj().max(a).regex(b5,"must not contain control characters"),b7=h.Ik({tenantName:b6(200),userEmail:b6(320),role:b6(64),keyKind:b6(64),serverTime:b6(64)});h.Ik({error:h.Ik({code:h.Yj().optional(),message:h.Yj().optional()}).optional()});let b8=h.k5(["unauthorized","forbidden","route-absent","invalid-request","rejected","unreachable"]).extract(["unauthorized","forbidden","unreachable"]);h.Ik({deviceId:b6(128).min(1),hostname:b6(255).min(1),os:b6(64).min(1),cliVersion:b6(64).min(1),label:b6(200).optional()}).meta({id:"AttachDeviceRequest"}),h.Ik({deviceCode:b6(128).min(1)}).meta({id:"AttachTokenRequest"}),h.Ik({deviceCode:b6(128),userCode:b6(32),verificationUri:b6(512),verificationUriComplete:b6(512).optional(),expiresIn:h.ai().int().positive(),interval:h.ai().int().positive()});let b9=h.Ik({status:h.eu("pending")}),ca=h.Ik({status:h.eu("slow_down"),interval:h.ai().int().positive()}),cb=h.Ik({status:h.eu("denied"),message:b6(500).optional()}),cc=h.Ik({status:h.eu("expired")}),cd=h.Ik({status:h.eu("issued"),apiKey:h.Yj().min(1).max(512),endpoint:b6(512),tenantName:b6(200).optional(),userEmail:b6(320).optional()});h.KC([cd,b9,ca,cb,cc,h.Ik({status:b6(64)})]);let ce=h.k5(["shares_rescan"]),cf=h.Ik({id:b6(128).min(1),kind:ce,issuedAt:b6(64).min(1),expiresAt:b6(64).min(1)}).strict(),cg=h.Ik({command:cf.nullable()}),ch=h.k5(["scan_failed","no_projects","expired"]),ci=h.gM("outcome",[h.Ik({outcome:h.eu("reported"),projectsScanned:h.ai().int().nonnegative()}).strict(),h.Ik({outcome:h.eu("failed"),reason:ch,projectsScanned:h.ai().int().nonnegative()}).strict()]),cj=h.Yj().regex(/^[a-z][a-z0-9-]*$/),ck=h.Yj().regex(/^[a-z][a-z0-9-]*$/),cl=h.Yj().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/),cm=h.k5(["labs","user","org"]),cn=h.k5(["keyword","regex"]).meta({id:"MatcherType"});h.k5(["safe","quarantined"]).meta({id:"RuleProbeVerdict"});let co=h.re({type:h.eu("keyword"),keywords:h.YO(h.Yj().min(1)).min(1),caseSensitive:h.zM().default(!1)});function cp(a){return a.replace(/[gy]/g,"")}let cq=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,cp(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}|`,cp(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.`})}),cr=h.gM("type",[co,cq]).meta({id:"Matcher"});cn.options;let cs=h.re({extensions:h.YO(h.Yj().regex(/^\.[A-Za-z0-9]+$/)).min(1)}).meta({id:"AppliesTo"}),ct=h.k5(["entropy","luhn"]).meta({id:"PostValidatorName"}),cu=h.KC([ct,h.re({name:ct,config:h.g1(h.Yj(),h.L5()).optional()})],{error:()=>`not a valid post-validator: use a bare name (${ct.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"}),cv=h.re({categories:h.YO(aj).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 cw=h.re({specVersion:h.eu(1),id:h.Yj().regex(/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/),name:h.Yj(),category:aj,severity:ak,matcher:cr,appliesTo:cs.optional(),postValidators:h.YO(cu).optional(),requiresNearby:cv.optional(),examples:h.YO(h.Yj()).optional()}).meta({id:"Rule"}),cx=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:cx.optional(),license:h.Yj().optional(),sourceUrl:h.OZ().optional()}).meta({id:"PackManifest"});let cy=h.k5(["library","custom"]).meta({id:"OriginEnum"}),cz=h.k5(["all","library","custom","customized","updates"]),cA=h.k5(["new","imported","update"]).meta({id:"LibraryStateEnum"}),cB=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"}),cC=h.Ik({id:h.Yj(),name:h.Yj(),version:cl,enabled:h.zM(),origin:cy,publisher:cj.optional(),publisherKind:cm.optional(),ruleCount:h.ai().int().nonnegative(),namespace:cj,packId:ck,policyId:h.Yj().optional(),latestVersion:cl.optional()}).meta({id:"DetectionListItem"});h.Ik({counts:cB,items:h.YO(cC)}).meta({id:"ListDetectionsResponse"}),h.Ik({filter:cz.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 cD=h.Ik({id:h.Yj(),name:h.Yj(),category:aj,severity:ak,matcher:cr,appliesTo:cs.optional(),postValidators:h.YO(cu).optional(),requiresNearby:cv.optional(),examples:h.YO(h.Yj()).optional()}).meta({id:"DetectionRule"}),cE=h.Ik({available:h.zM(),latestVersion:cl,latestRuleCount:h.ai().int().nonnegative().optional()}).nullable().meta({id:"DetectionUpdate"});h.Ik({id:h.Yj(),name:h.Yj(),version:cl,enabled:h.zM(),origin:cy,publisher:cj.optional(),publisherKind:cm.optional(),ruleCount:h.ai().int().nonnegative(),namespace:cj,packId:ck,description:h.Yj().optional(),editedAt:ab.w$(),findingsLast30d:h.ai().int().nonnegative(),latestVersion:cl.nullable().optional(),update:cE,rules:h.YO(cD),modified:h.zM(),policyId:h.Yj().optional()}).meta({id:"DetectionDetail"});let cF=h.Ik({id:h.Yj(),name:h.Yj(),publisher:cj,publisherKind:cm.optional(),category:aj.optional(),version:cl,ruleCount:h.ai().int().nonnegative(),description:h.Yj().optional(),updatedAt:ab.w$(),state:cA,importedAs:h.Yj().nullable()}).meta({id:"LibraryItem"});function cG(a,b,c){return void 0!==c&&b.success&&void 0!==b.data?{[a]:b.data}:{}}h.Ik({categories:h.YO(aj),items:h.YO(cF)}).meta({id:"ListLibraryResponse"}),h.Ik({libraryId:h.Yj().refine(a=>/^[^/]+\/[^/]+$/.test(a),{message:"libraryId must be in namespace/packId format"})}).meta({id:"ImportDetectionRequest"});let cH={library:!0,custom:!0};function cI(a){return null!=a&&Object.hasOwn(cH,a)?a:"library"}function cJ(a){return{id:`${a.namespace}/${a.packId}`,name:a.name,version:a.version,enabled:a.enabled,origin:cI(a.origin),namespace:a.namespace,packId:a.packId,ruleCount:a.ruleCount,...null!=a.policyId?{policyId:a.policyId}:{},...null!=a.latestVersion?{latestVersion:a.latestVersion}:{}}}function cK(a,b,c){let d=a.rules.flatMap(a=>{var b;let c=cr.safeParse(a.matcher);return c.success?[{id:a.id,name:a.name,category:a.category,severity:a.severity,matcher:c.data,...cG("appliesTo",cs.safeParse(a.appliesTo),a.appliesTo),...cG("postValidators",cu.array().safeParse(a.postValidators),a.postValidators),...cG("requiresNearby",cv.safeParse(a.requiresNearby),a.requiresNearby),...cG("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:cI(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 cL(a){let b=a.indexOf("/");return b<1||b===a.length-1?null:{namespace:a.slice(0,b),packId:a.slice(b+1)}}function cM(a,b){let c=a.filter(a=>null!=a.latestVersion),d=a=>cI(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(cJ)}}let cN=h.k5(["prompt","response","code_change","tool_use"]).meta({id:"EventKind"}),cO=cN.options.map(a=>`'${a}'`).join(","),cP=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().min(1).optional(),conversationId:h.Yj().optional(),inspectionMs:h.ai().int().nonnegative().optional(),redactDegradedTo:al.optional()}).meta({id:"EventMetadata"}),cQ=h.Ik({id:h.Os(),sourceTool:ag,kind:cN,occurredAt:ab.w$(),contentHash:h.Yj(),content:h.Yj(),metadata:cP.optional()}).meta({id:"Event"}).meta({id:"IngestEvent"});h.Ik({events:h.YO(cQ).min(1).max(100),dedupe:h.eu("content-hash").optional()}).meta({id:"IngestBatch"});let cR=h.k5(["once","temporary","permanent"]),cS=h.Ik({repo:h.Yj().optional(),sourceTool:h.Yj().optional(),provider:h.Yj().optional()}).strict(),cT=h.k5(["suppress","reveal_to_model"]),cU=h.Ik({id:h.Os(),ruleId:h.Yj(),category:aj,valueFingerprint:h.Yj().regex(/^[0-9a-f]{64}$/),keyVersion:h.ai().int().positive(),maskedValue:h.Yj(),capability:cT.default("suppress"),scope:cR,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:cS.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()}),cV=cU.pick({id:!0,ruleId:!0,valueFingerprint:!0,keyVersion:!0,capability:!0,expiresAt:!0,maxUses:!0,useCount:!0,conditions:!0});function cW(a,b){return"present"===b.status&&b.version===a}cU.omit({valueFingerprint:!0});let cX=h.Yj().optional(),cY=h.Ik({reference:h.Yj(),scope:h.Yj(),reason:h.Yj(),confirmation:cX}),cZ=h.Ik({ruleId:h.Yj(),value:h.Yj(),scope:h.Yj(),reason:h.Yj(),confirmation:cX}),c$=h.Ik({pointer:h.Yj(),scope:h.Yj(),justification:h.Yj(),confirmation:cX}),c_=h.Ik({id:h.Yj(),reason:h.Yj()}),c0=h.Ik({confirmation:h.Yj()});function c1(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 c2=as.options;function c3(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)&&c2.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 c4(a,b){return Object.hasOwn(a,b)?a[b]:void 0}function c5(a){return c4({log:"monitored",block:"blocked",redact:"redacted",warn:"warned",allow:"allowed"},a)??"allowed"}function c6(a){if("code_context"===a)return"source_code";let b=aq.safeParse(a);return b.success?b.data:"custom"}function c7(a){return c4(ai,a)??ad.Api}let c8=["open","handled","dismissed","resolved"];function c9(a){let b=new Set(a.filter(a=>void 0!==a));if(0!==b.size){for(let a of c8)if(b.has(a))return a}}function da(a){return"code_change"!==a.kind?"handled":null===a.findingKey?"open":"resolved"===a.latestResolutionStatus?"resolved":"dismissed"===a.latestResolutionStatus?"dismissed":"open"}function db(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(c7))].sort(),g=new Set(e.actionsTaken.map(c5)),h=1===g.size?[...g][0]??null:null,i=c6(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:c9(e.statusInputs.map(da)),...a.length>0?{users:a}:{}};de.set(j,[...g]),void 0!==e.searchText&&dc.set(j,dd(j,e.searchText)),d.push(j)}return d}let dc=new WeakMap;function dd(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 de=new WeakMap;function df(a){return de.get(a)??[]}function dg(a,b){let c=new Set(b),d=0;for(let b of a){if(void 0===b.count)return null;c.has(da(b))&&(d+=b.count)}return d}function dh(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=>df(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=dc.get(a);if(void 0!==b)return b;let c=dd(a);return dc.set(a,c),c})(b).includes(a))}return c}let di=Object.fromEntries(ak.options.map((a,b)=>[a,b]));function dj(a,b){let c=(c4(di,a.severity)??-1)-(c4(di,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 dk(a){return[...a].sort(dj)}function dl(a,b){let c=dh(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=dh(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=dh(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 df(a))h.set(b,(h.get(b)??0)+1);let i=dh(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=dh(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 dm(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 dn=["severity","subtype","providers","actions","statuses","deliveries","tools","repo","file","q"];function dp(a,b,c){for(let d of dn)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(c7(a.sourceTool));case"actions":return!b.actions?.length||b.actions.includes(c5(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 dq(a){return[...a.entries()].map(([a,b])=>({value:a,count:b})).sort((a,b)=>b.count-a.count||a.value.localeCompare(b.value)||dm(a.value,b.value))}function dr(a,b,c=1){a.set(b,(a.get(b)??0)+c)}function ds(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){dp(i,a,"severity")&&dr(b,i.severity),dp(i,a,"subtype")&&dr(c,i.ruleId),dp(i,a,"providers")&&dr(d,c7(i.sourceTool)),dp(i,a,"actions")&&dr(e,c5(i.actionTaken)),void 0!==i.status&&dp(i,a,"statuses")&&dr(f,i.status),void 0!==i.toolName&&dp(i,a,"tools")&&dr(g,i.toolName),void 0!==i.delivery&&dp(i,a,"deliveries")&&dr(h,i.delivery.state)},facets:()=>({severity:dq(b),subtype:dq(c),provider:dq(d),action:dq(e),status:dq(f),tool:dq(g),deployment:dq(h)})}}function dt(a){let b=c6(a.category);return{id:a.id,provider:c7(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:c5(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 du(){return{instanceCount:0,maxSeverityRank:Number.MAX_SAFE_INTEGER,maxSeverity:"low",latestDetectedAt:"",statuses:[],ruleIds:new Set}}function dv(a,b){a.instanceCount+=1;let c=c4(di,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 dw(a,b){let c=c4(di,a.maxSeverity)??-1,d=c4(di,b.maxSeverity)??-1;if(c!==d)return c-d;if(a.latestDetectedAt!==b.latestDetectedAt)return a.latestDetectedAt<b.latestDetectedAt?1:-1;let e=dm(a.repo,b.repo);return 0!==e?e:dm(a.file,b.file)}function dx(a,b){return`${dy(a)}/${dy(b)}`}function dy(a){return encodeURIComponent(a.replace(/[\uD800-\uDFFF]/gu,"�"))}let dz=h.Ik({id:h.Os(),namespace:cj,packId:ck,version:cl,name:h.Yj(),enabled:h.zM().default(!0),policyId:h.Yj().optional()}).meta({id:"InstalledPack"});h.Ik({namespace:cj,packId:ck,version:cl}).meta({id:"InstallPackRequest"}),h.Ik({items:h.YO(dz)}).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 dA=h.k5(["global","repo","user"]).meta({id:"PolicyScope"}),dB=h.KC([h.Ik({ruleId:h.Yj()}),h.Ik({category:aj})]).meta({id:"PolicyTarget"}),dC=h.k5(["builtin","custom"]).meta({id:"PolicyKind"}),dD=h.k5(["builtin","authored"]).meta({id:"PolicyProvenance"}),dE=h.Ik({id:h.Os(),scope:dA,target:dB,action:al,enabled:h.zM().default(!0),customKeywords:h.YO(h.Yj()).optional(),name:h.Yj().optional(),provenance:dD.optional()}).meta({id:"Policy"}),dF=["monitor","warn","redact","vault","block"],dG=h.k5(dF).meta({id:"BuiltinPolicyId"}),dH=dG.extract(["monitor","warn","block"]).meta({id:"RedactFallback"}),dI=h.Ik({version:h.Yj(),policies:h.YO(dE),rules:h.YO(cw).optional(),rulesComplete:h.zM().optional(),exceptions:h.YO(cV).optional(),reversibleRuleIds:h.YO(h.Yj()).optional(),ruleVersions:h.g1(h.Yj(),h.Yj()).optional(),prohibitedModels:h.YO(h.Yj()).optional(),redactFallback:dH.optional(),customKeywords:h.YO(h.Yj()),fetchedAt:ab.w$()}).meta({id:"PolicyBundle"});[...Object.keys(dI.shape),...Object.keys(dE.shape).map(a=>`policies.${a}`),...dB.options.flatMap(a=>"shape"in a?Object.keys(a.shape):[]).map(a=>`policies.target.${a}`),...Object.keys(cV.shape).map(a=>`exceptions.${a}`)].sort().join(",");let dJ=["config"],dK=aj.options.filter(a=>!dJ.includes(a)),dL={secret:"critical",financial:"critical",code_flaw:"critical",pii:"high",phi:"high",custom:"high",code_context:"low",config:"low"},dM=dF,dN={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 dO(a){return dN[a].action}let dP=[...new Set(dF.map(dO))],dQ=[...am.filter(a=>!dP.includes(a)),...dP];function dR(a){return dQ.indexOf(a)}function dS(a,b){return dR(a)>=dR(b)}function dT(a,b){return dR(a)>=dR(b)?a:b}function dU(a){return dF.find(b=>dS(dO(b),a))??"block"}h.Ik({floor:dG,locked:h.zM()}).describe("PackPolicyFloor");let dV=dF.filter(a=>!dN[a].reversible);dF.filter(a=>dN[a].reversible);let dW=h.k5(dV).meta({id:"CategoryPolicyId"});function dX(a){let b=dG.safeParse(a??d$);return dN[b.success?b.data:d$].reversible}let dY=Object.fromEntries(aj.options.map(a=>[a,dO(function(a){if(dJ.includes(a))return"monitor";let b=dL[a];return"critical"===b||"high"===b?"warn":"monitor"}(a))])),dZ=Object.fromEntries(dF.map(a=>[a,{id:a,...dN[a]}])),d$="monitor";function d_(a){let b=dG.safeParse(a??d$);return dZ[b.success?b.data:d$].action}let d0=h.Ik({id:h.Yj(),name:h.Yj(),ruleCount:h.ai().int().nonnegative(),enabled:h.zM()}).meta({id:"UsedByItem"}),d1=h.Ik({id:h.Yj(),kind:dC,name:h.Yj(),enabled:h.zM(),usedByCount:h.ai().int().nonnegative()}).meta({id:"PolicyListItem"});h.Ik({items:h.YO(d1)}).meta({id:"ListPoliciesResponse"}),h.Ik({specVersion:h.eu(1),id:h.Yj(),kind:dC,name:h.Yj(),enabled:h.zM(),description:h.Yj(),usedBy:h.YO(d0)}).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 d2=2,d3=aj.options.join("|"),d4=RegExp(`\\[\\[aka:(?:${d3}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`),d5=RegExp(`^${d4.source}$`);function d6(){return RegExp(d4.source,"g")}let d7=h.Yj().regex(d5);h.Ik({category:aj,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:aj,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:aj,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 d8=h.k5(["human","model"]),d9=h.k5(["display","explicit-reveal","view-render","model-input","remediation","purge"]),ea=h.k5(["revealed","refused","unavailable"]),eb=["display","view-render"];function ec(a){return eb.includes(a)}let ed=h.Ik({id:h.Os(),pointerId:h.Yj(),at:h.Yj(),target:d8,reason:d9,outcome:ea,grantId:h.Yj().optional(),pointerCount:h.ai().int().positive().default(1)}),ee=h.k5(["prompt","tool-input","tool-output","file","transcript"]),ef=h.Ik({location:h.Yj(),kind:ee,firstSeen:h.Yj(),lastSeen:h.Yj()}),eg=h.Ik({pointerId:h.Yj(),category:aj,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(ef)}),eh=50,ei=50,ej=200,ek=h.Ik({limit:ac.ai().int().min(1).max(ej).optional(),cursor:h.Yj().optional()});h.Ik({totals:h.Ik({values:h.ai().int().nonnegative()}),items:h.YO(eg),nextCursor:h.Yj().nullable()});let el=h.Ik({limit:ac.ai().int().min(1).max(ej).optional(),cursor:h.Yj().optional()});h.Ik({totals:h.Ik({reused:h.ai().int().nonnegative()}),items:h.YO(eg),nextCursor:h.Yj().nullable()});let em=h.Ik({includeBatched:h.zM().optional(),limit:ac.ai().int().min(1).max(ej).optional(),cursor:h.Yj().optional()});h.Ik({items:h.YO(ed),nextCursor:h.Yj().nullable(),hiddenBatched:h.ai().int().nonnegative()});let en=h.Yj(),eo=h.k5(["masked","full","off"]),ep=1,eq=h.Ik({acknowledgedAt:ab.w$(),version:h.ai().int().positive()});function er(a){return a?.version===ep}let es=1,et=3,eu=h.k5(["standalone","attached"]),ev=h.Ik({endpoint:h.Yj().min(1),label:h.Yj().min(1).optional(),attachedAt:ab.w$()}).meta({id:"ControlPlaneConnection"}),ew=h.k5(["redact","warn"]),ex=h.k5(["full","session-only"]),ey=h.Ik({acknowledgedAt:ab.w$(),payloadVersion:h.ai().int().positive()});function ez(a){return a?.payloadVersion===es}let eA=h.Ik({acknowledgedAt:ab.w$(),payloadVersion:h.ai().int().positive(),endpoint:h.Yj()});function eB(a,b){return void 0!==a&&void 0!==b&&a.payloadVersion===et&&a.endpoint===b}let eC=1,eD=h.Ik({acknowledgedAt:ab.w$(),version:h.ai().int().positive()}),eE=h.k5(["with-findings","always","never"]),eF=h.Ik({responses:eE.default("with-findings"),account:h.zM().default(!1),consent:eD.optional()});function eG(a){return a?.version===eC}let eH=h.Ik({enabled:h.zM().default(!1),retainDays:h.ai().int().min(1).max(3650).default(30)}).meta({id:"BodyRetention"}),eI=h.Ik({specVersion:h.ai().int().positive().default(8),runMode:eu.default("standalone"),controlPlane:ev.optional(),policy:ew.default("redact"),historicalAccess:ex.default("session-only"),dataSharesInPlace:h.zM().default(!0),vaultConsent:eq.optional(),vaultKeyCustody:en.default("file"),vaultInlineReveal:eo.default("masked"),redactFallback:dH.default("warn"),onboardedAt:ab.w$().optional(),modelJudgeConsent:ey.optional(),historySyncConsent:eA.optional(),webChatCapture:eF.optional(),bodyRetention:eH.default({enabled:!1,retainDays:30})});function eJ(){return eI.parse({})}function eK(a){return a.webChatCapture??eF.parse({})}function eL(a){return"attached"===a.runMode&&void 0!==a.controlPlane}function eM(a){return a.label??a.endpoint}function eN(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 eO(a,b,c){return{id:b,url:a.url,name:a.name??null,attributes:JSON.stringify(a.attributes),firstSeen:c,lastSeen:c}}function eP(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 eQ(a,b){return{id:b,class:a.class,label:a.label??null,attributes:a.attributes?JSON.stringify(a.attributes):null}}function eR(a,b){return{id:b,ruleId:a.ruleId,name:a.name,category:a.category,severity:a.severity,definition:a.definition,version:a.version}}function eS(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 eT(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&&""!==b.messageId?{message_id:b.messageId}:{},...b?.conversationId!==void 0?{conversation_id:b.conversationId}:{}}}function eU(a){return`capture/${a.category}/${a.severity}`}function eV(a){return{ruleId:a.ruleId,version:eU(a),name:a.ruleId,category:a.category,severity:a.severity,definition:JSON.stringify({ruleId:a.ruleId})}}var eW=c(10539);let eX="managed-settings.json",eY=h.k5(["runMode","historicalAccess","vaultConsent","vaultKeyCustody","vaultInlineReveal","modelJudgeConsent","dataSharesInPlace","redactFallback","bodyRetention"]).meta({id:"ManagedSettingKey"}),eZ=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:dH.optional(),bodyRetention:eH.optional()}).meta({id:"ManagedSettingsValues"}),e$=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)eY.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(eZ.shape,a)?g[a]=c:h.push(a);let i=eZ.safeParse(g);if(!i.success){for(let a of i.error.issues)d.addIssue({...a,path:["values",...a.path]});return eW.tm}return{...c,values:i.data,lockedFields:e,...f.length>0?{unknownLockedFields:f}:{},...h.length>0?{unknownValueFields:h}:{}}}).meta({id:"ManagedSettings"}),e_={present:!1,lockedFields:[]},e0=h.Ik({path:h.Yj().min(1),name:h.Yj().min(1),origin:bf,defaultAccess:be});h.Ik({files:h.YO(e0),truncated:h.zM(),scannedAt:h.Yj()});let e1=["7d","30d","3m","6m"],e2=h.k5(e1).meta({id:"TimeRange"}),e3={"7d":7,"30d":30,"3m":90,"6m":180};e2.catch("7d");let e4=h.k5(["still-valid","unknown","invalid"]),e5=h.Ik({filePath:h.Yj(),span:an.optional()}).strict(),e6=h.Ik({provider:h.Yj(),maskedToken:h.Yj(),where:e5,state:e4,observedAt:ab.w$().optional()}).strict();h.Ik({provider:h.Yj(),maskedToken:h.Yj(),consolePath:h.Yj(),occurrenceSpread:h.ai().int().positive()}).strict();let e7=h.k5(["redact-rotation-checklist","redact-only","set-secret-redact","leave"]),e8=h.k5(["first-run","pre-push","secret-scan"]);h.Ik({entrySource:e8}).strict();let e9=h.Ik({id:e7,label:h.Yj()}),fa=h.Ik({kind:h.eu("decision"),entrySource:e8,secretCount:h.ai().int().positive(),prompt:h.Yj(),options:h.PV([e9.extend({id:h.eu("redact-rotation-checklist")}),e9.extend({id:h.eu("redact-only")}),e9.extend({id:h.eu("set-secret-redact")}),e9.extend({id:h.eu("leave")})])}),fb=h.Ik({kind:h.eu("no-decision")});h.gM("kind",[fa,fb]);let fc=h.Ik({severity:ak,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(fc)}).meta({id:"SeveritySummaryResponse"}),h.Ik({range:h.k5(e1).default("7d")});let fd=h.k5(["blocked","redacted","warned"]).meta({id:"EnforcementActionKind"}),fe=h.Ik({kind:fd,count:h.ai().int().nonnegative(),delta:h.ai().int()}).meta({id:"EnforcementAction"});h.Ik({range:e2,total:h.ai().int().nonnegative(),actions:h.YO(fe)}).meta({id:"EnforcementActionsResponse"});let ff=h.k5(["day","week"]).meta({id:"TimeseriesGranularity"}),fg=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:e2,granularity:ff,points:h.YO(fg)}).meta({id:"FindingsTimeseriesResponse"});let fh=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:e2,granularity:ff,points:h.YO(fh)}).meta({id:"MttrTrendResponse"});let fi=h.Ik({findingKey:h.Yj(),ruleId:h.Yj(),severity:ak,repo:h.Yj().optional(),path:h.Yj(),resolvedAt:ab.w$(),detectedAt:ab.w$()}).meta({id:"ResolvedFeedItem"});h.Ik({items:h.YO(fi)}).meta({id:"RecentlyResolvedResponse"});let fj=["repo","user"],fk=h.k5(fj).meta({id:"SourceKind"}),fl=h.Ik({id:h.Yj(),name:h.Yj(),kind:fk,findingsCount:h.ai().int().nonnegative()}).meta({id:"TopSource"});h.Ik({range:e2,items:h.YO(fl)}).meta({id:"TopSourcesResponse"}),h.Ik({range:h.k5(e1).default("7d"),limit:ac.ai().int().min(1).max(50).default(5),kind:h.k5(fj).optional()});let fm=ae.extract(["ClaudeCode","Cursor","Codex","Antigravity","ClaudeAi","ChatGpt","Copilot","Api"]).meta({id:"Provider"}),fn=h.Ik({provider:fm,coverage:h.ai().int().min(0).max(100),supported:h.zM()}).meta({id:"ScanCoverageProvider"});h.Ik({range:e2,providers:h.YO(fn)}).meta({id:"ScanCoverageResponse"});let fo=h.k5(["repo","user","team","policy","share","rule"]).meta({id:"SubjectType"}),fp=h.Ik({type:fo,id:h.Yj(),label:h.Yj()}).meta({id:"RecommendationSubject"}),fq=h.k5(["apply","navigate"]).meta({id:"RecommendationActionMode"}),fr=h.Ik({mode:fq,type:h.Yj(),label:h.Yj(),href:h.Yj().optional(),policyId:h.Yj().optional(),teamId:h.Yj().optional()}).meta({id:"RecommendationAction"}),fs=h.Ik({id:h.Yj(),category:h.Yj(),severity:ak,title:h.Yj(),description:h.Yj(),subjects:h.YO(fp),action:fr}).meta({id:"RecommendedAction"});h.Ik({items:h.YO(fs)}).meta({id:"RecommendedActionsResponse"}),h.Ik({limit:ac.ai().int().min(1).max(20).default(3)});let ft=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:ft}).meta({id:"ApplyRecommendedActionResponse"}),h.Ik({id:h.Yj(),status:h.eu("dismissed")}).meta({id:"DismissRecommendedActionResponse"}),h.Ik({id:h.Yj()});let fu=h.k5(["granted","revoked","unchanged"]).meta({id:"HistorySyncConsentChoice"}),fv=h.k5(["granted","revoked","unchanged"]).meta({id:"ModelJudgeConsentChoice"}),fw=h.k5(["granted","revoked","unchanged"]).meta({id:"WebChatCaptureConsentChoice"}),fx=h.Ik({historicalAccess:h.Yj(),modelJudgeConsent:fv,historySyncConsent:fu,vaultConsent:h.Yj(),vaultInlineReveal:h.Yj(),webChatCaptureConsent:fw,redactFallback:h.Yj(),bodyRetention:h.Ik({enabled:h.zM(),retainDays:h.ai()})}),fy=h.Ik({endpoint:h.Yj(),label:b6(200).optional(),accessKey:h.Yj()});h.Ik({ruleId:h.Yj(),category:aj,severity:ak,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 fz=h.Ik({category:aj,action:dW,reasoning:h.Yj(),genuineCount:h.ai().int().nonnegative(),fpCount:h.ai().int().nonnegative(),fpIds:h.YO(h.Yj())});h.Ik({perCategory:h.YO(fz),notes:h.Yj()});let fA=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"]}),fB=h.Ik({ruleId:h.Yj(),category:aj,valueFingerprint:h.Yj(),keyVersion:h.ai().int().nonnegative()}),fC=h.Ik({pattern:h.Yj(),count:h.ai().int().nonnegative(),values:h.YO(fB).min(1)}),fD=h.Ik({category:aj,count:h.ai().int().nonnegative(),egress:h.zM()}),fE=h.Ik({counts:fA,routineCategories:h.YO(aj),surfacedCategories:h.YO(aj),findingKinds:h.YO(fD),posture:h.g1(aj,dG),maskedFindings:h.YO(e6).optional(),falsePositivePatterns:h.YO(fC).optional()}),fF=fz.pick({category:!0,genuineCount:!0,fpCount:!0}).extend({egress:h.zM()});h.Ik({categories:h.YO(fF),posture:h.g1(aj,dG)}),h.Ik({frame:fE,copy:h.Yj()}),h.k5(["scan","floor"]);let fG=h.Ik({id:h.k5(["enter-remediation","open-dashboard","not-now"]),label:h.Yj()}),fH=h.PV([fG.extend({id:h.eu("open-dashboard")}),fG.extend({id:h.eu("not-now")})]),fI=h.PV([fG.extend({id:h.eu("enter-remediation")}),fG.extend({id:h.eu("open-dashboard")}),fG.extend({id:h.eu("not-now")})]);h.Ik({worthALook:h.ai().int().nonnegative(),liveKeys:h.ai().int().nonnegative().optional(),options:h.KC([fH,fI])}).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 fJ=new Set(["recognized","internal"]);function fK(a){return fJ.has(a)?"allowed":"review"}function fL(a){return"block"===a?"blocked":"allowed"}function fM(a,b){return null===b?fK(a):fL(b)}function fN(a,b){return null!==b&&fL(b)!==fK(a)}function fO(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 fP(a){return Array.from(new Set(a))}function fQ(a){let b=new Set(a);return bz.filter(a=>b.has(a))}function fR(a){return fQ(a)[0]??"none"}let fS={raw_ip:0,unverified_domain:1,plaintext_transport:2};function fT(a){return 0===a.length?1/0:Math.min(...a.map(a=>fS[a]))}let fU=h.k5(["site","estimated","none"]),fV=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()}),fW=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:fV.optional(),usageSource:fU,stopReason:h.Yj().optional(),conversationId:h.Yj().optional(),turnIndex:h.ai().int().nonnegative().optional(),toolCalls:h.YO(fW).default([]),responseText:h.Yj().optional(),truncated:h.zM().default(!1)});let fX=h.k5(["watching","composer-only","button-only","unattached","unknown"]),fY=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([]),conversationEndpoints:h.ai().int().nonnegative().default(0),closed:h.zM().default(!1),enforcement:fX.default("unknown")});function fZ(a){return a.find(a=>{var b;return!(b=a.status).patched||0===b.conversationEndpoints||b.blind||b.shapeMisses.length>0||b.parseFailures>0||b.unparsedBodies>0||b.exchangesSeenNet>0})??a[0]}let f$=2592e6,f_=30;function f0(a){let b=aS.safeParse(a);if(!b.success)return null;let c=b.data,d=fY.safeParse({patched:c.patched,live:c.live,blind:c.blind,sendsSeenDom:c.sends_seen_dom,exchangesSeenNet:c.exchanges_seen_net,parseFailures:c.parse_failures,unparsedBodies:c.unparsed_bodies,shapeMisses:c.shape_misses,conversationEndpoints:c.conversation_endpoints,closed:c.closed,enforcement:c.enforcement});return d.success?d.data:null}}};