@akasecurity/cli 0.9.11 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/cli.js +4764 -3653
  2. package/extension/content.js +1 -1
  3. package/extension/manifest.json +1 -1
  4. package/native-host/host.js +1576 -870
  5. package/native-host/scan-worker.js +237 -18
  6. package/native-host/sync.js +333 -65
  7. package/package.json +5 -5
  8. package/web-ui/web-ui/.next/BUILD_ID +1 -1
  9. package/web-ui/web-ui/.next/app-build-manifest.json +87 -87
  10. package/web-ui/web-ui/.next/app-path-routes-manifest.json +5 -5
  11. package/web-ui/web-ui/.next/build-manifest.json +2 -2
  12. package/web-ui/web-ui/.next/prerender-manifest.json +3 -3
  13. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js +2 -2
  14. package/web-ui/web-ui/.next/server/app/(app)/activity/page.js.nft.json +1 -1
  15. package/web-ui/web-ui/.next/server/app/(app)/activity/page_client-reference-manifest.js +1 -1
  16. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js +2 -2
  17. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page.js.nft.json +1 -1
  18. package/web-ui/web-ui/.next/server/app/(app)/data-shares/page_client-reference-manifest.js +1 -1
  19. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js +2 -2
  20. package/web-ui/web-ui/.next/server/app/(app)/detections/page.js.nft.json +1 -1
  21. package/web-ui/web-ui/.next/server/app/(app)/detections/page_client-reference-manifest.js +1 -1
  22. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js +2 -2
  23. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page.js.nft.json +1 -1
  24. package/web-ui/web-ui/.next/server/app/(app)/exceptions/[id]/page_client-reference-manifest.js +1 -1
  25. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js +1 -1
  26. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page.js.nft.json +1 -1
  27. package/web-ui/web-ui/.next/server/app/(app)/exceptions/new/page_client-reference-manifest.js +1 -1
  28. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js +1 -1
  29. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page.js.nft.json +1 -1
  30. package/web-ui/web-ui/.next/server/app/(app)/exceptions/page_client-reference-manifest.js +1 -1
  31. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js +2 -2
  32. package/web-ui/web-ui/.next/server/app/(app)/findings/page.js.nft.json +1 -1
  33. package/web-ui/web-ui/.next/server/app/(app)/findings/page_client-reference-manifest.js +1 -1
  34. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js +2 -2
  35. package/web-ui/web-ui/.next/server/app/(app)/inventory/page.js.nft.json +1 -1
  36. package/web-ui/web-ui/.next/server/app/(app)/inventory/page_client-reference-manifest.js +1 -1
  37. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js +2 -2
  38. package/web-ui/web-ui/.next/server/app/(app)/policies/page.js.nft.json +1 -1
  39. package/web-ui/web-ui/.next/server/app/(app)/policies/page_client-reference-manifest.js +1 -1
  40. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js +3 -3
  41. package/web-ui/web-ui/.next/server/app/(app)/scan/page.js.nft.json +1 -1
  42. package/web-ui/web-ui/.next/server/app/(app)/scan/page_client-reference-manifest.js +1 -1
  43. package/web-ui/web-ui/.next/server/app/(app)/security/page.js +2 -2
  44. package/web-ui/web-ui/.next/server/app/(app)/security/page.js.nft.json +1 -1
  45. package/web-ui/web-ui/.next/server/app/(app)/security/page_client-reference-manifest.js +1 -1
  46. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js +2 -2
  47. package/web-ui/web-ui/.next/server/app/(app)/settings/page.js.nft.json +1 -1
  48. package/web-ui/web-ui/.next/server/app/(app)/settings/page_client-reference-manifest.js +1 -1
  49. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js +2 -2
  50. package/web-ui/web-ui/.next/server/app/(app)/updates/page.js.nft.json +1 -1
  51. package/web-ui/web-ui/.next/server/app/(app)/updates/page_client-reference-manifest.js +1 -1
  52. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js +2 -2
  53. package/web-ui/web-ui/.next/server/app/(app)/vault/page.js.nft.json +1 -1
  54. package/web-ui/web-ui/.next/server/app/(app)/vault/page_client-reference-manifest.js +1 -1
  55. package/web-ui/web-ui/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  56. package/web-ui/web-ui/.next/server/app/_not-found.html +1 -1
  57. package/web-ui/web-ui/.next/server/app/_not-found.rsc +2 -2
  58. package/web-ui/web-ui/.next/server/app/index.html +1 -1
  59. package/web-ui/web-ui/.next/server/app/index.rsc +2 -2
  60. package/web-ui/web-ui/.next/server/app/page_client-reference-manifest.js +1 -1
  61. package/web-ui/web-ui/.next/server/app-paths-manifest.json +5 -5
  62. package/web-ui/web-ui/.next/server/chunks/{739.js → 121.js} +1 -1
  63. package/web-ui/web-ui/.next/server/chunks/290.js +6 -0
  64. package/web-ui/web-ui/.next/server/chunks/475.js +1 -1
  65. package/web-ui/web-ui/.next/server/chunks/589.js +1 -1
  66. package/web-ui/web-ui/.next/server/chunks/611.js +1015 -0
  67. package/web-ui/web-ui/.next/server/chunks/7.js +1 -1
  68. package/web-ui/web-ui/.next/server/chunks/816.js +1 -0
  69. package/web-ui/web-ui/.next/server/chunks/935.js +1 -1
  70. package/web-ui/web-ui/.next/server/chunks/968.js +1006 -0
  71. package/web-ui/web-ui/.next/server/functions-config-manifest.json +6 -6
  72. package/web-ui/web-ui/.next/server/middleware-manifest.json +5 -5
  73. package/web-ui/web-ui/.next/server/pages/404.html +1 -1
  74. package/web-ui/web-ui/.next/server/pages/500.html +1 -1
  75. package/web-ui/web-ui/.next/server/server-reference-manifest.js +1 -1
  76. package/web-ui/web-ui/.next/server/server-reference-manifest.json +1 -1
  77. package/web-ui/web-ui/.next/static/chunks/{526-026c69b926a17dbb.js → 526-f0156de7831566b3.js} +1 -1
  78. package/web-ui/web-ui/.next/static/chunks/674-d8237c5d0faa4a53.js +1 -0
  79. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-a27c8937989448e4.js +1 -0
  80. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-2b805f9e1f995092.js +1 -0
  81. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-a87cfee370c4e0f4.js +1 -0
  82. package/web-ui/web-ui/.next/static/chunks/app/(app)/{error-dead9507fc349f26.js → error-190085728a856072.js} +1 -1
  83. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-4e214491c7be8d43.js +1 -0
  84. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-c1bb992ee1f12566.js +1 -0
  85. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-f16ba40d88e414b1.js +1 -0
  86. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-59c76da638f22b0e.js +1 -0
  87. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-c37447caf89a86e1.js +1 -0
  88. package/web-ui/web-ui/.next/static/chunks/app/(app)/{layout-dc7ae7664dcdc3c5.js → layout-cb3c8c7b6b33414c.js} +1 -1
  89. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-ab639e48f60ad7ee.js +1 -0
  90. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-494614fccc8c62cc.js +1 -0
  91. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-a3095119b3e87341.js +1 -0
  92. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-469613d499e41093.js +1 -0
  93. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-5b32bd569c9569d9.js +1 -0
  94. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-3152ceb31f024b8d.js +1 -0
  95. package/web-ui/web-ui/.next/static/css/6e72259eccdf4435.css +2 -0
  96. package/web-ui/web-ui/dist/scan-worker.js +237 -18
  97. package/web-ui/web-ui/.next/server/chunks/471.js +0 -950
  98. package/web-ui/web-ui/.next/server/chunks/766.js +0 -6
  99. package/web-ui/web-ui/.next/server/chunks/851.js +0 -1
  100. package/web-ui/web-ui/.next/server/chunks/905.js +0 -959
  101. package/web-ui/web-ui/.next/static/chunks/907-2ba9428e7818b656.js +0 -1
  102. package/web-ui/web-ui/.next/static/chunks/app/(app)/activity/page-c5a55618d187c906.js +0 -1
  103. package/web-ui/web-ui/.next/static/chunks/app/(app)/data-shares/page-b1c76b8c00e1ae2a.js +0 -1
  104. package/web-ui/web-ui/.next/static/chunks/app/(app)/detections/page-159167b47a005b33.js +0 -1
  105. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/[id]/page-5e872a82af85ef64.js +0 -1
  106. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/new/page-0695d0006518b2cb.js +0 -1
  107. package/web-ui/web-ui/.next/static/chunks/app/(app)/exceptions/page-adec99f2f4bbc180.js +0 -1
  108. package/web-ui/web-ui/.next/static/chunks/app/(app)/findings/page-d013384d2ddb3036.js +0 -1
  109. package/web-ui/web-ui/.next/static/chunks/app/(app)/inventory/page-42c1b48a01fdecb0.js +0 -1
  110. package/web-ui/web-ui/.next/static/chunks/app/(app)/policies/page-9b6d7cc4ce9fb33e.js +0 -1
  111. package/web-ui/web-ui/.next/static/chunks/app/(app)/scan/page-f3ee9ecde06df153.js +0 -1
  112. package/web-ui/web-ui/.next/static/chunks/app/(app)/security/page-24a003c709776317.js +0 -1
  113. package/web-ui/web-ui/.next/static/chunks/app/(app)/settings/page-4ea49ce2e765fffb.js +0 -1
  114. package/web-ui/web-ui/.next/static/chunks/app/(app)/updates/page-6c7b94b070de8986.js +0 -1
  115. package/web-ui/web-ui/.next/static/chunks/app/(app)/vault/page-f37ab8e1edc67663.js +0 -1
  116. package/web-ui/web-ui/.next/static/css/c6954dd65f2115e6.css +0 -2
  117. /package/web-ui/web-ui/.next/static/{osEmGZG6yEV-XkQlklt-B → PMeePXfXsQ2xxrXppySG_}/_buildManifest.js +0 -0
  118. /package/web-ui/web-ui/.next/static/{osEmGZG6yEV-XkQlklt-B → PMeePXfXsQ2xxrXppySG_}/_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
@@ -505,6 +505,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
505
505
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
506
506
  import { join as join2 } from "path";
507
507
 
508
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
509
+ var DEFERRED_MIGRATION_TAGS = [
510
+ "0031_audit_capture_by_time_index",
511
+ "0032_audit_capture_by_id_index",
512
+ "0033_audit_capture_location_index",
513
+ "0034_findings_read_indexes"
514
+ ];
515
+
508
516
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
509
517
  var SQLITE_MIGRATIONS = [
510
518
  {
@@ -622,6 +630,30 @@ var SQLITE_MIGRATIONS = [
622
630
  {
623
631
  tag: "0028_activity_session_probe_indexes",
624
632
  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"
633
+ },
634
+ {
635
+ tag: "0029_audit_capture_rollup_index",
636
+ 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');"
637
+ },
638
+ {
639
+ tag: "0030_audit_content_expiry",
640
+ 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;"
641
+ },
642
+ {
643
+ tag: "0031_audit_capture_by_time_index",
644
+ 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');"
645
+ },
646
+ {
647
+ tag: "0032_audit_capture_by_id_index",
648
+ 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');"
649
+ },
650
+ {
651
+ tag: "0033_audit_capture_location_index",
652
+ 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');"
653
+ },
654
+ {
655
+ tag: "0034_findings_read_indexes",
656
+ 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
657
  }
626
658
  ];
627
659
 
@@ -20622,7 +20654,7 @@ var TOOL_TO_HARNESS = {
20622
20654
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20623
20655
  };
20624
20656
  function harnessFromTool(tool) {
20625
- return TOOL_TO_HARNESS[tool] ?? tool;
20657
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20626
20658
  }
20627
20659
 
20628
20660
  // ../../packages/schema/src/zod/finding.ts
@@ -20672,6 +20704,15 @@ var FindingCategory = external_exports.enum([
20672
20704
  ]).meta({ id: "FindingCategory" });
20673
20705
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20674
20706
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20707
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20708
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20709
+ var FindingDelivery = external_exports.object({
20710
+ state: FindingDeliveryState,
20711
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20712
+ at: external_exports.iso.datetime().optional(),
20713
+ // Only on `not_sent`, and only when a known reason was recorded.
20714
+ reason: SyncFailureReason.optional()
20715
+ }).meta({ id: "FindingDelivery" });
20675
20716
  var ResolutionMethod = external_exports.enum([
20676
20717
  "enforced-in-flight",
20677
20718
  "fixed-at-source",
@@ -20728,7 +20769,10 @@ var FindingInstance = external_exports.object({
20728
20769
  // The session that event belongs to, when it has one — the seam a
20729
20770
  // per-instance "view session" link needs. Absent for events captured
20730
20771
  // outside a session.
20731
- sessionId: external_exports.string().optional()
20772
+ sessionId: external_exports.string().optional(),
20773
+ // The delivery state of the event above (see FindingDelivery). Optional so
20774
+ // readers that do not project it stay valid.
20775
+ delivery: FindingDelivery.optional()
20732
20776
  }).meta({ id: "FindingInstance" });
20733
20777
  var FindingGroup = external_exports.object({
20734
20778
  id: external_exports.string(),
@@ -20780,7 +20824,10 @@ var FindingFacets = external_exports.object({
20780
20824
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
20825
  // reads, which can filter by it; the type-level read omits the dimension
20782
20826
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20827
+ tool: external_exports.array(FindingFacetItem).optional(),
20828
+ // Delivery states (FindingDeliveryState). Present only on the
20829
+ // instance-level reads, like `tool`.
20830
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20831
  }).meta({ id: "FindingFacets" });
20785
20832
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20786
20833
  id: "FindingTypeSummary"
@@ -20891,6 +20938,8 @@ var ListFindingInstancesQuery = external_exports.object({
20891
20938
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20892
20939
  // where the free-text `q` can only match the rendered "via Bash" label.
20893
20940
  tool: external_exports.array(external_exports.string()).optional(),
20941
+ // The delivery state of each finding's event (see FindingDelivery).
20942
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20894
20943
  // Exact repository / file-path matches, for the drill-down out of the
20895
20944
  // locations view. A row whose event carries no repo/file matches neither.
20896
20945
  repo: external_exports.string().optional(),
@@ -20911,6 +20960,10 @@ var ListFindingInstancesResponse = external_exports.object({
20911
20960
  items: external_exports.array(FindingInstanceDetail),
20912
20961
  nextCursor: external_exports.string().nullable()
20913
20962
  }).meta({ id: "ListFindingInstancesResponse" });
20963
+ var ListFindingInstancesPage = external_exports.object({
20964
+ items: external_exports.array(FindingInstanceDetail),
20965
+ nextCursor: external_exports.string().nullable()
20966
+ }).meta({ id: "ListFindingInstancesPage" });
20914
20967
  var FindingLocationSummary = external_exports.object({
20915
20968
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20916
20969
  // because a location's identity is two values and a URL param carries one:
@@ -20953,6 +21006,8 @@ var ListFindingLocationsQuery = external_exports.object({
20953
21006
  // instances that match, and folds its status from those.
20954
21007
  status: external_exports.array(FindingStatus).optional(),
20955
21008
  tool: external_exports.array(external_exports.string()).optional(),
21009
+ // The delivery state of each finding's event (see FindingDelivery).
21010
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20956
21011
  q: external_exports.string().optional(),
20957
21012
  sessionId: external_exports.string().optional(),
20958
21013
  from: external_exports.iso.datetime().optional(),
@@ -21155,6 +21210,10 @@ var CaptureAttributes = external_exports.object({
21155
21210
  // to 'allow' — the enforcement audit trail's link back to the grant that
21156
21211
  // authorized the bypass.
21157
21212
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21213
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21214
+ // join back to the `llm_call` leaf for the same assistant turn.
21215
+ message_id: external_exports.string().optional(),
21216
+ conversation_id: external_exports.string().optional(),
21158
21217
  // Whole milliseconds this capture's inspection blocked its caller — the
21159
21218
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21160
21219
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21163,7 +21222,19 @@ var CaptureAttributes = external_exports.object({
21163
21222
  // inline json_extract and is not itself an optimization.
21164
21223
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21165
21224
  // before the measurement shipped — never present as a placeholder 0.
21166
- inspection_ms: external_exports.number().int().nonnegative().optional()
21225
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21226
+ // What a `redact` this capture could not carry out became instead (see
21227
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21228
+ // degrade actually happened, so absence is the ordinary case rather than a
21229
+ // reader having to distinguish it from a zero.
21230
+ //
21231
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21232
+ // so on a multi-finding row this does not say which finding degraded, and
21233
+ // its presence does not mean the fallback decided the capture's action. A
21234
+ // capture denied by another finding's own Block policy carries `block`
21235
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21236
+ // repeated rather than referenced because a store reader opens this file.
21237
+ redact_degraded_to: ActionTaken.optional()
21167
21238
  }).catchall(external_exports.unknown());
21168
21239
  var ToolCallInspection = external_exports.object({
21169
21240
  ruleId: external_exports.string().min(1),
@@ -21362,7 +21433,17 @@ var AuditEvent = external_exports.object({
21362
21433
  /** `share` to a first-party/internal destination. */
21363
21434
  internal: external_exports.boolean(),
21364
21435
  /** Event needs review (e.g. unverified egress). */
21365
- flagged: external_exports.boolean()
21436
+ flagged: external_exports.boolean(),
21437
+ /**
21438
+ * The body this event's `title` is drawn from was cleared by local body
21439
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21440
+ *
21441
+ * A separate flag rather than a sentinel written into `title`: the title is
21442
+ * rendered text, and a store-layer module that invented display copy for it
21443
+ * would be choosing words the view is supposed to choose. Additive and
21444
+ * defaulted, so an older producer still validates.
21445
+ */
21446
+ bodyExpired: external_exports.boolean().default(false)
21366
21447
  }).meta({ id: "ActivityAuditEvent" });
21367
21448
  var ActivitySessionSummary = external_exports.object({
21368
21449
  id: external_exports.string(),
@@ -22817,6 +22898,12 @@ var EventMetadata = external_exports.object({
22817
22898
  // to 'allow' — the enforcement audit trail's link back to the grant that
22818
22899
  // authorized the bypass. Absent on captures where no exception applied.
22819
22900
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22901
+ // The assistant message this capture belongs to, and the conversation it sits
22902
+ // in — set by the browser extension's network capture so a stored `response`
22903
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22904
+ // on every other capture path, which has no such id.
22905
+ messageId: external_exports.string().optional(),
22906
+ conversationId: external_exports.string().optional(),
22820
22907
  // How long THIS capture's inspection blocked its caller, in whole
22821
22908
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22822
22909
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22829,7 +22916,37 @@ var EventMetadata = external_exports.object({
22829
22916
  // Absent is also what every pre-measurement client writes, and what a
22830
22917
  // clock failure degrades to — a reader must treat absence as "not measured"
22831
22918
  // and never as a zero, which would read as "inspection is free".
22832
- inspectionMs: external_exports.number().int().nonnegative().optional()
22919
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22920
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22921
+ // workspace's `redactFallback`, applied because the field could not be
22922
+ // masked in place (a shell command, a URL, or any argument on a host whose
22923
+ // hook contract offers no rewrite channel).
22924
+ //
22925
+ // It exists because the action alone cannot say why. A finding recorded as
22926
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22927
+ // assigned Redact on a field that could not take one — and those are
22928
+ // different facts about the same row: the first is a policy the user chose,
22929
+ // the second is a masking the host could not perform. Absent means no
22930
+ // degrade happened, which is every ordinary capture.
22931
+ //
22932
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22933
+ // is the CAPTURE while `actionTaken` is per FINDING:
22934
+ //
22935
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22936
+ // `redact` alongside a finding ASSIGNED the same action stores both
22937
+ // identically and one reason for the pair; attributing it to both
22938
+ // describes the assigned one wrongly, and to neither loses the degrade.
22939
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22940
+ // became, not the reason the capture ended as it did — a capture denied
22941
+ // by some other finding's own Block policy still carries `block` here,
22942
+ // and clearing the workspace's fallback would not have let it through.
22943
+ // Gate on the value against what a fallback can produce; never read the
22944
+ // field's presence as "this was the fallback's doing".
22945
+ //
22946
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22947
+ // Closing either means moving the reason onto the finding row, which
22948
+ // already carries its own action.
22949
+ redactDegradedTo: ActionTaken.optional()
22833
22950
  }).meta({ id: "EventMetadata" });
22834
22951
  var Event = external_exports.object({
22835
22952
  id: external_exports.guid(),
@@ -22939,7 +23056,32 @@ var RotateKeyInput = external_exports.object({
22939
23056
  confirmation: external_exports.string()
22940
23057
  });
22941
23058
 
23059
+ // ../../packages/schema/src/zod/finding-delivery.ts
23060
+ var KNOWN_REASONS = SyncFailureReason.options;
23061
+ function knownReason(value) {
23062
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23063
+ }
23064
+ function deriveFindingDelivery(row) {
23065
+ if (row.kind === "code_change") return { state: "local_scan" };
23066
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23067
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23068
+ }
23069
+ if (row.syncedAt !== null) {
23070
+ const reason = knownReason(row.syncFailure);
23071
+ return {
23072
+ state: "not_sent",
23073
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23074
+ ...reason === void 0 ? {} : { reason }
23075
+ };
23076
+ }
23077
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23078
+ return { state: "never_offered" };
23079
+ }
23080
+
22942
23081
  // ../../packages/schema/src/zod/findings-group-build.ts
23082
+ function lookupOwn(map2, key) {
23083
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23084
+ }
22943
23085
  function toApiAction(dbVal) {
22944
23086
  const map2 = {
22945
23087
  log: "monitored",
@@ -22948,7 +23090,7 @@ function toApiAction(dbVal) {
22948
23090
  warn: "warned",
22949
23091
  allow: "allowed"
22950
23092
  };
22951
- return map2[dbVal] ?? "allowed";
23093
+ return lookupOwn(map2, dbVal) ?? "allowed";
22952
23094
  }
22953
23095
  function toApiCategory(dbVal) {
22954
23096
  if (dbVal === "code_context") return "source_code";
@@ -22956,13 +23098,18 @@ function toApiCategory(dbVal) {
22956
23098
  return parsed2.success ? parsed2.data : "custom";
22957
23099
  }
22958
23100
  function toApiProvider(sourceTool) {
22959
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23101
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22960
23102
  }
22961
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23103
+ var FINDING_STATUS_PRECEDENCE = [
23104
+ "open",
23105
+ "handled",
23106
+ "dismissed",
23107
+ "resolved"
23108
+ ];
22962
23109
  function foldGroupStatus(instanceStatuses) {
22963
23110
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22964
23111
  if (statuses.size === 0) return void 0;
22965
- for (const candidate of STATUS_PRECEDENCE) {
23112
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22966
23113
  if (statuses.has(candidate)) return candidate;
22967
23114
  }
22968
23115
  return void 0;
@@ -23069,11 +23216,16 @@ function applyFindingFilters(types, opts) {
23069
23216
  }
23070
23217
  return filtered;
23071
23218
  }
23072
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
23073
- var SEVERITY_RANK = SEVERITY_ORDER;
23219
+ function rankByOrder(members2) {
23220
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23221
+ }
23222
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23223
+ function severityRank(severity) {
23224
+ return lookupOwn(SEVERITY_RANK, severity);
23225
+ }
23074
23226
  function compareFindingGroupOrder(a, b) {
23075
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
23076
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23227
+ const rankA = severityRank(a.severity) ?? -1;
23228
+ const rankB = severityRank(b.severity) ?? -1;
23077
23229
  const severityDiff = rankA - rankB;
23078
23230
  if (severityDiff !== 0) return severityDiff;
23079
23231
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23148,6 +23300,20 @@ function computeFindingFacets(allTypes, opts) {
23148
23300
  }
23149
23301
 
23150
23302
  // ../../packages/schema/src/zod/findings-flat-build.ts
23303
+ function compareCodePoints(a, b) {
23304
+ const aIter = a[Symbol.iterator]();
23305
+ const bIter = b[Symbol.iterator]();
23306
+ for (; ; ) {
23307
+ const aNext = aIter.next();
23308
+ const bNext = bIter.next();
23309
+ if (aNext.done && bNext.done) return 0;
23310
+ if (aNext.done) return -1;
23311
+ if (bNext.done) return 1;
23312
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23313
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23314
+ if (aPoint !== bPoint) return aPoint - bPoint;
23315
+ }
23316
+ }
23151
23317
  function rowHaystack(row) {
23152
23318
  return [
23153
23319
  row.ruleId,
@@ -23172,6 +23338,8 @@ function matchesDimension(row, opts, dimension) {
23172
23338
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23173
23339
  case "statuses":
23174
23340
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23341
+ case "deliveries":
23342
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23175
23343
  case "tools":
23176
23344
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23177
23345
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23198,6 +23366,7 @@ var DIMENSIONS = [
23198
23366
  "providers",
23199
23367
  "actions",
23200
23368
  "statuses",
23369
+ "deliveries",
23201
23370
  "tools",
23202
23371
  "repo",
23203
23372
  "file",
@@ -23211,10 +23380,19 @@ function matchesInstanceFilters(row, opts, except) {
23211
23380
  return true;
23212
23381
  }
23213
23382
  function toItems(counts) {
23214
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23383
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23384
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23385
+ // NFD spelling of the same text) as equal, so a count tie between
23386
+ // them would otherwise be ordered by whichever the Map iteration
23387
+ // produced. compareCodePoints breaks that tie deterministically, which
23388
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23389
+ // which it need not: foldFacetTuples runs this same sort over grouped
23390
+ // tuples, so both paths order facets identically by construction.
23391
+ compareCodePoints(a.value, b.value)
23392
+ );
23215
23393
  }
23216
- function bump(counts, value) {
23217
- counts.set(value, (counts.get(value) ?? 0) + 1);
23394
+ function bump(counts, value, by = 1) {
23395
+ counts.set(value, (counts.get(value) ?? 0) + by);
23218
23396
  }
23219
23397
  function createInstanceFacetAccumulator(opts) {
23220
23398
  const severity = /* @__PURE__ */ new Map();
@@ -23223,6 +23401,7 @@ function createInstanceFacetAccumulator(opts) {
23223
23401
  const action = /* @__PURE__ */ new Map();
23224
23402
  const status = /* @__PURE__ */ new Map();
23225
23403
  const tool = /* @__PURE__ */ new Map();
23404
+ const deployment = /* @__PURE__ */ new Map();
23226
23405
  return {
23227
23406
  add(row) {
23228
23407
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23237,6 +23416,9 @@ function createInstanceFacetAccumulator(opts) {
23237
23416
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23238
23417
  bump(tool, row.toolName);
23239
23418
  }
23419
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23420
+ bump(deployment, row.delivery.state);
23421
+ }
23240
23422
  },
23241
23423
  facets: () => ({
23242
23424
  severity: toItems(severity),
@@ -23244,7 +23426,8 @@ function createInstanceFacetAccumulator(opts) {
23244
23426
  provider: toItems(provider),
23245
23427
  action: toItems(action),
23246
23428
  status: toItems(status),
23247
- tool: toItems(tool)
23429
+ tool: toItems(tool),
23430
+ deployment: toItems(deployment)
23248
23431
  })
23249
23432
  };
23250
23433
  }
@@ -23258,6 +23441,7 @@ function toInstanceDetail(row) {
23258
23441
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23259
23442
  eventId: row.eventId,
23260
23443
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23444
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23261
23445
  ...row.user === void 0 ? {} : { user: row.user },
23262
23446
  action: toApiAction(row.actionTaken),
23263
23447
  detectedAt: row.occurredAt,
@@ -23272,12 +23456,6 @@ function toInstanceDetail(row) {
23272
23456
  policy: { id: `category:${category}`, name: category }
23273
23457
  };
23274
23458
  }
23275
- var SEVERITY_ORDER2 = {
23276
- critical: 0,
23277
- high: 1,
23278
- medium: 2,
23279
- low: 3
23280
- };
23281
23459
  function newLocationAccumulator() {
23282
23460
  return {
23283
23461
  instanceCount: 0,
@@ -23292,7 +23470,7 @@ function newLocationAccumulator() {
23292
23470
  }
23293
23471
  function addToLocation(acc, row) {
23294
23472
  acc.instanceCount += 1;
23295
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23473
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23296
23474
  if (rank < acc.maxSeverityRank) {
23297
23475
  acc.maxSeverityRank = rank;
23298
23476
  acc.maxSeverity = row.severity;
@@ -23302,15 +23480,15 @@ function addToLocation(acc, row) {
23302
23480
  acc.ruleIds.add(row.ruleId);
23303
23481
  }
23304
23482
  function compareLocationOrder(a, b) {
23305
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23306
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23483
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23484
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23307
23485
  if (rankA !== rankB) return rankA - rankB;
23308
23486
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23309
23487
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23310
23488
  }
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;
23489
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23490
+ if (repoDiff !== 0) return repoDiff;
23491
+ return compareCodePoints(a.file, b.file);
23314
23492
  }
23315
23493
  function encodeLocationId(repo, file2) {
23316
23494
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23385,6 +23563,11 @@ var Policy = external_exports.object({
23385
23563
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23386
23564
  provenance: PolicyProvenance.optional()
23387
23565
  }).meta({ id: "Policy" });
23566
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23567
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23568
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23569
+ id: "RedactFallback"
23570
+ });
23388
23571
  var PolicyBundle = external_exports.object({
23389
23572
  version: external_exports.string(),
23390
23573
  policies: external_exports.array(Policy),
@@ -23432,6 +23615,16 @@ var PolicyBundle = external_exports.object({
23432
23615
  // control plane), so no name resolution stands between the decision and the
23433
23616
  // comparison.
23434
23617
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23618
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23619
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23620
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23621
+ // a control plane can tighten a machine and never loosen one — the same
23622
+ // direction `mergeRaiseOnly` enforces for policies.
23623
+ //
23624
+ // Optional so an older backend, and an older on-disk cache, still parses;
23625
+ // absent leaves the device's own setting in force, which is the behaviour
23626
+ // that predates the field and the safe direction to default.
23627
+ redactFallback: RedactFallback.optional(),
23435
23628
  customKeywords: external_exports.array(external_exports.string()),
23436
23629
  fetchedAt: external_exports.iso.datetime()
23437
23630
  }).meta({ id: "PolicyBundle" });
@@ -23461,11 +23654,6 @@ function severityFloorPolicy(category) {
23461
23654
  const peak = CATEGORY_PEAK_SEVERITY[category];
23462
23655
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23463
23656
  }
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
23657
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23470
23658
  var BUILTIN_POLICY_SPECS = {
23471
23659
  monitor: {
@@ -23521,6 +23709,11 @@ function isActionAtLeast(action, floor) {
23521
23709
  function strongerAction(a, b) {
23522
23710
  return actionRank(a) >= actionRank(b) ? a : b;
23523
23711
  }
23712
+ function strongerRedactFallback(local, remote) {
23713
+ if (remote === void 0) return local;
23714
+ const localAction = builtinPolicyToAction(local);
23715
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23716
+ }
23524
23717
  function weakestBuiltinAtLeast(floor) {
23525
23718
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23526
23719
  }
@@ -23761,7 +23954,7 @@ var VaultConsent = external_exports.object({
23761
23954
  });
23762
23955
 
23763
23956
  // ../../packages/schema/src/zod/local.ts
23764
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23957
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23765
23958
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23766
23959
  var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23767
23960
  var RunMode = external_exports.enum(["standalone", "attached"]);
@@ -23786,6 +23979,15 @@ function isHistorySyncConsentValid(consent, endpoint) {
23786
23979
  if (consent === void 0 || endpoint === void 0) return false;
23787
23980
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23788
23981
  }
23982
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23983
+ var BodyRetention = external_exports.object({
23984
+ enabled: external_exports.boolean().default(false),
23985
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23986
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23987
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23988
+ // candidate set that is already bounded by "delivered, or never owed".
23989
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23990
+ }).meta({ id: "BodyRetention" });
23789
23991
  var WorkspaceSettings = external_exports.object({
23790
23992
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23791
23993
  runMode: RunMode.default("standalone"),
@@ -23834,7 +24036,13 @@ var WorkspaceSettings = external_exports.object({
23834
24036
  // carry prompt/reply/tool-output text in `content`; the key name predates
23835
24037
  // both widenings. Absent until granted, and a grant for a different endpoint
23836
24038
  // or an older payload no longer counts.
23837
- historySyncConsent: HistorySyncConsent.optional()
24039
+ historySyncConsent: HistorySyncConsent.optional(),
24040
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24041
+ // body never removes the row or its findings.
24042
+ bodyRetention: BodyRetention.default({
24043
+ enabled: false,
24044
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24045
+ })
23838
24046
  });
23839
24047
  function defaultWorkspaceSettings() {
23840
24048
  return WorkspaceSettings.parse({});
@@ -23929,12 +24137,15 @@ function toCaptureAttributes(event) {
23929
24137
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23930
24138
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23931
24139
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24140
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23932
24141
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23933
24142
  // has ever populated either), but every legacy metadata key still rides
23934
24143
  // the bag rather than being silently dropped — CaptureAttributes'
23935
24144
  // `.catchall(z.unknown())` carries the long tail.
23936
24145
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23937
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24146
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24147
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24148
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23938
24149
  };
23939
24150
  }
23940
24151
  function captureDefinitionVersion(finding2) {
@@ -23962,13 +24173,22 @@ var ManagedSettingKey = external_exports.enum([
23962
24173
  "vaultInlineReveal",
23963
24174
  "modelJudgeConsent",
23964
24175
  "dataSharesInPlace",
23965
- "redactFallback"
24176
+ "redactFallback",
24177
+ // Pins the toggle and the day count together — see BodyRetention on why the
24178
+ // two are one unit. An administrator mandating a window wants the count
24179
+ // enforced with it, not one a user can widen while the toggle stays on.
24180
+ "bodyRetention"
23966
24181
  ]).meta({ id: "ManagedSettingKey" });
23967
24182
  function isManagedSettingKey(value) {
23968
24183
  return ManagedSettingKey.safeParse(value).success;
23969
24184
  }
23970
24185
  var ManagedSettingsValues = external_exports.object({
23971
24186
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24187
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24188
+ // plain, non-strict objects: a key under either that this build does not know
24189
+ // is stripped and nothing reports it. The unknown-value split in
24190
+ // ManagedSettings below classifies top-level names only, so it stops at
24191
+ // these boundaries.
23972
24192
  controlPlane: external_exports.object({
23973
24193
  endpoint: external_exports.string().min(1),
23974
24194
  label: external_exports.string().min(1).optional()
@@ -23979,7 +24199,8 @@ var ManagedSettingsValues = external_exports.object({
23979
24199
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23980
24200
  modelJudgeConsent: external_exports.boolean().optional(),
23981
24201
  dataSharesInPlace: external_exports.boolean().optional(),
23982
- redactFallback: RedactFallback.optional()
24202
+ redactFallback: RedactFallback.optional(),
24203
+ bodyRetention: BodyRetention.optional()
23983
24204
  }).meta({ id: "ManagedSettingsValues" });
23984
24205
  var ManagedSettings = external_exports.object({
23985
24206
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23987,7 +24208,21 @@ var ManagedSettings = external_exports.object({
23987
24208
  // decision from a bug. Absent renders as a generic "your organization".
23988
24209
  organization: external_exports.string().min(1).optional(),
23989
24210
  // What the administrator pinned.
23990
- values: ManagedSettingsValues.default({}),
24211
+ //
24212
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24213
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24214
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24215
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24216
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24217
+ // exactly the file an administrator is most likely to write while a fleet
24218
+ // is mid-upgrade.
24219
+ //
24220
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24221
+ // file, which is the outcome the lock half already rejected — an older
24222
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24223
+ // value still fails, because the nested schema is re-run over the known
24224
+ // subset and its issues are re-raised on this parse.
24225
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23991
24226
  // Which of those the user may not change. A key here with no matching value
23992
24227
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23993
24228
  // the user may still override. The two are separable on purpose.
@@ -24000,17 +24235,31 @@ var ManagedSettings = external_exports.object({
24000
24235
  // the fleets most likely to carry a version skew. A name outside the enum
24001
24236
  // is still never HONOURED: the lockable set stays explicit above.
24002
24237
  lockedFields: external_exports.array(external_exports.string()).default([])
24003
- }).transform(({ lockedFields, ...rest }) => {
24238
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24004
24239
  const known = [];
24005
24240
  const unknown2 = [];
24006
24241
  for (const name2 of lockedFields) {
24007
24242
  if (isManagedSettingKey(name2)) known.push(name2);
24008
24243
  else unknown2.push(name2);
24009
24244
  }
24245
+ const knownValues = /* @__PURE__ */ Object.create(null);
24246
+ const unknownValues = [];
24247
+ for (const [name2, value] of Object.entries(values)) {
24248
+ if (Object.hasOwn(ManagedSettingsValues.shape, name2)) knownValues[name2] = value;
24249
+ else unknownValues.push(name2);
24250
+ }
24251
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24252
+ if (!pinned.success) {
24253
+ for (const issue2 of pinned.error.issues)
24254
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24255
+ return external_exports.NEVER;
24256
+ }
24010
24257
  return {
24011
24258
  ...rest,
24259
+ values: pinned.data,
24012
24260
  lockedFields: known,
24013
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24261
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24262
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24014
24263
  };
24015
24264
  }).meta({ id: "ManagedSettings" });
24016
24265
 
@@ -24274,7 +24523,23 @@ var SaveSettingsInput = external_exports.object({
24274
24523
  modelJudgeConsent: ModelJudgeConsentChoice,
24275
24524
  historySyncConsent: HistorySyncConsentChoice,
24276
24525
  vaultConsent: external_exports.string(),
24277
- vaultInlineReveal: external_exports.string()
24526
+ vaultInlineReveal: external_exports.string(),
24527
+ // Widened to `string` like its neighbours rather than typed as
24528
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24529
+ // the call site, so the domain check receives the type it was written for.
24530
+ //
24531
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24532
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24533
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24534
+ // trade against. The real cost runs the other way and is the part worth
24535
+ // knowing: a value this schema admits and the domain enum then rejects lands
24536
+ // on the action's shared refusal, which names NO field, where a shape
24537
+ // rejection reaches `malformedInput` and names the schema key.
24538
+ redactFallback: external_exports.string(),
24539
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24540
+ // `BodyRetention`'s and the action checks it there, so there is one place
24541
+ // that decides what a legal horizon is rather than two that can drift.
24542
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24278
24543
  });
24279
24544
  var AttachInput = external_exports.object({
24280
24545
  endpoint: external_exports.string(),
@@ -24446,6 +24711,52 @@ function reviewSeverityRank(reasons) {
24446
24711
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24447
24712
  }
24448
24713
 
24714
+ // ../../packages/schema/src/zod/web-capture.ts
24715
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24716
+ var WebUsage = external_exports.object({
24717
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24718
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24719
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24720
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24721
+ });
24722
+ var WebToolCall = external_exports.object({
24723
+ toolUseId: external_exports.string().min(1),
24724
+ toolName: external_exports.string().min(1),
24725
+ target: external_exports.string().optional(),
24726
+ isError: external_exports.boolean().optional(),
24727
+ inputSize: external_exports.number().int().nonnegative().optional(),
24728
+ outputSize: external_exports.number().int().nonnegative().optional()
24729
+ });
24730
+ var WebExchange = external_exports.object({
24731
+ messageId: external_exports.string().min(1),
24732
+ startedAt: external_exports.iso.datetime(),
24733
+ model: external_exports.string().optional(),
24734
+ usage: WebUsage.optional(),
24735
+ usageSource: WebUsageSource,
24736
+ stopReason: external_exports.string().optional(),
24737
+ conversationId: external_exports.string().optional(),
24738
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24739
+ toolCalls: external_exports.array(WebToolCall).default([]),
24740
+ // Absent when the adapter recovered no text. Capped by the caller at
24741
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24742
+ // short capture is never mistaken for a short reply.
24743
+ responseText: external_exports.string().optional(),
24744
+ truncated: external_exports.boolean().default(false)
24745
+ });
24746
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24747
+ var WebCaptureStatus = external_exports.object({
24748
+ patched: external_exports.boolean(),
24749
+ live: external_exports.boolean(),
24750
+ blind: external_exports.boolean(),
24751
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24752
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24753
+ parseFailures: external_exports.number().int().nonnegative(),
24754
+ unparsedBodies: external_exports.number().int().nonnegative(),
24755
+ // The adapter-declared JSON key paths that were absent from a real payload —
24756
+ // the earliest signal that a site's contract moved.
24757
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24758
+ });
24759
+
24449
24760
  // ../../packages/persistence/src/paths.ts
24450
24761
  import {
24451
24762
  chmodSync,
@@ -24810,6 +25121,22 @@ function discardStore(file2, backup) {
24810
25121
  }
24811
25122
  }
24812
25123
 
25124
+ // ../../packages/persistence/src/internal/sql-functions.ts
25125
+ var utf8 = new TextDecoder();
25126
+ function akaLower(value) {
25127
+ if (value === null) return null;
25128
+ if (typeof value === "string") return value.toLowerCase();
25129
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25130
+ return utf8.decode(value).toLowerCase();
25131
+ }
25132
+ function registerSqlFunctions(db) {
25133
+ db.function(
25134
+ "aka_lower",
25135
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25136
+ akaLower
25137
+ );
25138
+ }
25139
+
24813
25140
  // ../../packages/persistence/src/internal/sql-text.ts
24814
25141
  function escapeLikePattern(s) {
24815
25142
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24894,6 +25221,11 @@ function schemaObjectExists(db, kind, name2) {
24894
25221
  function indexExists(db, name2) {
24895
25222
  return schemaObjectExists(db, "index", name2);
24896
25223
  }
25224
+ function indexColumns(db, name2) {
25225
+ if (!indexExists(db, name2)) return [];
25226
+ const columns = db.prepare(`PRAGMA index_info(${name2})`).all();
25227
+ return columns.map((c) => c.name).filter((c) => c !== null);
25228
+ }
24897
25229
  function columnNames(db, table, opts) {
24898
25230
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24899
25231
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24955,177 +25287,819 @@ function mapRowsTolerant(rows, map2) {
24955
25287
  return out;
24956
25288
  }
24957
25289
 
24958
- // ../../packages/persistence/src/migrations.ts
24959
- function describeObject(object2) {
24960
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24961
- }
24962
- function splitStatements(sql) {
24963
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24964
- }
24965
- function createdIndexName(statement) {
24966
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24967
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25290
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25291
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25292
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25293
+
25294
+ // ../../packages/persistence/src/sync-failure.ts
25295
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25296
+ function syncFailureRejectCondition(column = "sync_failure") {
25297
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25298
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24968
25299
  }
24969
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24970
- function applyMigrations(db, file2) {
24971
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24972
- db.exec(
24973
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24974
- );
24975
- const applied = new Set(
24976
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24977
- );
24978
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24979
- const record2 = db.prepare(
24980
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24981
- );
24982
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24983
- if (applied.has(migration.tag)) continue;
24984
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24985
- const evidence = evidenceObjects(migration.sql);
24986
- const present = evidence.filter((o) => evidenceExists(db, o));
24987
- if (present.length > 0 && present.length < evidence.length) {
24988
- const missing = evidence.filter((o) => !present.includes(o));
24989
- const message2 = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24990
- akaWarn(message2);
24991
- throw new Error(`[aka] ${message2}`);
24992
- }
24993
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24994
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24995
- const statements = splitStatements(migration.sql);
24996
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24997
- try {
24998
- withTransaction(
24999
- db,
25000
- () => {
25001
- for (const statement of statements) {
25002
- const indexName = createdIndexName(statement);
25003
- if (indexName === void 0) {
25004
- if (alreadyApplied) continue;
25005
- } else if (indexExists(db, indexName)) {
25006
- continue;
25007
- }
25008
- db.exec(statement);
25009
- }
25010
- if (wantsFkOff && !alreadyApplied) {
25011
- const violations = db.prepare("PRAGMA foreign_key_check").all();
25012
- if (violations.length > 0) {
25013
- throw new Error(
25014
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25015
- );
25016
- }
25017
- }
25018
- record2.run(migration.tag, Date.now());
25019
- },
25020
- "IMMEDIATE"
25021
- );
25022
- } finally {
25023
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25024
- }
25300
+
25301
+ // ../../packages/persistence/src/repositories/history-sync.ts
25302
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25303
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25304
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25305
+ var COUNTED_EVENT_TYPES = [
25306
+ ...STRUCTURAL_EVENT_TYPES,
25307
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25308
+ ];
25309
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25310
+ var PARTITION_BUCKETS = `
25311
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25312
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25313
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25314
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25315
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25316
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25317
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25318
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25319
+ -- added later lands in no bucket and fails the sum assertion, instead
25320
+ -- of silently joining this one.
25321
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25322
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25323
+ THEN 1 ELSE 0 END) AS failed,
25324
+ COUNT(*) AS total`;
25325
+ var COUNTED_SCOPE = `
25326
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25327
+ AND (
25328
+ event_type IN (${TYPE_LIST})
25329
+ OR synced_at IS NOT NULL
25330
+ OR outbox_owed = 1
25331
+ )`;
25332
+ var SKIPPED = -1;
25333
+ var ROW_COLUMNS = `id,
25334
+ parent_id AS parentId,
25335
+ root_session_id AS rootSessionId,
25336
+ event_type AS eventType,
25337
+ host_id AS hostId,
25338
+ harness_id AS harnessId,
25339
+ source_project_id AS sourceProjectId,
25340
+ started_at AS startedAt,
25341
+ ended_at AS endedAt,
25342
+ severity,
25343
+ priority,
25344
+ content,
25345
+ content_hash AS contentHash,
25346
+ attributes`;
25347
+ var SqliteHistorySyncRepository = class {
25348
+ constructor(db) {
25349
+ this.db = db;
25350
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25351
+ this.sessionsStmt = db.prepare(
25352
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25353
+ FROM audit_events
25354
+ WHERE synced_at IS NULL
25355
+ AND event_type IN (${TYPE_LIST})
25356
+ AND started_at < :before
25357
+ GROUP BY sessionId
25358
+ ORDER BY earliest
25359
+ LIMIT :limit`
25360
+ );
25361
+ this.rowsStmt = db.prepare(
25362
+ `SELECT ${ROW_COLUMNS}
25363
+ FROM audit_events
25364
+ WHERE synced_at IS NULL
25365
+ AND event_type IN (${TYPE_LIST})
25366
+ AND started_at < :before
25367
+ AND COALESCE(root_session_id, id) = :sessionId
25368
+ ORDER BY (event_type = 'session') DESC, started_at
25369
+ LIMIT :limit`
25370
+ );
25371
+ this.captureRowsStmt = db.prepare(
25372
+ `SELECT ${ROW_COLUMNS}
25373
+ FROM audit_events
25374
+ WHERE synced_at IS NULL
25375
+ AND sync_claimed_at IS NULL
25376
+ AND outbox_owed = 1
25377
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25378
+ AND started_at < :before
25379
+ ORDER BY started_at
25380
+ LIMIT :limit`
25381
+ );
25382
+ this.markOwedStmt = db.prepare(
25383
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25384
+ );
25385
+ this.markCaptureBacklogOwedStmt = db.prepare(
25386
+ `UPDATE audit_events SET outbox_owed = 1
25387
+ WHERE synced_at IS NULL
25388
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25389
+ AND started_at < :before`
25390
+ );
25391
+ this.stampStmt = db.prepare(
25392
+ `UPDATE audit_events
25393
+ SET synced_at = :at,
25394
+ sync_claimed_at = NULL,
25395
+ sync_failed_at = :failedAt,
25396
+ sync_failure = :failure
25397
+ WHERE id = :id`
25398
+ );
25399
+ this.claimRowStmt = db.prepare(
25400
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25401
+ );
25402
+ this.releaseRowStmt = db.prepare(
25403
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25404
+ );
25405
+ this.releaseStaleClaimsStmt = db.prepare(
25406
+ `UPDATE audit_events SET sync_claimed_at = NULL
25407
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25408
+ );
25409
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25410
+ FROM audit_events${COUNTED_SCOPE}`);
25411
+ this.partitionByKindStmt = db.prepare(
25412
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25413
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25414
+ GROUP BY event_type`
25415
+ );
25416
+ this.countsStmt = db.prepare(
25417
+ `SELECT
25418
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25419
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25420
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25421
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25422
+ THEN 1 ELSE 0 END) AS skipped,
25423
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25424
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25425
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25426
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25427
+ FROM audit_events
25428
+ WHERE event_type IN (${TYPE_LIST})`
25429
+ );
25430
+ this.captureSkipCountStmt = db.prepare(
25431
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25432
+ // way the structural totals are. The split exists because a refusal is
25433
+ // terminal only against the deployment that gave it, and the structural
25434
+ // re-arm frees it on a change of deployment. The capture lane has no such
25435
+ // escape: re-arming a capture would offer one deployment's undelivered
25436
+ // prompts, with their text, to a deployment that never saw them, which is
25437
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25438
+ // reasons mean the same thing — this row will not be sent — and splitting
25439
+ // them would put refused captures in a bucket nothing reads and nothing
25440
+ // frees.
25441
+ `SELECT COUNT(*) AS skipped
25442
+ FROM audit_events
25443
+ WHERE synced_at = ${String(SKIPPED)}
25444
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25445
+ );
25446
+ this.fingerprintStmt = db.prepare(
25447
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25448
+ FROM history_sync WHERE id = 1`
25449
+ );
25450
+ this.setFingerprintStmt = db.prepare(
25451
+ `UPDATE history_sync
25452
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25453
+ WHERE id = 1`
25454
+ );
25455
+ this.disownCapturesStmt = db.prepare(
25456
+ `UPDATE audit_events SET outbox_owed = NULL
25457
+ WHERE outbox_owed IS NOT NULL
25458
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25459
+ AND started_at < :attachedAt`
25460
+ );
25461
+ this.rearmStmt = db.prepare(
25462
+ `UPDATE audit_events
25463
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25464
+ WHERE (synced_at > 0
25465
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25466
+ AND event_type IN (${TYPE_LIST})`
25467
+ );
25468
+ this.claimStmt = db.prepare(
25469
+ `UPDATE history_sync
25470
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25471
+ WHERE id = 1
25472
+ AND (owner_pid IS NULL
25473
+ OR heartbeat_at IS NULL
25474
+ OR heartbeat_at < :staleBefore
25475
+ OR heartbeat_at > :now)`
25476
+ );
25477
+ this.heartbeatStmt = db.prepare(
25478
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25479
+ );
25480
+ this.releaseStmt = db.prepare(
25481
+ `UPDATE history_sync
25482
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25483
+ WHERE id = 1 AND owner_pid = :pid`
25484
+ );
25485
+ this.closeWindowStmt = db.prepare(
25486
+ `UPDATE audit_events
25487
+ SET synced_at = ${String(SKIPPED)},
25488
+ sync_failed_at = :at,
25489
+ sync_failure = 'detached_undelivered'
25490
+ WHERE synced_at IS NULL
25491
+ AND event_type IN (${TYPE_LIST})
25492
+ AND started_at >= :attachedAt`
25493
+ );
25494
+ this.releaseBoundaryStmt = db.prepare(
25495
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25496
+ );
25497
+ this.freezeBoundaryStmt = db.prepare(
25498
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25499
+ );
25500
+ this.leaseStmt = db.prepare(
25501
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25502
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25503
+ FROM history_sync WHERE id = 1`
25504
+ );
25505
+ this.inspectionsStmt = db.prepare(
25506
+ `SELECT d.rule_id AS ruleId,
25507
+ d.name AS ruleName,
25508
+ d.version AS ruleVersion,
25509
+ d.category AS category,
25510
+ d.severity AS severity,
25511
+ f.span_start AS spanStart,
25512
+ f.span_end AS spanEnd,
25513
+ f.masked_match AS maskedMatch,
25514
+ f.action_taken AS actionTaken,
25515
+ f.confidence AS confidence
25516
+ FROM inspection_findings f
25517
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25518
+ WHERE f.audit_event_id = :auditEventId
25519
+ ORDER BY f.span_start, f.id`
25520
+ );
25025
25521
  }
25026
- if (legacyCount < SQLITE_MIGRATIONS.length) {
25027
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25522
+ db;
25523
+ ensureRowStmt;
25524
+ sessionsStmt;
25525
+ rowsStmt;
25526
+ stampStmt;
25527
+ countsStmt;
25528
+ fingerprintStmt;
25529
+ setFingerprintStmt;
25530
+ rearmStmt;
25531
+ claimStmt;
25532
+ heartbeatStmt;
25533
+ releaseStmt;
25534
+ leaseStmt;
25535
+ inspectionsStmt;
25536
+ closeWindowStmt;
25537
+ releaseBoundaryStmt;
25538
+ freezeBoundaryStmt;
25539
+ captureRowsStmt;
25540
+ markOwedStmt;
25541
+ markCaptureBacklogOwedStmt;
25542
+ captureSkipCountStmt;
25543
+ disownCapturesStmt;
25544
+ partitionStmt;
25545
+ partitionByKindStmt;
25546
+ claimRowStmt;
25547
+ releaseRowStmt;
25548
+ releaseStaleClaimsStmt;
25549
+ /**
25550
+ * The masked detections recorded against one tool call.
25551
+ *
25552
+ * These travel with the event because a tool call's target is not
25553
+ * re-inspectable from the event alone — unlike a capture, where the text
25554
+ * itself is re-scannable. What crosses is the masked match and the rule that
25555
+ * produced it, never the value.
25556
+ */
25557
+ inspectionsFor(auditEventId) {
25558
+ return allRows(this.inspectionsStmt, { auditEventId });
25028
25559
  }
25029
- ensureSyncedAtColumn(db, "audit_events");
25030
- ensureScanLedgerTable(db);
25031
- ensureHistorySyncTable(db);
25032
- ensureBlockedDetectionsTable(db);
25033
- ensureRuleProbeCacheTable(db);
25034
- ensureWriteGateTrigger(db);
25035
- ensureTokenUsageColumns(db);
25036
- reconcileSourceProjectIds(db);
25037
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25038
- const drained = runLegacyHistoryBackfill(db);
25039
- if (drained) applyLegacyDropMigration(db, file2);
25560
+ /**
25561
+ * Sessions with structural rows still to send, oldest first.
25562
+ *
25563
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25564
+ * read. Anything recorded after the machine attached is the live forward
25565
+ * path's to deliver; this drain exists for what was recorded before it, and a
25566
+ * row both paths send is at best a duplicate request and at worst — for a
25567
+ * session root — an overwrite of the inventory ids the live path resolved.
25568
+ */
25569
+ pendingSessions(limit, before) {
25570
+ return allRows(this.sessionsStmt, { limit, before }).map(
25571
+ (r) => r.sessionId
25572
+ );
25040
25573
  }
25041
- }
25042
- function readLegacyTables(db) {
25043
- let holdsRows = false;
25044
- const marks = [];
25045
- for (const table of ["events", "findings"]) {
25046
- try {
25047
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25048
- if (row === void 0) {
25049
- holdsRows = true;
25050
- marks.push(`${table}:unreadable`);
25051
- continue;
25052
- }
25053
- if (row.n > 0) holdsRows = true;
25054
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25055
- } catch {
25056
- holdsRows = true;
25057
- marks.push(`${table}:unreadable`);
25058
- }
25574
+ /** One session's undelivered structural rows within the backlog, root first. */
25575
+ pendingRows(sessionId, limit, before) {
25576
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25059
25577
  }
25060
- return { holdsRows, mark: marks.join("|") };
25061
- }
25062
- function applyLegacyDropMigration(db, file2) {
25063
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25064
- if (!migration) return;
25065
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25066
- if (file2 !== void 0 && before?.holdsRows === true) {
25067
- try {
25068
- backupBeforeLegacyDrop(db, file2);
25069
- } catch (error61) {
25070
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25071
- return;
25072
- }
25578
+ /**
25579
+ * Captures this machine still owes the deployment, oldest first.
25580
+ *
25581
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25582
+ * by a time window — see captureRowsStmt for why a window could not express
25583
+ * this. `before` is the grace window that leaves a just-recorded capture to
25584
+ * the live path.
25585
+ */
25586
+ pendingCaptureRows(limit, before) {
25587
+ return allRows(this.captureRowsStmt, { limit, before });
25073
25588
  }
25074
- try {
25589
+ /**
25590
+ * Record that a capture is OWED to the deployment.
25591
+ *
25592
+ * Written by the attached forward path when a live send did not confirm
25593
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25594
+ * a fact rather than an inference: the machine was attached, the send did not
25595
+ * land, so the row is owed — which no time window can state, because the same
25596
+ * window that holds the rows a past attachment left owed also holds every
25597
+ * capture recorded while the machine was DETACHED, and those were never
25598
+ * offered to anyone.
25599
+ *
25600
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25601
+ * out of the drain's read.
25602
+ */
25603
+ markCaptureOwed(id) {
25604
+ this.markOwedStmt.run({ id });
25605
+ }
25606
+ /**
25607
+ * Mark every capture already on disk as owed, as of `before`.
25608
+ *
25609
+ * The consent-time backfill, called once from `aka attach` when a human
25610
+ * grants existing-history consent — never from an ongoing drain pass, and
25611
+ * never inferred from a boundary that could later move. `before` is the
25612
+ * caller's own "now" at the moment consent was granted, so what this marks
25613
+ * is exactly the backlog the consent prompt already counted, not whatever a
25614
+ * later re-attach or key rotation might widen it to.
25615
+ *
25616
+ * Returns how many rows matched, for the caller to log or test against. Not a
25617
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25618
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25619
+ */
25620
+ markCaptureBacklogOwed(before) {
25621
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25622
+ }
25623
+ /**
25624
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25625
+ *
25626
+ * CLEARS any failure reason in the same statement. A row that failed against
25627
+ * one deployment and then landed is delivered, and leaving the reason behind
25628
+ * would leave the store holding two contradictory answers about one row —
25629
+ * with the surface free to render either.
25630
+ */
25631
+ markSynced(ids, atMs) {
25632
+ this.stampAll(ids, atMs, null);
25633
+ }
25634
+ /**
25635
+ * Record that THIS MACHINE cannot express the row on the wire.
25636
+ *
25637
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25638
+ * payload, or a body the client itself refused to send. It fails identically
25639
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25640
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25641
+ * is retried; marking those would turn one outage into permanent data loss.
25642
+ */
25643
+ markSkipped(ids, atMs) {
25644
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25645
+ }
25646
+ /**
25647
+ * Record that THIS DEPLOYMENT refused the row.
25648
+ *
25649
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25650
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25651
+ * row is outstanding rather than why. What separates them is the reason, and
25652
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25653
+ * on one body, so it is terminal only for as long as this machine points at
25654
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25655
+ *
25656
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25657
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25658
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25659
+ */
25660
+ markRefused(ids, atMs) {
25661
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25662
+ }
25663
+ eachInTransaction(ids, run) {
25664
+ if (ids.length === 0) return;
25075
25665
  withTransaction(
25076
- db,
25666
+ this.db,
25077
25667
  () => {
25078
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25079
- if (alreadyDropped) return;
25080
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25081
- akaWarn(
25082
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25083
- );
25084
- return;
25085
- }
25086
- for (const statement of splitStatements(migration.sql)) {
25087
- db.exec(statement);
25088
- }
25089
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25090
- migration.tag,
25091
- Date.now()
25092
- );
25668
+ for (const id of ids) run(id);
25093
25669
  },
25094
25670
  "IMMEDIATE"
25095
25671
  );
25096
- } catch (error61) {
25097
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25098
25672
  }
25099
- }
25100
- function backupBeforeLegacyDrop(db, file2) {
25101
- reapStalePartials(file2);
25102
- const backup = backupPath(file2, "pre-drop");
25103
- snapshotStore(db, backup);
25104
- return backup;
25105
- }
25106
- var TOKEN_USAGE_COLUMNS = [
25107
- {
25108
- name: "input_tokens",
25109
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25110
- },
25111
- {
25112
- name: "output_tokens",
25113
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25114
- },
25115
- {
25116
- name: "cache_creation_input_tokens",
25117
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25118
- },
25119
- {
25120
- name: "cache_read_input_tokens",
25121
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25122
- },
25123
- {
25124
- name: "model",
25125
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25126
- },
25127
- {
25128
- name: "provider",
25673
+ stampAll(ids, value, failure, failedAtMs) {
25674
+ if (ids.length === 0) return;
25675
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25676
+ withTransaction(
25677
+ this.db,
25678
+ () => {
25679
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25680
+ },
25681
+ "IMMEDIATE"
25682
+ );
25683
+ }
25684
+ /**
25685
+ * Claim rows as in-flight.
25686
+ *
25687
+ * Advisory in exactly the sense the lease is: it records that a send is in
25688
+ * progress so a surface can say so, and a lost claim costs a row showing as
25689
+ * queued while it is actually being sent. It is not exclusion — the far side
25690
+ * settles a duplicate on the row id.
25691
+ */
25692
+ claimRows(ids, atMs) {
25693
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25694
+ }
25695
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25696
+ releaseRows(ids) {
25697
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25698
+ }
25699
+ /**
25700
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25701
+ *
25702
+ * A process killed between claiming and settling leaves rows claimed with
25703
+ * nothing left to settle them. Without this they read as "sending" for ever.
25704
+ */
25705
+ releaseStaleClaims(staleBefore) {
25706
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25707
+ }
25708
+ /**
25709
+ * Every tracked row in exactly one delivery state.
25710
+ *
25711
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25712
+ * pick up now", which is a different question from "what state is this row
25713
+ * in" — and a machine that has never attached has no boundary to pass, so
25714
+ * requiring one would force a caller to invent one and report the whole store
25715
+ * as queued.
25716
+ */
25717
+ /**
25718
+ * The same partition, one row per kind that a lane carries.
25719
+ *
25720
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25721
+ * scope decides which rows exist at all, so a kind that has never been
25722
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25723
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25724
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25725
+ * different things.
25726
+ */
25727
+ partitionByKind() {
25728
+ return allRows(
25729
+ this.partitionByKindStmt,
25730
+ {}
25731
+ ).map((row) => ({
25732
+ kind: row.kind,
25733
+ queued: row.queued ?? 0,
25734
+ inProgress: row.inProgress ?? 0,
25735
+ synced: row.synced ?? 0,
25736
+ failed: row.failed ?? 0,
25737
+ refused: row.refused ?? 0,
25738
+ detached: row.detached ?? 0,
25739
+ total: row.total ?? 0
25740
+ }));
25741
+ }
25742
+ partition() {
25743
+ const row = getRow(this.partitionStmt, {});
25744
+ return {
25745
+ queued: row?.queued ?? 0,
25746
+ inProgress: row?.inProgress ?? 0,
25747
+ synced: row?.synced ?? 0,
25748
+ failed: row?.failed ?? 0,
25749
+ refused: row?.refused ?? 0,
25750
+ detached: row?.detached ?? 0,
25751
+ total: row?.total ?? 0
25752
+ };
25753
+ }
25754
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25755
+ counts(before) {
25756
+ const row = getRow(this.countsStmt, { before });
25757
+ const captures = getRow(this.captureSkipCountStmt);
25758
+ return {
25759
+ pending: row?.pending ?? 0,
25760
+ sent: row?.sent ?? 0,
25761
+ skipped: row?.skipped ?? 0,
25762
+ refused: row?.refused ?? 0,
25763
+ detached: row?.detached ?? 0,
25764
+ capturesSkipped: captures?.skipped ?? 0
25765
+ };
25766
+ }
25767
+ /**
25768
+ * The deployment the current stamps were made against, and where its backlog
25769
+ * ends.
25770
+ *
25771
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25772
+ * machine that has never drained is — and every writer below seeds the row
25773
+ * before it needs one, so nothing depends on this creating it. Keeping the
25774
+ * write off the gate path matters because the gate runs on every pass while a
25775
+ * write has to take the database's write lock.
25776
+ */
25777
+ deployment() {
25778
+ const row = getRow(
25779
+ this.fingerprintStmt
25780
+ );
25781
+ return {
25782
+ fingerprint: row?.fingerprint ?? void 0,
25783
+ backlogBefore: row?.backlogBefore ?? void 0
25784
+ };
25785
+ }
25786
+ /**
25787
+ * Point the ledger at a different deployment, discarding what it recorded
25788
+ * about the previous one.
25789
+ *
25790
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25791
+ * machine has just left are undelivered as far as the new one is concerned.
25792
+ * All four in one transaction, so a crash between them cannot leave stamps
25793
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25794
+ * a disown with no re-mark to follow it.
25795
+ *
25796
+ * The boundary is written HERE and only here, which is what freezes it: a
25797
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25798
+ * unchanged, so this never runs and the backlog does not widen back over rows
25799
+ * the live path has since delivered.
25800
+ *
25801
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25802
+ * granted existing-history consent for the deployment this call is arming —
25803
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25804
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25805
+ * apart. Passed only when that grant is valid, since this method has no way
25806
+ * to check consent itself and must not mark a row owed for a machine that
25807
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25808
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25809
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25810
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25811
+ * on the cleared side of that bound — and the re-mark in the same
25812
+ * transaction is what puts those rows back. A crash between the two cannot
25813
+ * strand the ledger disowned with nothing re-marked — the transaction either
25814
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25815
+ * committed re-enters this method on the very next pass. Omit it (the
25816
+ * structural-only tests do) to exercise the disown in isolation.
25817
+ *
25818
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25819
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25820
+ * live path can mark a capture owed from the moment `aka attach` writes the
25821
+ * descriptor, before the drain's first pass ever reaches this method, and
25822
+ * such a row sits at or after the bound rather than below it. What keeps the
25823
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25824
+ * bound — disown runs first, re-mark second, both inside the one
25825
+ * transaction above.
25826
+ */
25827
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25828
+ this.ensureRowStmt.run();
25829
+ withTransaction(
25830
+ this.db,
25831
+ () => {
25832
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25833
+ this.rearmStmt.run();
25834
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25835
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25836
+ }
25837
+ if (backfillCapturesBefore !== void 0) {
25838
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25839
+ }
25840
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25841
+ },
25842
+ "IMMEDIATE"
25843
+ );
25844
+ }
25845
+ /**
25846
+ * End the attached period: hand its rows to the live path, and release the
25847
+ * boundary so the next attachment can freeze a new one.
25848
+ *
25849
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25850
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25851
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25852
+ * during the detached period, because the machine is not attached. Rows
25853
+ * recorded in that window sit after the boundary and before the re-attach, so
25854
+ * neither path takes them, and the pending count reports none outstanding.
25855
+ *
25856
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25857
+ * closing attachment's to deliver and are no longer outstanding — that is what
25858
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25859
+ * distinction is not academic: this used to write a delivery TIME, which every
25860
+ * read treats as delivery, so one detach turned a window of undelivered rows
25861
+ * into a window of delivered ones and no surface could tell. It writes the
25862
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25863
+ * "received" stop being the same fact.
25864
+ *
25865
+ * A change of deployment still frees them (see the re-arm), because the next
25866
+ * deployment has seen none of this machine's history — so the rows reach it
25867
+ * exactly as they did when this wrote a delivery time.
25868
+ *
25869
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25870
+ * window unstamped — that half-state would re-send the whole attached period
25871
+ * on the next attach, which is the failure the boundary exists to prevent.
25872
+ */
25873
+ closeAttachedWindow(attachedAtMs, atMs) {
25874
+ this.ensureRowStmt.run();
25875
+ withTransaction(
25876
+ this.db,
25877
+ () => {
25878
+ const row = getRow(this.fingerprintStmt);
25879
+ const from = row?.backlogBefore ?? attachedAtMs;
25880
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25881
+ this.releaseBoundaryStmt.run();
25882
+ },
25883
+ "IMMEDIATE"
25884
+ );
25885
+ }
25886
+ /**
25887
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25888
+ *
25889
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25890
+ * different deployment and therefore discards what was delivered to the old
25891
+ * one: here the recipient is the same, so everything already sent to it stays
25892
+ * sent.
25893
+ */
25894
+ freezeBoundary(backlogBefore) {
25895
+ this.ensureRowStmt.run();
25896
+ this.freezeBoundaryStmt.run({ backlogBefore });
25897
+ }
25898
+ /** Take the claim, or report that someone live already holds it. */
25899
+ claim(pid, host, nowMs, staleAfterMs) {
25900
+ this.ensureRowStmt.run();
25901
+ let taken = false;
25902
+ withTransaction(
25903
+ this.db,
25904
+ () => {
25905
+ const result = this.claimStmt.run({
25906
+ pid,
25907
+ host,
25908
+ now: nowMs,
25909
+ staleBefore: nowMs - staleAfterMs
25910
+ });
25911
+ taken = result.changes === 1;
25912
+ },
25913
+ "IMMEDIATE"
25914
+ );
25915
+ return taken;
25916
+ }
25917
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25918
+ heartbeat(pid, nowMs) {
25919
+ this.heartbeatStmt.run({ now: nowMs, pid });
25920
+ }
25921
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25922
+ release(pid) {
25923
+ this.releaseStmt.run({ pid });
25924
+ }
25925
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25926
+ lease() {
25927
+ return getRow(this.leaseStmt);
25928
+ }
25929
+ };
25930
+
25931
+ // ../../packages/persistence/src/migrations.ts
25932
+ function describeObject(object2) {
25933
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25934
+ }
25935
+ function splitStatements(sql) {
25936
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25937
+ }
25938
+ function createdIndexName(statement) {
25939
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25940
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25941
+ }
25942
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25943
+ function applyMigrations(db, file2, options = {}) {
25944
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25945
+ db.exec(
25946
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25947
+ );
25948
+ const applied = new Set(
25949
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25950
+ );
25951
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25952
+ const record2 = db.prepare(
25953
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25954
+ );
25955
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25956
+ if (applied.has(migration.tag)) continue;
25957
+ if (options.skipTags?.has(migration.tag) === true) continue;
25958
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25959
+ const evidence = evidenceObjects(migration.sql);
25960
+ const present = evidence.filter((o) => evidenceExists(db, o));
25961
+ if (present.length > 0 && present.length < evidence.length) {
25962
+ const missing = evidence.filter((o) => !present.includes(o));
25963
+ const message2 = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25964
+ akaWarn(message2);
25965
+ throw new Error(`[aka] ${message2}`);
25966
+ }
25967
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25968
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25969
+ const statements = splitStatements(migration.sql);
25970
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25971
+ try {
25972
+ withTransaction(
25973
+ db,
25974
+ () => {
25975
+ for (const statement of statements) {
25976
+ const indexName = createdIndexName(statement);
25977
+ if (indexName === void 0) {
25978
+ if (alreadyApplied) continue;
25979
+ } else if (indexExists(db, indexName)) {
25980
+ continue;
25981
+ }
25982
+ db.exec(statement);
25983
+ }
25984
+ if (wantsFkOff && !alreadyApplied) {
25985
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25986
+ if (violations.length > 0) {
25987
+ throw new Error(
25988
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25989
+ );
25990
+ }
25991
+ }
25992
+ record2.run(migration.tag, Date.now());
25993
+ },
25994
+ "IMMEDIATE"
25995
+ );
25996
+ } finally {
25997
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25998
+ }
25999
+ }
26000
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
26001
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
26002
+ }
26003
+ ensureSyncedAtColumn(db, "audit_events");
26004
+ ensureScanLedgerTable(db);
26005
+ ensureHistorySyncTable(db);
26006
+ ensureBlockedDetectionsTable(db);
26007
+ ensureRuleProbeCacheTable(db);
26008
+ ensureWriteGateTrigger(db);
26009
+ ensureTokenUsageColumns(db);
26010
+ reconcileSourceProjectIds(db);
26011
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
26012
+ const drained = runLegacyHistoryBackfill(db);
26013
+ if (drained) applyLegacyDropMigration(db, file2);
26014
+ }
26015
+ }
26016
+ function readLegacyTables(db) {
26017
+ let holdsRows = false;
26018
+ const marks = [];
26019
+ for (const table of ["events", "findings"]) {
26020
+ try {
26021
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
26022
+ if (row === void 0) {
26023
+ holdsRows = true;
26024
+ marks.push(`${table}:unreadable`);
26025
+ continue;
26026
+ }
26027
+ if (row.n > 0) holdsRows = true;
26028
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
26029
+ } catch {
26030
+ holdsRows = true;
26031
+ marks.push(`${table}:unreadable`);
26032
+ }
26033
+ }
26034
+ return { holdsRows, mark: marks.join("|") };
26035
+ }
26036
+ function applyLegacyDropMigration(db, file2) {
26037
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
26038
+ if (!migration) return;
26039
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
26040
+ if (file2 !== void 0 && before?.holdsRows === true) {
26041
+ try {
26042
+ backupBeforeLegacyDrop(db, file2);
26043
+ } catch (error61) {
26044
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
26045
+ return;
26046
+ }
26047
+ }
26048
+ try {
26049
+ withTransaction(
26050
+ db,
26051
+ () => {
26052
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
26053
+ if (alreadyDropped) return;
26054
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
26055
+ akaWarn(
26056
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
26057
+ );
26058
+ return;
26059
+ }
26060
+ for (const statement of splitStatements(migration.sql)) {
26061
+ db.exec(statement);
26062
+ }
26063
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
26064
+ migration.tag,
26065
+ Date.now()
26066
+ );
26067
+ },
26068
+ "IMMEDIATE"
26069
+ );
26070
+ } catch (error61) {
26071
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
26072
+ }
26073
+ }
26074
+ function backupBeforeLegacyDrop(db, file2) {
26075
+ reapStalePartials(file2);
26076
+ const backup = backupPath(file2, "pre-drop");
26077
+ snapshotStore(db, backup);
26078
+ return backup;
26079
+ }
26080
+ var TOKEN_USAGE_COLUMNS = [
26081
+ {
26082
+ name: "input_tokens",
26083
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
26084
+ },
26085
+ {
26086
+ name: "output_tokens",
26087
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
26088
+ },
26089
+ {
26090
+ name: "cache_creation_input_tokens",
26091
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
26092
+ },
26093
+ {
26094
+ name: "cache_read_input_tokens",
26095
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
26096
+ },
26097
+ {
26098
+ name: "model",
26099
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
26100
+ },
26101
+ {
26102
+ name: "provider",
25129
26103
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25130
26104
  }
25131
26105
  ];
@@ -25387,10 +26361,62 @@ function ensureSyncedAtColumn(db, table) {
25387
26361
  if (!columns.includes("outbox_owed")) {
25388
26362
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25389
26363
  }
26364
+ if (!columns.includes("sync_failed_at")) {
26365
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26366
+ }
26367
+ if (!columns.includes("sync_failure")) {
26368
+ withTransaction(
26369
+ db,
26370
+ () => {
26371
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26372
+ db.exec(
26373
+ `UPDATE ${table} SET synced_at = NULL
26374
+ WHERE synced_at = -1
26375
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26376
+ );
26377
+ },
26378
+ "IMMEDIATE"
26379
+ );
26380
+ }
25390
26381
  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)`
26382
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26383
+ BEFORE UPDATE OF sync_failure ON ${table}
26384
+ WHEN ${syncFailureRejectCondition()}
26385
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25393
26386
  );
26387
+ const syncIndexColumns = [
26388
+ "event_type",
26389
+ "synced_at",
26390
+ "sync_claimed_at",
26391
+ "started_at",
26392
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26393
+ // has to be in the index for the read to stay covered — but putting it
26394
+ // ahead of `started_at` would reorder the prefix the structural drain's
26395
+ // reads match on.
26396
+ "sync_failure"
26397
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26398
+ //
26399
+ // The delivery-state read tests it — a capture's state depends on whether a
26400
+ // live forward marked it owed — so carrying it here makes that read covering
26401
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26402
+ // But a sixth column changes what the planner charges for this index, and
26403
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26404
+ // then stops choosing the per-session index for the token rollup and walks
26405
+ // every `llm_call` in the store through the event-type index instead. That
26406
+ // read grows with the store; this one does not.
26407
+ //
26408
+ // 40 ms on the largest store measured, once per render, is a cost worth
26409
+ // paying to leave every other read's plan where it was.
26410
+ ];
26411
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26412
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26413
+ if (!syncIndexMatches) {
26414
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26415
+ db.exec(
26416
+ `CREATE INDEX idx_audit_events_sync
26417
+ ON audit_events (${syncIndexColumns.join(", ")})`
26418
+ );
26419
+ }
25394
26420
  db.exec(
25395
26421
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25396
26422
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25612,7 +26638,11 @@ function buildAuditEvent(row) {
25612
26638
  link: linkParsed?.success ? linkParsed.data : null,
25613
26639
  targetId: row.target_id,
25614
26640
  internal: intToBool(row.internal),
25615
- flagged: intToBool(row.flagged)
26641
+ flagged: intToBool(row.flagged),
26642
+ // Only meaningful when the title came out empty — a row whose body was
26643
+ // expired but whose title fell back to `tool_name` still has something to
26644
+ // render, and flagging it would make the view apologise for nothing.
26645
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25616
26646
  };
25617
26647
  }
25618
26648
  var TIMELINE_COLUMNS = `
@@ -25620,6 +26650,7 @@ var TIMELINE_COLUMNS = `
25620
26650
  event_type,
25621
26651
  started_at,
25622
26652
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26653
+ content_expired_at,
25623
26654
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25624
26655
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25625
26656
  json_extract(attributes, '$.severity') AS severity,
@@ -26285,6 +27316,88 @@ var SqliteAuditEventsRepository = class {
26285
27316
  }
26286
27317
  };
26287
27318
 
27319
+ // ../../packages/persistence/src/repositories/body-retention.ts
27320
+ var DEFAULT_BATCH_SIZE = 500;
27321
+ var DEFAULT_MAX_ROWS = 5e4;
27322
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27323
+ var SqliteBodyRetentionRepository = class {
27324
+ constructor(db) {
27325
+ this.db = db;
27326
+ const select = (laneClause) => `
27327
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27328
+ FROM audit_events
27329
+ WHERE content IS NOT NULL
27330
+ AND started_at < :cutoff
27331
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27332
+ ${laneClause}
27333
+ ORDER BY started_at
27334
+ LIMIT :limit`;
27335
+ this.candidatesStmt = this.db.prepare(select(""));
27336
+ this.candidatesSyncSafeStmt = this.db.prepare(
27337
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27338
+ );
27339
+ this.heldBySyncStmt = this.db.prepare(`
27340
+ SELECT COUNT(*) AS n
27341
+ FROM audit_events
27342
+ WHERE content IS NOT NULL
27343
+ AND started_at < :cutoff
27344
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27345
+ AND synced_at IS NULL`);
27346
+ this.expireStmt = this.db.prepare(
27347
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27348
+ );
27349
+ }
27350
+ db;
27351
+ candidatesStmt;
27352
+ candidatesSyncSafeStmt;
27353
+ heldBySyncStmt;
27354
+ expireStmt;
27355
+ /** How many bytes a pass with these options would free, changing nothing. */
27356
+ preview(opts) {
27357
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27358
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27359
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27360
+ return {
27361
+ rowsExpired: rows.length,
27362
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27363
+ rowsHeldBySync: this.countHeldBySync(opts)
27364
+ };
27365
+ }
27366
+ /** Clear eligible bodies, in bounded batches. */
27367
+ expire(opts) {
27368
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27369
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27370
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27371
+ let rowsExpired = 0;
27372
+ let bytesFreed = 0;
27373
+ let done = true;
27374
+ while (rowsExpired < maxRows) {
27375
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27376
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27377
+ if (batch.length === 0) break;
27378
+ withTransaction(
27379
+ this.db,
27380
+ () => {
27381
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27382
+ },
27383
+ "IMMEDIATE"
27384
+ );
27385
+ rowsExpired += batch.length;
27386
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27387
+ if (batch.length < remaining) break;
27388
+ if (rowsExpired >= maxRows) {
27389
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27390
+ }
27391
+ }
27392
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27393
+ }
27394
+ countHeldBySync(opts) {
27395
+ if (opts.sweepSyncLane) return 0;
27396
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27397
+ return row.n;
27398
+ }
27399
+ };
27400
+
26288
27401
  // ../../packages/persistence/src/repositories/classified-data.ts
26289
27402
  var SqliteClassifiedDataRepository = class {
26290
27403
  constructor(db) {
@@ -27113,7 +28226,15 @@ function toFlatFindingRow(r) {
27113
28226
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
27114
28227
  eventId: r.event_id,
27115
28228
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27116
- status: deriveInstanceStatus(r)
28229
+ status: deriveInstanceStatus(r),
28230
+ delivery: deriveFindingDelivery({
28231
+ kind: r.kind,
28232
+ syncedAt: r.synced_at,
28233
+ syncClaimedAt: r.sync_claimed_at,
28234
+ syncFailedAt: r.sync_failed_at,
28235
+ syncFailure: r.sync_failure,
28236
+ outboxOwed: r.outbox_owed
28237
+ })
27117
28238
  };
27118
28239
  }
27119
28240
  function encodeGroupCursor(group) {
@@ -27177,7 +28298,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27177
28298
  e.tool_name AS tool_name,
27178
28299
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27179
28300
  e.event_type AS kind, f.finding_key AS finding_key,
27180
- ${latestResolutionStatusSql("f")} AS latest_status`;
28301
+ ${latestResolutionStatusSql("f")} AS latest_status,
28302
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28303
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28304
+ e.outbox_owed AS outbox_owed`;
27181
28305
  var DAY_MS3 = 864e5;
27182
28306
  var SqliteFindingsRepository = class {
27183
28307
  constructor(db) {
@@ -27422,6 +28546,7 @@ var SqliteFindingsRepository = class {
27422
28546
  providers: query.provider,
27423
28547
  actions: query.action,
27424
28548
  statuses: query.status,
28549
+ deliveries: query.deployment,
27425
28550
  tools: query.tool,
27426
28551
  repo: query.repo,
27427
28552
  file: query.file,
@@ -27489,6 +28614,7 @@ var SqliteFindingsRepository = class {
27489
28614
  providers: query.provider,
27490
28615
  actions: query.action,
27491
28616
  statuses: query.status,
28617
+ deliveries: query.deployment,
27492
28618
  tools: query.tool,
27493
28619
  q: query.q
27494
28620
  };
@@ -27752,7 +28878,9 @@ var SqliteFindingsRepository = class {
27752
28878
  )
27753
28879
  );
27754
28880
  for (const row of grouped) {
27755
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28881
+ if (Object.hasOwn(byAction, row.action_taken)) {
28882
+ byAction[row.action_taken] = row.c;
28883
+ }
27756
28884
  }
27757
28885
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27758
28886
  const sevRows = allRows(
@@ -27769,7 +28897,9 @@ var SqliteFindingsRepository = class {
27769
28897
  )
27770
28898
  );
27771
28899
  for (const row of sevRows) {
27772
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28900
+ if (Object.hasOwn(bySeverity, row.severity)) {
28901
+ bySeverity[row.severity] = row.c;
28902
+ }
27773
28903
  }
27774
28904
  const categories = ENFORCEABLE_CATEGORIES;
27775
28905
  const enabledRows = allRows(
@@ -27818,525 +28948,6 @@ function isoDay(ms) {
27818
28948
  return new Date(ms).toISOString().slice(0, 10);
27819
28949
  }
27820
28950
 
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
28951
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28341
28952
  var SqliteInspectionDefinitionsRepository = class {
28342
28953
  constructor(db) {
@@ -28564,6 +29175,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28564
29175
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28565
29176
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28566
29177
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29178
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28567
29179
  if (values.vaultConsent !== void 0) {
28568
29180
  merged.vaultConsent = values.vaultConsent ? (
28569
29181
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -31071,7 +31683,7 @@ var SqliteSecurityRepository = class {
31071
31683
  ELSE 0
31072
31684
  END) AS open_at_rest
31073
31685
  FROM inspection_findings f
31074
- JOIN audit_events e ON e.id = f.audit_event_id
31686
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31075
31687
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31076
31688
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31077
31689
  ON latest.finding_key = f.finding_key
@@ -31297,7 +31909,7 @@ var SqliteSecurityRepository = class {
31297
31909
  this.db.prepare(
31298
31910
  `SELECT e.repo AS repo, count(*) AS c
31299
31911
  FROM inspection_findings f
31300
- JOIN audit_events e ON e.id = f.audit_event_id
31912
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31301
31913
  WHERE e.started_at >= :from AND e.started_at < :to
31302
31914
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31303
31915
  AND e.repo IS NOT NULL
@@ -31421,7 +32033,7 @@ var SqliteSecurityRepository = class {
31421
32033
  d.severity AS severity,
31422
32034
  COUNT(*) AS count
31423
32035
  FROM inspection_findings f
31424
- JOIN audit_events e ON e.id = f.audit_event_id
32036
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31425
32037
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31426
32038
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31427
32039
  ON latest.finding_key = f.finding_key
@@ -31456,7 +32068,7 @@ var SqliteSecurityRepository = class {
31456
32068
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31457
32069
  d.rule_id AS rule_id, d.category AS category
31458
32070
  FROM inspection_findings f
31459
- JOIN audit_events e ON e.id = f.audit_event_id
32071
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31460
32072
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31461
32073
  WHERE e.started_at >= :from AND e.started_at < :to
31462
32074
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32297,6 +32909,7 @@ function openWithPragmas(file2) {
32297
32909
  db.exec("PRAGMA journal_mode = WAL");
32298
32910
  db.exec("PRAGMA busy_timeout = 2000");
32299
32911
  db.exec("PRAGMA foreign_keys = ON");
32912
+ registerSqlFunctions(db);
32300
32913
  } catch (err) {
32301
32914
  closeQuietly(db);
32302
32915
  throw err;
@@ -32326,7 +32939,7 @@ function backupLegacyStore(db, file2) {
32326
32939
  discardStore(file2, backup);
32327
32940
  return backup;
32328
32941
  }
32329
- function openAndInitialize(file2, base) {
32942
+ function openAndInitialize(file2, base, skipTags) {
32330
32943
  let db = openWithPragmas(file2);
32331
32944
  try {
32332
32945
  if (isForeignSqliteLineage(db)) {
@@ -32336,7 +32949,7 @@ function openAndInitialize(file2, base) {
32336
32949
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32337
32950
  );
32338
32951
  }
32339
- applyMigrations(db, file2);
32952
+ applyMigrations(db, file2, { skipTags });
32340
32953
  tightenPerms(file2);
32341
32954
  const policies = new SqlitePoliciesRepository(db);
32342
32955
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32351,6 +32964,7 @@ function openAndInitialize(file2, base) {
32351
32964
  exceptions: new SqliteExceptionsRepository(db),
32352
32965
  resolutions: new SqliteResolutionsRepository(db),
32353
32966
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32967
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32354
32968
  security: new SqliteSecurityRepository(db),
32355
32969
  detections: new SqliteDetectionsRepository(db),
32356
32970
  shares: new SqliteSharesRepository(db),
@@ -32373,7 +32987,8 @@ function openAndInitialize(file2, base) {
32373
32987
  throw err;
32374
32988
  }
32375
32989
  }
32376
- function openLocalDatabase(dir) {
32990
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32991
+ function openLocalDatabase(dir, options = {}) {
32377
32992
  ensureDataDirSync(dir);
32378
32993
  const file2 = join7(dir, DB_FILENAME);
32379
32994
  reapStalePartials(file2);
@@ -32385,6 +33000,7 @@ function openLocalDatabase(dir) {
32385
33000
  installedPacks,
32386
33001
  scanLedger,
32387
33002
  historySync,
33003
+ bodyRetention,
32388
33004
  secretVault,
32389
33005
  exceptions,
32390
33006
  resolutions,
@@ -32408,7 +33024,8 @@ function openLocalDatabase(dir) {
32408
33024
  // `dir` is always `<base>/data` — every caller resolves it through
32409
33025
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32410
33026
  // settings/ and data/, and the pack-policy floor needs both halves.
32411
- dirname2(dir)
33027
+ dirname2(dir),
33028
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32412
33029
  );
32413
33030
  function captureRowId(event) {
32414
33031
  return captureId(
@@ -32601,6 +33218,7 @@ function openLocalDatabase(dir) {
32601
33218
  installedPacks,
32602
33219
  scanLedger,
32603
33220
  historySync,
33221
+ bodyRetention,
32604
33222
  secretVault,
32605
33223
  exceptions,
32606
33224
  resolutions,
@@ -32641,8 +33259,35 @@ function openLocalDatabase(dir) {
32641
33259
 
32642
33260
  // ../../packages/persistence/src/egress-wire.ts
32643
33261
  import { createHash as createHash3 } from "crypto";
33262
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33263
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33264
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33265
+ var FILE_URL = /^file:\/\//i;
33266
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33267
+ var SLASH = "/".charCodeAt(0);
33268
+ var GIT_SUFFIX = ".git";
33269
+ function trimSlashes(path) {
33270
+ let start = 0;
33271
+ let end = path.length;
33272
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33273
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33274
+ return path.slice(start, end);
33275
+ }
33276
+ function canonicalGitUrl(url2) {
33277
+ const trimmed = url2.trim();
33278
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33279
+ const scheme = SCHEME_FORM.exec(trimmed);
33280
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33281
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33282
+ if (host === void 0) return trimmed;
33283
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33284
+ const bare = trimSlashes(path);
33285
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33286
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33287
+ }
32644
33288
  function hashProjectKey(projectKey) {
32645
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33289
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33290
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32646
33291
  }
32647
33292
  function toIngestHit(hit) {
32648
33293
  return {
@@ -32809,18 +33454,50 @@ function fingerprintValue(key, raw) {
32809
33454
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32810
33455
  }
32811
33456
 
33457
+ // ../../packages/persistence/src/forward-health.ts
33458
+ import { readFileSync as readFileSync7 } from "fs";
33459
+ import { join as join9 } from "path";
33460
+ var FAILURES = /* @__PURE__ */ new Set([
33461
+ "unauthorized",
33462
+ "forbidden",
33463
+ "unreachable"
33464
+ ]);
33465
+ var BREAKER_COOLDOWN_MS = 3e4;
33466
+ function parseForwardHealth(raw, nowMs) {
33467
+ try {
33468
+ const parsed2 = JSON.parse(raw);
33469
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33470
+ const record2 = parsed2;
33471
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33472
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33473
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33474
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33475
+ } catch {
33476
+ return null;
33477
+ }
33478
+ }
33479
+ function isForwardPaused(health, nowMs) {
33480
+ const openedAtMs = health?.openedAtMs ?? null;
33481
+ if (openedAtMs === null) return false;
33482
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33483
+ }
33484
+
32812
33485
  // ../../packages/persistence/src/history-backfill.ts
32813
33486
  import { existsSync as existsSync4 } from "fs";
32814
- import { join as join9 } from "path";
33487
+ import { join as join10 } from "path";
32815
33488
 
32816
33489
  // ../../packages/persistence/src/history-preview.ts
32817
33490
  import { existsSync as existsSync5 } from "fs";
32818
- import { join as join10 } from "path";
33491
+ import { join as join11 } from "path";
32819
33492
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32820
33493
 
33494
+ // ../../packages/persistence/src/history-sync-state.ts
33495
+ import { readFileSync as readFileSync8 } from "fs";
33496
+ import { join as join12 } from "path";
33497
+
32821
33498
  // ../../packages/persistence/src/store-symlinks.ts
32822
33499
  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";
33500
+ import { dirname as dirname3, join as join13, resolve } from "path";
32824
33501
 
32825
33502
  // ../../packages/persistence/src/vault/crypto.ts
32826
33503
  import {
@@ -32834,19 +33511,19 @@ import {
32834
33511
  // ../../packages/persistence/src/vault/key-provider.ts
32835
33512
  import { execFileSync } from "child_process";
32836
33513
  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";
33514
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33515
+ import { join as join14 } from "path";
32839
33516
 
32840
33517
  // ../../packages/persistence/src/vault/vault.ts
32841
33518
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32842
33519
 
32843
33520
  // ../../packages/persistence/src/warn-era-cap.ts
32844
33521
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32845
- import { join as join13 } from "path";
33522
+ import { join as join15 } from "path";
32846
33523
  var MARKER = "warn-era-capped";
32847
33524
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32848
33525
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32849
- const marker = join13(dataDir2, MARKER);
33526
+ const marker = join15(dataDir2, MARKER);
32850
33527
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32851
33528
  const capped = db.policies.capCategoryActions();
32852
33529
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -33037,10 +33714,10 @@ function parsed(schema, body, route) {
33037
33714
  }
33038
33715
  function withoutTrailingSlashes(endpoint) {
33039
33716
  let end = endpoint.length;
33040
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33717
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
33041
33718
  return endpoint.slice(0, end);
33042
33719
  }
33043
- var SLASH = "/".charCodeAt(0);
33720
+ var SLASH2 = "/".charCodeAt(0);
33044
33721
  function createRemoteClient(options) {
33045
33722
  const base = withoutTrailingSlashes(options.endpoint);
33046
33723
  const url2 = (route) => `${base}${route}`;
@@ -33222,11 +33899,11 @@ function withTimeout(promise2, ms) {
33222
33899
  }
33223
33900
 
33224
33901
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
33225
- import { readFileSync as readFileSync8 } from "fs";
33226
- import { join as join14 } from "path";
33902
+ import { readFileSync as readFileSync10 } from "fs";
33903
+ import { join as join16 } from "path";
33227
33904
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
33228
33905
  function forwardDropsPath(dataDir2) {
33229
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
33906
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
33230
33907
  }
33231
33908
  function recordForwardDrops(dataDir2, count, nowMs) {
33232
33909
  if (count <= 0) return;
@@ -33244,7 +33921,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
33244
33921
  }
33245
33922
  function readForwardDrops(dataDir2) {
33246
33923
  try {
33247
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33924
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
33248
33925
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
33249
33926
  const record2 = parsed2;
33250
33927
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -33262,13 +33939,12 @@ function readForwardDrops(dataDir2) {
33262
33939
 
33263
33940
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33264
33941
  import { randomUUID as randomUUID15 } from "crypto";
33265
- import { readFileSync as readFileSync15 } from "fs";
33266
33942
  import { readFile, rename, writeFile } from "fs/promises";
33267
- import { join as join24 } from "path";
33943
+ import { join as join26 } from "path";
33268
33944
 
33269
33945
  // ../../packages/plugin-sdk/src/config.ts
33270
33946
  import { existsSync as existsSync8 } from "fs";
33271
- import { join as join15 } from "path";
33947
+ import { join as join17 } from "path";
33272
33948
 
33273
33949
  // ../../packages/plugin-sdk/src/provider-env.ts
33274
33950
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33322,7 +33998,7 @@ function resolveProvider() {
33322
33998
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33323
33999
  try {
33324
34000
  ensureLayoutDirSync(base);
33325
- const settingsFile = join15(settingsDir(base), "settings.json");
34001
+ const settingsFile = join17(settingsDir(base), "settings.json");
33326
34002
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33327
34003
  } catch {
33328
34004
  }
@@ -33346,9 +34022,9 @@ function resolveProviderSafe(resolveProviderFn) {
33346
34022
  }
33347
34023
 
33348
34024
  // ../../packages/plugin-sdk/src/config-inventory.ts
33349
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34025
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33350
34026
  import { homedir as homedir2 } from "os";
33351
- import { basename as basename4, join as join17 } from "path";
34027
+ import { basename as basename4, join as join19 } from "path";
33352
34028
 
33353
34029
  // ../../packages/detections/src/egress/registry.ts
33354
34030
  var EXTRACTOR_VERSION = "1";
@@ -36564,8 +37240,8 @@ function maskText(text) {
36564
37240
  }
36565
37241
 
36566
37242
  // ../../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";
37243
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37244
+ import { basename as basename3, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36569
37245
  function resolveRepoIdentity(cwd) {
36570
37246
  try {
36571
37247
  const root = findGitRoot(cwd);
@@ -36615,7 +37291,7 @@ function resolveGitBranch(cwd) {
36615
37291
  try {
36616
37292
  const root = findGitRoot(cwd);
36617
37293
  if (!root) return void 0;
36618
- const dotGit = join16(root, ".git");
37294
+ const dotGit = join18(root, ".git");
36619
37295
  let gitdir;
36620
37296
  try {
36621
37297
  gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
@@ -36623,7 +37299,7 @@ function resolveGitBranch(cwd) {
36623
37299
  return void 0;
36624
37300
  }
36625
37301
  if (gitdir === void 0) return void 0;
36626
- const head = safeRead(join16(gitdir, "HEAD"));
37302
+ const head = safeRead(join18(gitdir, "HEAD"));
36627
37303
  if (!head) return void 0;
36628
37304
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
36629
37305
  } catch {
@@ -36633,41 +37309,41 @@ function resolveGitBranch(cwd) {
36633
37309
  function resolveWorktreeGitdir(root, dotGitFile) {
36634
37310
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
36635
37311
  if (!target) return void 0;
36636
- return isAbsolute(target) ? target : join16(root, target);
37312
+ return isAbsolute(target) ? target : join18(root, target);
36637
37313
  }
36638
37314
  function findGitRoot(start) {
36639
37315
  let dir = start;
36640
37316
  for (; ; ) {
36641
- if (existsSync9(join16(dir, ".git"))) return dir;
37317
+ if (existsSync9(join18(dir, ".git"))) return dir;
36642
37318
  const parent = dirname4(dir);
36643
37319
  if (parent === dir) return void 0;
36644
37320
  dir = parent;
36645
37321
  }
36646
37322
  }
36647
37323
  function resolveGitContext(root) {
36648
- const dotGit = join16(root, ".git");
37324
+ const dotGit = join18(root, ".git");
36649
37325
  try {
36650
37326
  if (statSync6(dotGit).isDirectory()) {
36651
- return { configPath: join16(dotGit, "config"), headRoot: root };
37327
+ return { configPath: join18(dotGit, "config"), headRoot: root };
36652
37328
  }
36653
37329
  } catch {
36654
37330
  return void 0;
36655
37331
  }
36656
37332
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36657
37333
  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 };
37334
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
37335
+ if (existsSync9(join18(gitdir, "config"))) {
37336
+ return { configPath: join18(gitdir, "config"), headRoot: root };
36661
37337
  }
36662
- const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
37338
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
36663
37339
  if (!commonRaw) return void 0;
36664
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
37340
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
36665
37341
  const headRoot = basename3(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36666
- return { configPath: join16(commonGitDir, "config"), headRoot };
37342
+ return { configPath: join18(commonGitDir, "config"), headRoot };
36667
37343
  }
36668
37344
  function safeRead(path) {
36669
37345
  try {
36670
- return readFileSync9(path, "utf8");
37346
+ return readFileSync11(path, "utf8");
36671
37347
  } catch {
36672
37348
  return void 0;
36673
37349
  }
@@ -36729,31 +37405,31 @@ function resolveConfigInventory(input2) {
36729
37405
  };
36730
37406
  try {
36731
37407
  const home = input2.homeDir ?? homedir2();
36732
- const claudeDir = join17(home, ".claude");
37408
+ const claudeDir = join19(home, ".claude");
36733
37409
  const repo = resolveRepoIdentity(input2.cwd);
36734
37410
  const repoIdentity = repo?.url ?? input2.cwd;
36735
37411
  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");
37412
+ collectSettingsHooks(scan2, join19(claudeDir, "settings.json"), "user");
37413
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.json"), "project");
37414
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.local.json"), "local");
36739
37415
  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"), {
37416
+ collectMcpFile(scan2, join19(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
37417
+ collectUserClaudeJson(scan2, join19(home, ".claude.json"), input2.cwd, repoIdentity);
37418
+ collectMcpFile(scan2, join19(claudeDir, "settings.json"), { scope: "user" });
37419
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.json"), projectOrigin);
37420
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.local.json"), {
36745
37421
  scope: "local",
36746
37422
  project: repoIdentity
36747
37423
  });
36748
37424
  collectConfigFiles(scan2, claudeDir, input2.cwd);
36749
- collectSkillsDir(scan2, join17(claudeDir, "skills"), { source: "local", scope: "user" });
36750
- collectSkillsDir(scan2, join17(input2.cwd, ".claude", "skills"), {
37425
+ collectSkillsDir(scan2, join19(claudeDir, "skills"), { source: "local", scope: "user" });
37426
+ collectSkillsDir(scan2, join19(input2.cwd, ".claude", "skills"), {
36751
37427
  source: projectSource,
36752
37428
  scope: "project"
36753
37429
  });
36754
37430
  collectInstalledPlugins(scan2, claudeDir);
36755
37431
  collectMarketplaceSkills(scan2, claudeDir);
36756
- collectSkillsDir(scan2, join17(input2.cwd, "skills"), { source: projectSource, scope: "project" });
37432
+ collectSkillsDir(scan2, join19(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36757
37433
  scan2.skills = dedupeSkills(scan2.skills);
36758
37434
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
36759
37435
  } catch (err) {
@@ -36882,7 +37558,7 @@ function projectEntryFor(projects, cwd) {
36882
37558
  return void 0;
36883
37559
  }
36884
37560
  function collectPluginManifestMcp(scan2, installPath, origin) {
36885
- const manifestPath = join17(installPath, ".claude-plugin", "plugin.json");
37561
+ const manifestPath = join19(installPath, ".claude-plugin", "plugin.json");
36886
37562
  const raw = readOptional(manifestPath);
36887
37563
  if (raw === void 0) return;
36888
37564
  try {
@@ -36890,7 +37566,7 @@ function collectPluginManifestMcp(scan2, installPath, origin) {
36890
37566
  if (typeof parsed2 !== "object" || parsed2 === null) return;
36891
37567
  const declared = parsed2.mcpServers;
36892
37568
  if (typeof declared === "string" && declared.length > 0) {
36893
- collectMcpFile(scan2, join17(installPath, declared), origin, { recordErrors: true });
37569
+ collectMcpFile(scan2, join19(installPath, declared), origin, { recordErrors: true });
36894
37570
  } else {
36895
37571
  collectMcpObject(scan2, declared, manifestPath, origin);
36896
37572
  }
@@ -36907,14 +37583,14 @@ var SETTINGS_KEY_LABELS = [
36907
37583
  ["statusLine", "status line"]
36908
37584
  ];
36909
37585
  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");
37586
+ settingsConfigFile(scan2, join19(claudeDir, "settings.json"), "user", "User settings");
37587
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.json"), "project", "Project settings");
37588
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
37589
+ memoryConfigFile(scan2, join19(claudeDir, "CLAUDE.md"), "user", "User memory");
37590
+ memoryConfigFile(scan2, join19(cwd, "CLAUDE.md"), "project", "Project memory");
37591
+ mcpJsonConfigFile(scan2, join19(cwd, ".mcp.json"));
37592
+ dirConfigFile(scan2, join19(cwd, ".claude", "commands"), "Slash commands", "command");
37593
+ dirConfigFile(scan2, join19(cwd, ".claude", "agents"), "Subagents", "subagent");
36918
37594
  }
36919
37595
  function configFileEntry(path, scope, kind) {
36920
37596
  try {
@@ -36989,7 +37665,7 @@ function countMarkdownFiles(dir, depth) {
36989
37665
  let count = 0;
36990
37666
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
36991
37667
  if (dirent.name.startsWith(".")) continue;
36992
- if (dirent.isDirectory()) count += countMarkdownFiles(join17(dir, dirent.name), depth + 1);
37668
+ if (dirent.isDirectory()) count += countMarkdownFiles(join19(dir, dirent.name), depth + 1);
36993
37669
  else if (dirent.name.endsWith(".md")) count += 1;
36994
37670
  }
36995
37671
  return count;
@@ -37002,7 +37678,7 @@ function collectSkillsDir(scan2, dir, origin) {
37002
37678
  return;
37003
37679
  }
37004
37680
  for (const name2 of names) {
37005
- const skillFile = join17(dir, name2, "SKILL.md");
37681
+ const skillFile = join19(dir, name2, "SKILL.md");
37006
37682
  try {
37007
37683
  const raw = readOptional(skillFile);
37008
37684
  if (raw === void 0) continue;
@@ -37011,7 +37687,7 @@ function collectSkillsDir(scan2, dir, origin) {
37011
37687
  name: front.name ?? name2,
37012
37688
  source: origin.source,
37013
37689
  scope: origin.scope,
37014
- location: join17(dir, name2),
37690
+ location: join19(dir, name2),
37015
37691
  updatedAt: statSync7(skillFile).mtime.toISOString()
37016
37692
  };
37017
37693
  const version3 = front.version ?? origin.defaultVersion;
@@ -37042,7 +37718,7 @@ function parseFrontmatter(raw) {
37042
37718
  return out;
37043
37719
  }
37044
37720
  function collectInstalledPlugins(scan2, claudeDir) {
37045
- const manifestPath = join17(claudeDir, "plugins", "installed_plugins.json");
37721
+ const manifestPath = join19(claudeDir, "plugins", "installed_plugins.json");
37046
37722
  const raw = readOptional(manifestPath);
37047
37723
  if (raw === void 0) return;
37048
37724
  let plugins;
@@ -37067,7 +37743,7 @@ function collectInstalledPlugins(scan2, claudeDir) {
37067
37743
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
37068
37744
  seen.add(installPath);
37069
37745
  const version3 = install.version;
37070
- const hooksPath = join17(installPath, "hooks", "hooks.json");
37746
+ const hooksPath = join19(installPath, "hooks", "hooks.json");
37071
37747
  const hooksRaw = readOptional(hooksPath);
37072
37748
  if (hooksRaw !== void 0) {
37073
37749
  try {
@@ -37087,22 +37763,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
37087
37763
  }
37088
37764
  const origin = { source: marketplace, scope: "plugin", pluginName };
37089
37765
  if (typeof version3 === "string") origin.defaultVersion = version3;
37090
- collectSkillsDir(scan2, join17(installPath, "skills"), origin);
37766
+ collectSkillsDir(scan2, join19(installPath, "skills"), origin);
37091
37767
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
37092
- collectMcpFile(scan2, join17(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
37768
+ collectMcpFile(scan2, join19(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
37093
37769
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
37094
37770
  }
37095
37771
  }
37096
37772
  }
37097
37773
  function collectMarketplaceSkills(scan2, claudeDir) {
37098
- for (const mp of readMarketplaces(join17(claudeDir, "plugins", "known_marketplaces.json"))) {
37774
+ for (const mp of readMarketplaces(join19(claudeDir, "plugins", "known_marketplaces.json"))) {
37099
37775
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
37100
- collectSkillsDir(scan2, join17(mp.installLocation, "skills"), {
37776
+ collectSkillsDir(scan2, join19(mp.installLocation, "skills"), {
37101
37777
  source: mp.name,
37102
37778
  scope: "plugin"
37103
37779
  });
37104
- collectPluginSkillDirs(scan2, join17(mp.installLocation, "plugins"), mp.name);
37105
- collectPluginSkillDirs(scan2, join17(mp.installLocation, "external_plugins"), mp.name);
37780
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "plugins"), mp.name);
37781
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "external_plugins"), mp.name);
37106
37782
  }
37107
37783
  }
37108
37784
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -37113,7 +37789,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
37113
37789
  return;
37114
37790
  }
37115
37791
  for (const plugin of plugins) {
37116
- collectSkillsDir(scan2, join17(pluginsDir, plugin, "skills"), {
37792
+ collectSkillsDir(scan2, join19(pluginsDir, plugin, "skills"), {
37117
37793
  source: marketplace,
37118
37794
  scope: "plugin",
37119
37795
  pluginName: plugin
@@ -37167,7 +37843,7 @@ function dedupeMcpServers(servers) {
37167
37843
  }
37168
37844
  function readOptional(path) {
37169
37845
  try {
37170
- return readFileSync10(path, "utf8");
37846
+ return readFileSync12(path, "utf8");
37171
37847
  } catch {
37172
37848
  return void 0;
37173
37849
  }
@@ -37698,8 +38374,8 @@ function createGuardedScanner(partition, gateway, opts) {
37698
38374
  }
37699
38375
 
37700
38376
  // ../../packages/plugin-sdk/src/host-floor.ts
37701
- import { readFileSync as readFileSync12 } from "fs";
37702
- import { join as join19 } from "path";
38377
+ import { readFileSync as readFileSync14 } from "fs";
38378
+ import { join as join21 } from "path";
37703
38379
 
37704
38380
  // ../../packages/plugin-sdk/src/model-governance.ts
37705
38381
  import {
@@ -37707,11 +38383,11 @@ import {
37707
38383
  fstatSync,
37708
38384
  mkdirSync as mkdirSync2,
37709
38385
  openSync as openSync2,
37710
- readFileSync as readFileSync11,
38386
+ readFileSync as readFileSync13,
37711
38387
  readSync,
37712
38388
  writeFileSync as writeFileSync5
37713
38389
  } from "fs";
37714
- import { join as join18 } from "path";
38390
+ import { join as join20 } from "path";
37715
38391
  var TAIL_BYTES = 256 * 1024;
37716
38392
 
37717
38393
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -37734,11 +38410,11 @@ var HOST_FLOORS = {
37734
38410
 
37735
38411
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37736
38412
  var import_ignore = __toESM(require_ignore(), 1);
37737
- import { readFileSync as readFileSync13 } from "fs";
37738
- import { join as join20 } from "path";
38413
+ import { readFileSync as readFileSync15 } from "fs";
38414
+ import { join as join22 } from "path";
37739
38415
  function readIgnoreLayer(dir, filename, anchorLen) {
37740
38416
  try {
37741
- return { matcher: (0, import_ignore.default)().add(readFileSync13(join20(dir, filename), "utf8")), anchorLen };
38417
+ return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
37742
38418
  } catch {
37743
38419
  return void 0;
37744
38420
  }
@@ -37795,17 +38471,17 @@ function resolveInventoryContext(input2) {
37795
38471
  }
37796
38472
 
37797
38473
  // ../../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";
38474
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
38475
+ import { join as join23 } from "path";
37800
38476
  var SESSION_START_MARKER = "session-start-last";
37801
38477
  function claimSessionStart(dataDir2, sessionId) {
37802
38478
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
37803
38479
  }
37804
38480
  function claimOncePerSession(dataDir2, marker, sessionId) {
37805
38481
  if (!sessionId) return true;
37806
- const path = join21(dataDir2, marker);
38482
+ const path = join23(dataDir2, marker);
37807
38483
  try {
37808
- if (readFileSync14(path, "utf8") === sessionId) return false;
38484
+ if (readFileSync16(path, "utf8") === sessionId) return false;
37809
38485
  } catch {
37810
38486
  }
37811
38487
  try {
@@ -37857,7 +38533,7 @@ function createPolicyResolver(bundle) {
37857
38533
 
37858
38534
  // ../../packages/plugin-sdk/src/project-files.ts
37859
38535
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37860
- import { basename as basename6, join as join22 } from "path";
38536
+ import { basename as basename6, join as join24 } from "path";
37861
38537
  var SKIP_DIRS = /* @__PURE__ */ new Set([
37862
38538
  ".git",
37863
38539
  "node_modules",
@@ -37954,8 +38630,8 @@ function resolveProjectFiles(cwd, opts = {}) {
37954
38630
  }
37955
38631
  if (entry.isDirectory()) {
37956
38632
  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;
38633
+ const fullPath = join24(dir, entry.name);
38634
+ if (existsSync11(join24(fullPath, ".git"))) continue;
37959
38635
  if (depth >= bounds.maxDepth) {
37960
38636
  walk.omitted = true;
37961
38637
  continue;
@@ -38067,7 +38743,7 @@ function createPluginRuntime(gateway, settings, opts) {
38067
38743
  bundlesPacked = true;
38068
38744
  }
38069
38745
  const policyMode = settings.policy;
38070
- const redactFallback = settings.redactFallback;
38746
+ let redactFallback = settings.redactFallback;
38071
38747
  const dataDir2 = opts?.dataDir;
38072
38748
  let rules = [];
38073
38749
  let scanner;
@@ -38111,6 +38787,7 @@ function createPluginRuntime(gateway, settings, opts) {
38111
38787
  rules = [...verified, ...unverified];
38112
38788
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
38113
38789
  bundleExceptions = bundle.exceptions ?? [];
38790
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
38114
38791
  initialized = true;
38115
38792
  }
38116
38793
  let cachedKey;
@@ -38149,11 +38826,13 @@ function createPluginRuntime(gateway, settings, opts) {
38149
38826
  function decide(findings, text, excepted, rewritable = true) {
38150
38827
  if (findings.length === 0) return { action: "log", text, findings: [] };
38151
38828
  const actionFor = (finding2) => actionForFinding(finding2, excepted, rewritable);
38829
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38830
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
38152
38831
  let worst = "log";
38153
38832
  for (const finding2 of findings) {
38154
38833
  worst = strongerAction(worst, actionFor(finding2));
38155
38834
  }
38156
- if (worst === "block") return { action: "block", text: null, findings };
38835
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
38157
38836
  if (worst === "redact") {
38158
38837
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
38159
38838
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -38163,9 +38842,13 @@ function createPluginRuntime(gateway, settings, opts) {
38163
38842
  findings,
38164
38843
  enforcedFindings: redactFindings,
38165
38844
  reversibleFindings
38845
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38846
+ // CAPTURE, so on an unrewritable field every redact has already become
38847
+ // the fallback and this branch is unreachable. Spreading it would read
38848
+ // as a case that can happen.
38166
38849
  };
38167
38850
  }
38168
- return { action: worst, text, findings };
38851
+ return { action: worst, text, findings, ...degraded };
38169
38852
  }
38170
38853
  function fingerprintOf(key, finding2, cache) {
38171
38854
  let fp = cache.get(finding2);
@@ -38294,8 +38977,8 @@ function createPluginRuntime(gateway, settings, opts) {
38294
38977
  };
38295
38978
  }
38296
38979
  }
38297
- async function processText(text, context) {
38298
- return (await evaluate(text, context, {})).decision;
38980
+ async function processText(text, context, opts2 = {}) {
38981
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
38299
38982
  }
38300
38983
  async function capture(input2, opts2 = {}) {
38301
38984
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -38318,10 +39001,12 @@ function createPluginRuntime(gateway, settings, opts) {
38318
39001
  );
38319
39002
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
38320
39003
  const inspectionMs = elapsedMs(timingStartedAt);
38321
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
39004
+ const redactDegradedTo = decision.redactDegradedTo;
39005
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
38322
39006
  ...input2.metadata,
38323
39007
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
38324
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
39008
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
39009
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
38325
39010
  } : input2.metadata;
38326
39011
  const event = buildIngestEvent({
38327
39012
  kind: input2.kind,
@@ -38393,9 +39078,9 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38393
39078
 
38394
39079
  // ../../packages/plugin-sdk/src/throttle.ts
38395
39080
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38396
- import { join as join23 } from "path";
39081
+ import { join as join25 } from "path";
38397
39082
  function throttled(dataDir2, markerName, windowMs) {
38398
- const marker = join23(dataDir2, markerName);
39083
+ const marker = join25(dataDir2, markerName);
38399
39084
  try {
38400
39085
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
38401
39086
  } catch {
@@ -38422,31 +39107,12 @@ function isServerRejection(err) {
38422
39107
  var FORWARD_BUDGET_MS = 1500;
38423
39108
  var DECISION_PATH_BUDGET_MS = 800;
38424
39109
  var BREAKER_FAILURE_THRESHOLD = 3;
38425
- var BREAKER_COOLDOWN_MS = 3e4;
38426
39110
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
38427
- var FAILURES = /* @__PURE__ */ new Set([
38428
- "unauthorized",
38429
- "forbidden",
38430
- "unreachable"
38431
- ]);
38432
39111
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
38433
39112
  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
39113
  function createForwardPolicy(deps) {
38448
39114
  const now = deps.now ?? (() => Date.now());
38449
- const file2 = join24(deps.dir, STATE_FILENAME);
39115
+ const file2 = join26(deps.dir, STATE_FILENAME);
38450
39116
  let state = null;
38451
39117
  let loading = null;
38452
39118
  async function readState() {
@@ -38456,7 +39122,7 @@ function createForwardPolicy(deps) {
38456
39122
  } catch {
38457
39123
  return { ...CLOSED };
38458
39124
  }
38459
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39125
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
38460
39126
  }
38461
39127
  async function load() {
38462
39128
  if (state !== null) return state;
@@ -38502,7 +39168,7 @@ function createForwardPolicy(deps) {
38502
39168
  };
38503
39169
  const at = now();
38504
39170
  if (current.openedAtMs !== null) {
38505
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39171
+ if (isForwardPaused(current, at)) {
38506
39172
  return { ok: false, reason: "breaker-open" };
38507
39173
  }
38508
39174
  await persist({
@@ -39039,7 +39705,18 @@ var AttachedDataGateway = class {
39039
39705
  // and the spread above would otherwise drop the field silently — which is
39040
39706
  // exactly what it did, leaving the whole control inert on every device
39041
39707
  // while every test around it stayed green.
39042
- prohibitedModels: cached2.prohibitedModels
39708
+ prohibitedModels: cached2.prohibitedModels,
39709
+ // NAMED for the same reason as the line above, and it is the same defect
39710
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
39711
+ // only the cache carries is dropped in silence. That is what left
39712
+ // `prohibitedModels` inert on every attached device with every test
39713
+ // around it green.
39714
+ //
39715
+ // Taken from the cache rather than merged here, because merging it needs
39716
+ // the device's own SETTING — which is not a bundle field and is not in
39717
+ // scope at this seam. The runtime does that merge, raise-only, where both
39718
+ // values are in hand (createPluginRuntime's ensureInitialized).
39719
+ redactFallback: cached2.redactFallback
39043
39720
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39044
39721
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39045
39722
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39167,10 +39844,6 @@ function toolAuditEvent(input2) {
39167
39844
  };
39168
39845
  }
39169
39846
 
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
39847
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39175
39848
  import { createHash as createHash6 } from "crypto";
39176
39849
  import { hostname as hostname5 } from "os";
@@ -39179,6 +39852,10 @@ import { hostname as hostname5 } from "os";
39179
39852
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39180
39853
  var TRACE_ID = EventMetadata.shape.traceId;
39181
39854
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
39855
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
39856
+
39857
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
39858
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39182
39859
 
39183
39860
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39184
39861
  import { spawn } from "child_process";
@@ -39229,7 +39906,7 @@ function createPluginBlock(build, policyStore) {
39229
39906
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39230
39907
  import { randomUUID as randomUUID16 } from "crypto";
39231
39908
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39232
- import { join as join26 } from "path";
39909
+ import { join as join27 } from "path";
39233
39910
 
39234
39911
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39235
39912
  import { rename as rename2 } from "fs/promises";
@@ -39253,7 +39930,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39253
39930
 
39254
39931
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39255
39932
  function createPolicyStore(dir = dataDir()) {
39256
- const file2 = join26(dir, "policy-cache.json");
39933
+ const file2 = join27(dir, "policy-cache.json");
39257
39934
  async function read() {
39258
39935
  try {
39259
39936
  const raw = await readFile2(file2, "utf8");
@@ -39484,11 +40161,11 @@ function readStorePosture(dbPath2) {
39484
40161
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39485
40162
  import { randomUUID as randomUUID17 } from "crypto";
39486
40163
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39487
- import { join as join27 } from "path";
40164
+ import { join as join28 } from "path";
39488
40165
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39489
40166
  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");
40167
+ const file2 = join28(dir, "posture-state.json");
40168
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
39492
40169
  async function persist(state) {
39493
40170
  await ensureDataDir(dir);
39494
40171
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39557,7 +40234,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39557
40234
 
39558
40235
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39559
40236
  import { readFileSync as readFileSync18 } from "fs";
39560
- import { join as join28 } from "path";
40237
+ import { join as join29 } from "path";
39561
40238
 
39562
40239
  // ../../packages/plugin-runtime/src/attached/status.ts
39563
40240
  var REFUSAL_LINES = {
@@ -39599,6 +40276,34 @@ function spawnDetached2(scriptPath) {
39599
40276
  child.unref();
39600
40277
  }
39601
40278
 
40279
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40280
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40281
+
40282
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40283
+ import { spawn as spawn3 } from "child_process";
40284
+ import { fileURLToPath as fileURLToPath4 } from "url";
40285
+ var CONTENT_RETENTION_MARKER_NAME = "content-retention-last-attempt";
40286
+ var CONTENT_RETENTION_SCRIPT_NAME = "content-retention.js";
40287
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40288
+ function triggerContentRetention(config2, deps = {}) {
40289
+ try {
40290
+ if (!config2.settings.bodyRetention.enabled) return;
40291
+ const isThrottled = deps.isThrottled ?? ((dir) => throttled(dir, CONTENT_RETENTION_MARKER_NAME, CONTENT_RETENTION_THROTTLE_MS));
40292
+ if (isThrottled(config2.dataDir)) return;
40293
+ const scriptPath = fileURLToPath4(
40294
+ deps.scriptUrl ?? new URL(CONTENT_RETENTION_SCRIPT_NAME, import.meta.url)
40295
+ );
40296
+ (deps.spawnChild ?? spawnDetached3)(scriptPath);
40297
+ } catch {
40298
+ }
40299
+ }
40300
+ function spawnDetached3(scriptPath) {
40301
+ const child = spawn3(process.execPath, [scriptPath], { detached: true, stdio: "ignore" });
40302
+ child.on("error", () => {
40303
+ });
40304
+ child.unref();
40305
+ }
40306
+
39602
40307
  // ../../packages/plugin-runtime/src/attached/factory.ts
39603
40308
  import { hostname as hostname6 } from "os";
39604
40309
 
@@ -40048,13 +40753,13 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
40048
40753
  }
40049
40754
 
40050
40755
  // ../../packages/plugin-runtime/src/handle-capture.ts
40051
- async function handleCapture(input2, config2 = loadConfig()) {
40756
+ async function handleCapture(input2, config2 = loadConfig(), opts = {}) {
40052
40757
  try {
40053
40758
  const gateway = resolveDataGateway(config2);
40054
40759
  const runtime = createPluginRuntime(gateway, config2.settings, { dataDir: config2.dataDir });
40055
40760
  let result;
40056
40761
  try {
40057
- result = await runtime.capture(input2);
40762
+ result = await runtime.capture(input2, opts);
40058
40763
  } finally {
40059
40764
  await runtime.close();
40060
40765
  }
@@ -40132,6 +40837,7 @@ async function handleSessionStart(input2, config2 = loadConfig()) {
40132
40837
  }
40133
40838
  triggerPolicySync(config2);
40134
40839
  triggerHistorySync(config2);
40840
+ triggerContentRetention(config2);
40135
40841
  if (input2.harnessVersion !== void 0 && offersMaintenance(gateway, "staleBinaryNotice")) {
40136
40842
  return { staleBinaryNotice: gateway.staleBinaryNotice(input2.harnessVersion) };
40137
40843
  }