@akasecurity/cli 0.9.11 → 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 (124) hide show
  1. package/dist/cli.js +4334 -2752
  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 +2320 -837
  10. package/native-host/scan-worker.js +441 -30
  11. package/native-host/sync.js +578 -92
  12. package/package.json +7 -7
  13. package/web-ui/web-ui/.next/BUILD_ID +1 -1
  14. package/web-ui/web-ui/.next/app-build-manifest.json +84 -84
  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 +2 -2
  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 -0
  68. package/web-ui/web-ui/.next/server/chunks/130.js +1026 -0
  69. package/web-ui/web-ui/.next/server/chunks/290.js +6 -0
  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/589.js +1 -1
  74. package/web-ui/web-ui/.next/server/chunks/662.js +1 -0
  75. package/web-ui/web-ui/.next/server/chunks/70.js +1 -0
  76. package/web-ui/web-ui/.next/server/chunks/935.js +1 -1
  77. package/web-ui/web-ui/.next/server/functions-config-manifest.json +5 -5
  78. package/web-ui/web-ui/.next/server/middleware-manifest.json +5 -5
  79. package/web-ui/web-ui/.next/server/pages/404.html +1 -1
  80. package/web-ui/web-ui/.next/server/pages/500.html +1 -1
  81. package/web-ui/web-ui/.next/server/server-reference-manifest.js +1 -1
  82. package/web-ui/web-ui/.next/server/server-reference-manifest.json +1 -1
  83. package/web-ui/web-ui/.next/static/chunks/421-cc967c01935826d1.js +1 -0
  84. package/web-ui/web-ui/.next/static/chunks/{526-026c69b926a17dbb.js → 526-f0156de7831566b3.js} +1 -1
  85. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-41fba0354cc950be.js +1 -0
  86. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-d2e03c3ab61af01a.js +1 -0
  87. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-566036afcc87e4c9.js +1 -0
  88. package/web-ui/web-ui/.next/static/chunks/app/(app)/{error-dead9507fc349f26.js → error-4baae46bcee63009.js} +1 -1
  89. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-73dbcf0078b82ec4.js +1 -0
  90. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/{page-0695d0006518b2cb.js → page-8051503193da1baf.js} +1 -1
  91. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-32c8a853bc8b5d34.js +1 -0
  92. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-dc8fadb56d6d1e77.js +1 -0
  93. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-9b49ef42350ea7bd.js +1 -0
  94. package/web-ui/web-ui/.next/static/chunks/app/(app)/{layout-dc7ae7664dcdc3c5.js → layout-f5f361f817f90ac9.js} +1 -1
  95. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-01b303adf3c8ee56.js +1 -0
  96. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-8db3b62245c333a3.js +1 -0
  97. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-7a4ba61626e0d130.js +1 -0
  98. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-0930b49f6ab951bc.js +1 -0
  99. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-9b04f3441a1a3f96.js +1 -0
  100. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/{page-f37ab8e1edc67663.js → page-911a76e75f5a1419.js} +1 -1
  101. package/web-ui/web-ui/.next/static/css/298a651f6af38209.css +2 -0
  102. package/web-ui/web-ui/dist/scan-worker.js +441 -30
  103. package/web-ui/web-ui/.next/server/chunks/471.js +0 -950
  104. package/web-ui/web-ui/.next/server/chunks/7.js +0 -1
  105. package/web-ui/web-ui/.next/server/chunks/739.js +0 -1
  106. package/web-ui/web-ui/.next/server/chunks/766.js +0 -6
  107. package/web-ui/web-ui/.next/server/chunks/851.js +0 -1
  108. package/web-ui/web-ui/.next/server/chunks/905.js +0 -959
  109. package/web-ui/web-ui/.next/static/chunks/907-2ba9428e7818b656.js +0 -1
  110. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-c5a55618d187c906.js +0 -1
  111. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-b1c76b8c00e1ae2a.js +0 -1
  112. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-159167b47a005b33.js +0 -1
  113. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-5e872a82af85ef64.js +0 -1
  114. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-adec99f2f4bbc180.js +0 -1
  115. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-d013384d2ddb3036.js +0 -1
  116. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-42c1b48a01fdecb0.js +0 -1
  117. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-9b6d7cc4ce9fb33e.js +0 -1
  118. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-f3ee9ecde06df153.js +0 -1
  119. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-24a003c709776317.js +0 -1
  120. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-4ea49ce2e765fffb.js +0 -1
  121. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-6c7b94b070de8986.js +0 -1
  122. package/web-ui/web-ui/.next/static/css/c6954dd65f2115e6.css +0 -2
  123. /package/web-ui/web-ui/.next/static/{osEmGZG6yEV-XkQlklt-B → pkVZ1_T311YNkJgZOLTx5}/_buildManifest.js +0 -0
  124. /package/web-ui/web-ui/.next/static/{osEmGZG6yEV-XkQlklt-B → pkVZ1_T311YNkJgZOLTx5}/_ssgManifest.js +0 -0
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,6 +492,7 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/native-host/host.ts
495
+ import { randomUUID as randomUUID20 } from "crypto";
495
496
  import { homedir as homedir3 } from "os";
496
497
 
497
498
  // ../../packages/persistence/src/attached-derived.ts
@@ -505,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
505
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
506
507
  import { join as join2 } from "path";
507
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
508
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
509
518
  var SQLITE_MIGRATIONS = [
510
519
  {
@@ -622,6 +631,30 @@ var SQLITE_MIGRATIONS = [
622
631
  {
623
632
  tag: "0028_activity_session_probe_indexes",
624
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> 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"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ 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');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ 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');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ 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');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ 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');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
625
658
  }
626
659
  ];
627
660
 
@@ -3426,12 +3459,12 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
3426
3459
  });
3427
3460
  var URL_BAD_FORMAT = 1;
3428
3461
  var URL_UNPARSEABLE = 2;
3429
- function parseURLObject(trimmed, def) {
3430
- if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
3462
+ function parseURLObject(trimmed2, def) {
3463
+ if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed2)) {
3431
3464
  return URL_BAD_FORMAT;
3432
3465
  }
3433
3466
  try {
3434
- return new URL(trimmed);
3467
+ return new URL(trimmed2);
3435
3468
  } catch {
3436
3469
  return URL_UNPARSEABLE;
3437
3470
  }
@@ -3452,8 +3485,8 @@ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
3452
3485
  $ZodStringFormat.init(inst, def);
3453
3486
  inst._zod.check = (payload) => {
3454
3487
  try {
3455
- const trimmed = payload.value.trim();
3456
- const url2 = parseURLObject(trimmed, def);
3488
+ const trimmed2 = payload.value.trim();
3489
+ const url2 = parseURLObject(trimmed2, def);
3457
3490
  if (url2 === URL_BAD_FORMAT) {
3458
3491
  payload.issues.push({
3459
3492
  code: "invalid_format",
@@ -3497,7 +3530,7 @@ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
3497
3530
  continue: !def.abort
3498
3531
  });
3499
3532
  }
3500
- payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed);
3533
+ payload.value = def.normalize ? url2.href : stripTabAndNewline(trimmed2);
3501
3534
  return;
3502
3535
  } catch (_) {
3503
3536
  payload.issues.push({
@@ -20449,7 +20482,17 @@ var UNPRICEABLE_PROVIDERS = Object.freeze([
20449
20482
  "gateway",
20450
20483
  "unknown",
20451
20484
  "cli",
20452
- "api"
20485
+ "api",
20486
+ // The browser extension's native host records these as `llm_call.provider`
20487
+ // for a web-chat turn — the web tool id, deliberately never the vendor id
20488
+ // (`openai`/`anthropic`) the session root carries. Subscription traffic
20489
+ // burns rate-limit budget, not dollar credits, and listing them here is
20490
+ // what keeps that true structurally: a later maintainer who wants to price
20491
+ // web-chat traffic at API rates has to delete this entry first, and meet
20492
+ // the reason on the way, rather than quietly adding one to
20493
+ // PROVIDER_PLATFORM.
20494
+ "chatgpt",
20495
+ "claude-ai"
20453
20496
  ]);
20454
20497
  function platformForProvider(provider) {
20455
20498
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
@@ -20592,7 +20635,12 @@ var HARNESS = {
20592
20635
  ClaudeDesktop: "claudedesktop",
20593
20636
  ChatGpt: "chatgpt",
20594
20637
  ClaudeAi: "claudeai",
20595
- Api: "api"
20638
+ Api: "api",
20639
+ // Not a coding assistant a person drives — an in-process SDK embedded in an
20640
+ // application, so it has no IDE/CLI/desktop/web surface of its own. Carries
20641
+ // the same id as its SOURCE_TOOL counterpart, unlike every capture-side tool
20642
+ // whose wire spelling differs from its display spelling.
20643
+ AiTcSdk: "ai-tc-sdk"
20596
20644
  };
20597
20645
  var Harness = external_exports.enum(HARNESS).meta({ id: "Harness" });
20598
20646
  var SOURCE_TOOL = {
@@ -20608,9 +20656,15 @@ var SOURCE_TOOL = {
20608
20656
  // whose tool could not be identified both render through the read side's
20609
20657
  // miss path rather than as a harness of their own.
20610
20658
  Cli: "cli",
20611
- Unknown: "unknown"
20659
+ Unknown: "unknown",
20660
+ // The wire id an in-process, request-path SDK stamps on its own structural
20661
+ // rows (`request_decision`) — never a capture of prompt/response/tool text,
20662
+ // since the SDK sits in front of a model call rather than inside a coding
20663
+ // assistant's own hook contract.
20664
+ AiTcSdk: "ai-tc-sdk"
20612
20665
  };
20613
20666
  var SourceTool = external_exports.enum(SOURCE_TOOL).meta({ id: "SourceTool" });
20667
+ var WebSourceTool = SourceTool.extract(["ChatGpt", "ClaudeAi"]);
20614
20668
  var TOOL_TO_HARNESS = {
20615
20669
  [SOURCE_TOOL.ClaudeCode]: HARNESS.ClaudeCode,
20616
20670
  [SOURCE_TOOL.ClaudeDesktop]: HARNESS.ClaudeDesktop,
@@ -20619,10 +20673,15 @@ var TOOL_TO_HARNESS = {
20619
20673
  [SOURCE_TOOL.ChatGpt]: HARNESS.ChatGpt,
20620
20674
  [SOURCE_TOOL.Codex]: HARNESS.Codex,
20621
20675
  [SOURCE_TOOL.Antigravity]: HARNESS.Antigravity,
20622
- [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20676
+ [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi,
20677
+ // Wire and display id are the same string here, but the row still belongs:
20678
+ // both vocabularies carry the `AiTcSdk` member, and the join is exactly
20679
+ // their intersection — leaving a shared member out would read as an
20680
+ // uninstrumented tool on both surfaces, which this one is not.
20681
+ [SOURCE_TOOL.AiTcSdk]: HARNESS.AiTcSdk
20623
20682
  };
20624
20683
  function harnessFromTool(tool) {
20625
- return TOOL_TO_HARNESS[tool] ?? tool;
20684
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20626
20685
  }
20627
20686
 
20628
20687
  // ../../packages/schema/src/zod/finding.ts
@@ -20656,7 +20715,8 @@ var FindingProvider = Harness.extract([
20656
20715
  "ClaudeAi",
20657
20716
  "Codex",
20658
20717
  "Antigravity",
20659
- "Api"
20718
+ "Api",
20719
+ "AiTcSdk"
20660
20720
  ]).meta({ id: "FindingProvider" });
20661
20721
  var FindingCategory = external_exports.enum([
20662
20722
  "secret",
@@ -20672,6 +20732,15 @@ var FindingCategory = external_exports.enum([
20672
20732
  ]).meta({ id: "FindingCategory" });
20673
20733
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20674
20734
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20735
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20736
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20737
+ var FindingDelivery = external_exports.object({
20738
+ state: FindingDeliveryState,
20739
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20740
+ at: external_exports.iso.datetime().optional(),
20741
+ // Only on `not_sent`, and only when a known reason was recorded.
20742
+ reason: SyncFailureReason.optional()
20743
+ }).meta({ id: "FindingDelivery" });
20675
20744
  var ResolutionMethod = external_exports.enum([
20676
20745
  "enforced-in-flight",
20677
20746
  "fixed-at-source",
@@ -20728,7 +20797,10 @@ var FindingInstance = external_exports.object({
20728
20797
  // The session that event belongs to, when it has one — the seam a
20729
20798
  // per-instance "view session" link needs. Absent for events captured
20730
20799
  // outside a session.
20731
- sessionId: external_exports.string().optional()
20800
+ sessionId: external_exports.string().optional(),
20801
+ // The delivery state of the event above (see FindingDelivery). Optional so
20802
+ // readers that do not project it stay valid.
20803
+ delivery: FindingDelivery.optional()
20732
20804
  }).meta({ id: "FindingInstance" });
20733
20805
  var FindingGroup = external_exports.object({
20734
20806
  id: external_exports.string(),
@@ -20780,7 +20852,10 @@ var FindingFacets = external_exports.object({
20780
20852
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
20853
  // reads, which can filter by it; the type-level read omits the dimension
20782
20854
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20855
+ tool: external_exports.array(FindingFacetItem).optional(),
20856
+ // Delivery states (FindingDeliveryState). Present only on the
20857
+ // instance-level reads, like `tool`.
20858
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20859
  }).meta({ id: "FindingFacets" });
20785
20860
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20786
20861
  id: "FindingTypeSummary"
@@ -20891,6 +20966,8 @@ var ListFindingInstancesQuery = external_exports.object({
20891
20966
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20892
20967
  // where the free-text `q` can only match the rendered "via Bash" label.
20893
20968
  tool: external_exports.array(external_exports.string()).optional(),
20969
+ // The delivery state of each finding's event (see FindingDelivery).
20970
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20894
20971
  // Exact repository / file-path matches, for the drill-down out of the
20895
20972
  // locations view. A row whose event carries no repo/file matches neither.
20896
20973
  repo: external_exports.string().optional(),
@@ -20911,6 +20988,10 @@ var ListFindingInstancesResponse = external_exports.object({
20911
20988
  items: external_exports.array(FindingInstanceDetail),
20912
20989
  nextCursor: external_exports.string().nullable()
20913
20990
  }).meta({ id: "ListFindingInstancesResponse" });
20991
+ var ListFindingInstancesPage = external_exports.object({
20992
+ items: external_exports.array(FindingInstanceDetail),
20993
+ nextCursor: external_exports.string().nullable()
20994
+ }).meta({ id: "ListFindingInstancesPage" });
20914
20995
  var FindingLocationSummary = external_exports.object({
20915
20996
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20916
20997
  // because a location's identity is two values and a URL param carries one:
@@ -20953,6 +21034,8 @@ var ListFindingLocationsQuery = external_exports.object({
20953
21034
  // instances that match, and folds its status from those.
20954
21035
  status: external_exports.array(FindingStatus).optional(),
20955
21036
  tool: external_exports.array(external_exports.string()).optional(),
21037
+ // The delivery state of each finding's event (see FindingDelivery).
21038
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20956
21039
  q: external_exports.string().optional(),
20957
21040
  sessionId: external_exports.string().optional(),
20958
21041
  from: external_exports.iso.datetime().optional(),
@@ -21010,18 +21093,41 @@ var AuditEventType = external_exports.enum([
21010
21093
  // 'tool_call' is the reconciler's structural row for every call, while
21011
21094
  // 'tool_use' exists only where a hook enforced against the arguments.
21012
21095
  "tool_use",
21013
- // One row per model REFUSAL: a switch onto a prohibited model that was
21014
- // denied, or a turn refused because the session was already running on one.
21015
- // A structural row like the ones above rather than a capture — it carries
21016
- // the model that was refused and nothing the user typed, because what is
21017
- // worth recording about a governance decision is the decision, and prompt
21018
- // text is the thing this product exists to keep from travelling.
21096
+ // One row per model REFUSAL, across all four seams a prohibited model can be
21097
+ // stopped at: a switch onto it, a turn already running on it, a subagent
21098
+ // spawn asking for it, or a request-path refusal an embedded request-path
21099
+ // SDK makes in-process before the call leaves the application. Which seam
21100
+ // rides `attributes.refusal_seam`, never this member name. A structural row
21101
+ // like the ones above rather than a capture — it carries the model that was
21102
+ // refused and nothing the user typed, because what is worth recording about
21103
+ // a governance decision is the decision, and prompt text is the thing this
21104
+ // product exists to keep from travelling.
21019
21105
  "model_refusal",
21106
+ // One row per request-path DECISION: a policy check an embedded request-path
21107
+ // SDK performs in-process before a model call leaves the application, or
21108
+ // against that call's non-streamed response. A structural row like
21109
+ // 'model_refusal' rather than a capture — content-free in the same way:
21110
+ // which side, which seam, what action and which field are decided rides
21111
+ // `attributes`, never this member name, and the matched text itself never
21112
+ // travels.
21113
+ //
21114
+ // A prohibited-model refusal on the request path is deliberately NOT this
21115
+ // member: it stays 'model_refusal' with `refusal_seam: 'request'`, so it
21116
+ // shares one bucket with the plugin's switch/turn/spawn refusals rather
21117
+ // than splitting one governance concept across two event types. This
21118
+ // member carries every OTHER request-path decision.
21119
+ "request_decision",
21020
21120
  // One row per config-inventory scan, hung off the session root. It is the
21021
21121
  // fact the posture inspection findings reference (findings require an
21022
21122
  // audit_event_id), and its started_at is the "scanned Nm ago" the read
21023
21123
  // surface renders.
21024
- "config_scan"
21124
+ "config_scan",
21125
+ // One row per reported browser-extension capture status, hung off the web
21126
+ // session root. The durable home of what one tab's network interception
21127
+ // is doing — a write-through of the native host's in-memory tracker, so a
21128
+ // second process (aka extension status) and a restarted host both have
21129
+ // somewhere to read it back from.
21130
+ "capture_status"
21025
21131
  ]).meta({ id: "AuditEventType" });
21026
21132
  var AttributeBag = external_exports.record(external_exports.string(), external_exports.unknown());
21027
21133
  var HostAttributes = external_exports.object({
@@ -21155,6 +21261,10 @@ var CaptureAttributes = external_exports.object({
21155
21261
  // to 'allow' — the enforcement audit trail's link back to the grant that
21156
21262
  // authorized the bypass.
21157
21263
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21264
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21265
+ // join back to the `llm_call` leaf for the same assistant turn.
21266
+ message_id: external_exports.string().optional(),
21267
+ conversation_id: external_exports.string().optional(),
21158
21268
  // Whole milliseconds this capture's inspection blocked its caller — the
21159
21269
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21160
21270
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21163,7 +21273,33 @@ var CaptureAttributes = external_exports.object({
21163
21273
  // inline json_extract and is not itself an optimization.
21164
21274
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21165
21275
  // before the measurement shipped — never present as a placeholder 0.
21166
- inspection_ms: external_exports.number().int().nonnegative().optional()
21276
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21277
+ // What a `redact` this capture could not carry out became instead (see
21278
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21279
+ // degrade actually happened, so absence is the ordinary case rather than a
21280
+ // reader having to distinguish it from a zero.
21281
+ //
21282
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21283
+ // so on a multi-finding row this does not say which finding degraded, and
21284
+ // its presence does not mean the fallback decided the capture's action. A
21285
+ // capture denied by another finding's own Block policy carries `block`
21286
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21287
+ // repeated rather than referenced because a store reader opens this file.
21288
+ redact_degraded_to: ActionTaken.optional()
21289
+ }).catchall(external_exports.unknown());
21290
+ var CaptureStatusAttributes = external_exports.object({
21291
+ source_tool: external_exports.string().optional(),
21292
+ patched: external_exports.boolean().optional(),
21293
+ live: external_exports.boolean().optional(),
21294
+ blind: external_exports.boolean().optional(),
21295
+ sends_seen_dom: external_exports.number().int().nonnegative().optional(),
21296
+ exchanges_seen_net: external_exports.number().int().nonnegative().optional(),
21297
+ parse_failures: external_exports.number().int().nonnegative().optional(),
21298
+ unparsed_bodies: external_exports.number().int().nonnegative().optional(),
21299
+ shape_misses: external_exports.array(external_exports.string()).optional(),
21300
+ conversation_endpoints: external_exports.number().int().nonnegative().optional(),
21301
+ closed: external_exports.boolean().optional(),
21302
+ enforcement: external_exports.string().optional()
21167
21303
  }).catchall(external_exports.unknown());
21168
21304
  var ToolCallInspection = external_exports.object({
21169
21305
  ruleId: external_exports.string().min(1),
@@ -21362,7 +21498,17 @@ var AuditEvent = external_exports.object({
21362
21498
  /** `share` to a first-party/internal destination. */
21363
21499
  internal: external_exports.boolean(),
21364
21500
  /** Event needs review (e.g. unverified egress). */
21365
- flagged: external_exports.boolean()
21501
+ flagged: external_exports.boolean(),
21502
+ /**
21503
+ * The body this event's `title` is drawn from was cleared by local body
21504
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21505
+ *
21506
+ * A separate flag rather than a sentinel written into `title`: the title is
21507
+ * rendered text, and a store-layer module that invented display copy for it
21508
+ * would be choosing words the view is supposed to choose. Additive and
21509
+ * defaulted, so an older producer still validates.
21510
+ */
21511
+ bodyExpired: external_exports.boolean().default(false)
21366
21512
  }).meta({ id: "ActivityAuditEvent" });
21367
21513
  var ActivitySessionSummary = external_exports.object({
21368
21514
  id: external_exports.string(),
@@ -22128,6 +22274,30 @@ var AttachedCredential = external_exports.object({
22128
22274
  keyPrefix: external_exports.string().min(1).max(16).optional(),
22129
22275
  mintedAt: external_exports.iso.datetime().optional()
22130
22276
  });
22277
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
22278
+ function unsafeEndpointReason(endpoint) {
22279
+ let parsed2;
22280
+ try {
22281
+ parsed2 = new URL(endpoint);
22282
+ } catch {
22283
+ return "unparseable";
22284
+ }
22285
+ if (parsed2.username !== "" || parsed2.password !== "") return "userinfo";
22286
+ if (parsed2.search !== "" || parsed2.hash !== "") return "query-or-fragment";
22287
+ if (parsed2.protocol === "https:") return null;
22288
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname) ? null : "insecure";
22289
+ }
22290
+ function isSafeEndpoint(endpoint) {
22291
+ return unsafeEndpointReason(endpoint) === null;
22292
+ }
22293
+ function originOnly(endpoint) {
22294
+ try {
22295
+ const parsed2 = new URL(endpoint);
22296
+ return `${parsed2.protocol}//${parsed2.host}`;
22297
+ } catch {
22298
+ return "(unparseable endpoint)";
22299
+ }
22300
+ }
22131
22301
  var MAX_DATE_MS = 253402300799999;
22132
22302
  var MAX_INT4 = 2147483647;
22133
22303
  var StorePosturePack = external_exports.object({
@@ -22282,6 +22452,11 @@ var RemoteFailureKind = external_exports.enum([
22282
22452
  "rejected",
22283
22453
  "unreachable"
22284
22454
  ]);
22455
+ var ControlPlaneFailure = RemoteFailureKind.extract([
22456
+ "unauthorized",
22457
+ "forbidden",
22458
+ "unreachable"
22459
+ ]);
22285
22460
  var AttachDeviceRequest = external_exports.object({
22286
22461
  // This machine's own continuity id, so re-attaching ROTATES the credential
22287
22462
  // on one machine record instead of producing a second one. Client-minted
@@ -22817,6 +22992,17 @@ var EventMetadata = external_exports.object({
22817
22992
  // to 'allow' — the enforcement audit trail's link back to the grant that
22818
22993
  // authorized the bypass. Absent on captures where no exception applied.
22819
22994
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22995
+ // The assistant message this capture belongs to, and the conversation it sits
22996
+ // in — set by the browser extension's network capture so a stored `response`
22997
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22998
+ // on every other capture path, which has no such id.
22999
+ //
23000
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
23001
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
23002
+ // places an event is PARSED; the local write path types the event and parses
23003
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
23004
+ messageId: external_exports.string().min(1).optional(),
23005
+ conversationId: external_exports.string().optional(),
22820
23006
  // How long THIS capture's inspection blocked its caller, in whole
22821
23007
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22822
23008
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22829,7 +23015,37 @@ var EventMetadata = external_exports.object({
22829
23015
  // Absent is also what every pre-measurement client writes, and what a
22830
23016
  // clock failure degrades to — a reader must treat absence as "not measured"
22831
23017
  // and never as a zero, which would read as "inspection is free".
22832
- inspectionMs: external_exports.number().int().nonnegative().optional()
23018
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
23019
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
23020
+ // workspace's `redactFallback`, applied because the field could not be
23021
+ // masked in place (a shell command, a URL, or any argument on a host whose
23022
+ // hook contract offers no rewrite channel).
23023
+ //
23024
+ // It exists because the action alone cannot say why. A finding recorded as
23025
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
23026
+ // assigned Redact on a field that could not take one — and those are
23027
+ // different facts about the same row: the first is a policy the user chose,
23028
+ // the second is a masking the host could not perform. Absent means no
23029
+ // degrade happened, which is every ordinary capture.
23030
+ //
23031
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
23032
+ // is the CAPTURE while `actionTaken` is per FINDING:
23033
+ //
23034
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
23035
+ // `redact` alongside a finding ASSIGNED the same action stores both
23036
+ // identically and one reason for the pair; attributing it to both
23037
+ // describes the assigned one wrongly, and to neither loses the degrade.
23038
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
23039
+ // became, not the reason the capture ended as it did — a capture denied
23040
+ // by some other finding's own Block policy still carries `block` here,
23041
+ // and clearing the workspace's fallback would not have let it through.
23042
+ // Gate on the value against what a fallback can produce; never read the
23043
+ // field's presence as "this was the fallback's doing".
23044
+ //
23045
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23046
+ // Closing either means moving the reason onto the finding row, which
23047
+ // already carries its own action.
23048
+ redactDegradedTo: ActionTaken.optional()
22833
23049
  }).meta({ id: "EventMetadata" });
22834
23050
  var Event = external_exports.object({
22835
23051
  id: external_exports.guid(),
@@ -22939,7 +23155,32 @@ var RotateKeyInput = external_exports.object({
22939
23155
  confirmation: external_exports.string()
22940
23156
  });
22941
23157
 
23158
+ // ../../packages/schema/src/zod/finding-delivery.ts
23159
+ var KNOWN_REASONS = SyncFailureReason.options;
23160
+ function knownReason(value) {
23161
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23162
+ }
23163
+ function deriveFindingDelivery(row) {
23164
+ if (row.kind === "code_change") return { state: "local_scan" };
23165
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23166
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23167
+ }
23168
+ if (row.syncedAt !== null) {
23169
+ const reason = knownReason(row.syncFailure);
23170
+ return {
23171
+ state: "not_sent",
23172
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23173
+ ...reason === void 0 ? {} : { reason }
23174
+ };
23175
+ }
23176
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23177
+ return { state: "never_offered" };
23178
+ }
23179
+
22942
23180
  // ../../packages/schema/src/zod/findings-group-build.ts
23181
+ function lookupOwn(map2, key) {
23182
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23183
+ }
22943
23184
  function toApiAction(dbVal) {
22944
23185
  const map2 = {
22945
23186
  log: "monitored",
@@ -22948,7 +23189,7 @@ function toApiAction(dbVal) {
22948
23189
  warn: "warned",
22949
23190
  allow: "allowed"
22950
23191
  };
22951
- return map2[dbVal] ?? "allowed";
23192
+ return lookupOwn(map2, dbVal) ?? "allowed";
22952
23193
  }
22953
23194
  function toApiCategory(dbVal) {
22954
23195
  if (dbVal === "code_context") return "source_code";
@@ -22956,13 +23197,18 @@ function toApiCategory(dbVal) {
22956
23197
  return parsed2.success ? parsed2.data : "custom";
22957
23198
  }
22958
23199
  function toApiProvider(sourceTool) {
22959
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23200
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22960
23201
  }
22961
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23202
+ var FINDING_STATUS_PRECEDENCE = [
23203
+ "open",
23204
+ "handled",
23205
+ "dismissed",
23206
+ "resolved"
23207
+ ];
22962
23208
  function foldGroupStatus(instanceStatuses) {
22963
23209
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22964
23210
  if (statuses.size === 0) return void 0;
22965
- for (const candidate of STATUS_PRECEDENCE) {
23211
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22966
23212
  if (statuses.has(candidate)) return candidate;
22967
23213
  }
22968
23214
  return void 0;
@@ -23069,11 +23315,16 @@ function applyFindingFilters(types, opts) {
23069
23315
  }
23070
23316
  return filtered;
23071
23317
  }
23072
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
23073
- var SEVERITY_RANK = SEVERITY_ORDER;
23318
+ function rankByOrder(members2) {
23319
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23320
+ }
23321
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23322
+ function severityRank(severity) {
23323
+ return lookupOwn(SEVERITY_RANK, severity);
23324
+ }
23074
23325
  function compareFindingGroupOrder(a, b) {
23075
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
23076
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23326
+ const rankA = severityRank(a.severity) ?? -1;
23327
+ const rankB = severityRank(b.severity) ?? -1;
23077
23328
  const severityDiff = rankA - rankB;
23078
23329
  if (severityDiff !== 0) return severityDiff;
23079
23330
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23148,6 +23399,20 @@ function computeFindingFacets(allTypes, opts) {
23148
23399
  }
23149
23400
 
23150
23401
  // ../../packages/schema/src/zod/findings-flat-build.ts
23402
+ function compareCodePoints(a, b) {
23403
+ const aIter = a[Symbol.iterator]();
23404
+ const bIter = b[Symbol.iterator]();
23405
+ for (; ; ) {
23406
+ const aNext = aIter.next();
23407
+ const bNext = bIter.next();
23408
+ if (aNext.done && bNext.done) return 0;
23409
+ if (aNext.done) return -1;
23410
+ if (bNext.done) return 1;
23411
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23412
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23413
+ if (aPoint !== bPoint) return aPoint - bPoint;
23414
+ }
23415
+ }
23151
23416
  function rowHaystack(row) {
23152
23417
  return [
23153
23418
  row.ruleId,
@@ -23172,6 +23437,8 @@ function matchesDimension(row, opts, dimension) {
23172
23437
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23173
23438
  case "statuses":
23174
23439
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23440
+ case "deliveries":
23441
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23175
23442
  case "tools":
23176
23443
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23177
23444
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23198,6 +23465,7 @@ var DIMENSIONS = [
23198
23465
  "providers",
23199
23466
  "actions",
23200
23467
  "statuses",
23468
+ "deliveries",
23201
23469
  "tools",
23202
23470
  "repo",
23203
23471
  "file",
@@ -23211,10 +23479,19 @@ function matchesInstanceFilters(row, opts, except) {
23211
23479
  return true;
23212
23480
  }
23213
23481
  function toItems(counts) {
23214
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23482
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23483
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23484
+ // NFD spelling of the same text) as equal, so a count tie between
23485
+ // them would otherwise be ordered by whichever the Map iteration
23486
+ // produced. compareCodePoints breaks that tie deterministically, which
23487
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23488
+ // which it need not: foldFacetTuples runs this same sort over grouped
23489
+ // tuples, so both paths order facets identically by construction.
23490
+ compareCodePoints(a.value, b.value)
23491
+ );
23215
23492
  }
23216
- function bump(counts, value) {
23217
- counts.set(value, (counts.get(value) ?? 0) + 1);
23493
+ function bump(counts, value, by = 1) {
23494
+ counts.set(value, (counts.get(value) ?? 0) + by);
23218
23495
  }
23219
23496
  function createInstanceFacetAccumulator(opts) {
23220
23497
  const severity = /* @__PURE__ */ new Map();
@@ -23223,6 +23500,7 @@ function createInstanceFacetAccumulator(opts) {
23223
23500
  const action = /* @__PURE__ */ new Map();
23224
23501
  const status = /* @__PURE__ */ new Map();
23225
23502
  const tool = /* @__PURE__ */ new Map();
23503
+ const deployment = /* @__PURE__ */ new Map();
23226
23504
  return {
23227
23505
  add(row) {
23228
23506
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23237,6 +23515,9 @@ function createInstanceFacetAccumulator(opts) {
23237
23515
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23238
23516
  bump(tool, row.toolName);
23239
23517
  }
23518
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23519
+ bump(deployment, row.delivery.state);
23520
+ }
23240
23521
  },
23241
23522
  facets: () => ({
23242
23523
  severity: toItems(severity),
@@ -23244,7 +23525,8 @@ function createInstanceFacetAccumulator(opts) {
23244
23525
  provider: toItems(provider),
23245
23526
  action: toItems(action),
23246
23527
  status: toItems(status),
23247
- tool: toItems(tool)
23528
+ tool: toItems(tool),
23529
+ deployment: toItems(deployment)
23248
23530
  })
23249
23531
  };
23250
23532
  }
@@ -23258,6 +23540,7 @@ function toInstanceDetail(row) {
23258
23540
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23259
23541
  eventId: row.eventId,
23260
23542
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23543
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23261
23544
  ...row.user === void 0 ? {} : { user: row.user },
23262
23545
  action: toApiAction(row.actionTaken),
23263
23546
  detectedAt: row.occurredAt,
@@ -23272,12 +23555,6 @@ function toInstanceDetail(row) {
23272
23555
  policy: { id: `category:${category}`, name: category }
23273
23556
  };
23274
23557
  }
23275
- var SEVERITY_ORDER2 = {
23276
- critical: 0,
23277
- high: 1,
23278
- medium: 2,
23279
- low: 3
23280
- };
23281
23558
  function newLocationAccumulator() {
23282
23559
  return {
23283
23560
  instanceCount: 0,
@@ -23292,7 +23569,7 @@ function newLocationAccumulator() {
23292
23569
  }
23293
23570
  function addToLocation(acc, row) {
23294
23571
  acc.instanceCount += 1;
23295
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23572
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23296
23573
  if (rank < acc.maxSeverityRank) {
23297
23574
  acc.maxSeverityRank = rank;
23298
23575
  acc.maxSeverity = row.severity;
@@ -23302,15 +23579,15 @@ function addToLocation(acc, row) {
23302
23579
  acc.ruleIds.add(row.ruleId);
23303
23580
  }
23304
23581
  function compareLocationOrder(a, b) {
23305
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23306
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23582
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23583
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23307
23584
  if (rankA !== rankB) return rankA - rankB;
23308
23585
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23309
23586
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23310
23587
  }
23311
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23312
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23313
- return 0;
23588
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23589
+ if (repoDiff !== 0) return repoDiff;
23590
+ return compareCodePoints(a.file, b.file);
23314
23591
  }
23315
23592
  function encodeLocationId(repo, file2) {
23316
23593
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23385,6 +23662,11 @@ var Policy = external_exports.object({
23385
23662
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23386
23663
  provenance: PolicyProvenance.optional()
23387
23664
  }).meta({ id: "Policy" });
23665
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23666
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23667
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23668
+ id: "RedactFallback"
23669
+ });
23388
23670
  var PolicyBundle = external_exports.object({
23389
23671
  version: external_exports.string(),
23390
23672
  policies: external_exports.array(Policy),
@@ -23432,6 +23714,16 @@ var PolicyBundle = external_exports.object({
23432
23714
  // control plane), so no name resolution stands between the decision and the
23433
23715
  // comparison.
23434
23716
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23717
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23718
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23719
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23720
+ // a control plane can tighten a machine and never loosen one — the same
23721
+ // direction `mergeRaiseOnly` enforces for policies.
23722
+ //
23723
+ // Optional so an older backend, and an older on-disk cache, still parses;
23724
+ // absent leaves the device's own setting in force, which is the behaviour
23725
+ // that predates the field and the safe direction to default.
23726
+ redactFallback: RedactFallback.optional(),
23435
23727
  customKeywords: external_exports.array(external_exports.string()),
23436
23728
  fetchedAt: external_exports.iso.datetime()
23437
23729
  }).meta({ id: "PolicyBundle" });
@@ -23461,11 +23753,6 @@ function severityFloorPolicy(category) {
23461
23753
  const peak = CATEGORY_PEAK_SEVERITY[category];
23462
23754
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23463
23755
  }
23464
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23465
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23466
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23467
- id: "RedactFallback"
23468
- });
23469
23756
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23470
23757
  var BUILTIN_POLICY_SPECS = {
23471
23758
  monitor: {
@@ -23521,6 +23808,11 @@ function isActionAtLeast(action, floor) {
23521
23808
  function strongerAction(a, b) {
23522
23809
  return actionRank(a) >= actionRank(b) ? a : b;
23523
23810
  }
23811
+ function strongerRedactFallback(local, remote) {
23812
+ if (remote === void 0) return local;
23813
+ const localAction = builtinPolicyToAction(local);
23814
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23815
+ }
23524
23816
  function weakestBuiltinAtLeast(floor) {
23525
23817
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23526
23818
  }
@@ -23556,6 +23848,85 @@ function policyIdIsReversible(policyId) {
23556
23848
  var DEFAULT_ACTIONS = Object.fromEntries(
23557
23849
  DetectionCategory.options.map((c) => [c, builtinPolicyToAction(severityFloorPolicy(c))])
23558
23850
  );
23851
+ function ruleCategoryMap(wireRules, localRules, compiledRules) {
23852
+ const map2 = /* @__PURE__ */ new Map();
23853
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
23854
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
23855
+ for (const rule of compiledRules) map2.set(rule.id, rule.category);
23856
+ return map2;
23857
+ }
23858
+ function policyKey(policy) {
23859
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
23860
+ }
23861
+ function floorFor(policy, categoryByRuleId) {
23862
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
23863
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
23864
+ }
23865
+ function strongerOf(a, b) {
23866
+ if (a === null) return b;
23867
+ if (b === null) return a;
23868
+ return strongerAction(a, b);
23869
+ }
23870
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
23871
+ const merged = /* @__PURE__ */ new Map();
23872
+ const disabled = [];
23873
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
23874
+ for (const policy of remotePolicies) {
23875
+ if (!policy.enabled) continue;
23876
+ if (!("category" in policy.target)) continue;
23877
+ if (remoteCategoryAction.has(policy.target.category)) continue;
23878
+ const floor = floorFor(policy, categoryByRuleId);
23879
+ remoteCategoryAction.set(
23880
+ policy.target.category,
23881
+ floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
23882
+ );
23883
+ }
23884
+ for (const policy of localPolicies) {
23885
+ if (!policy.enabled) {
23886
+ disabled.push(policy);
23887
+ continue;
23888
+ }
23889
+ const key = policyKey(policy);
23890
+ if (merged.has(key)) continue;
23891
+ let remoteFloor = null;
23892
+ if ("ruleId" in policy.target) {
23893
+ const category = categoryByRuleId.get(policy.target.ruleId);
23894
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
23895
+ }
23896
+ merged.set(
23897
+ key,
23898
+ remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
23899
+ );
23900
+ }
23901
+ const localCategoryAction = /* @__PURE__ */ new Map();
23902
+ for (const policy of merged.values()) {
23903
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
23904
+ }
23905
+ for (const policy of remotePolicies) {
23906
+ if (!policy.enabled) {
23907
+ disabled.push(policy);
23908
+ continue;
23909
+ }
23910
+ const key = policyKey(policy);
23911
+ const floor = floorFor(policy, categoryByRuleId);
23912
+ let localFloor = null;
23913
+ if ("ruleId" in policy.target) {
23914
+ const category = categoryByRuleId.get(policy.target.ruleId);
23915
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
23916
+ }
23917
+ const effectiveFloor = strongerOf(floor, localFloor);
23918
+ const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
23919
+ const existing = merged.get(key);
23920
+ if (existing === void 0) {
23921
+ merged.set(key, clamped);
23922
+ continue;
23923
+ }
23924
+ if (actionRank(clamped.action) > actionRank(existing.action)) {
23925
+ merged.set(key, clamped);
23926
+ }
23927
+ }
23928
+ return [...merged.values(), ...disabled];
23929
+ }
23559
23930
  var BUILTIN_POLICIES = Object.fromEntries(
23560
23931
  KNOWN_BUILTIN_IDS.map((id) => [id, { id, ...BUILTIN_POLICY_SPECS[id] }])
23561
23932
  );
@@ -23761,7 +24132,7 @@ var VaultConsent = external_exports.object({
23761
24132
  });
23762
24133
 
23763
24134
  // ../../packages/schema/src/zod/local.ts
23764
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
24135
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23765
24136
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23766
24137
  var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23767
24138
  var RunMode = external_exports.enum(["standalone", "attached"]);
@@ -23786,6 +24157,31 @@ function isHistorySyncConsentValid(consent, endpoint) {
23786
24157
  if (consent === void 0 || endpoint === void 0) return false;
23787
24158
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23788
24159
  }
24160
+ var WEB_CHAT_CAPTURE_CONSENT_VERSION = 1;
24161
+ var WebChatCaptureConsent = external_exports.object({
24162
+ acknowledgedAt: external_exports.iso.datetime(),
24163
+ version: external_exports.number().int().positive()
24164
+ });
24165
+ var WebChatResponseCapture = external_exports.enum(["with-findings", "always", "never"]);
24166
+ var WebChatCapture = external_exports.object({
24167
+ responses: WebChatResponseCapture.default("with-findings"),
24168
+ account: external_exports.boolean().default(false),
24169
+ // Absent until granted. Presence alone does not authorize anything — see
24170
+ // isWebChatCaptureConsentValid.
24171
+ consent: WebChatCaptureConsent.optional()
24172
+ });
24173
+ function isWebChatCaptureConsentValid(consent) {
24174
+ return consent?.version === WEB_CHAT_CAPTURE_CONSENT_VERSION;
24175
+ }
24176
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
24177
+ var BodyRetention = external_exports.object({
24178
+ enabled: external_exports.boolean().default(false),
24179
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
24180
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
24181
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
24182
+ // candidate set that is already bounded by "delivered, or never owed".
24183
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
24184
+ }).meta({ id: "BodyRetention" });
23789
24185
  var WorkspaceSettings = external_exports.object({
23790
24186
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23791
24187
  runMode: RunMode.default("standalone"),
@@ -23834,11 +24230,30 @@ var WorkspaceSettings = external_exports.object({
23834
24230
  // carry prompt/reply/tool-output text in `content`; the key name predates
23835
24231
  // both widenings. Absent until granted, and a grant for a different endpoint
23836
24232
  // or an older payload no longer counts.
23837
- historySyncConsent: HistorySyncConsent.optional()
24233
+ historySyncConsent: HistorySyncConsent.optional(),
24234
+ // What the browser extension may record from a web chat, and the grant that
24235
+ // authorizes it. Absent until the user answers: recording something that was
24236
+ // never recorded before is never an assumed grant on upgrade, so the whole
24237
+ // block is optional rather than defaulted in. What an absent block means is
24238
+ // webChatCaptureOf's answer, in one place.
24239
+ //
24240
+ // Enforcement is NOT gated on this. A machine that has never answered still
24241
+ // blocks, redacts and warns on what a user sends; the grant covers what is
24242
+ // written down.
24243
+ webChatCapture: WebChatCapture.optional(),
24244
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24245
+ // body never removes the row or its findings.
24246
+ bodyRetention: BodyRetention.default({
24247
+ enabled: false,
24248
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24249
+ })
23838
24250
  });
23839
24251
  function defaultWorkspaceSettings() {
23840
24252
  return WorkspaceSettings.parse({});
23841
24253
  }
24254
+ function webChatCaptureOf(settings) {
24255
+ return settings.webChatCapture ?? WebChatCapture.parse({});
24256
+ }
23842
24257
  function isAttached(settings) {
23843
24258
  return settings.runMode === "attached" && settings.controlPlane !== void 0;
23844
24259
  }
@@ -23929,12 +24344,18 @@ function toCaptureAttributes(event) {
23929
24344
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23930
24345
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23931
24346
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24347
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23932
24348
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23933
24349
  // has ever populated either), but every legacy metadata key still rides
23934
24350
  // the bag rather than being silently dropped — CaptureAttributes'
23935
24351
  // `.catchall(z.unknown())` carries the long tail.
23936
24352
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23937
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24353
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24354
+ // A blank id is omitted rather than stored: it is a join key and `''` joins
24355
+ // nothing. This runs on the local write path, which types the event but
24356
+ // never parses it, so EventMetadata's own `.min(1)` does not reach here.
24357
+ ...metadata?.messageId !== void 0 && metadata.messageId !== "" ? { message_id: metadata.messageId } : {},
24358
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23938
24359
  };
23939
24360
  }
23940
24361
  function captureDefinitionVersion(finding2) {
@@ -23962,13 +24383,22 @@ var ManagedSettingKey = external_exports.enum([
23962
24383
  "vaultInlineReveal",
23963
24384
  "modelJudgeConsent",
23964
24385
  "dataSharesInPlace",
23965
- "redactFallback"
24386
+ "redactFallback",
24387
+ // Pins the toggle and the day count together — see BodyRetention on why the
24388
+ // two are one unit. An administrator mandating a window wants the count
24389
+ // enforced with it, not one a user can widen while the toggle stays on.
24390
+ "bodyRetention"
23966
24391
  ]).meta({ id: "ManagedSettingKey" });
23967
24392
  function isManagedSettingKey(value) {
23968
24393
  return ManagedSettingKey.safeParse(value).success;
23969
24394
  }
23970
24395
  var ManagedSettingsValues = external_exports.object({
23971
24396
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24397
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24398
+ // plain, non-strict objects: a key under either that this build does not know
24399
+ // is stripped and nothing reports it. The unknown-value split in
24400
+ // ManagedSettings below classifies top-level names only, so it stops at
24401
+ // these boundaries.
23972
24402
  controlPlane: external_exports.object({
23973
24403
  endpoint: external_exports.string().min(1),
23974
24404
  label: external_exports.string().min(1).optional()
@@ -23979,7 +24409,8 @@ var ManagedSettingsValues = external_exports.object({
23979
24409
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23980
24410
  modelJudgeConsent: external_exports.boolean().optional(),
23981
24411
  dataSharesInPlace: external_exports.boolean().optional(),
23982
- redactFallback: RedactFallback.optional()
24412
+ redactFallback: RedactFallback.optional(),
24413
+ bodyRetention: BodyRetention.optional()
23983
24414
  }).meta({ id: "ManagedSettingsValues" });
23984
24415
  var ManagedSettings = external_exports.object({
23985
24416
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23987,7 +24418,21 @@ var ManagedSettings = external_exports.object({
23987
24418
  // decision from a bug. Absent renders as a generic "your organization".
23988
24419
  organization: external_exports.string().min(1).optional(),
23989
24420
  // What the administrator pinned.
23990
- values: ManagedSettingsValues.default({}),
24421
+ //
24422
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24423
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24424
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24425
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24426
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24427
+ // exactly the file an administrator is most likely to write while a fleet
24428
+ // is mid-upgrade.
24429
+ //
24430
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24431
+ // file, which is the outcome the lock half already rejected — an older
24432
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24433
+ // value still fails, because the nested schema is re-run over the known
24434
+ // subset and its issues are re-raised on this parse.
24435
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23991
24436
  // Which of those the user may not change. A key here with no matching value
23992
24437
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23993
24438
  // the user may still override. The two are separable on purpose.
@@ -24000,17 +24445,31 @@ var ManagedSettings = external_exports.object({
24000
24445
  // the fleets most likely to carry a version skew. A name outside the enum
24001
24446
  // is still never HONOURED: the lockable set stays explicit above.
24002
24447
  lockedFields: external_exports.array(external_exports.string()).default([])
24003
- }).transform(({ lockedFields, ...rest }) => {
24448
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24004
24449
  const known = [];
24005
24450
  const unknown2 = [];
24006
24451
  for (const name2 of lockedFields) {
24007
24452
  if (isManagedSettingKey(name2)) known.push(name2);
24008
24453
  else unknown2.push(name2);
24009
24454
  }
24455
+ const knownValues = /* @__PURE__ */ Object.create(null);
24456
+ const unknownValues = [];
24457
+ for (const [name2, value] of Object.entries(values)) {
24458
+ if (Object.hasOwn(ManagedSettingsValues.shape, name2)) knownValues[name2] = value;
24459
+ else unknownValues.push(name2);
24460
+ }
24461
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24462
+ if (!pinned.success) {
24463
+ for (const issue2 of pinned.error.issues)
24464
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24465
+ return external_exports.NEVER;
24466
+ }
24010
24467
  return {
24011
24468
  ...rest,
24469
+ values: pinned.data,
24012
24470
  lockedFields: known,
24013
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24471
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24472
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24014
24473
  };
24015
24474
  }).meta({ id: "ManagedSettings" });
24016
24475
 
@@ -24269,12 +24728,30 @@ var RecommendedActionIdParam = external_exports.object({ id: external_exports.st
24269
24728
  // ../../packages/schema/src/zod/settings-action.ts
24270
24729
  var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24271
24730
  var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
24731
+ var WebChatCaptureConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "WebChatCaptureConsentChoice" });
24272
24732
  var SaveSettingsInput = external_exports.object({
24273
24733
  historicalAccess: external_exports.string(),
24274
24734
  modelJudgeConsent: ModelJudgeConsentChoice,
24275
24735
  historySyncConsent: HistorySyncConsentChoice,
24276
24736
  vaultConsent: external_exports.string(),
24277
- vaultInlineReveal: external_exports.string()
24737
+ vaultInlineReveal: external_exports.string(),
24738
+ webChatCaptureConsent: WebChatCaptureConsentChoice,
24739
+ // Widened to `string` like its neighbours rather than typed as
24740
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24741
+ // the call site, so the domain check receives the type it was written for.
24742
+ //
24743
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24744
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24745
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24746
+ // trade against. The real cost runs the other way and is the part worth
24747
+ // knowing: a value this schema admits and the domain enum then rejects lands
24748
+ // on the action's shared refusal, which names NO field, where a shape
24749
+ // rejection reaches `malformedInput` and names the schema key.
24750
+ redactFallback: external_exports.string(),
24751
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24752
+ // `BodyRetention`'s and the action checks it there, so there is one place
24753
+ // that decides what a legal horizon is rather than two that can drift.
24754
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24278
24755
  });
24279
24756
  var AttachInput = external_exports.object({
24280
24757
  endpoint: external_exports.string(),
@@ -24446,6 +24923,139 @@ function reviewSeverityRank(reasons) {
24446
24923
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24447
24924
  }
24448
24925
 
24926
+ // ../../packages/schema/src/zod/web-capture.ts
24927
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24928
+ var WebUsage = external_exports.object({
24929
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24930
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24931
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24932
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24933
+ });
24934
+ var WebToolCall = external_exports.object({
24935
+ toolUseId: external_exports.string().min(1),
24936
+ toolName: external_exports.string().min(1),
24937
+ target: external_exports.string().optional(),
24938
+ isError: external_exports.boolean().optional(),
24939
+ inputSize: external_exports.number().int().nonnegative().optional(),
24940
+ outputSize: external_exports.number().int().nonnegative().optional()
24941
+ });
24942
+ var WebExchange = external_exports.object({
24943
+ messageId: external_exports.string().min(1),
24944
+ startedAt: external_exports.iso.datetime(),
24945
+ model: external_exports.string().optional(),
24946
+ usage: WebUsage.optional(),
24947
+ usageSource: WebUsageSource,
24948
+ stopReason: external_exports.string().optional(),
24949
+ conversationId: external_exports.string().optional(),
24950
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24951
+ toolCalls: external_exports.array(WebToolCall).default([]),
24952
+ // Absent when the adapter recovered no text. Capped by the caller at
24953
+ // RESPONSE_TEXT_MAX_BYTES, so a short capture is never mistaken for a short
24954
+ // reply.
24955
+ responseText: external_exports.string().optional(),
24956
+ // The stored text is short of the reply. It does NOT say which of the two
24957
+ // ceilings on this path cut it: the caller applies its own cap on the raw
24958
+ // bytes it reads off the wire, which can be reached by a stream whose
24959
+ // recovered text stays well under RESPONSE_TEXT_MAX_BYTES, and applies that
24960
+ // one to the text. A reader cannot tell them apart, and nothing downstream
24961
+ // should branch as though it could.
24962
+ truncated: external_exports.boolean().default(false)
24963
+ });
24964
+ var WebEnforcementState = external_exports.enum([
24965
+ "watching",
24966
+ "composer-only",
24967
+ "button-only",
24968
+ "unattached",
24969
+ "unknown"
24970
+ ]);
24971
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24972
+ var WebCaptureStatus = external_exports.object({
24973
+ patched: external_exports.boolean(),
24974
+ live: external_exports.boolean(),
24975
+ blind: external_exports.boolean(),
24976
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24977
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24978
+ parseFailures: external_exports.number().int().nonnegative(),
24979
+ unparsedBodies: external_exports.number().int().nonnegative(),
24980
+ // The adapter-declared JSON key paths that were absent from a real payload —
24981
+ // the earliest signal that a site's contract moved.
24982
+ shapeMisses: external_exports.array(external_exports.string()).default([]),
24983
+ // How many `kind: 'conversation'` endpoints the reporting tab's adapter
24984
+ // compiled. Zero means this build declares none for the site, so observing
24985
+ // nothing is the design rather than a fault — the one fact that separates a
24986
+ // site nobody has surveyed yet from one whose contract moved. Defaulted so a
24987
+ // build predating the field is read as declaring nothing rather than refused.
24988
+ conversationEndpoints: external_exports.number().int().nonnegative().default(0),
24989
+ // The document that sent this report is going away. The bridge sets it on
24990
+ // its `pagehide` report and nowhere else.
24991
+ //
24992
+ // A property of the REPORT rather than of capture health, which is why
24993
+ // nothing in `deriveWebCaptureState` reads it and why it stays out of the
24994
+ // bridge's own report signature — a closing tab's last word must not be
24995
+ // suppressed for carrying the same health as the report before it. What
24996
+ // reads it is the per-site fold: a document that said it was unloading stops
24997
+ // voting on the site's state, so the reload the `blind` remediation asks for
24998
+ // can actually clear the verdict it was shown. A document that dies without
24999
+ // sending one is covered by CAPTURE_STATUS_DOCUMENT_QUIET_MS instead.
25000
+ //
25001
+ // Defaulted so a build predating the field reads as a document that never
25002
+ // said it was closing — which keeps it voting, the same as every report that
25003
+ // is not a final one.
25004
+ closed: external_exports.boolean().default(false),
25005
+ // What the DOM enforcement path is doing, which none of the counters above
25006
+ // can say: `sendsSeenDom` rises only once a send has COMPLETED, so a tab
25007
+ // whose watcher never bound reports zero exactly like a tab nobody typed in.
25008
+ // Defaulted to 'unknown' rather than 'watching' so a status from a build
25009
+ // predating the field is not read as reporting a healthy one.
25010
+ enforcement: WebEnforcementState.default("unknown")
25011
+ });
25012
+ function webCaptureStatusObservedTurnPath(status) {
25013
+ if (!status.patched) return true;
25014
+ if (status.conversationEndpoints === 0) return true;
25015
+ return status.blind || status.shapeMisses.length > 0 || status.parseFailures > 0 || status.unparsedBodies > 0 || status.exchangesSeenNet > 0;
25016
+ }
25017
+ function pickReportedCaptureStatus(candidates) {
25018
+ return candidates.find((c) => webCaptureStatusObservedTurnPath(c.status)) ?? candidates[0];
25019
+ }
25020
+ var CAPTURE_STATUS_RECENCY_MS = 30 * 24 * 60 * 60 * 1e3;
25021
+ var CAPTURE_STATUS_RECENCY_DAYS = CAPTURE_STATUS_RECENCY_MS / (24 * 60 * 60 * 1e3);
25022
+ var CAPTURE_STATUS_DOCUMENT_QUIET_MS = 12 * 60 * 60 * 1e3;
25023
+ function toCaptureStatusAttributes(status, tool) {
25024
+ return {
25025
+ source_tool: tool,
25026
+ patched: status.patched,
25027
+ live: status.live,
25028
+ blind: status.blind,
25029
+ sends_seen_dom: status.sendsSeenDom,
25030
+ exchanges_seen_net: status.exchangesSeenNet,
25031
+ parse_failures: status.parseFailures,
25032
+ unparsed_bodies: status.unparsedBodies,
25033
+ shape_misses: status.shapeMisses,
25034
+ conversation_endpoints: status.conversationEndpoints,
25035
+ closed: status.closed,
25036
+ enforcement: status.enforcement
25037
+ };
25038
+ }
25039
+ function fromCaptureStatusAttributes(bag) {
25040
+ const parsedBag = CaptureStatusAttributes.safeParse(bag);
25041
+ if (!parsedBag.success) return null;
25042
+ const b = parsedBag.data;
25043
+ const parsedStatus = WebCaptureStatus.safeParse({
25044
+ patched: b.patched,
25045
+ live: b.live,
25046
+ blind: b.blind,
25047
+ sendsSeenDom: b.sends_seen_dom,
25048
+ exchangesSeenNet: b.exchanges_seen_net,
25049
+ parseFailures: b.parse_failures,
25050
+ unparsedBodies: b.unparsed_bodies,
25051
+ shapeMisses: b.shape_misses,
25052
+ conversationEndpoints: b.conversation_endpoints,
25053
+ closed: b.closed,
25054
+ enforcement: b.enforcement
25055
+ });
25056
+ return parsedStatus.success ? parsedStatus.data : null;
25057
+ }
25058
+
24449
25059
  // ../../packages/persistence/src/paths.ts
24450
25060
  import {
24451
25061
  chmodSync,
@@ -24575,17 +25185,6 @@ function publishByLink(tmp, file2, data) {
24575
25185
  function controlPlaneCredentialPath(settingsDir2) {
24576
25186
  return join2(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
24577
25187
  }
24578
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
24579
- function isSafeEndpoint(endpoint) {
24580
- let parsed2;
24581
- try {
24582
- parsed2 = new URL(endpoint);
24583
- } catch {
24584
- return false;
24585
- }
24586
- if (parsed2.protocol === "https:") return true;
24587
- return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
24588
- }
24589
25188
  function repairOrRefuseMode(file2) {
24590
25189
  const link = lstatSync2(file2, { throwIfNoEntry: false });
24591
25190
  if (link === void 0) return "absent";
@@ -24810,6 +25409,22 @@ function discardStore(file2, backup) {
24810
25409
  }
24811
25410
  }
24812
25411
 
25412
+ // ../../packages/persistence/src/internal/sql-functions.ts
25413
+ var utf8 = new TextDecoder();
25414
+ function akaLower(value) {
25415
+ if (value === null) return null;
25416
+ if (typeof value === "string") return value.toLowerCase();
25417
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25418
+ return utf8.decode(value).toLowerCase();
25419
+ }
25420
+ function registerSqlFunctions(db) {
25421
+ db.function(
25422
+ "aka_lower",
25423
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25424
+ akaLower
25425
+ );
25426
+ }
25427
+
24813
25428
  // ../../packages/persistence/src/internal/sql-text.ts
24814
25429
  function escapeLikePattern(s) {
24815
25430
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24894,6 +25509,11 @@ function schemaObjectExists(db, kind, name2) {
24894
25509
  function indexExists(db, name2) {
24895
25510
  return schemaObjectExists(db, "index", name2);
24896
25511
  }
25512
+ function indexColumns(db, name2) {
25513
+ if (!indexExists(db, name2)) return [];
25514
+ const columns = db.prepare(`PRAGMA index_info(${name2})`).all();
25515
+ return columns.map((c) => c.name).filter((c) => c !== null);
25516
+ }
24897
25517
  function columnNames(db, table, opts) {
24898
25518
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24899
25519
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24955,6 +25575,647 @@ function mapRowsTolerant(rows, map2) {
24955
25575
  return out;
24956
25576
  }
24957
25577
 
25578
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25579
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25580
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25581
+
25582
+ // ../../packages/persistence/src/sync-failure.ts
25583
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25584
+ function syncFailureRejectCondition(column = "sync_failure") {
25585
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25586
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
25587
+ }
25588
+
25589
+ // ../../packages/persistence/src/repositories/history-sync.ts
25590
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25591
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25592
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25593
+ var COUNTED_EVENT_TYPES = [
25594
+ ...STRUCTURAL_EVENT_TYPES,
25595
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25596
+ ];
25597
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25598
+ var PARTITION_BUCKETS = `
25599
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25600
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25601
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25602
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25603
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25604
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25605
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25606
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25607
+ -- added later lands in no bucket and fails the sum assertion, instead
25608
+ -- of silently joining this one.
25609
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25610
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25611
+ THEN 1 ELSE 0 END) AS failed,
25612
+ COUNT(*) AS total`;
25613
+ var COUNTED_SCOPE = `
25614
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25615
+ AND (
25616
+ event_type IN (${TYPE_LIST})
25617
+ OR synced_at IS NOT NULL
25618
+ OR outbox_owed = 1
25619
+ )`;
25620
+ var SKIPPED = -1;
25621
+ var ROW_COLUMNS = `id,
25622
+ parent_id AS parentId,
25623
+ root_session_id AS rootSessionId,
25624
+ event_type AS eventType,
25625
+ host_id AS hostId,
25626
+ harness_id AS harnessId,
25627
+ source_project_id AS sourceProjectId,
25628
+ started_at AS startedAt,
25629
+ ended_at AS endedAt,
25630
+ severity,
25631
+ priority,
25632
+ content,
25633
+ content_hash AS contentHash,
25634
+ attributes`;
25635
+ var SqliteHistorySyncRepository = class {
25636
+ constructor(db) {
25637
+ this.db = db;
25638
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25639
+ this.sessionsStmt = db.prepare(
25640
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25641
+ FROM audit_events
25642
+ WHERE synced_at IS NULL
25643
+ AND event_type IN (${TYPE_LIST})
25644
+ AND started_at < :before
25645
+ GROUP BY sessionId
25646
+ ORDER BY earliest
25647
+ LIMIT :limit`
25648
+ );
25649
+ this.rowsStmt = db.prepare(
25650
+ `SELECT ${ROW_COLUMNS}
25651
+ FROM audit_events
25652
+ WHERE synced_at IS NULL
25653
+ AND event_type IN (${TYPE_LIST})
25654
+ AND started_at < :before
25655
+ AND COALESCE(root_session_id, id) = :sessionId
25656
+ ORDER BY (event_type = 'session') DESC, started_at
25657
+ LIMIT :limit`
25658
+ );
25659
+ this.captureRowsStmt = db.prepare(
25660
+ `SELECT ${ROW_COLUMNS}
25661
+ FROM audit_events
25662
+ WHERE synced_at IS NULL
25663
+ AND sync_claimed_at IS NULL
25664
+ AND outbox_owed = 1
25665
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25666
+ AND started_at < :before
25667
+ ORDER BY started_at
25668
+ LIMIT :limit`
25669
+ );
25670
+ this.markOwedStmt = db.prepare(
25671
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25672
+ );
25673
+ this.markCaptureBacklogOwedStmt = db.prepare(
25674
+ `UPDATE audit_events SET outbox_owed = 1
25675
+ WHERE synced_at IS NULL
25676
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25677
+ AND started_at < :before`
25678
+ );
25679
+ this.stampStmt = db.prepare(
25680
+ `UPDATE audit_events
25681
+ SET synced_at = :at,
25682
+ sync_claimed_at = NULL,
25683
+ sync_failed_at = :failedAt,
25684
+ sync_failure = :failure
25685
+ WHERE id = :id`
25686
+ );
25687
+ this.claimRowStmt = db.prepare(
25688
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25689
+ );
25690
+ this.releaseRowStmt = db.prepare(
25691
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25692
+ );
25693
+ this.releaseStaleClaimsStmt = db.prepare(
25694
+ `UPDATE audit_events SET sync_claimed_at = NULL
25695
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25696
+ );
25697
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25698
+ FROM audit_events${COUNTED_SCOPE}`);
25699
+ this.partitionByKindStmt = db.prepare(
25700
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25701
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25702
+ GROUP BY event_type`
25703
+ );
25704
+ this.countsStmt = db.prepare(
25705
+ `SELECT
25706
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25707
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25708
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25709
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25710
+ THEN 1 ELSE 0 END) AS skipped,
25711
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25712
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25713
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25714
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25715
+ FROM audit_events
25716
+ WHERE event_type IN (${TYPE_LIST})`
25717
+ );
25718
+ this.captureSkipCountStmt = db.prepare(
25719
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25720
+ // way the structural totals are. The split exists because a refusal is
25721
+ // terminal only against the deployment that gave it, and the structural
25722
+ // re-arm frees it on a change of deployment. The capture lane has no such
25723
+ // escape: re-arming a capture would offer one deployment's undelivered
25724
+ // prompts, with their text, to a deployment that never saw them, which is
25725
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25726
+ // reasons mean the same thing — this row will not be sent — and splitting
25727
+ // them would put refused captures in a bucket nothing reads and nothing
25728
+ // frees.
25729
+ `SELECT COUNT(*) AS skipped
25730
+ FROM audit_events
25731
+ WHERE synced_at = ${String(SKIPPED)}
25732
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25733
+ );
25734
+ this.fingerprintStmt = db.prepare(
25735
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25736
+ FROM history_sync WHERE id = 1`
25737
+ );
25738
+ this.setFingerprintStmt = db.prepare(
25739
+ `UPDATE history_sync
25740
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25741
+ WHERE id = 1`
25742
+ );
25743
+ this.disownCapturesStmt = db.prepare(
25744
+ `UPDATE audit_events SET outbox_owed = NULL
25745
+ WHERE outbox_owed IS NOT NULL
25746
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25747
+ AND started_at < :attachedAt`
25748
+ );
25749
+ this.rearmStmt = db.prepare(
25750
+ `UPDATE audit_events
25751
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25752
+ WHERE (synced_at > 0
25753
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25754
+ AND event_type IN (${TYPE_LIST})`
25755
+ );
25756
+ this.claimStmt = db.prepare(
25757
+ `UPDATE history_sync
25758
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25759
+ WHERE id = 1
25760
+ AND (owner_pid IS NULL
25761
+ OR heartbeat_at IS NULL
25762
+ OR heartbeat_at < :staleBefore
25763
+ OR heartbeat_at > :now)`
25764
+ );
25765
+ this.heartbeatStmt = db.prepare(
25766
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25767
+ );
25768
+ this.releaseStmt = db.prepare(
25769
+ `UPDATE history_sync
25770
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25771
+ WHERE id = 1 AND owner_pid = :pid`
25772
+ );
25773
+ this.closeWindowStmt = db.prepare(
25774
+ `UPDATE audit_events
25775
+ SET synced_at = ${String(SKIPPED)},
25776
+ sync_failed_at = :at,
25777
+ sync_failure = 'detached_undelivered'
25778
+ WHERE synced_at IS NULL
25779
+ AND event_type IN (${TYPE_LIST})
25780
+ AND started_at >= :attachedAt`
25781
+ );
25782
+ this.releaseBoundaryStmt = db.prepare(
25783
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25784
+ );
25785
+ this.freezeBoundaryStmt = db.prepare(
25786
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25787
+ );
25788
+ this.leaseStmt = db.prepare(
25789
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25790
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25791
+ FROM history_sync WHERE id = 1`
25792
+ );
25793
+ this.inspectionsStmt = db.prepare(
25794
+ `SELECT d.rule_id AS ruleId,
25795
+ d.name AS ruleName,
25796
+ d.version AS ruleVersion,
25797
+ d.category AS category,
25798
+ d.severity AS severity,
25799
+ f.span_start AS spanStart,
25800
+ f.span_end AS spanEnd,
25801
+ f.masked_match AS maskedMatch,
25802
+ f.action_taken AS actionTaken,
25803
+ f.confidence AS confidence
25804
+ FROM inspection_findings f
25805
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25806
+ WHERE f.audit_event_id = :auditEventId
25807
+ ORDER BY f.span_start, f.id`
25808
+ );
25809
+ }
25810
+ db;
25811
+ ensureRowStmt;
25812
+ sessionsStmt;
25813
+ rowsStmt;
25814
+ stampStmt;
25815
+ countsStmt;
25816
+ fingerprintStmt;
25817
+ setFingerprintStmt;
25818
+ rearmStmt;
25819
+ claimStmt;
25820
+ heartbeatStmt;
25821
+ releaseStmt;
25822
+ leaseStmt;
25823
+ inspectionsStmt;
25824
+ closeWindowStmt;
25825
+ releaseBoundaryStmt;
25826
+ freezeBoundaryStmt;
25827
+ captureRowsStmt;
25828
+ markOwedStmt;
25829
+ markCaptureBacklogOwedStmt;
25830
+ captureSkipCountStmt;
25831
+ disownCapturesStmt;
25832
+ partitionStmt;
25833
+ partitionByKindStmt;
25834
+ claimRowStmt;
25835
+ releaseRowStmt;
25836
+ releaseStaleClaimsStmt;
25837
+ /**
25838
+ * The masked detections recorded against one tool call.
25839
+ *
25840
+ * These travel with the event because a tool call's target is not
25841
+ * re-inspectable from the event alone — unlike a capture, where the text
25842
+ * itself is re-scannable. What crosses is the masked match and the rule that
25843
+ * produced it, never the value.
25844
+ */
25845
+ inspectionsFor(auditEventId) {
25846
+ return allRows(this.inspectionsStmt, { auditEventId });
25847
+ }
25848
+ /**
25849
+ * Sessions with structural rows still to send, oldest first.
25850
+ *
25851
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25852
+ * read. Anything recorded after the machine attached is the live forward
25853
+ * path's to deliver; this drain exists for what was recorded before it, and a
25854
+ * row both paths send is at best a duplicate request and at worst — for a
25855
+ * session root — an overwrite of the inventory ids the live path resolved.
25856
+ */
25857
+ pendingSessions(limit, before) {
25858
+ return allRows(this.sessionsStmt, { limit, before }).map(
25859
+ (r) => r.sessionId
25860
+ );
25861
+ }
25862
+ /** One session's undelivered structural rows within the backlog, root first. */
25863
+ pendingRows(sessionId, limit, before) {
25864
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25865
+ }
25866
+ /**
25867
+ * Captures this machine still owes the deployment, oldest first.
25868
+ *
25869
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25870
+ * by a time window — see captureRowsStmt for why a window could not express
25871
+ * this. `before` is the grace window that leaves a just-recorded capture to
25872
+ * the live path.
25873
+ */
25874
+ pendingCaptureRows(limit, before) {
25875
+ return allRows(this.captureRowsStmt, { limit, before });
25876
+ }
25877
+ /**
25878
+ * Record that a capture is OWED to the deployment.
25879
+ *
25880
+ * Written by the attached forward path when a live send did not confirm
25881
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25882
+ * a fact rather than an inference: the machine was attached, the send did not
25883
+ * land, so the row is owed — which no time window can state, because the same
25884
+ * window that holds the rows a past attachment left owed also holds every
25885
+ * capture recorded while the machine was DETACHED, and those were never
25886
+ * offered to anyone.
25887
+ *
25888
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25889
+ * out of the drain's read.
25890
+ */
25891
+ markCaptureOwed(id) {
25892
+ this.markOwedStmt.run({ id });
25893
+ }
25894
+ /**
25895
+ * Mark every capture already on disk as owed, as of `before`.
25896
+ *
25897
+ * The consent-time backfill, called once from `aka attach` when a human
25898
+ * grants existing-history consent — never from an ongoing drain pass, and
25899
+ * never inferred from a boundary that could later move. `before` is the
25900
+ * caller's own "now" at the moment consent was granted, so what this marks
25901
+ * is exactly the backlog the consent prompt already counted, not whatever a
25902
+ * later re-attach or key rotation might widen it to.
25903
+ *
25904
+ * Returns how many rows matched, for the caller to log or test against. Not a
25905
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25906
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25907
+ */
25908
+ markCaptureBacklogOwed(before) {
25909
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25910
+ }
25911
+ /**
25912
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25913
+ *
25914
+ * CLEARS any failure reason in the same statement. A row that failed against
25915
+ * one deployment and then landed is delivered, and leaving the reason behind
25916
+ * would leave the store holding two contradictory answers about one row —
25917
+ * with the surface free to render either.
25918
+ */
25919
+ markSynced(ids, atMs) {
25920
+ this.stampAll(ids, atMs, null);
25921
+ }
25922
+ /**
25923
+ * Record that THIS MACHINE cannot express the row on the wire.
25924
+ *
25925
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25926
+ * payload, or a body the client itself refused to send. It fails identically
25927
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25928
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25929
+ * is retried; marking those would turn one outage into permanent data loss.
25930
+ */
25931
+ markSkipped(ids, atMs) {
25932
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25933
+ }
25934
+ /**
25935
+ * Record that THIS DEPLOYMENT refused the row.
25936
+ *
25937
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25938
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25939
+ * row is outstanding rather than why. What separates them is the reason, and
25940
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25941
+ * on one body, so it is terminal only for as long as this machine points at
25942
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25943
+ *
25944
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25945
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25946
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25947
+ */
25948
+ markRefused(ids, atMs) {
25949
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25950
+ }
25951
+ eachInTransaction(ids, run) {
25952
+ if (ids.length === 0) return;
25953
+ withTransaction(
25954
+ this.db,
25955
+ () => {
25956
+ for (const id of ids) run(id);
25957
+ },
25958
+ "IMMEDIATE"
25959
+ );
25960
+ }
25961
+ stampAll(ids, value, failure, failedAtMs) {
25962
+ if (ids.length === 0) return;
25963
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25964
+ withTransaction(
25965
+ this.db,
25966
+ () => {
25967
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25968
+ },
25969
+ "IMMEDIATE"
25970
+ );
25971
+ }
25972
+ /**
25973
+ * Claim rows as in-flight.
25974
+ *
25975
+ * Advisory in exactly the sense the lease is: it records that a send is in
25976
+ * progress so a surface can say so, and a lost claim costs a row showing as
25977
+ * queued while it is actually being sent. It is not exclusion — the far side
25978
+ * settles a duplicate on the row id.
25979
+ */
25980
+ claimRows(ids, atMs) {
25981
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25982
+ }
25983
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25984
+ releaseRows(ids) {
25985
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25986
+ }
25987
+ /**
25988
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25989
+ *
25990
+ * A process killed between claiming and settling leaves rows claimed with
25991
+ * nothing left to settle them. Without this they read as "sending" for ever.
25992
+ */
25993
+ releaseStaleClaims(staleBefore) {
25994
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25995
+ }
25996
+ /**
25997
+ * Every tracked row in exactly one delivery state.
25998
+ *
25999
+ * Takes no boundary on purpose. The boundary answers "what should the drain
26000
+ * pick up now", which is a different question from "what state is this row
26001
+ * in" — and a machine that has never attached has no boundary to pass, so
26002
+ * requiring one would force a caller to invent one and report the whole store
26003
+ * as queued.
26004
+ */
26005
+ /**
26006
+ * The same partition, one row per kind that a lane carries.
26007
+ *
26008
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
26009
+ * scope decides which rows exist at all, so a kind that has never been
26010
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
26011
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
26012
+ * rows", never as "zero sent"; the two look identical in a bar and mean
26013
+ * different things.
26014
+ */
26015
+ partitionByKind() {
26016
+ return allRows(
26017
+ this.partitionByKindStmt,
26018
+ {}
26019
+ ).map((row) => ({
26020
+ kind: row.kind,
26021
+ queued: row.queued ?? 0,
26022
+ inProgress: row.inProgress ?? 0,
26023
+ synced: row.synced ?? 0,
26024
+ failed: row.failed ?? 0,
26025
+ refused: row.refused ?? 0,
26026
+ detached: row.detached ?? 0,
26027
+ total: row.total ?? 0
26028
+ }));
26029
+ }
26030
+ partition() {
26031
+ const row = getRow(this.partitionStmt, {});
26032
+ return {
26033
+ queued: row?.queued ?? 0,
26034
+ inProgress: row?.inProgress ?? 0,
26035
+ synced: row?.synced ?? 0,
26036
+ failed: row?.failed ?? 0,
26037
+ refused: row?.refused ?? 0,
26038
+ detached: row?.detached ?? 0,
26039
+ total: row?.total ?? 0
26040
+ };
26041
+ }
26042
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
26043
+ counts(before) {
26044
+ const row = getRow(this.countsStmt, { before });
26045
+ const captures = getRow(this.captureSkipCountStmt);
26046
+ return {
26047
+ pending: row?.pending ?? 0,
26048
+ sent: row?.sent ?? 0,
26049
+ skipped: row?.skipped ?? 0,
26050
+ refused: row?.refused ?? 0,
26051
+ detached: row?.detached ?? 0,
26052
+ capturesSkipped: captures?.skipped ?? 0
26053
+ };
26054
+ }
26055
+ /**
26056
+ * The deployment the current stamps were made against, and where its backlog
26057
+ * ends.
26058
+ *
26059
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
26060
+ * machine that has never drained is — and every writer below seeds the row
26061
+ * before it needs one, so nothing depends on this creating it. Keeping the
26062
+ * write off the gate path matters because the gate runs on every pass while a
26063
+ * write has to take the database's write lock.
26064
+ */
26065
+ deployment() {
26066
+ const row = getRow(
26067
+ this.fingerprintStmt
26068
+ );
26069
+ return {
26070
+ fingerprint: row?.fingerprint ?? void 0,
26071
+ backlogBefore: row?.backlogBefore ?? void 0
26072
+ };
26073
+ }
26074
+ /**
26075
+ * Point the ledger at a different deployment, discarding what it recorded
26076
+ * about the previous one.
26077
+ *
26078
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
26079
+ * machine has just left are undelivered as far as the new one is concerned.
26080
+ * All four in one transaction, so a crash between them cannot leave stamps
26081
+ * attributed to the wrong deployment, a boundary that belongs to another, or
26082
+ * a disown with no re-mark to follow it.
26083
+ *
26084
+ * The boundary is written HERE and only here, which is what freezes it: a
26085
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
26086
+ * unchanged, so this never runs and the backlog does not widen back over rows
26087
+ * the live path has since delivered.
26088
+ *
26089
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
26090
+ * granted existing-history consent for the deployment this call is arming —
26091
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
26092
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
26093
+ * apart. Passed only when that grant is valid, since this method has no way
26094
+ * to check consent itself and must not mark a row owed for a machine that
26095
+ * never agreed to it. Applied AFTER the disown above, in the SAME
26096
+ * transaction: what the disown clears is every marker below `backlogBefore`,
26097
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
26098
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
26099
+ * on the cleared side of that bound — and the re-mark in the same
26100
+ * transaction is what puts those rows back. A crash between the two cannot
26101
+ * strand the ledger disowned with nothing re-marked — the transaction either
26102
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
26103
+ * committed re-enters this method on the very next pass. Omit it (the
26104
+ * structural-only tests do) to exercise the disown in isolation.
26105
+ *
26106
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
26107
+ * touching a marker the NEW deployment's OWN live path has already set: B's
26108
+ * live path can mark a capture owed from the moment `aka attach` writes the
26109
+ * descriptor, before the drain's first pass ever reaches this method, and
26110
+ * such a row sits at or after the bound rather than below it. What keeps the
26111
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
26112
+ * bound — disown runs first, re-mark second, both inside the one
26113
+ * transaction above.
26114
+ */
26115
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
26116
+ this.ensureRowStmt.run();
26117
+ withTransaction(
26118
+ this.db,
26119
+ () => {
26120
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
26121
+ this.rearmStmt.run();
26122
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
26123
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
26124
+ }
26125
+ if (backfillCapturesBefore !== void 0) {
26126
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
26127
+ }
26128
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
26129
+ },
26130
+ "IMMEDIATE"
26131
+ );
26132
+ }
26133
+ /**
26134
+ * End the attached period: hand its rows to the live path, and release the
26135
+ * boundary so the next attachment can freeze a new one.
26136
+ *
26137
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
26138
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
26139
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
26140
+ * during the detached period, because the machine is not attached. Rows
26141
+ * recorded in that window sit after the boundary and before the re-attach, so
26142
+ * neither path takes them, and the pending count reports none outstanding.
26143
+ *
26144
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
26145
+ * closing attachment's to deliver and are no longer outstanding — that is what
26146
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
26147
+ * distinction is not academic: this used to write a delivery TIME, which every
26148
+ * read treats as delivery, so one detach turned a window of undelivered rows
26149
+ * into a window of delivered ones and no surface could tell. It writes the
26150
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
26151
+ * "received" stop being the same fact.
26152
+ *
26153
+ * A change of deployment still frees them (see the re-arm), because the next
26154
+ * deployment has seen none of this machine's history — so the rows reach it
26155
+ * exactly as they did when this wrote a delivery time.
26156
+ *
26157
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
26158
+ * window unstamped — that half-state would re-send the whole attached period
26159
+ * on the next attach, which is the failure the boundary exists to prevent.
26160
+ */
26161
+ closeAttachedWindow(attachedAtMs, atMs) {
26162
+ this.ensureRowStmt.run();
26163
+ withTransaction(
26164
+ this.db,
26165
+ () => {
26166
+ const row = getRow(this.fingerprintStmt);
26167
+ const from = row?.backlogBefore ?? attachedAtMs;
26168
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
26169
+ this.releaseBoundaryStmt.run();
26170
+ },
26171
+ "IMMEDIATE"
26172
+ );
26173
+ }
26174
+ /**
26175
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
26176
+ *
26177
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
26178
+ * different deployment and therefore discards what was delivered to the old
26179
+ * one: here the recipient is the same, so everything already sent to it stays
26180
+ * sent.
26181
+ */
26182
+ freezeBoundary(backlogBefore) {
26183
+ this.ensureRowStmt.run();
26184
+ this.freezeBoundaryStmt.run({ backlogBefore });
26185
+ }
26186
+ /** Take the claim, or report that someone live already holds it. */
26187
+ claim(pid, host, nowMs, staleAfterMs) {
26188
+ this.ensureRowStmt.run();
26189
+ let taken = false;
26190
+ withTransaction(
26191
+ this.db,
26192
+ () => {
26193
+ const result = this.claimStmt.run({
26194
+ pid,
26195
+ host,
26196
+ now: nowMs,
26197
+ staleBefore: nowMs - staleAfterMs
26198
+ });
26199
+ taken = result.changes === 1;
26200
+ },
26201
+ "IMMEDIATE"
26202
+ );
26203
+ return taken;
26204
+ }
26205
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
26206
+ heartbeat(pid, nowMs) {
26207
+ this.heartbeatStmt.run({ now: nowMs, pid });
26208
+ }
26209
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
26210
+ release(pid) {
26211
+ this.releaseStmt.run({ pid });
26212
+ }
26213
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
26214
+ lease() {
26215
+ return getRow(this.leaseStmt);
26216
+ }
26217
+ };
26218
+
24958
26219
  // ../../packages/persistence/src/migrations.ts
24959
26220
  function describeObject(object2) {
24960
26221
  return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
@@ -24967,7 +26228,7 @@ function createdIndexName(statement) {
24967
26228
  return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
24968
26229
  }
24969
26230
  var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24970
- function applyMigrations(db, file2) {
26231
+ function applyMigrations(db, file2, options = {}) {
24971
26232
  const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24972
26233
  db.exec(
24973
26234
  "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
@@ -24981,6 +26242,7 @@ function applyMigrations(db, file2) {
24981
26242
  );
24982
26243
  for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24983
26244
  if (applied.has(migration.tag)) continue;
26245
+ if (options.skipTags?.has(migration.tag) === true) continue;
24984
26246
  if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24985
26247
  const evidence = evidenceObjects(migration.sql);
24986
26248
  const present = evidence.filter((o) => evidenceExists(db, o));
@@ -25387,10 +26649,62 @@ function ensureSyncedAtColumn(db, table) {
25387
26649
  if (!columns.includes("outbox_owed")) {
25388
26650
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25389
26651
  }
26652
+ if (!columns.includes("sync_failed_at")) {
26653
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26654
+ }
26655
+ if (!columns.includes("sync_failure")) {
26656
+ withTransaction(
26657
+ db,
26658
+ () => {
26659
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26660
+ db.exec(
26661
+ `UPDATE ${table} SET synced_at = NULL
26662
+ WHERE synced_at = -1
26663
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26664
+ );
26665
+ },
26666
+ "IMMEDIATE"
26667
+ );
26668
+ }
25390
26669
  db.exec(
25391
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25392
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26670
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26671
+ BEFORE UPDATE OF sync_failure ON ${table}
26672
+ WHEN ${syncFailureRejectCondition()}
26673
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25393
26674
  );
26675
+ const syncIndexColumns = [
26676
+ "event_type",
26677
+ "synced_at",
26678
+ "sync_claimed_at",
26679
+ "started_at",
26680
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26681
+ // has to be in the index for the read to stay covered — but putting it
26682
+ // ahead of `started_at` would reorder the prefix the structural drain's
26683
+ // reads match on.
26684
+ "sync_failure"
26685
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26686
+ //
26687
+ // The delivery-state read tests it — a capture's state depends on whether a
26688
+ // live forward marked it owed — so carrying it here makes that read covering
26689
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26690
+ // But a sixth column changes what the planner charges for this index, and
26691
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26692
+ // then stops choosing the per-session index for the token rollup and walks
26693
+ // every `llm_call` in the store through the event-type index instead. That
26694
+ // read grows with the store; this one does not.
26695
+ //
26696
+ // 40 ms on the largest store measured, once per render, is a cost worth
26697
+ // paying to leave every other read's plan where it was.
26698
+ ];
26699
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26700
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26701
+ if (!syncIndexMatches) {
26702
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26703
+ db.exec(
26704
+ `CREATE INDEX idx_audit_events_sync
26705
+ ON audit_events (${syncIndexColumns.join(", ")})`
26706
+ );
26707
+ }
25394
26708
  db.exec(
25395
26709
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25396
26710
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25612,7 +26926,11 @@ function buildAuditEvent(row) {
25612
26926
  link: linkParsed?.success ? linkParsed.data : null,
25613
26927
  targetId: row.target_id,
25614
26928
  internal: intToBool(row.internal),
25615
- flagged: intToBool(row.flagged)
26929
+ flagged: intToBool(row.flagged),
26930
+ // Only meaningful when the title came out empty — a row whose body was
26931
+ // expired but whose title fell back to `tool_name` still has something to
26932
+ // render, and flagging it would make the view apologise for nothing.
26933
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25616
26934
  };
25617
26935
  }
25618
26936
  var TIMELINE_COLUMNS = `
@@ -25620,6 +26938,7 @@ var TIMELINE_COLUMNS = `
25620
26938
  event_type,
25621
26939
  started_at,
25622
26940
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26941
+ content_expired_at,
25623
26942
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25624
26943
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25625
26944
  json_extract(attributes, '$.severity') AS severity,
@@ -25662,7 +26981,7 @@ var SESSION_ROOT = `event_type = 'session'`;
25662
26981
  var HAS_ACTIVITY = `EXISTS (
25663
26982
  SELECT 1 FROM audit_events c
25664
26983
  WHERE c.root_session_id = audit_events.id
25665
- AND c.event_type NOT IN ('hook', 'config_scan'))`;
26984
+ AND c.event_type NOT IN ('hook', 'config_scan', 'capture_status'))`;
25666
26985
  var SqliteActivityRepository = class {
25667
26986
  constructor(db, now = () => Date.now()) {
25668
26987
  this.db = db;
@@ -25689,10 +27008,10 @@ var SqliteActivityRepository = class {
25689
27008
  SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
25690
27009
  UNION
25691
27010
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
25692
- WHERE started_at >= ?
27011
+ WHERE started_at >= ? AND event_type <> 'capture_status'
25693
27012
  UNION
25694
27013
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
25695
- WHERE ended_at >= ?)`,
27014
+ WHERE ended_at >= ? AND event_type <> 'capture_status')`,
25696
27015
  [liveThreshold, liveThreshold, liveThreshold]
25697
27016
  );
25698
27017
  const toolCallsToday = countScalar(
@@ -26099,7 +27418,10 @@ var SqliteAuditEventsRepository = class {
26099
27418
  attributes = excluded.attributes,
26100
27419
  ended_at = excluded.ended_at
26101
27420
  WHERE COALESCE(json_extract(excluded.attributes, '$.output_tokens'), 0)
26102
- > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)`
27421
+ > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)
27422
+ OR (json_extract(excluded.attributes, '$.usage_source') IS NOT NULL
27423
+ AND json_extract(excluded.attributes, '$.output_tokens') IS NULL
27424
+ AND excluded.attributes <> audit_events.attributes)`
26103
27425
  );
26104
27426
  this.upsertSessionRootStmt = db.prepare(
26105
27427
  `INSERT OR IGNORE INTO audit_events
@@ -26285,6 +27607,169 @@ var SqliteAuditEventsRepository = class {
26285
27607
  }
26286
27608
  };
26287
27609
 
27610
+ // ../../packages/persistence/src/repositories/body-retention.ts
27611
+ var DEFAULT_BATCH_SIZE = 500;
27612
+ var DEFAULT_MAX_ROWS = 5e4;
27613
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27614
+ var SqliteBodyRetentionRepository = class {
27615
+ constructor(db) {
27616
+ this.db = db;
27617
+ const select = (laneClause) => `
27618
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27619
+ FROM audit_events
27620
+ WHERE content IS NOT NULL
27621
+ AND started_at < :cutoff
27622
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27623
+ ${laneClause}
27624
+ ORDER BY started_at
27625
+ LIMIT :limit`;
27626
+ this.candidatesStmt = this.db.prepare(select(""));
27627
+ this.candidatesSyncSafeStmt = this.db.prepare(
27628
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27629
+ );
27630
+ this.heldBySyncStmt = this.db.prepare(`
27631
+ SELECT COUNT(*) AS n
27632
+ FROM audit_events
27633
+ WHERE content IS NOT NULL
27634
+ AND started_at < :cutoff
27635
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27636
+ AND synced_at IS NULL`);
27637
+ this.expireStmt = this.db.prepare(
27638
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27639
+ );
27640
+ }
27641
+ db;
27642
+ candidatesStmt;
27643
+ candidatesSyncSafeStmt;
27644
+ heldBySyncStmt;
27645
+ expireStmt;
27646
+ /** How many bytes a pass with these options would free, changing nothing. */
27647
+ preview(opts) {
27648
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27649
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27650
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27651
+ return {
27652
+ rowsExpired: rows.length,
27653
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27654
+ rowsHeldBySync: this.countHeldBySync(opts)
27655
+ };
27656
+ }
27657
+ /** Clear eligible bodies, in bounded batches. */
27658
+ expire(opts) {
27659
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27660
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27661
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27662
+ let rowsExpired = 0;
27663
+ let bytesFreed = 0;
27664
+ let done = true;
27665
+ while (rowsExpired < maxRows) {
27666
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27667
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27668
+ if (batch.length === 0) break;
27669
+ withTransaction(
27670
+ this.db,
27671
+ () => {
27672
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27673
+ },
27674
+ "IMMEDIATE"
27675
+ );
27676
+ rowsExpired += batch.length;
27677
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27678
+ if (batch.length < remaining) break;
27679
+ if (rowsExpired >= maxRows) {
27680
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27681
+ }
27682
+ }
27683
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27684
+ }
27685
+ countHeldBySync(opts) {
27686
+ if (opts.sweepSyncLane) return 0;
27687
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27688
+ return row.n;
27689
+ }
27690
+ };
27691
+
27692
+ // ../../packages/persistence/src/repositories/capture-status.ts
27693
+ var STATUS_LOOKBACK_ROWS = 128;
27694
+ var SqliteCaptureStatusRepository = class {
27695
+ constructor(db) {
27696
+ this.db = db;
27697
+ this.recentStmt = db.prepare(
27698
+ `SELECT a.started_at AS startedAt,
27699
+ a.attributes AS attributes,
27700
+ a.root_session_id AS rootSessionId
27701
+ FROM audit_events a
27702
+ WHERE a.event_type = 'capture_status'
27703
+ AND a.source_tool = ?
27704
+ AND a.started_at >= ?
27705
+ ORDER BY a.started_at DESC, a.id DESC
27706
+ LIMIT ?`
27707
+ );
27708
+ }
27709
+ db;
27710
+ recentStmt;
27711
+ /**
27712
+ * Every document that reported for a site, in registry order by site, from
27713
+ * the last `CAPTURE_STATUS_RECENCY_MS`.
27714
+ *
27715
+ * SEVERAL per site, not one: a browser is many documents and each reports
27716
+ * for itself, so one row per site is a choice about which of them a user
27717
+ * sees — and the newest is the wrong one, since a healthy tab writing a
27718
+ * fresh report would hide a drifting tab's verdict, which is the whole
27719
+ * reason these rows exist. The pick WITHIN a document is made here (the
27720
+ * unchanged `pickReportedCaptureStatus`, over that document's own rows);
27721
+ * choosing between documents belongs where the state semantics live, and
27722
+ * that is `reportedCaptureDocumentForSite` in `@akasecurity/detections` —
27723
+ * this package may not import it.
27724
+ *
27725
+ * `now` is a required argument rather than a `Date.now()` read, so a caller
27726
+ * that already holds a render instant passes THAT one and a test can drive
27727
+ * the window without moving the wall clock.
27728
+ *
27729
+ * A site whose reports have all aged out contributes nothing, so it derives
27730
+ * to `unreported`. That is the point: nothing but the browser extension ever
27731
+ * writes these rows, so an uninstalled extension's last verdict would
27732
+ * otherwise stand as a live claim for ever with no later report able to
27733
+ * clear it.
27734
+ */
27735
+ latest(now) {
27736
+ const since = now - CAPTURE_STATUS_RECENCY_MS;
27737
+ const documents = [];
27738
+ for (const tool of WebSourceTool.options) {
27739
+ const rows = /* @__PURE__ */ new Map();
27740
+ const lastWord = /* @__PURE__ */ new Map();
27741
+ for (const row of allRows(this.recentStmt, [
27742
+ tool,
27743
+ since,
27744
+ STATUS_LOOKBACK_ROWS
27745
+ ])) {
27746
+ const status = fromCaptureStatusAttributes(parseJsonObject(row.attributes));
27747
+ if (status === null) continue;
27748
+ const record2 = { tool, observedAt: epochMillisToIso(row.startedAt), status };
27749
+ const group = rows.get(row.rootSessionId);
27750
+ if (group === void 0) {
27751
+ rows.set(row.rootSessionId, [record2]);
27752
+ lastWord.set(row.rootSessionId, { at: record2.observedAt, closed: status.closed });
27753
+ } else {
27754
+ group.push(record2);
27755
+ }
27756
+ }
27757
+ for (const [root, candidates] of rows) {
27758
+ const picked = pickReportedCaptureStatus(candidates);
27759
+ const last = lastWord.get(root);
27760
+ if (picked === void 0 || last === void 0) continue;
27761
+ documents.push({
27762
+ ...picked,
27763
+ ...root === null ? {} : { rootSessionId: root },
27764
+ lastReportAt: last.at,
27765
+ closed: last.closed
27766
+ });
27767
+ }
27768
+ }
27769
+ return documents;
27770
+ }
27771
+ };
27772
+
26288
27773
  // ../../packages/persistence/src/repositories/classified-data.ts
26289
27774
  var SqliteClassifiedDataRepository = class {
26290
27775
  constructor(db) {
@@ -27113,7 +28598,15 @@ function toFlatFindingRow(r) {
27113
28598
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
27114
28599
  eventId: r.event_id,
27115
28600
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27116
- status: deriveInstanceStatus(r)
28601
+ status: deriveInstanceStatus(r),
28602
+ delivery: deriveFindingDelivery({
28603
+ kind: r.kind,
28604
+ syncedAt: r.synced_at,
28605
+ syncClaimedAt: r.sync_claimed_at,
28606
+ syncFailedAt: r.sync_failed_at,
28607
+ syncFailure: r.sync_failure,
28608
+ outboxOwed: r.outbox_owed
28609
+ })
27117
28610
  };
27118
28611
  }
27119
28612
  function encodeGroupCursor(group) {
@@ -27177,7 +28670,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27177
28670
  e.tool_name AS tool_name,
27178
28671
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27179
28672
  e.event_type AS kind, f.finding_key AS finding_key,
27180
- ${latestResolutionStatusSql("f")} AS latest_status`;
28673
+ ${latestResolutionStatusSql("f")} AS latest_status,
28674
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28675
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28676
+ e.outbox_owed AS outbox_owed`;
27181
28677
  var DAY_MS3 = 864e5;
27182
28678
  var SqliteFindingsRepository = class {
27183
28679
  constructor(db) {
@@ -27422,6 +28918,7 @@ var SqliteFindingsRepository = class {
27422
28918
  providers: query.provider,
27423
28919
  actions: query.action,
27424
28920
  statuses: query.status,
28921
+ deliveries: query.deployment,
27425
28922
  tools: query.tool,
27426
28923
  repo: query.repo,
27427
28924
  file: query.file,
@@ -27489,6 +28986,7 @@ var SqliteFindingsRepository = class {
27489
28986
  providers: query.provider,
27490
28987
  actions: query.action,
27491
28988
  statuses: query.status,
28989
+ deliveries: query.deployment,
27492
28990
  tools: query.tool,
27493
28991
  q: query.q
27494
28992
  };
@@ -27752,7 +29250,9 @@ var SqliteFindingsRepository = class {
27752
29250
  )
27753
29251
  );
27754
29252
  for (const row of grouped) {
27755
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
29253
+ if (Object.hasOwn(byAction, row.action_taken)) {
29254
+ byAction[row.action_taken] = row.c;
29255
+ }
27756
29256
  }
27757
29257
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27758
29258
  const sevRows = allRows(
@@ -27769,7 +29269,9 @@ var SqliteFindingsRepository = class {
27769
29269
  )
27770
29270
  );
27771
29271
  for (const row of sevRows) {
27772
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
29272
+ if (Object.hasOwn(bySeverity, row.severity)) {
29273
+ bySeverity[row.severity] = row.c;
29274
+ }
27773
29275
  }
27774
29276
  const categories = ENFORCEABLE_CATEGORIES;
27775
29277
  const enabledRows = allRows(
@@ -27818,525 +29320,6 @@ function isoDay(ms) {
27818
29320
  return new Date(ms).toISOString().slice(0, 10);
27819
29321
  }
27820
29322
 
27821
- // ../../packages/persistence/src/repositories/history-sync.ts
27822
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27823
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27824
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27825
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27826
- var SKIPPED = -1;
27827
- var ROW_COLUMNS = `id,
27828
- parent_id AS parentId,
27829
- root_session_id AS rootSessionId,
27830
- event_type AS eventType,
27831
- host_id AS hostId,
27832
- harness_id AS harnessId,
27833
- source_project_id AS sourceProjectId,
27834
- started_at AS startedAt,
27835
- ended_at AS endedAt,
27836
- severity,
27837
- priority,
27838
- content,
27839
- content_hash AS contentHash,
27840
- attributes`;
27841
- var SqliteHistorySyncRepository = class {
27842
- constructor(db) {
27843
- this.db = db;
27844
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27845
- this.sessionsStmt = db.prepare(
27846
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27847
- FROM audit_events
27848
- WHERE synced_at IS NULL
27849
- AND event_type IN (${TYPE_LIST})
27850
- AND started_at < :before
27851
- GROUP BY sessionId
27852
- ORDER BY earliest
27853
- LIMIT :limit`
27854
- );
27855
- this.rowsStmt = db.prepare(
27856
- `SELECT ${ROW_COLUMNS}
27857
- FROM audit_events
27858
- WHERE synced_at IS NULL
27859
- AND event_type IN (${TYPE_LIST})
27860
- AND started_at < :before
27861
- AND COALESCE(root_session_id, id) = :sessionId
27862
- ORDER BY (event_type = 'session') DESC, started_at
27863
- LIMIT :limit`
27864
- );
27865
- this.captureRowsStmt = db.prepare(
27866
- `SELECT ${ROW_COLUMNS}
27867
- FROM audit_events
27868
- WHERE synced_at IS NULL
27869
- AND sync_claimed_at IS NULL
27870
- AND outbox_owed = 1
27871
- AND event_type IN (${CAPTURE_TYPE_LIST})
27872
- AND started_at < :before
27873
- ORDER BY started_at
27874
- LIMIT :limit`
27875
- );
27876
- this.markOwedStmt = db.prepare(
27877
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27878
- );
27879
- this.markCaptureBacklogOwedStmt = db.prepare(
27880
- `UPDATE audit_events SET outbox_owed = 1
27881
- WHERE synced_at IS NULL
27882
- AND event_type IN (${CAPTURE_TYPE_LIST})
27883
- AND started_at < :before`
27884
- );
27885
- this.stampStmt = db.prepare(
27886
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27887
- );
27888
- this.claimRowStmt = db.prepare(
27889
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27890
- );
27891
- this.releaseRowStmt = db.prepare(
27892
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27893
- );
27894
- this.releaseStaleClaimsStmt = db.prepare(
27895
- `UPDATE audit_events SET sync_claimed_at = NULL
27896
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27897
- );
27898
- this.partitionStmt = db.prepare(
27899
- `SELECT
27900
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27901
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27902
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27903
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27904
- COUNT(*) AS total
27905
- FROM audit_events
27906
- WHERE event_type IN (${TYPE_LIST})`
27907
- );
27908
- this.countsStmt = db.prepare(
27909
- `SELECT
27910
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27911
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27912
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27913
- FROM audit_events
27914
- WHERE event_type IN (${TYPE_LIST})`
27915
- );
27916
- this.captureSkipCountStmt = db.prepare(
27917
- `SELECT COUNT(*) AS skipped
27918
- FROM audit_events
27919
- WHERE synced_at = ${String(SKIPPED)}
27920
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27921
- );
27922
- this.fingerprintStmt = db.prepare(
27923
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27924
- FROM history_sync WHERE id = 1`
27925
- );
27926
- this.setFingerprintStmt = db.prepare(
27927
- `UPDATE history_sync
27928
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27929
- WHERE id = 1`
27930
- );
27931
- this.disownCapturesStmt = db.prepare(
27932
- `UPDATE audit_events SET outbox_owed = NULL
27933
- WHERE outbox_owed IS NOT NULL
27934
- AND event_type IN (${CAPTURE_TYPE_LIST})
27935
- AND started_at < :attachedAt`
27936
- );
27937
- this.rearmStmt = db.prepare(
27938
- `UPDATE audit_events SET synced_at = NULL
27939
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27940
- );
27941
- this.claimStmt = db.prepare(
27942
- `UPDATE history_sync
27943
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27944
- WHERE id = 1
27945
- AND (owner_pid IS NULL
27946
- OR heartbeat_at IS NULL
27947
- OR heartbeat_at < :staleBefore
27948
- OR heartbeat_at > :now)`
27949
- );
27950
- this.heartbeatStmt = db.prepare(
27951
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27952
- );
27953
- this.releaseStmt = db.prepare(
27954
- `UPDATE history_sync
27955
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27956
- WHERE id = 1 AND owner_pid = :pid`
27957
- );
27958
- this.closeWindowStmt = db.prepare(
27959
- `UPDATE audit_events SET synced_at = :at
27960
- WHERE synced_at IS NULL
27961
- AND event_type IN (${TYPE_LIST})
27962
- AND started_at >= :attachedAt`
27963
- );
27964
- this.releaseBoundaryStmt = db.prepare(
27965
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27966
- );
27967
- this.freezeBoundaryStmt = db.prepare(
27968
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27969
- );
27970
- this.leaseStmt = db.prepare(
27971
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27972
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27973
- FROM history_sync WHERE id = 1`
27974
- );
27975
- this.inspectionsStmt = db.prepare(
27976
- `SELECT d.rule_id AS ruleId,
27977
- d.name AS ruleName,
27978
- d.version AS ruleVersion,
27979
- d.category AS category,
27980
- d.severity AS severity,
27981
- f.span_start AS spanStart,
27982
- f.span_end AS spanEnd,
27983
- f.masked_match AS maskedMatch,
27984
- f.action_taken AS actionTaken,
27985
- f.confidence AS confidence
27986
- FROM inspection_findings f
27987
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27988
- WHERE f.audit_event_id = :auditEventId
27989
- ORDER BY f.span_start, f.id`
27990
- );
27991
- }
27992
- db;
27993
- ensureRowStmt;
27994
- sessionsStmt;
27995
- rowsStmt;
27996
- stampStmt;
27997
- countsStmt;
27998
- fingerprintStmt;
27999
- setFingerprintStmt;
28000
- rearmStmt;
28001
- claimStmt;
28002
- heartbeatStmt;
28003
- releaseStmt;
28004
- leaseStmt;
28005
- inspectionsStmt;
28006
- closeWindowStmt;
28007
- releaseBoundaryStmt;
28008
- freezeBoundaryStmt;
28009
- captureRowsStmt;
28010
- markOwedStmt;
28011
- markCaptureBacklogOwedStmt;
28012
- captureSkipCountStmt;
28013
- disownCapturesStmt;
28014
- partitionStmt;
28015
- claimRowStmt;
28016
- releaseRowStmt;
28017
- releaseStaleClaimsStmt;
28018
- /**
28019
- * The masked detections recorded against one tool call.
28020
- *
28021
- * These travel with the event because a tool call's target is not
28022
- * re-inspectable from the event alone — unlike a capture, where the text
28023
- * itself is re-scannable. What crosses is the masked match and the rule that
28024
- * produced it, never the value.
28025
- */
28026
- inspectionsFor(auditEventId) {
28027
- return allRows(this.inspectionsStmt, { auditEventId });
28028
- }
28029
- /**
28030
- * Sessions with structural rows still to send, oldest first.
28031
- *
28032
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
28033
- * read. Anything recorded after the machine attached is the live forward
28034
- * path's to deliver; this drain exists for what was recorded before it, and a
28035
- * row both paths send is at best a duplicate request and at worst — for a
28036
- * session root — an overwrite of the inventory ids the live path resolved.
28037
- */
28038
- pendingSessions(limit, before) {
28039
- return allRows(this.sessionsStmt, { limit, before }).map(
28040
- (r) => r.sessionId
28041
- );
28042
- }
28043
- /** One session's undelivered structural rows within the backlog, root first. */
28044
- pendingRows(sessionId, limit, before) {
28045
- return allRows(this.rowsStmt, { sessionId, limit, before });
28046
- }
28047
- /**
28048
- * Captures this machine still owes the deployment, oldest first.
28049
- *
28050
- * Selected by the `outbox_owed` marker the attached forward path writes, not
28051
- * by a time window — see captureRowsStmt for why a window could not express
28052
- * this. `before` is the grace window that leaves a just-recorded capture to
28053
- * the live path.
28054
- */
28055
- pendingCaptureRows(limit, before) {
28056
- return allRows(this.captureRowsStmt, { limit, before });
28057
- }
28058
- /**
28059
- * Record that a capture is OWED to the deployment.
28060
- *
28061
- * Written by the attached forward path when a live send did not confirm
28062
- * delivery, and read by the drain as the whole of its eligibility test. It is
28063
- * a fact rather than an inference: the machine was attached, the send did not
28064
- * land, so the row is owed — which no time window can state, because the same
28065
- * window that holds the rows a past attachment left owed also holds every
28066
- * capture recorded while the machine was DETACHED, and those were never
28067
- * offered to anyone.
28068
- *
28069
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
28070
- * out of the drain's read.
28071
- */
28072
- markCaptureOwed(id) {
28073
- this.markOwedStmt.run({ id });
28074
- }
28075
- /**
28076
- * Mark every capture already on disk as owed, as of `before`.
28077
- *
28078
- * The consent-time backfill, called once from `aka attach` when a human
28079
- * grants existing-history consent — never from an ongoing drain pass, and
28080
- * never inferred from a boundary that could later move. `before` is the
28081
- * caller's own "now" at the moment consent was granted, so what this marks
28082
- * is exactly the backlog the consent prompt already counted, not whatever a
28083
- * later re-attach or key rotation might widen it to.
28084
- *
28085
- * Returns how many rows matched, for the caller to log or test against. Not a
28086
- * count of NEWLY marked rows — a row still unsynced from an earlier call
28087
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
28088
- */
28089
- markCaptureBacklogOwed(before) {
28090
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
28091
- }
28092
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
28093
- markSynced(ids, atMs) {
28094
- this.stampAll(ids, atMs);
28095
- }
28096
- /**
28097
- * Record that a row will never be sent.
28098
- *
28099
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
28100
- * payload. A row that merely failed to reach the deployment stays NULL, so it
28101
- * is retried; marking those would turn one outage into permanent data loss.
28102
- */
28103
- markSkipped(ids) {
28104
- this.stampAll(ids, SKIPPED);
28105
- }
28106
- eachInTransaction(ids, run) {
28107
- if (ids.length === 0) return;
28108
- withTransaction(
28109
- this.db,
28110
- () => {
28111
- for (const id of ids) run(id);
28112
- },
28113
- "IMMEDIATE"
28114
- );
28115
- }
28116
- stampAll(ids, value) {
28117
- if (ids.length === 0) return;
28118
- withTransaction(
28119
- this.db,
28120
- () => {
28121
- for (const id of ids) this.stampStmt.run({ at: value, id });
28122
- },
28123
- "IMMEDIATE"
28124
- );
28125
- }
28126
- /**
28127
- * Claim rows as in-flight.
28128
- *
28129
- * Advisory in exactly the sense the lease is: it records that a send is in
28130
- * progress so a surface can say so, and a lost claim costs a row showing as
28131
- * queued while it is actually being sent. It is not exclusion — the far side
28132
- * settles a duplicate on the row id.
28133
- */
28134
- claimRows(ids, atMs) {
28135
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28136
- }
28137
- /** Give back a claim without settling — the send failed, the row is queued again. */
28138
- releaseRows(ids) {
28139
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28140
- }
28141
- /**
28142
- * Clear claims older than `staleBefore`, and report how many were cleared.
28143
- *
28144
- * A process killed between claiming and settling leaves rows claimed with
28145
- * nothing left to settle them. Without this they read as "sending" for ever.
28146
- */
28147
- releaseStaleClaims(staleBefore) {
28148
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28149
- }
28150
- /**
28151
- * Every tracked row in exactly one delivery state.
28152
- *
28153
- * Takes no boundary on purpose. The boundary answers "what should the drain
28154
- * pick up now", which is a different question from "what state is this row
28155
- * in" — and a machine that has never attached has no boundary to pass, so
28156
- * requiring one would force a caller to invent one and report the whole store
28157
- * as queued.
28158
- */
28159
- partition() {
28160
- const row = getRow(this.partitionStmt, {});
28161
- return {
28162
- queued: row?.queued ?? 0,
28163
- inProgress: row?.inProgress ?? 0,
28164
- synced: row?.synced ?? 0,
28165
- failed: row?.failed ?? 0,
28166
- total: row?.total ?? 0
28167
- };
28168
- }
28169
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28170
- counts(before) {
28171
- const row = getRow(
28172
- this.countsStmt,
28173
- { before }
28174
- );
28175
- const captures = getRow(this.captureSkipCountStmt);
28176
- return {
28177
- pending: row?.pending ?? 0,
28178
- sent: row?.sent ?? 0,
28179
- skipped: row?.skipped ?? 0,
28180
- capturesSkipped: captures?.skipped ?? 0
28181
- };
28182
- }
28183
- /**
28184
- * The deployment the current stamps were made against, and where its backlog
28185
- * ends.
28186
- *
28187
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28188
- * machine that has never drained is — and every writer below seeds the row
28189
- * before it needs one, so nothing depends on this creating it. Keeping the
28190
- * write off the gate path matters because the gate runs on every pass while a
28191
- * write has to take the database's write lock.
28192
- */
28193
- deployment() {
28194
- const row = getRow(
28195
- this.fingerprintStmt
28196
- );
28197
- return {
28198
- fingerprint: row?.fingerprint ?? void 0,
28199
- backlogBefore: row?.backlogBefore ?? void 0
28200
- };
28201
- }
28202
- /**
28203
- * Point the ledger at a different deployment, discarding what it recorded
28204
- * about the previous one.
28205
- *
28206
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28207
- * machine has just left are undelivered as far as the new one is concerned.
28208
- * All four in one transaction, so a crash between them cannot leave stamps
28209
- * attributed to the wrong deployment, a boundary that belongs to another, or
28210
- * a disown with no re-mark to follow it.
28211
- *
28212
- * The boundary is written HERE and only here, which is what freezes it: a
28213
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28214
- * unchanged, so this never runs and the backlog does not widen back over rows
28215
- * the live path has since delivered.
28216
- *
28217
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28218
- * granted existing-history consent for the deployment this call is arming —
28219
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28220
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28221
- * apart. Passed only when that grant is valid, since this method has no way
28222
- * to check consent itself and must not mark a row owed for a machine that
28223
- * never agreed to it. Applied AFTER the disown above, in the SAME
28224
- * transaction: what the disown clears is every marker below `backlogBefore`,
28225
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28226
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28227
- * on the cleared side of that bound — and the re-mark in the same
28228
- * transaction is what puts those rows back. A crash between the two cannot
28229
- * strand the ledger disowned with nothing re-marked — the transaction either
28230
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28231
- * committed re-enters this method on the very next pass. Omit it (the
28232
- * structural-only tests do) to exercise the disown in isolation.
28233
- *
28234
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28235
- * touching a marker the NEW deployment's OWN live path has already set: B's
28236
- * live path can mark a capture owed from the moment `aka attach` writes the
28237
- * descriptor, before the drain's first pass ever reaches this method, and
28238
- * such a row sits at or after the bound rather than below it. What keeps the
28239
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28240
- * bound — disown runs first, re-mark second, both inside the one
28241
- * transaction above.
28242
- */
28243
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28244
- this.ensureRowStmt.run();
28245
- withTransaction(
28246
- this.db,
28247
- () => {
28248
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28249
- this.rearmStmt.run();
28250
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28251
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28252
- }
28253
- if (backfillCapturesBefore !== void 0) {
28254
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28255
- }
28256
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28257
- },
28258
- "IMMEDIATE"
28259
- );
28260
- }
28261
- /**
28262
- * End the attached period: hand its rows to the live path, and release the
28263
- * boundary so the next attachment can freeze a new one.
28264
- *
28265
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28266
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28267
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28268
- * during the detached period, because the machine is not attached. Rows
28269
- * recorded in that window sit after the boundary and before the re-attach, so
28270
- * neither path takes them, and the pending count reports none outstanding.
28271
- *
28272
- * Stamping the attached window is not a claim that every one of those rows
28273
- * reached the deployment — the live path drops on failure and says so
28274
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28275
- * status quo: they sit outside the frozen boundary today and are equally never
28276
- * re-sent. Making it explicit is what lets the boundary move.
28277
- *
28278
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28279
- * window unstamped — that half-state would re-send the whole attached period
28280
- * on the next attach, which is the failure the boundary exists to prevent.
28281
- */
28282
- closeAttachedWindow(attachedAtMs, atMs) {
28283
- this.ensureRowStmt.run();
28284
- withTransaction(
28285
- this.db,
28286
- () => {
28287
- const row = getRow(this.fingerprintStmt);
28288
- const from = row?.backlogBefore ?? attachedAtMs;
28289
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28290
- this.releaseBoundaryStmt.run();
28291
- },
28292
- "IMMEDIATE"
28293
- );
28294
- }
28295
- /**
28296
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28297
- *
28298
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28299
- * different deployment and therefore discards what was delivered to the old
28300
- * one: here the recipient is the same, so everything already sent to it stays
28301
- * sent.
28302
- */
28303
- freezeBoundary(backlogBefore) {
28304
- this.ensureRowStmt.run();
28305
- this.freezeBoundaryStmt.run({ backlogBefore });
28306
- }
28307
- /** Take the claim, or report that someone live already holds it. */
28308
- claim(pid, host, nowMs, staleAfterMs) {
28309
- this.ensureRowStmt.run();
28310
- let taken = false;
28311
- withTransaction(
28312
- this.db,
28313
- () => {
28314
- const result = this.claimStmt.run({
28315
- pid,
28316
- host,
28317
- now: nowMs,
28318
- staleBefore: nowMs - staleAfterMs
28319
- });
28320
- taken = result.changes === 1;
28321
- },
28322
- "IMMEDIATE"
28323
- );
28324
- return taken;
28325
- }
28326
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28327
- heartbeat(pid, nowMs) {
28328
- this.heartbeatStmt.run({ now: nowMs, pid });
28329
- }
28330
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28331
- release(pid) {
28332
- this.releaseStmt.run({ pid });
28333
- }
28334
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28335
- lease() {
28336
- return getRow(this.leaseStmt);
28337
- }
28338
- };
28339
-
28340
29323
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28341
29324
  var SqliteInspectionDefinitionsRepository = class {
28342
29325
  constructor(db) {
@@ -28564,6 +29547,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28564
29547
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28565
29548
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28566
29549
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29550
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28567
29551
  if (values.vaultConsent !== void 0) {
28568
29552
  merged.vaultConsent = values.vaultConsent ? (
28569
29553
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -31071,7 +32055,7 @@ var SqliteSecurityRepository = class {
31071
32055
  ELSE 0
31072
32056
  END) AS open_at_rest
31073
32057
  FROM inspection_findings f
31074
- JOIN audit_events e ON e.id = f.audit_event_id
32058
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31075
32059
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31076
32060
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31077
32061
  ON latest.finding_key = f.finding_key
@@ -31297,7 +32281,7 @@ var SqliteSecurityRepository = class {
31297
32281
  this.db.prepare(
31298
32282
  `SELECT e.repo AS repo, count(*) AS c
31299
32283
  FROM inspection_findings f
31300
- JOIN audit_events e ON e.id = f.audit_event_id
32284
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31301
32285
  WHERE e.started_at >= :from AND e.started_at < :to
31302
32286
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31303
32287
  AND e.repo IS NOT NULL
@@ -31421,7 +32405,7 @@ var SqliteSecurityRepository = class {
31421
32405
  d.severity AS severity,
31422
32406
  COUNT(*) AS count
31423
32407
  FROM inspection_findings f
31424
- JOIN audit_events e ON e.id = f.audit_event_id
32408
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31425
32409
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31426
32410
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31427
32411
  ON latest.finding_key = f.finding_key
@@ -31456,7 +32440,7 @@ var SqliteSecurityRepository = class {
31456
32440
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31457
32441
  d.rule_id AS rule_id, d.category AS category
31458
32442
  FROM inspection_findings f
31459
- JOIN audit_events e ON e.id = f.audit_event_id
32443
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31460
32444
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31461
32445
  WHERE e.started_at >= :from AND e.started_at < :to
31462
32446
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32297,6 +33281,7 @@ function openWithPragmas(file2) {
32297
33281
  db.exec("PRAGMA journal_mode = WAL");
32298
33282
  db.exec("PRAGMA busy_timeout = 2000");
32299
33283
  db.exec("PRAGMA foreign_keys = ON");
33284
+ registerSqlFunctions(db);
32300
33285
  } catch (err) {
32301
33286
  closeQuietly(db);
32302
33287
  throw err;
@@ -32326,7 +33311,7 @@ function backupLegacyStore(db, file2) {
32326
33311
  discardStore(file2, backup);
32327
33312
  return backup;
32328
33313
  }
32329
- function openAndInitialize(file2, base) {
33314
+ function openAndInitialize(file2, base, skipTags) {
32330
33315
  let db = openWithPragmas(file2);
32331
33316
  try {
32332
33317
  if (isForeignSqliteLineage(db)) {
@@ -32336,7 +33321,7 @@ function openAndInitialize(file2, base) {
32336
33321
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32337
33322
  );
32338
33323
  }
32339
- applyMigrations(db, file2);
33324
+ applyMigrations(db, file2, { skipTags });
32340
33325
  tightenPerms(file2);
32341
33326
  const policies = new SqlitePoliciesRepository(db);
32342
33327
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32351,6 +33336,7 @@ function openAndInitialize(file2, base) {
32351
33336
  exceptions: new SqliteExceptionsRepository(db),
32352
33337
  resolutions: new SqliteResolutionsRepository(db),
32353
33338
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
33339
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32354
33340
  security: new SqliteSecurityRepository(db),
32355
33341
  detections: new SqliteDetectionsRepository(db),
32356
33342
  shares: new SqliteSharesRepository(db),
@@ -32361,6 +33347,7 @@ function openAndInitialize(file2, base) {
32361
33347
  activity: new SqliteActivityRepository(db),
32362
33348
  sourceProject: new SqliteSourceProjectRepository(db),
32363
33349
  auditEvents: new SqliteAuditEventsRepository(db),
33350
+ captureStatus: new SqliteCaptureStatusRepository(db),
32364
33351
  classifiedData: new SqliteClassifiedDataRepository(db),
32365
33352
  inspectionDefinitions: new SqliteInspectionDefinitionsRepository(db),
32366
33353
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
@@ -32373,7 +33360,8 @@ function openAndInitialize(file2, base) {
32373
33360
  throw err;
32374
33361
  }
32375
33362
  }
32376
- function openLocalDatabase(dir) {
33363
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
33364
+ function openLocalDatabase(dir, options = {}) {
32377
33365
  ensureDataDirSync(dir);
32378
33366
  const file2 = join7(dir, DB_FILENAME);
32379
33367
  reapStalePartials(file2);
@@ -32385,6 +33373,7 @@ function openLocalDatabase(dir) {
32385
33373
  installedPacks,
32386
33374
  scanLedger,
32387
33375
  historySync,
33376
+ bodyRetention,
32388
33377
  secretVault,
32389
33378
  exceptions,
32390
33379
  resolutions,
@@ -32399,6 +33388,7 @@ function openLocalDatabase(dir) {
32399
33388
  activity,
32400
33389
  sourceProject,
32401
33390
  auditEvents,
33391
+ captureStatus,
32402
33392
  classifiedData,
32403
33393
  inspectionDefinitions,
32404
33394
  inspectionFindings,
@@ -32408,7 +33398,8 @@ function openLocalDatabase(dir) {
32408
33398
  // `dir` is always `<base>/data` — every caller resolves it through
32409
33399
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32410
33400
  // settings/ and data/, and the pack-policy floor needs both halves.
32411
- dirname2(dir)
33401
+ dirname2(dir),
33402
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32412
33403
  );
32413
33404
  function captureRowId(event) {
32414
33405
  return captureId(
@@ -32601,6 +33592,7 @@ function openLocalDatabase(dir) {
32601
33592
  installedPacks,
32602
33593
  scanLedger,
32603
33594
  historySync,
33595
+ bodyRetention,
32604
33596
  secretVault,
32605
33597
  exceptions,
32606
33598
  resolutions,
@@ -32614,6 +33606,7 @@ function openLocalDatabase(dir) {
32614
33606
  activity,
32615
33607
  sourceProject,
32616
33608
  auditEvents,
33609
+ captureStatus,
32617
33610
  classifiedData,
32618
33611
  inspectionDefinitions,
32619
33612
  inspectionFindings,
@@ -32641,8 +33634,35 @@ function openLocalDatabase(dir) {
32641
33634
 
32642
33635
  // ../../packages/persistence/src/egress-wire.ts
32643
33636
  import { createHash as createHash3 } from "crypto";
33637
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33638
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33639
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33640
+ var FILE_URL = /^file:\/\//i;
33641
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33642
+ var SLASH = "/".charCodeAt(0);
33643
+ var GIT_SUFFIX = ".git";
33644
+ function trimSlashes(path) {
33645
+ let start = 0;
33646
+ let end = path.length;
33647
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33648
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33649
+ return path.slice(start, end);
33650
+ }
33651
+ function canonicalGitUrl(url2) {
33652
+ const trimmed2 = url2.trim();
33653
+ if (DOS_DRIVE.test(trimmed2) || FILE_URL.test(trimmed2)) return trimmed2;
33654
+ const scheme = SCHEME_FORM.exec(trimmed2);
33655
+ const scp = scheme === null ? SCP_FORM.exec(trimmed2) : null;
33656
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33657
+ if (host === void 0) return trimmed2;
33658
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33659
+ const bare = trimSlashes(path);
33660
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33661
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33662
+ }
32644
33663
  function hashProjectKey(projectKey) {
32645
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33664
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33665
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32646
33666
  }
32647
33667
  function toIngestHit(hit) {
32648
33668
  return {
@@ -32809,18 +33829,46 @@ function fingerprintValue(key, raw) {
32809
33829
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32810
33830
  }
32811
33831
 
33832
+ // ../../packages/persistence/src/forward-health.ts
33833
+ import { readFileSync as readFileSync7 } from "fs";
33834
+ import { join as join9 } from "path";
33835
+ var BREAKER_COOLDOWN_MS = 3e4;
33836
+ function parseForwardHealth(raw, nowMs) {
33837
+ try {
33838
+ const parsed2 = JSON.parse(raw);
33839
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33840
+ const record2 = parsed2;
33841
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33842
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33843
+ const parsedFailure = ControlPlaneFailure.safeParse(record2.lastFailure);
33844
+ const lastFailure = parsedFailure.success ? parsedFailure.data : null;
33845
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33846
+ } catch {
33847
+ return null;
33848
+ }
33849
+ }
33850
+ function isForwardPaused(health, nowMs) {
33851
+ const openedAtMs = health?.openedAtMs ?? null;
33852
+ if (openedAtMs === null) return false;
33853
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33854
+ }
33855
+
32812
33856
  // ../../packages/persistence/src/history-backfill.ts
32813
33857
  import { existsSync as existsSync4 } from "fs";
32814
- import { join as join9 } from "path";
33858
+ import { join as join10 } from "path";
32815
33859
 
32816
33860
  // ../../packages/persistence/src/history-preview.ts
32817
33861
  import { existsSync as existsSync5 } from "fs";
32818
- import { join as join10 } from "path";
33862
+ import { join as join11 } from "path";
32819
33863
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32820
33864
 
33865
+ // ../../packages/persistence/src/history-sync-state.ts
33866
+ import { readFileSync as readFileSync8 } from "fs";
33867
+ import { join as join12 } from "path";
33868
+
32821
33869
  // ../../packages/persistence/src/store-symlinks.ts
32822
33870
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32823
- import { dirname as dirname3, join as join11, resolve } from "path";
33871
+ import { dirname as dirname3, join as join13, resolve } from "path";
32824
33872
 
32825
33873
  // ../../packages/persistence/src/vault/crypto.ts
32826
33874
  import {
@@ -32834,19 +33882,19 @@ import {
32834
33882
  // ../../packages/persistence/src/vault/key-provider.ts
32835
33883
  import { execFileSync } from "child_process";
32836
33884
  import { randomBytes as randomBytes2 } from "crypto";
32837
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32838
- import { join as join12 } from "path";
33885
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33886
+ import { join as join14 } from "path";
32839
33887
 
32840
33888
  // ../../packages/persistence/src/vault/vault.ts
32841
33889
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32842
33890
 
32843
33891
  // ../../packages/persistence/src/warn-era-cap.ts
32844
33892
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32845
- import { join as join13 } from "path";
33893
+ import { join as join15 } from "path";
32846
33894
  var MARKER = "warn-era-capped";
32847
33895
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32848
33896
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32849
- const marker = join13(dataDir2, MARKER);
33897
+ const marker = join15(dataDir2, MARKER);
32850
33898
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32851
33899
  const capped = db.policies.capCategoryActions();
32852
33900
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32883,6 +33931,12 @@ var RemoteRequestInvalid = class extends Error {
32883
33931
  }
32884
33932
  cause;
32885
33933
  };
33934
+ var RemoteEndpointRefused = class extends Error {
33935
+ constructor(endpoint) {
33936
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
33937
+ this.name = "RemoteEndpointRefused";
33938
+ }
33939
+ };
32886
33940
  var RemoteResponseInvalid = class extends Error {
32887
33941
  constructor(route, detail) {
32888
33942
  super(`control plane answered ${route} with ${detail}`);
@@ -33035,14 +34089,15 @@ function parsed(schema, body, route) {
33035
34089
  }
33036
34090
  return result.data;
33037
34091
  }
33038
- function withoutTrailingSlashes(endpoint) {
34092
+ function resolveBaseUrl(endpoint) {
34093
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
33039
34094
  let end = endpoint.length;
33040
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
34095
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
33041
34096
  return endpoint.slice(0, end);
33042
34097
  }
33043
- var SLASH = "/".charCodeAt(0);
34098
+ var SLASH2 = "/".charCodeAt(0);
33044
34099
  function createRemoteClient(options) {
33045
- const base = withoutTrailingSlashes(options.endpoint);
34100
+ const base = resolveBaseUrl(options.endpoint);
33046
34101
  const url2 = (route) => `${base}${route}`;
33047
34102
  const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
33048
34103
  const sendOne = async (event) => {
@@ -33172,6 +34227,7 @@ function classifyRemoteFailure(err) {
33172
34227
  case "RemoteRouteAbsent":
33173
34228
  return "route-absent";
33174
34229
  case "RemoteRequestInvalid":
34230
+ case "RemoteEndpointRefused":
33175
34231
  return "invalid-request";
33176
34232
  case "RemoteResponseInvalid":
33177
34233
  return "rejected";
@@ -33222,11 +34278,11 @@ function withTimeout(promise2, ms) {
33222
34278
  }
33223
34279
 
33224
34280
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
33225
- import { readFileSync as readFileSync8 } from "fs";
33226
- import { join as join14 } from "path";
34281
+ import { readFileSync as readFileSync10 } from "fs";
34282
+ import { join as join16 } from "path";
33227
34283
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
33228
34284
  function forwardDropsPath(dataDir2) {
33229
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
34285
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
33230
34286
  }
33231
34287
  function recordForwardDrops(dataDir2, count, nowMs) {
33232
34288
  if (count <= 0) return;
@@ -33244,7 +34300,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
33244
34300
  }
33245
34301
  function readForwardDrops(dataDir2) {
33246
34302
  try {
33247
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
34303
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
33248
34304
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
33249
34305
  const record2 = parsed2;
33250
34306
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -33262,13 +34318,12 @@ function readForwardDrops(dataDir2) {
33262
34318
 
33263
34319
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33264
34320
  import { randomUUID as randomUUID15 } from "crypto";
33265
- import { readFileSync as readFileSync15 } from "fs";
33266
34321
  import { readFile, rename, writeFile } from "fs/promises";
33267
- import { join as join24 } from "path";
34322
+ import { join as join26 } from "path";
33268
34323
 
33269
34324
  // ../../packages/plugin-sdk/src/config.ts
33270
34325
  import { existsSync as existsSync8 } from "fs";
33271
- import { join as join15 } from "path";
34326
+ import { join as join17 } from "path";
33272
34327
 
33273
34328
  // ../../packages/plugin-sdk/src/provider-env.ts
33274
34329
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33322,7 +34377,7 @@ function resolveProvider() {
33322
34377
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33323
34378
  try {
33324
34379
  ensureLayoutDirSync(base);
33325
- const settingsFile = join15(settingsDir(base), "settings.json");
34380
+ const settingsFile = join17(settingsDir(base), "settings.json");
33326
34381
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33327
34382
  } catch {
33328
34383
  }
@@ -33346,9 +34401,9 @@ function resolveProviderSafe(resolveProviderFn) {
33346
34401
  }
33347
34402
 
33348
34403
  // ../../packages/plugin-sdk/src/config-inventory.ts
33349
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34404
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33350
34405
  import { homedir as homedir2 } from "os";
33351
- import { basename as basename4, join as join17 } from "path";
34406
+ import { basename as basename4, join as join19 } from "path";
33352
34407
 
33353
34408
  // ../../packages/detections/src/egress/registry.ts
33354
34409
  var EXTRACTOR_VERSION = "1";
@@ -34110,8 +35165,8 @@ function isCorroborated(candidate, candidates, text) {
34110
35165
  "label",
34111
35166
  req,
34112
35167
  () => labels.map((label) => {
34113
- const trimmed = label.trim();
34114
- return trimmed.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed)}(?![A-Za-z0-9])`, "i");
35168
+ const trimmed2 = label.trim();
35169
+ return trimmed2.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed2)}(?![A-Za-z0-9])`, "i");
34115
35170
  })
34116
35171
  )) {
34117
35172
  if (re?.test(haystack)) return true;
@@ -34371,6 +35426,96 @@ function whole(command) {
34371
35426
  return { start: 0, end: command.length };
34372
35427
  }
34373
35428
 
35429
+ // ../../packages/detections/src/posture/web-capture-posture.ts
35430
+ var RULE_VERSION2 = "1";
35431
+ var DRIFT_MIN_PARSE_FAILURES = 2;
35432
+ var WEB_CAPTURE_DRIFT_STATES = /* @__PURE__ */ new Set([
35433
+ "blind",
35434
+ "degraded"
35435
+ ]);
35436
+ var WEB_CAPTURE_DRIFT_RULE = {
35437
+ ruleId: "web-capture-drift",
35438
+ version: RULE_VERSION2,
35439
+ name: "Web chat capture is not reading the site",
35440
+ category: "config",
35441
+ severity: "medium",
35442
+ definition: JSON.stringify({
35443
+ kind: "web-capture-drift",
35444
+ states: [...WEB_CAPTURE_DRIFT_STATES],
35445
+ minParseFailures: DRIFT_MIN_PARSE_FAILURES
35446
+ })
35447
+ };
35448
+ function deriveWebCaptureState(status) {
35449
+ if (status === void 0) return "unreported";
35450
+ if (status.conversationEndpoints === 0) return "standby";
35451
+ if (!status.patched) return "unpatched";
35452
+ if (status.blind) return "blind";
35453
+ if (status.shapeMisses.length > 0) return "degraded";
35454
+ if (status.parseFailures >= DRIFT_MIN_PARSE_FAILURES) return "degraded";
35455
+ return status.live ? "active" : "idle";
35456
+ }
35457
+ var STATE_SEVERITY = {
35458
+ blind: 0,
35459
+ degraded: 1,
35460
+ unpatched: 2,
35461
+ idle: 3,
35462
+ standby: 4,
35463
+ active: 5,
35464
+ unreported: 6
35465
+ };
35466
+ function worseThan(a, b) {
35467
+ const sa = STATE_SEVERITY[deriveWebCaptureState(a.status)];
35468
+ const sb = STATE_SEVERITY[deriveWebCaptureState(b.status)];
35469
+ if (sa !== sb) return sa < sb;
35470
+ if (a.observedAt !== b.observedAt) return a.observedAt > b.observedAt;
35471
+ return (a.rootSessionId ?? "") > (b.rootSessionId ?? "");
35472
+ }
35473
+ function reportedCaptureDocumentForSite(documents) {
35474
+ let newestReport = "";
35475
+ for (const d of documents) if (d.lastReportAt > newestReport) newestReport = d.lastReportAt;
35476
+ const retired = (d) => {
35477
+ if (d.closed) return true;
35478
+ const behind = Date.parse(newestReport) - Date.parse(d.lastReportAt);
35479
+ return Number.isFinite(behind) && behind > CAPTURE_STATUS_DOCUMENT_QUIET_MS;
35480
+ };
35481
+ const voting = documents.filter((d) => !retired(d));
35482
+ const tested = voting.some((d) => webCaptureStatusObservedTurnPath(d.status));
35483
+ const pool = tested ? voting : documents;
35484
+ let worst;
35485
+ for (const d of pool) if (worst === void 0 || worseThan(d, worst)) worst = d;
35486
+ return worst;
35487
+ }
35488
+ var STATIC_COPY = {
35489
+ active: { headline: "turns are being observed on this site" },
35490
+ unreported: {
35491
+ // Says "recently" rather than "yet": the store read is bounded to
35492
+ // CAPTURE_STATUS_RECENCY_MS, so this state covers a site nothing has ever
35493
+ // reported for AND one whose last report has aged out. The two are the
35494
+ // same fact to a reader — nobody has confirmed anything lately — and the
35495
+ // copy may not claim the stronger of them.
35496
+ headline: `no report in the last ${String(CAPTURE_STATUS_RECENCY_DAYS)} days \u2014 open the site in Chrome with the extension loaded`
35497
+ },
35498
+ standby: {
35499
+ headline: "this build declares no endpoints for the site, so nothing is observed yet"
35500
+ },
35501
+ unpatched: {
35502
+ // Says what the flags say and no more. `patched` is false both for a tap
35503
+ // that installed and hooked neither transport and for one that never ran
35504
+ // at all — a page reports the same status either way, so the copy may not
35505
+ // assert one of them.
35506
+ headline: "the page tap captured neither fetch nor XHR \u2014 it may not have installed; reload the extension at chrome://extensions"
35507
+ },
35508
+ idle: { headline: "watching; no turn has been observed yet" },
35509
+ blind: {
35510
+ headline: "messages were sent in the page that the network capture never saw",
35511
+ remediation: "reload the tab. If it persists after `aka update` and reloading the extension at chrome://extensions, the site's send path has changed and needs a new extension build."
35512
+ },
35513
+ degraded: {
35514
+ headline: "the site's payloads no longer carry the fields the extension reads",
35515
+ remediation: "run `aka update`, then reload the extension at chrome://extensions. If it stays degraded after an update, the site's contract has changed and needs a new extension build."
35516
+ }
35517
+ };
35518
+
34374
35519
  // ../../packages/detections/src/security/redos-probe.ts
34375
35520
  var BUDGET_MS = 100;
34376
35521
  var EXPONENTIAL_UNITS = [
@@ -36564,8 +37709,8 @@ function maskText(text) {
36564
37709
  }
36565
37710
 
36566
37711
  // ../../packages/plugin-sdk/src/repo.ts
36567
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36568
- import { basename as basename3, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
37712
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37713
+ import { basename as basename3, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36569
37714
  function resolveRepoIdentity(cwd) {
36570
37715
  try {
36571
37716
  const root = findGitRoot(cwd);
@@ -36615,7 +37760,7 @@ function resolveGitBranch(cwd) {
36615
37760
  try {
36616
37761
  const root = findGitRoot(cwd);
36617
37762
  if (!root) return void 0;
36618
- const dotGit = join16(root, ".git");
37763
+ const dotGit = join18(root, ".git");
36619
37764
  let gitdir;
36620
37765
  try {
36621
37766
  gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
@@ -36623,7 +37768,7 @@ function resolveGitBranch(cwd) {
36623
37768
  return void 0;
36624
37769
  }
36625
37770
  if (gitdir === void 0) return void 0;
36626
- const head = safeRead(join16(gitdir, "HEAD"));
37771
+ const head = safeRead(join18(gitdir, "HEAD"));
36627
37772
  if (!head) return void 0;
36628
37773
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
36629
37774
  } catch {
@@ -36633,41 +37778,41 @@ function resolveGitBranch(cwd) {
36633
37778
  function resolveWorktreeGitdir(root, dotGitFile) {
36634
37779
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
36635
37780
  if (!target) return void 0;
36636
- return isAbsolute(target) ? target : join16(root, target);
37781
+ return isAbsolute(target) ? target : join18(root, target);
36637
37782
  }
36638
37783
  function findGitRoot(start) {
36639
37784
  let dir = start;
36640
37785
  for (; ; ) {
36641
- if (existsSync9(join16(dir, ".git"))) return dir;
37786
+ if (existsSync9(join18(dir, ".git"))) return dir;
36642
37787
  const parent = dirname4(dir);
36643
37788
  if (parent === dir) return void 0;
36644
37789
  dir = parent;
36645
37790
  }
36646
37791
  }
36647
37792
  function resolveGitContext(root) {
36648
- const dotGit = join16(root, ".git");
37793
+ const dotGit = join18(root, ".git");
36649
37794
  try {
36650
37795
  if (statSync6(dotGit).isDirectory()) {
36651
- return { configPath: join16(dotGit, "config"), headRoot: root };
37796
+ return { configPath: join18(dotGit, "config"), headRoot: root };
36652
37797
  }
36653
37798
  } catch {
36654
37799
  return void 0;
36655
37800
  }
36656
37801
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36657
37802
  if (!target) return void 0;
36658
- const gitdir = isAbsolute(target) ? target : join16(root, target);
36659
- if (existsSync9(join16(gitdir, "config"))) {
36660
- return { configPath: join16(gitdir, "config"), headRoot: root };
37803
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
37804
+ if (existsSync9(join18(gitdir, "config"))) {
37805
+ return { configPath: join18(gitdir, "config"), headRoot: root };
36661
37806
  }
36662
- const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
37807
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
36663
37808
  if (!commonRaw) return void 0;
36664
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
37809
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
36665
37810
  const headRoot = basename3(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36666
- return { configPath: join16(commonGitDir, "config"), headRoot };
37811
+ return { configPath: join18(commonGitDir, "config"), headRoot };
36667
37812
  }
36668
37813
  function safeRead(path) {
36669
37814
  try {
36670
- return readFileSync9(path, "utf8");
37815
+ return readFileSync11(path, "utf8");
36671
37816
  } catch {
36672
37817
  return void 0;
36673
37818
  }
@@ -36729,31 +37874,31 @@ function resolveConfigInventory(input2) {
36729
37874
  };
36730
37875
  try {
36731
37876
  const home = input2.homeDir ?? homedir2();
36732
- const claudeDir = join17(home, ".claude");
37877
+ const claudeDir = join19(home, ".claude");
36733
37878
  const repo = resolveRepoIdentity(input2.cwd);
36734
37879
  const repoIdentity = repo?.url ?? input2.cwd;
36735
37880
  const projectSource = `project:${repoIdentity}`;
36736
- collectSettingsHooks(scan2, join17(claudeDir, "settings.json"), "user");
36737
- collectSettingsHooks(scan2, join17(input2.cwd, ".claude", "settings.json"), "project");
36738
- collectSettingsHooks(scan2, join17(input2.cwd, ".claude", "settings.local.json"), "local");
37881
+ collectSettingsHooks(scan2, join19(claudeDir, "settings.json"), "user");
37882
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.json"), "project");
37883
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.local.json"), "local");
36739
37884
  const projectOrigin = { scope: "project", project: repoIdentity };
36740
- collectMcpFile(scan2, join17(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
36741
- collectUserClaudeJson(scan2, join17(home, ".claude.json"), input2.cwd, repoIdentity);
36742
- collectMcpFile(scan2, join17(claudeDir, "settings.json"), { scope: "user" });
36743
- collectMcpFile(scan2, join17(input2.cwd, ".claude", "settings.json"), projectOrigin);
36744
- collectMcpFile(scan2, join17(input2.cwd, ".claude", "settings.local.json"), {
37885
+ collectMcpFile(scan2, join19(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
37886
+ collectUserClaudeJson(scan2, join19(home, ".claude.json"), input2.cwd, repoIdentity);
37887
+ collectMcpFile(scan2, join19(claudeDir, "settings.json"), { scope: "user" });
37888
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.json"), projectOrigin);
37889
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.local.json"), {
36745
37890
  scope: "local",
36746
37891
  project: repoIdentity
36747
37892
  });
36748
37893
  collectConfigFiles(scan2, claudeDir, input2.cwd);
36749
- collectSkillsDir(scan2, join17(claudeDir, "skills"), { source: "local", scope: "user" });
36750
- collectSkillsDir(scan2, join17(input2.cwd, ".claude", "skills"), {
37894
+ collectSkillsDir(scan2, join19(claudeDir, "skills"), { source: "local", scope: "user" });
37895
+ collectSkillsDir(scan2, join19(input2.cwd, ".claude", "skills"), {
36751
37896
  source: projectSource,
36752
37897
  scope: "project"
36753
37898
  });
36754
37899
  collectInstalledPlugins(scan2, claudeDir);
36755
37900
  collectMarketplaceSkills(scan2, claudeDir);
36756
- collectSkillsDir(scan2, join17(input2.cwd, "skills"), { source: projectSource, scope: "project" });
37901
+ collectSkillsDir(scan2, join19(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36757
37902
  scan2.skills = dedupeSkills(scan2.skills);
36758
37903
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
36759
37904
  } catch (err) {
@@ -36869,8 +38014,8 @@ function collectUserClaudeJson(scan2, path, cwd, repoIdentity) {
36869
38014
  }
36870
38015
  function projectEntryFor(projects, cwd) {
36871
38016
  const candidates = /* @__PURE__ */ new Set([cwd]);
36872
- const trimmed = cwd.replace(/\/+$/, "");
36873
- if (trimmed.length > 0) candidates.add(trimmed);
38017
+ const trimmed2 = cwd.replace(/\/+$/, "");
38018
+ if (trimmed2.length > 0) candidates.add(trimmed2);
36874
38019
  try {
36875
38020
  candidates.add(realpathSync2(cwd));
36876
38021
  } catch {
@@ -36882,7 +38027,7 @@ function projectEntryFor(projects, cwd) {
36882
38027
  return void 0;
36883
38028
  }
36884
38029
  function collectPluginManifestMcp(scan2, installPath, origin) {
36885
- const manifestPath = join17(installPath, ".claude-plugin", "plugin.json");
38030
+ const manifestPath = join19(installPath, ".claude-plugin", "plugin.json");
36886
38031
  const raw = readOptional(manifestPath);
36887
38032
  if (raw === void 0) return;
36888
38033
  try {
@@ -36890,7 +38035,7 @@ function collectPluginManifestMcp(scan2, installPath, origin) {
36890
38035
  if (typeof parsed2 !== "object" || parsed2 === null) return;
36891
38036
  const declared = parsed2.mcpServers;
36892
38037
  if (typeof declared === "string" && declared.length > 0) {
36893
- collectMcpFile(scan2, join17(installPath, declared), origin, { recordErrors: true });
38038
+ collectMcpFile(scan2, join19(installPath, declared), origin, { recordErrors: true });
36894
38039
  } else {
36895
38040
  collectMcpObject(scan2, declared, manifestPath, origin);
36896
38041
  }
@@ -36907,14 +38052,14 @@ var SETTINGS_KEY_LABELS = [
36907
38052
  ["statusLine", "status line"]
36908
38053
  ];
36909
38054
  function collectConfigFiles(scan2, claudeDir, cwd) {
36910
- settingsConfigFile(scan2, join17(claudeDir, "settings.json"), "user", "User settings");
36911
- settingsConfigFile(scan2, join17(cwd, ".claude", "settings.json"), "project", "Project settings");
36912
- settingsConfigFile(scan2, join17(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
36913
- memoryConfigFile(scan2, join17(claudeDir, "CLAUDE.md"), "user", "User memory");
36914
- memoryConfigFile(scan2, join17(cwd, "CLAUDE.md"), "project", "Project memory");
36915
- mcpJsonConfigFile(scan2, join17(cwd, ".mcp.json"));
36916
- dirConfigFile(scan2, join17(cwd, ".claude", "commands"), "Slash commands", "command");
36917
- dirConfigFile(scan2, join17(cwd, ".claude", "agents"), "Subagents", "subagent");
38055
+ settingsConfigFile(scan2, join19(claudeDir, "settings.json"), "user", "User settings");
38056
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.json"), "project", "Project settings");
38057
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
38058
+ memoryConfigFile(scan2, join19(claudeDir, "CLAUDE.md"), "user", "User memory");
38059
+ memoryConfigFile(scan2, join19(cwd, "CLAUDE.md"), "project", "Project memory");
38060
+ mcpJsonConfigFile(scan2, join19(cwd, ".mcp.json"));
38061
+ dirConfigFile(scan2, join19(cwd, ".claude", "commands"), "Slash commands", "command");
38062
+ dirConfigFile(scan2, join19(cwd, ".claude", "agents"), "Subagents", "subagent");
36918
38063
  }
36919
38064
  function configFileEntry(path, scope, kind) {
36920
38065
  try {
@@ -36947,8 +38092,8 @@ function memoryConfigFile(scan2, path, scope, kind) {
36947
38092
  if (!entry) return;
36948
38093
  const raw = readOptional(path);
36949
38094
  if (raw !== void 0) {
36950
- const trimmed = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
36951
- const lines = trimmed === "" ? 0 : trimmed.split("\n").length;
38095
+ const trimmed2 = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
38096
+ const lines = trimmed2 === "" ? 0 : trimmed2.split("\n").length;
36952
38097
  entry.detail = `${String(lines)} lines`;
36953
38098
  }
36954
38099
  scan2.configFiles.push(entry);
@@ -36989,7 +38134,7 @@ function countMarkdownFiles(dir, depth) {
36989
38134
  let count = 0;
36990
38135
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
36991
38136
  if (dirent.name.startsWith(".")) continue;
36992
- if (dirent.isDirectory()) count += countMarkdownFiles(join17(dir, dirent.name), depth + 1);
38137
+ if (dirent.isDirectory()) count += countMarkdownFiles(join19(dir, dirent.name), depth + 1);
36993
38138
  else if (dirent.name.endsWith(".md")) count += 1;
36994
38139
  }
36995
38140
  return count;
@@ -37002,7 +38147,7 @@ function collectSkillsDir(scan2, dir, origin) {
37002
38147
  return;
37003
38148
  }
37004
38149
  for (const name2 of names) {
37005
- const skillFile = join17(dir, name2, "SKILL.md");
38150
+ const skillFile = join19(dir, name2, "SKILL.md");
37006
38151
  try {
37007
38152
  const raw = readOptional(skillFile);
37008
38153
  if (raw === void 0) continue;
@@ -37011,7 +38156,7 @@ function collectSkillsDir(scan2, dir, origin) {
37011
38156
  name: front.name ?? name2,
37012
38157
  source: origin.source,
37013
38158
  scope: origin.scope,
37014
- location: join17(dir, name2),
38159
+ location: join19(dir, name2),
37015
38160
  updatedAt: statSync7(skillFile).mtime.toISOString()
37016
38161
  };
37017
38162
  const version3 = front.version ?? origin.defaultVersion;
@@ -37042,7 +38187,7 @@ function parseFrontmatter(raw) {
37042
38187
  return out;
37043
38188
  }
37044
38189
  function collectInstalledPlugins(scan2, claudeDir) {
37045
- const manifestPath = join17(claudeDir, "plugins", "installed_plugins.json");
38190
+ const manifestPath = join19(claudeDir, "plugins", "installed_plugins.json");
37046
38191
  const raw = readOptional(manifestPath);
37047
38192
  if (raw === void 0) return;
37048
38193
  let plugins;
@@ -37067,7 +38212,7 @@ function collectInstalledPlugins(scan2, claudeDir) {
37067
38212
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
37068
38213
  seen.add(installPath);
37069
38214
  const version3 = install.version;
37070
- const hooksPath = join17(installPath, "hooks", "hooks.json");
38215
+ const hooksPath = join19(installPath, "hooks", "hooks.json");
37071
38216
  const hooksRaw = readOptional(hooksPath);
37072
38217
  if (hooksRaw !== void 0) {
37073
38218
  try {
@@ -37087,22 +38232,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
37087
38232
  }
37088
38233
  const origin = { source: marketplace, scope: "plugin", pluginName };
37089
38234
  if (typeof version3 === "string") origin.defaultVersion = version3;
37090
- collectSkillsDir(scan2, join17(installPath, "skills"), origin);
38235
+ collectSkillsDir(scan2, join19(installPath, "skills"), origin);
37091
38236
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
37092
- collectMcpFile(scan2, join17(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
38237
+ collectMcpFile(scan2, join19(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
37093
38238
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
37094
38239
  }
37095
38240
  }
37096
38241
  }
37097
38242
  function collectMarketplaceSkills(scan2, claudeDir) {
37098
- for (const mp of readMarketplaces(join17(claudeDir, "plugins", "known_marketplaces.json"))) {
38243
+ for (const mp of readMarketplaces(join19(claudeDir, "plugins", "known_marketplaces.json"))) {
37099
38244
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
37100
- collectSkillsDir(scan2, join17(mp.installLocation, "skills"), {
38245
+ collectSkillsDir(scan2, join19(mp.installLocation, "skills"), {
37101
38246
  source: mp.name,
37102
38247
  scope: "plugin"
37103
38248
  });
37104
- collectPluginSkillDirs(scan2, join17(mp.installLocation, "plugins"), mp.name);
37105
- collectPluginSkillDirs(scan2, join17(mp.installLocation, "external_plugins"), mp.name);
38249
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "plugins"), mp.name);
38250
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "external_plugins"), mp.name);
37106
38251
  }
37107
38252
  }
37108
38253
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -37113,7 +38258,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
37113
38258
  return;
37114
38259
  }
37115
38260
  for (const plugin of plugins) {
37116
- collectSkillsDir(scan2, join17(pluginsDir, plugin, "skills"), {
38261
+ collectSkillsDir(scan2, join19(pluginsDir, plugin, "skills"), {
37117
38262
  source: marketplace,
37118
38263
  scope: "plugin",
37119
38264
  pluginName: plugin
@@ -37167,7 +38312,7 @@ function dedupeMcpServers(servers) {
37167
38312
  }
37168
38313
  function readOptional(path) {
37169
38314
  try {
37170
- return readFileSync10(path, "utf8");
38315
+ return readFileSync12(path, "utf8");
37171
38316
  } catch {
37172
38317
  return void 0;
37173
38318
  }
@@ -37190,6 +38335,9 @@ function str2(value) {
37190
38335
  function offersMaintenance(gateway, member) {
37191
38336
  return typeof gateway[member] === "function";
37192
38337
  }
38338
+ function offersCaptureStatusReader(gateway) {
38339
+ return typeof gateway.readCaptureStatuses === "function";
38340
+ }
37193
38341
 
37194
38342
  // ../../packages/plugin-sdk/src/events.ts
37195
38343
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -37698,8 +38846,8 @@ function createGuardedScanner(partition, gateway, opts) {
37698
38846
  }
37699
38847
 
37700
38848
  // ../../packages/plugin-sdk/src/host-floor.ts
37701
- import { readFileSync as readFileSync12 } from "fs";
37702
- import { join as join19 } from "path";
38849
+ import { readFileSync as readFileSync14 } from "fs";
38850
+ import { join as join21 } from "path";
37703
38851
 
37704
38852
  // ../../packages/plugin-sdk/src/model-governance.ts
37705
38853
  import {
@@ -37707,11 +38855,11 @@ import {
37707
38855
  fstatSync,
37708
38856
  mkdirSync as mkdirSync2,
37709
38857
  openSync as openSync2,
37710
- readFileSync as readFileSync11,
38858
+ readFileSync as readFileSync13,
37711
38859
  readSync,
37712
38860
  writeFileSync as writeFileSync5
37713
38861
  } from "fs";
37714
- import { join as join18 } from "path";
38862
+ import { join as join20 } from "path";
37715
38863
  var TAIL_BYTES = 256 * 1024;
37716
38864
 
37717
38865
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -37734,11 +38882,11 @@ var HOST_FLOORS = {
37734
38882
 
37735
38883
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37736
38884
  var import_ignore = __toESM(require_ignore(), 1);
37737
- import { readFileSync as readFileSync13 } from "fs";
37738
- import { join as join20 } from "path";
38885
+ import { readFileSync as readFileSync15 } from "fs";
38886
+ import { join as join22 } from "path";
37739
38887
  function readIgnoreLayer(dir, filename, anchorLen) {
37740
38888
  try {
37741
- return { matcher: (0, import_ignore.default)().add(readFileSync13(join20(dir, filename), "utf8")), anchorLen };
38889
+ return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
37742
38890
  } catch {
37743
38891
  return void 0;
37744
38892
  }
@@ -37795,17 +38943,17 @@ function resolveInventoryContext(input2) {
37795
38943
  }
37796
38944
 
37797
38945
  // ../../packages/plugin-sdk/src/nudge.ts
37798
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
37799
- import { join as join21 } from "path";
38946
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
38947
+ import { join as join23 } from "path";
37800
38948
  var SESSION_START_MARKER = "session-start-last";
37801
38949
  function claimSessionStart(dataDir2, sessionId) {
37802
38950
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
37803
38951
  }
37804
38952
  function claimOncePerSession(dataDir2, marker, sessionId) {
37805
38953
  if (!sessionId) return true;
37806
- const path = join21(dataDir2, marker);
38954
+ const path = join23(dataDir2, marker);
37807
38955
  try {
37808
- if (readFileSync14(path, "utf8") === sessionId) return false;
38956
+ if (readFileSync16(path, "utf8") === sessionId) return false;
37809
38957
  } catch {
37810
38958
  }
37811
38959
  try {
@@ -37857,7 +39005,7 @@ function createPolicyResolver(bundle) {
37857
39005
 
37858
39006
  // ../../packages/plugin-sdk/src/project-files.ts
37859
39007
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37860
- import { basename as basename6, join as join22 } from "path";
39008
+ import { basename as basename6, join as join24 } from "path";
37861
39009
  var SKIP_DIRS = /* @__PURE__ */ new Set([
37862
39010
  ".git",
37863
39011
  "node_modules",
@@ -37954,8 +39102,8 @@ function resolveProjectFiles(cwd, opts = {}) {
37954
39102
  }
37955
39103
  if (entry.isDirectory()) {
37956
39104
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
37957
- const fullPath = join22(dir, entry.name);
37958
- if (existsSync11(join22(fullPath, ".git"))) continue;
39105
+ const fullPath = join24(dir, entry.name);
39106
+ if (existsSync11(join24(fullPath, ".git"))) continue;
37959
39107
  if (depth >= bounds.maxDepth) {
37960
39108
  walk.omitted = true;
37961
39109
  continue;
@@ -38067,7 +39215,7 @@ function createPluginRuntime(gateway, settings, opts) {
38067
39215
  bundlesPacked = true;
38068
39216
  }
38069
39217
  const policyMode = settings.policy;
38070
- const redactFallback = settings.redactFallback;
39218
+ let redactFallback = settings.redactFallback;
38071
39219
  const dataDir2 = opts?.dataDir;
38072
39220
  let rules = [];
38073
39221
  let scanner;
@@ -38111,6 +39259,7 @@ function createPluginRuntime(gateway, settings, opts) {
38111
39259
  rules = [...verified, ...unverified];
38112
39260
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
38113
39261
  bundleExceptions = bundle.exceptions ?? [];
39262
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
38114
39263
  initialized = true;
38115
39264
  }
38116
39265
  let cachedKey;
@@ -38149,11 +39298,13 @@ function createPluginRuntime(gateway, settings, opts) {
38149
39298
  function decide(findings, text, excepted, rewritable = true) {
38150
39299
  if (findings.length === 0) return { action: "log", text, findings: [] };
38151
39300
  const actionFor = (finding2) => actionForFinding(finding2, excepted, rewritable);
39301
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
39302
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
38152
39303
  let worst = "log";
38153
39304
  for (const finding2 of findings) {
38154
39305
  worst = strongerAction(worst, actionFor(finding2));
38155
39306
  }
38156
- if (worst === "block") return { action: "block", text: null, findings };
39307
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
38157
39308
  if (worst === "redact") {
38158
39309
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
38159
39310
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -38163,9 +39314,13 @@ function createPluginRuntime(gateway, settings, opts) {
38163
39314
  findings,
38164
39315
  enforcedFindings: redactFindings,
38165
39316
  reversibleFindings
39317
+ // No `degraded` here, and it is not an omission: `rewritable` is per
39318
+ // CAPTURE, so on an unrewritable field every redact has already become
39319
+ // the fallback and this branch is unreachable. Spreading it would read
39320
+ // as a case that can happen.
38166
39321
  };
38167
39322
  }
38168
- return { action: worst, text, findings };
39323
+ return { action: worst, text, findings, ...degraded };
38169
39324
  }
38170
39325
  function fingerprintOf(key, finding2, cache) {
38171
39326
  let fp = cache.get(finding2);
@@ -38294,8 +39449,8 @@ function createPluginRuntime(gateway, settings, opts) {
38294
39449
  };
38295
39450
  }
38296
39451
  }
38297
- async function processText(text, context) {
38298
- return (await evaluate(text, context, {})).decision;
39452
+ async function processText(text, context, opts2 = {}) {
39453
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
38299
39454
  }
38300
39455
  async function capture(input2, opts2 = {}) {
38301
39456
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -38318,10 +39473,12 @@ function createPluginRuntime(gateway, settings, opts) {
38318
39473
  );
38319
39474
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
38320
39475
  const inspectionMs = elapsedMs(timingStartedAt);
38321
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
39476
+ const redactDegradedTo = decision.redactDegradedTo;
39477
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
38322
39478
  ...input2.metadata,
38323
39479
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
38324
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
39480
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
39481
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
38325
39482
  } : input2.metadata;
38326
39483
  const event = buildIngestEvent({
38327
39484
  kind: input2.kind,
@@ -38393,9 +39550,9 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38393
39550
 
38394
39551
  // ../../packages/plugin-sdk/src/throttle.ts
38395
39552
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38396
- import { join as join23 } from "path";
39553
+ import { join as join25 } from "path";
38397
39554
  function throttled(dataDir2, markerName, windowMs) {
38398
- const marker = join23(dataDir2, markerName);
39555
+ const marker = join25(dataDir2, markerName);
38399
39556
  try {
38400
39557
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
38401
39558
  } catch {
@@ -38422,31 +39579,12 @@ function isServerRejection(err) {
38422
39579
  var FORWARD_BUDGET_MS = 1500;
38423
39580
  var DECISION_PATH_BUDGET_MS = 800;
38424
39581
  var BREAKER_FAILURE_THRESHOLD = 3;
38425
- var BREAKER_COOLDOWN_MS = 3e4;
38426
39582
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
38427
- var FAILURES = /* @__PURE__ */ new Set([
38428
- "unauthorized",
38429
- "forbidden",
38430
- "unreachable"
38431
- ]);
38432
39583
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
38433
39584
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
38434
- function parseBreakerState(raw, nowMs) {
38435
- try {
38436
- const parsed2 = JSON.parse(raw);
38437
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
38438
- const record2 = parsed2;
38439
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
38440
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
38441
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
38442
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
38443
- } catch {
38444
- return null;
38445
- }
38446
- }
38447
39585
  function createForwardPolicy(deps) {
38448
39586
  const now = deps.now ?? (() => Date.now());
38449
- const file2 = join24(deps.dir, STATE_FILENAME);
39587
+ const file2 = join26(deps.dir, STATE_FILENAME);
38450
39588
  let state = null;
38451
39589
  let loading = null;
38452
39590
  async function readState() {
@@ -38456,7 +39594,7 @@ function createForwardPolicy(deps) {
38456
39594
  } catch {
38457
39595
  return { ...CLOSED };
38458
39596
  }
38459
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39597
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
38460
39598
  }
38461
39599
  async function load() {
38462
39600
  if (state !== null) return state;
@@ -38502,7 +39640,7 @@ function createForwardPolicy(deps) {
38502
39640
  };
38503
39641
  const at = now();
38504
39642
  if (current.openedAtMs !== null) {
38505
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39643
+ if (isForwardPaused(current, at)) {
38506
39644
  return { ok: false, reason: "breaker-open" };
38507
39645
  }
38508
39646
  await persist({
@@ -38539,86 +39677,10 @@ function createForwardPolicy(deps) {
38539
39677
  }
38540
39678
 
38541
39679
  // ../../packages/plugin-runtime/src/attached/gateway.ts
38542
- function strongerOf(a, b) {
38543
- if (a === null) return b;
38544
- if (b === null) return a;
38545
- return strongerAction(a, b);
38546
- }
38547
- function ruleCategoryMap(wireRules, localRules) {
38548
- const map2 = /* @__PURE__ */ new Map();
38549
- for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
38550
- for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
38551
- for (const pack of bundledDetections()) {
38552
- for (const rule of pack.rules) map2.set(rule.id, rule.category);
38553
- }
38554
- return map2;
38555
- }
38556
- function policyKey(policy) {
38557
- return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
38558
- }
38559
- function floorFor(policy, categoryByRuleId) {
38560
- const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
38561
- return category === void 0 ? null : DEFAULT_ACTIONS[category];
38562
- }
38563
- function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
38564
- const merged = /* @__PURE__ */ new Map();
38565
- const disabled = [];
38566
- const remoteCategoryAction = /* @__PURE__ */ new Map();
38567
- for (const policy of remotePolicies) {
38568
- if (!policy.enabled) continue;
38569
- if (!("category" in policy.target)) continue;
38570
- if (remoteCategoryAction.has(policy.target.category)) continue;
38571
- const floor = floorFor(policy, categoryByRuleId);
38572
- remoteCategoryAction.set(
38573
- policy.target.category,
38574
- floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
38575
- );
38576
- }
38577
- for (const policy of localPolicies) {
38578
- if (!policy.enabled) {
38579
- disabled.push(policy);
38580
- continue;
38581
- }
38582
- const key = policyKey(policy);
38583
- if (merged.has(key)) continue;
38584
- let remoteFloor = null;
38585
- if ("ruleId" in policy.target) {
38586
- const category = categoryByRuleId.get(policy.target.ruleId);
38587
- if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
38588
- }
38589
- merged.set(
38590
- key,
38591
- remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
38592
- );
38593
- }
38594
- const localCategoryAction = /* @__PURE__ */ new Map();
38595
- for (const policy of merged.values()) {
38596
- if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
38597
- }
38598
- for (const policy of remotePolicies) {
38599
- if (!policy.enabled) {
38600
- disabled.push(policy);
38601
- continue;
38602
- }
38603
- const key = policyKey(policy);
38604
- const floor = floorFor(policy, categoryByRuleId);
38605
- let localFloor = null;
38606
- if ("ruleId" in policy.target) {
38607
- const category = categoryByRuleId.get(policy.target.ruleId);
38608
- if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
38609
- }
38610
- const effectiveFloor = strongerOf(floor, localFloor);
38611
- const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
38612
- const existing = merged.get(key);
38613
- if (existing === void 0) {
38614
- merged.set(key, clamped);
38615
- continue;
38616
- }
38617
- if (actionRank(clamped.action) > actionRank(existing.action)) {
38618
- merged.set(key, clamped);
38619
- }
38620
- }
38621
- return [...merged.values(), ...disabled];
39680
+ var bundledRulesFlatCache;
39681
+ function bundledRulesFlat() {
39682
+ bundledRulesFlatCache ??= bundledDetections().flatMap((pack) => pack.rules);
39683
+ return bundledRulesFlatCache;
38622
39684
  }
38623
39685
  var AttachedDataGateway = class {
38624
39686
  constructor(deps) {
@@ -38938,6 +40000,9 @@ var AttachedDataGateway = class {
38938
40000
  async readSessionProvider(sessionId) {
38939
40001
  return this.deps.local.readSessionProvider(sessionId);
38940
40002
  }
40003
+ async readCaptureStatuses() {
40004
+ return this.deps.local.readCaptureStatuses();
40005
+ }
38941
40006
  async facets() {
38942
40007
  return this.deps.local.facets();
38943
40008
  }
@@ -39020,7 +40085,7 @@ var AttachedDataGateway = class {
39020
40085
  policies: mergeRaiseOnly(
39021
40086
  local.policies,
39022
40087
  cached2.policies,
39023
- ruleCategoryMap(cached2.rules, local.rules)
40088
+ ruleCategoryMap(cached2.rules, local.rules, bundledRulesFlat())
39024
40089
  ),
39025
40090
  customKeywords: [...local.customKeywords, ...cached2.customKeywords],
39026
40091
  // TAKEN FROM THE CACHE, unlike the two fields below — and the asymmetry
@@ -39039,7 +40104,18 @@ var AttachedDataGateway = class {
39039
40104
  // and the spread above would otherwise drop the field silently — which is
39040
40105
  // exactly what it did, leaving the whole control inert on every device
39041
40106
  // while every test around it stayed green.
39042
- prohibitedModels: cached2.prohibitedModels
40107
+ prohibitedModels: cached2.prohibitedModels,
40108
+ // NAMED for the same reason as the line above, and it is the same defect
40109
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
40110
+ // only the cache carries is dropped in silence. That is what left
40111
+ // `prohibitedModels` inert on every attached device with every test
40112
+ // around it green.
40113
+ //
40114
+ // Taken from the cache rather than merged here, because merging it needs
40115
+ // the device's own SETTING — which is not a bundle field and is not in
40116
+ // scope at this seam. The runtime does that merge, raise-only, where both
40117
+ // values are in hand (createPluginRuntime's ensureInitialized).
40118
+ redactFallback: cached2.redactFallback
39043
40119
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39044
40120
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39045
40121
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39167,10 +40243,6 @@ function toolAuditEvent(input2) {
39167
40243
  };
39168
40244
  }
39169
40245
 
39170
- // ../../packages/plugin-runtime/src/attached/history-state.ts
39171
- import { readFileSync as readFileSync16 } from "fs";
39172
- import { join as join25 } from "path";
39173
-
39174
40246
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39175
40247
  import { createHash as createHash6 } from "crypto";
39176
40248
  import { hostname as hostname5 } from "os";
@@ -39179,6 +40251,10 @@ import { hostname as hostname5 } from "os";
39179
40251
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39180
40252
  var TRACE_ID = EventMetadata.shape.traceId;
39181
40253
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40254
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40255
+
40256
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
40257
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39182
40258
 
39183
40259
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39184
40260
  import { spawn } from "child_process";
@@ -39229,15 +40305,20 @@ function createPluginBlock(build, policyStore) {
39229
40305
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39230
40306
  import { randomUUID as randomUUID16 } from "crypto";
39231
40307
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39232
- import { join as join26 } from "path";
40308
+ import { join as join27 } from "path";
39233
40309
 
39234
40310
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39235
40311
  import { rename as rename2 } from "fs/promises";
39236
40312
  var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
39237
- var ATTEMPTS = 5;
40313
+ var IMMEDIATE_RETRIES = 8;
40314
+ var TIMED_RETRIES = 4;
40315
+ var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
39238
40316
  var delay = (ms) => new Promise((resolve2) => {
39239
40317
  setTimeout(resolve2, ms);
39240
40318
  });
40319
+ var yieldToLoop = () => new Promise((resolve2) => {
40320
+ setImmediate(resolve2);
40321
+ });
39241
40322
  async function publishByRename(tmp, file2, move = rename2) {
39242
40323
  for (let attempt = 1; ; attempt += 1) {
39243
40324
  try {
@@ -39246,14 +40327,14 @@ async function publishByRename(tmp, file2, move = rename2) {
39246
40327
  } catch (err) {
39247
40328
  const code = err.code;
39248
40329
  if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
39249
- await delay(attempt * 10);
40330
+ await (attempt <= IMMEDIATE_RETRIES ? yieldToLoop() : delay((attempt - IMMEDIATE_RETRIES) * 10));
39250
40331
  }
39251
40332
  }
39252
40333
  }
39253
40334
 
39254
40335
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39255
40336
  function createPolicyStore(dir = dataDir()) {
39256
- const file2 = join26(dir, "policy-cache.json");
40337
+ const file2 = join27(dir, "policy-cache.json");
39257
40338
  async function read() {
39258
40339
  try {
39259
40340
  const raw = await readFile2(file2, "utf8");
@@ -39484,11 +40565,11 @@ function readStorePosture(dbPath2) {
39484
40565
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39485
40566
  import { randomUUID as randomUUID17 } from "crypto";
39486
40567
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39487
- import { join as join27 } from "path";
40568
+ import { join as join28 } from "path";
39488
40569
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39489
40570
  function createPostureStore(dir = settingsDir(), legacyDir) {
39490
- const file2 = join27(dir, "posture-state.json");
39491
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
40571
+ const file2 = join28(dir, "posture-state.json");
40572
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
39492
40573
  async function persist(state) {
39493
40574
  await ensureDataDir(dir);
39494
40575
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39557,7 +40638,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39557
40638
 
39558
40639
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39559
40640
  import { readFileSync as readFileSync18 } from "fs";
39560
- import { join as join28 } from "path";
40641
+ import { join as join29 } from "path";
39561
40642
 
39562
40643
  // ../../packages/plugin-runtime/src/attached/status.ts
39563
40644
  var REFUSAL_LINES = {
@@ -39599,6 +40680,34 @@ function spawnDetached2(scriptPath) {
39599
40680
  child.unref();
39600
40681
  }
39601
40682
 
40683
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40684
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40685
+
40686
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40687
+ import { spawn as spawn3 } from "child_process";
40688
+ import { fileURLToPath as fileURLToPath4 } from "url";
40689
+ var CONTENT_RETENTION_MARKER_NAME = "content-retention-last-attempt";
40690
+ var CONTENT_RETENTION_SCRIPT_NAME = "content-retention.js";
40691
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40692
+ function triggerContentRetention(config2, deps = {}) {
40693
+ try {
40694
+ if (!config2.settings.bodyRetention.enabled) return;
40695
+ const isThrottled = deps.isThrottled ?? ((dir) => throttled(dir, CONTENT_RETENTION_MARKER_NAME, CONTENT_RETENTION_THROTTLE_MS));
40696
+ if (isThrottled(config2.dataDir)) return;
40697
+ const scriptPath = fileURLToPath4(
40698
+ deps.scriptUrl ?? new URL(CONTENT_RETENTION_SCRIPT_NAME, import.meta.url)
40699
+ );
40700
+ (deps.spawnChild ?? spawnDetached3)(scriptPath);
40701
+ } catch {
40702
+ }
40703
+ }
40704
+ function spawnDetached3(scriptPath) {
40705
+ const child = spawn3(process.execPath, [scriptPath], { detached: true, stdio: "ignore" });
40706
+ child.on("error", () => {
40707
+ });
40708
+ child.unref();
40709
+ }
40710
+
39602
40711
  // ../../packages/plugin-runtime/src/attached/factory.ts
39603
40712
  import { hostname as hostname6 } from "os";
39604
40713
 
@@ -39726,6 +40835,9 @@ var StandaloneDataGateway = class {
39726
40835
  readSessionProvider(sessionId) {
39727
40836
  return Promise.resolve(this.db.auditEvents.sessionProvider(sessionId));
39728
40837
  }
40838
+ readCaptureStatuses() {
40839
+ return Promise.resolve(this.db.captureStatus.latest(Date.now()));
40840
+ }
39729
40841
  facets() {
39730
40842
  return Promise.resolve(this.db.facets());
39731
40843
  }
@@ -40048,13 +41160,13 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
40048
41160
  }
40049
41161
 
40050
41162
  // ../../packages/plugin-runtime/src/handle-capture.ts
40051
- async function handleCapture(input2, config2 = loadConfig()) {
41163
+ async function handleCapture(input2, config2 = loadConfig(), opts = {}) {
40052
41164
  try {
40053
41165
  const gateway = resolveDataGateway(config2);
40054
41166
  const runtime = createPluginRuntime(gateway, config2.settings, { dataDir: config2.dataDir });
40055
41167
  let result;
40056
41168
  try {
40057
- result = await runtime.capture(input2);
41169
+ result = await runtime.capture(input2, opts);
40058
41170
  } finally {
40059
41171
  await runtime.close();
40060
41172
  }
@@ -40132,6 +41244,7 @@ async function handleSessionStart(input2, config2 = loadConfig()) {
40132
41244
  }
40133
41245
  triggerPolicySync(config2);
40134
41246
  triggerHistorySync(config2);
41247
+ triggerContentRetention(config2);
40135
41248
  if (input2.harnessVersion !== void 0 && offersMaintenance(gateway, "staleBinaryNotice")) {
40136
41249
  return { staleBinaryNotice: gateway.staleBinaryNotice(input2.harnessVersion) };
40137
41250
  }
@@ -40209,8 +41322,120 @@ function buildSessionRoot(sessionId, input2, ctx, resolved, provider, branch) {
40209
41322
  var name = "@akasecurity/plugin-browser-extension";
40210
41323
  var version2 = "0.9.4";
40211
41324
 
41325
+ // src/native-host/exchange.ts
41326
+ var MAX_TARGET_LEN = 500;
41327
+ var truncateTarget = (s) => s.length > MAX_TARGET_LEN ? `${s.slice(0, MAX_TARGET_LEN)}\u2026` : s;
41328
+ var TARGET_SCAN_MAX_BYTES = 64 * 1024;
41329
+ var MAX_TOOL_CALLS = 256;
41330
+ function cutToBytes(text, maxBytes) {
41331
+ const bytes = new TextEncoder().encode(text);
41332
+ if (bytes.byteLength <= maxBytes) return { text, truncated: false };
41333
+ let end = maxBytes;
41334
+ while (end > 0 && ((bytes[end] ?? 0) & 192) === 128) end -= 1;
41335
+ return { text: new TextDecoder().decode(bytes.subarray(0, end)), truncated: true };
41336
+ }
41337
+ function capResponseText(exchange, maxBytes = RESPONSE_TEXT_MAX_BYTES) {
41338
+ if (exchange.responseText === void 0) return exchange;
41339
+ const cut = cutToBytes(exchange.responseText, maxBytes);
41340
+ return {
41341
+ ...exchange,
41342
+ responseText: cut.text,
41343
+ // OR, never assign: a text already marked truncated upstream (the tap's
41344
+ // raw-byte cut, or the bridge's own text cut) must stay truncated even
41345
+ // when this cut has nothing left to do.
41346
+ truncated: exchange.truncated || cut.truncated
41347
+ };
41348
+ }
41349
+ function trimmed(value) {
41350
+ if (value === void 0) return void 0;
41351
+ const t = value.trim();
41352
+ return t === "" ? void 0 : t;
41353
+ }
41354
+ function setNum(attrs, key, value) {
41355
+ if (typeof value === "number" && Number.isFinite(value)) attrs[key] = value;
41356
+ }
41357
+ function toLlmCallInput(exchange, sessionId, tool) {
41358
+ const messageId = trimmed(exchange.messageId);
41359
+ if (messageId === void 0) return null;
41360
+ const attrs = { provider: tool, message_id: messageId };
41361
+ const model = trimmed(exchange.model);
41362
+ if (model !== void 0) attrs.model = model;
41363
+ if (exchange.usageSource === "site") {
41364
+ setNum(attrs, "input_tokens", exchange.usage?.inputTokens);
41365
+ setNum(attrs, "output_tokens", exchange.usage?.outputTokens);
41366
+ setNum(attrs, "cache_read_input_tokens", exchange.usage?.cacheReadInputTokens);
41367
+ setNum(attrs, "cache_creation_input_tokens", exchange.usage?.cacheCreationInputTokens);
41368
+ } else if (exchange.usageSource === "estimated") {
41369
+ setNum(attrs, "estimated_input_tokens", exchange.usage?.inputTokens);
41370
+ setNum(attrs, "estimated_output_tokens", exchange.usage?.outputTokens);
41371
+ }
41372
+ attrs.usage_source = exchange.usageSource;
41373
+ const stopReason = trimmed(exchange.stopReason);
41374
+ if (stopReason !== void 0) attrs.stop_reason = stopReason;
41375
+ const conversationId = trimmed(exchange.conversationId);
41376
+ if (conversationId !== void 0) {
41377
+ attrs.run_key = conversationId;
41378
+ attrs.site_conversation_id = conversationId;
41379
+ }
41380
+ if (exchange.turnIndex !== void 0) attrs.turn_index = exchange.turnIndex;
41381
+ if (exchange.truncated) attrs.response_truncated = true;
41382
+ return {
41383
+ sessionId,
41384
+ messageId,
41385
+ parentId: sessionId,
41386
+ rootSessionId: sessionId,
41387
+ startedAt: exchange.startedAt,
41388
+ attributes: attrs
41389
+ };
41390
+ }
41391
+ function toToolCallInputs(exchange, sessionId, scanTarget) {
41392
+ const conversationId = trimmed(exchange.conversationId);
41393
+ const seen = /* @__PURE__ */ new Set();
41394
+ const inputs = [];
41395
+ const toolCalls = exchange.toolCalls ?? [];
41396
+ for (const tc of toolCalls.slice(0, MAX_TOOL_CALLS)) {
41397
+ const toolUseId = trimmed(tc.toolUseId);
41398
+ if (toolUseId === void 0) continue;
41399
+ if (seen.has(toolUseId)) continue;
41400
+ seen.add(toolUseId);
41401
+ const attrs = { tool_use_id: toolUseId };
41402
+ const toolName = trimmed(tc.toolName);
41403
+ if (toolName !== void 0) attrs.tool_name = toolName;
41404
+ let inspections = [];
41405
+ if (tc.target !== void 0) {
41406
+ const { masked, findings } = scanTarget(cutToBytes(tc.target, TARGET_SCAN_MAX_BYTES).text);
41407
+ if (masked !== "") attrs.target = truncateTarget(masked);
41408
+ inspections = findings.map((f) => ({
41409
+ ruleId: f.ruleId,
41410
+ ruleName: f.ruleName,
41411
+ ruleVersion: f.ruleVersion,
41412
+ category: f.category,
41413
+ severity: f.severity,
41414
+ span: f.span,
41415
+ maskedMatch: f.maskedMatch,
41416
+ actionTaken: "log",
41417
+ confidence: f.confidence
41418
+ }));
41419
+ }
41420
+ if (tc.isError !== void 0) attrs.is_error = tc.isError;
41421
+ if (tc.inputSize !== void 0) attrs.input_size = tc.inputSize;
41422
+ if (tc.outputSize !== void 0) attrs.output_size = tc.outputSize;
41423
+ if (conversationId !== void 0) attrs.run_key = conversationId;
41424
+ inputs.push({
41425
+ sessionId,
41426
+ toolUseId,
41427
+ parentId: sessionId,
41428
+ rootSessionId: sessionId,
41429
+ startedAt: exchange.startedAt,
41430
+ attributes: attrs,
41431
+ inspections
41432
+ });
41433
+ }
41434
+ return inputs;
41435
+ }
41436
+
40212
41437
  // src/native-host/protocol.ts
40213
- var WEB_SOURCE_TOOLS = [SOURCE_TOOL.ChatGpt, SOURCE_TOOL.ClaudeAi];
41438
+ var WEB_SOURCE_TOOLS = WebSourceTool.options;
40214
41439
  function isWebSourceTool(value) {
40215
41440
  return WEB_SOURCE_TOOLS.includes(value);
40216
41441
  }
@@ -40226,6 +41451,16 @@ function isHostRequest(value) {
40226
41451
  return typeof v.sessionId === "string" && isWebSourceTool(v.tool) && typeof v.hostname === "string";
40227
41452
  case "capture":
40228
41453
  return typeof v.sessionId === "string" && isWebSourceTool(v.tool) && isEventKind(v.kind) && typeof v.text === "string";
41454
+ // A successful safeParse proves the payload is ACCEPTABLE, not that the
41455
+ // narrowed object carries the schema's defaults — `toolCalls` and
41456
+ // `truncated` are `.default(...)`, and a guard does not rewrite its input.
41457
+ // The handler re-parses and reads `parsed.data`; nothing may read
41458
+ // `request.exchange` / `request.status` directly.
41459
+ case "exchange":
41460
+ return typeof v.sessionId === "string" && isWebSourceTool(v.tool) && WebExchange.safeParse(v.exchange).success;
41461
+ case "capture_status":
41462
+ return typeof v.sessionId === "string" && isWebSourceTool(v.tool) && WebCaptureStatus.safeParse(v.status).success;
41463
+ case "capture_state":
40229
41464
  case "ping":
40230
41465
  case "health":
40231
41466
  return true;
@@ -40272,7 +41507,60 @@ var WEB_TOOL_TO_SOURCE = {
40272
41507
  [SOURCE_TOOL.ChatGpt]: SOURCE_TOOL.ChatGpt,
40273
41508
  [SOURCE_TOOL.ClaudeAi]: SOURCE_TOOL.ClaudeAi
40274
41509
  };
41510
+ var WEB_SOURCE_TOOLS2 = Object.keys(WEB_TOOL_TO_SOURCE);
40275
41511
  var PLUGIN_BUILD = { package: name, version: version2 };
41512
+ var MAX_TRACKED_SESSIONS = 32;
41513
+ var captureStatuses = /* @__PURE__ */ new Map();
41514
+ function readCaptureStatus(sessionId) {
41515
+ return captureStatuses.get(sessionId);
41516
+ }
41517
+ function recordCaptureStatus(sessionId, record2) {
41518
+ captureStatuses.delete(sessionId);
41519
+ captureStatuses.set(sessionId, record2);
41520
+ while (captureStatuses.size > MAX_TRACKED_SESSIONS) {
41521
+ const oldest = captureStatuses.keys().next().value;
41522
+ if (oldest === void 0) break;
41523
+ captureStatuses.delete(oldest);
41524
+ }
41525
+ }
41526
+ function trackedFor(tool) {
41527
+ return [...captureStatuses.entries()].filter(([, record2]) => record2.tool === tool).map(([sessionId, record2]) => ({
41528
+ tool: record2.tool,
41529
+ observedAt: record2.observedAt,
41530
+ status: record2.status,
41531
+ rootSessionId: sessionId,
41532
+ // One entry per session and every report overwrites it, so this IS the
41533
+ // document's last word — there is no older row here to pick between.
41534
+ lastReportAt: record2.observedAt,
41535
+ closed: record2.status.closed
41536
+ }));
41537
+ }
41538
+ function mergeCaptureDocuments(stored, tracked) {
41539
+ const byDocument = /* @__PURE__ */ new Map();
41540
+ for (const document of [...stored, ...tracked]) {
41541
+ const group = byDocument.get(document.rootSessionId);
41542
+ if (group === void 0) byDocument.set(document.rootSessionId, [document]);
41543
+ else group.push(document);
41544
+ }
41545
+ const merged = [];
41546
+ for (const group of byDocument.values()) {
41547
+ const ordered = [...group].sort(
41548
+ (a, b) => a.observedAt < b.observedAt ? 1 : a.observedAt > b.observedAt ? -1 : 0
41549
+ );
41550
+ const picked = pickReportedCaptureStatus(ordered);
41551
+ if (picked === void 0) continue;
41552
+ let lastReportAt = picked.lastReportAt;
41553
+ let closed = picked.closed;
41554
+ for (const document of group) {
41555
+ if (document.lastReportAt > lastReportAt) {
41556
+ lastReportAt = document.lastReportAt;
41557
+ closed = document.closed;
41558
+ }
41559
+ }
41560
+ merged.push({ ...picked, lastReportAt, closed });
41561
+ }
41562
+ return merged;
41563
+ }
40276
41564
  function resolveWebProvider(tool) {
40277
41565
  return () => tool === "chatgpt" ? { provider: "openai" } : { provider: "anthropic" };
40278
41566
  }
@@ -40347,6 +41635,200 @@ async function handleRequest(request, configForTool = defaultConfigForTool) {
40347
41635
  ...result.blockedReferences ? { blockedReferences: result.blockedReferences } : {}
40348
41636
  };
40349
41637
  }
41638
+ case "exchange": {
41639
+ const config2 = configForTool(request.tool);
41640
+ const webChat = webChatCaptureOf(config2.settings);
41641
+ if (!isWebChatCaptureConsentValid(webChat.consent)) {
41642
+ return {
41643
+ type: "exchange",
41644
+ requestId: request.requestId,
41645
+ ok: true,
41646
+ accepted: false,
41647
+ skipped: "no-consent",
41648
+ llmCalls: 0,
41649
+ toolCalls: 0,
41650
+ ruleIds: []
41651
+ };
41652
+ }
41653
+ const parsed2 = WebExchange.safeParse(request.exchange);
41654
+ if (!parsed2.success) {
41655
+ return {
41656
+ type: "error",
41657
+ requestId: request.requestId,
41658
+ ok: false,
41659
+ message: "malformed exchange payload"
41660
+ };
41661
+ }
41662
+ const exchange = capResponseText(parsed2.data);
41663
+ const llm = toLlmCallInput(exchange, request.sessionId, request.tool);
41664
+ let llmCalls = 0;
41665
+ let toolCalls = 0;
41666
+ if (llm !== null) {
41667
+ let gateway;
41668
+ try {
41669
+ gateway = resolveDataGateway(config2);
41670
+ await gateway.recordAuditEvent({
41671
+ id: request.sessionId,
41672
+ eventType: "session",
41673
+ startedAt: exchange.startedAt
41674
+ });
41675
+ await gateway.recordLlmCall(llm);
41676
+ llmCalls = 1;
41677
+ let ruleVersions;
41678
+ try {
41679
+ ruleVersions = (await gateway.getPolicyBundle()).ruleVersions;
41680
+ } catch {
41681
+ ruleVersions = void 0;
41682
+ }
41683
+ const tools = toToolCallInputs(
41684
+ exchange,
41685
+ request.sessionId,
41686
+ (text2) => scanText(text2, ruleVersions)
41687
+ );
41688
+ if (tools.length > 0) {
41689
+ await gateway.recordToolCalls(tools);
41690
+ toolCalls = tools.length;
41691
+ }
41692
+ } catch {
41693
+ } finally {
41694
+ await gateway?.close();
41695
+ }
41696
+ }
41697
+ const text = exchange.responseText;
41698
+ let responseAction = {};
41699
+ let ruleIds = [];
41700
+ const model = llm === null ? trimmed(exchange.model) : llm.attributes.model;
41701
+ const conversationId = llm === null ? trimmed(exchange.conversationId) : llm.attributes.site_conversation_id;
41702
+ if (text !== void 0 && text.length > 0 && webChat.responses !== "never") {
41703
+ const result = await handleCapture(
41704
+ {
41705
+ kind: "response",
41706
+ sourceTool: WEB_TOOL_TO_SOURCE[request.tool],
41707
+ text,
41708
+ occurredAt: exchange.startedAt,
41709
+ metadata: {
41710
+ sessionId: request.sessionId,
41711
+ ...model !== void 0 ? { model } : {},
41712
+ // Omitted for an unkeyable exchange rather than blanked: this is
41713
+ // correlation metadata, and an empty id correlates to nothing
41714
+ // while reading as an id that exists.
41715
+ ...llm !== null ? { messageId: llm.messageId } : {},
41716
+ ...conversationId !== void 0 ? { conversationId } : {},
41717
+ ...exchange.turnIndex !== void 0 ? { turnIndex: exchange.turnIndex } : {}
41718
+ }
41719
+ },
41720
+ config2,
41721
+ // No rewritable: false. Nothing about a response is rewritable in
41722
+ // the sense that field means (a host input it must not mutate) —
41723
+ // saying so here would degrade a resolved redact to
41724
+ // settings.redactFallback, trading a meaningless decision for a
41725
+ // real leak at rest. No dedupe, no preAuthorizedGrantIds either.
41726
+ { persist: webChat.responses === "always" ? "always" : "with-findings" }
41727
+ );
41728
+ responseAction = { responseAction: result.action };
41729
+ ruleIds = [...new Set(result.findings.map((f) => f.ruleId))];
41730
+ }
41731
+ return {
41732
+ type: "exchange",
41733
+ requestId: request.requestId,
41734
+ ok: true,
41735
+ // `accepted` is about the LEAVES, which an unkeyable exchange writes
41736
+ // none of — the response capture above may still have recorded a
41737
+ // finding, which `ruleIds` and `responseAction` report either way.
41738
+ accepted: llm !== null,
41739
+ ...llm === null ? { skipped: "unkeyable" } : {},
41740
+ llmCalls,
41741
+ toolCalls,
41742
+ ...responseAction,
41743
+ ruleIds
41744
+ };
41745
+ }
41746
+ case "capture_status": {
41747
+ const config2 = configForTool(request.tool);
41748
+ const webChat = webChatCaptureOf(config2.settings);
41749
+ if (!isWebChatCaptureConsentValid(webChat.consent)) {
41750
+ return {
41751
+ type: "capture_status",
41752
+ requestId: request.requestId,
41753
+ ok: true,
41754
+ accepted: false,
41755
+ skipped: "no-consent"
41756
+ };
41757
+ }
41758
+ const parsed2 = WebCaptureStatus.safeParse(request.status);
41759
+ if (!parsed2.success) {
41760
+ return {
41761
+ type: "error",
41762
+ requestId: request.requestId,
41763
+ ok: false,
41764
+ message: "malformed capture status payload"
41765
+ };
41766
+ }
41767
+ const observedAt = (/* @__PURE__ */ new Date()).toISOString();
41768
+ recordCaptureStatus(request.sessionId, {
41769
+ tool: request.tool,
41770
+ status: parsed2.data,
41771
+ observedAt
41772
+ });
41773
+ const gateway = resolveDataGateway(config2);
41774
+ try {
41775
+ await gateway.recordAuditEvent({
41776
+ id: randomUUID20(),
41777
+ eventType: "capture_status",
41778
+ startedAt: observedAt,
41779
+ parentId: request.sessionId,
41780
+ rootSessionId: request.sessionId,
41781
+ attributes: toCaptureStatusAttributes(parsed2.data, request.tool)
41782
+ });
41783
+ } catch {
41784
+ } finally {
41785
+ await gateway.close();
41786
+ }
41787
+ return { type: "capture_status", requestId: request.requestId, ok: true, accepted: true };
41788
+ }
41789
+ case "capture_state": {
41790
+ const config2 = configForTool(void 0);
41791
+ const webChat = webChatCaptureOf(config2.settings);
41792
+ let stored = [];
41793
+ let gateway;
41794
+ try {
41795
+ gateway = resolveDataGateway(config2);
41796
+ if (offersCaptureStatusReader(gateway)) stored = await gateway.readCaptureStatuses();
41797
+ } catch {
41798
+ stored = [];
41799
+ } finally {
41800
+ await gateway?.close();
41801
+ }
41802
+ const sites = WEB_SOURCE_TOOLS2.map((tool) => {
41803
+ const record2 = reportedCaptureDocumentForSite(
41804
+ mergeCaptureDocuments(
41805
+ stored.filter((s) => s.tool === tool),
41806
+ trackedFor(tool)
41807
+ )
41808
+ );
41809
+ return {
41810
+ tool,
41811
+ state: deriveWebCaptureState(record2?.status),
41812
+ ...record2 !== void 0 ? { enforcement: record2.status.enforcement, observedAt: record2.observedAt } : {}
41813
+ };
41814
+ });
41815
+ return {
41816
+ type: "capture_state",
41817
+ requestId: request.requestId,
41818
+ ok: true,
41819
+ consented: isWebChatCaptureConsentValid(webChat.consent),
41820
+ sites
41821
+ };
41822
+ }
41823
+ default: {
41824
+ const unrecognized = request;
41825
+ return {
41826
+ type: "error",
41827
+ requestId: unrecognized.requestId,
41828
+ ok: false,
41829
+ message: `unsupported request type: ${unrecognized.type}`
41830
+ };
41831
+ }
40350
41832
  }
40351
41833
  }
40352
41834
  async function runHost(stdin, stdout, configForTool = defaultConfigForTool) {
@@ -40386,5 +41868,6 @@ main().catch(() => {
40386
41868
  });
40387
41869
  export {
40388
41870
  handleRequest,
41871
+ readCaptureStatus,
40389
41872
  runHost
40390
41873
  };