@akasecurity/ai-tc-claude-code 0.9.10 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,8 +492,8 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync7 } from "fs";
496
- import { join as join13 } from "path";
495
+ import { existsSync as existsSync8 } from "fs";
496
+ import { join as join16 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20623,7 +20655,7 @@ var TOOL_TO_HARNESS = {
20623
20655
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20624
20656
  };
20625
20657
  function harnessFromTool(tool) {
20626
- return TOOL_TO_HARNESS[tool] ?? tool;
20658
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20627
20659
  }
20628
20660
 
20629
20661
  // ../../packages/schema/src/zod/finding.ts
@@ -20673,6 +20705,15 @@ var FindingCategory = external_exports.enum([
20673
20705
  ]).meta({ id: "FindingCategory" });
20674
20706
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20675
20707
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20708
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20709
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20710
+ var FindingDelivery = external_exports.object({
20711
+ state: FindingDeliveryState,
20712
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20713
+ at: external_exports.iso.datetime().optional(),
20714
+ // Only on `not_sent`, and only when a known reason was recorded.
20715
+ reason: SyncFailureReason.optional()
20716
+ }).meta({ id: "FindingDelivery" });
20676
20717
  var ResolutionMethod = external_exports.enum([
20677
20718
  "enforced-in-flight",
20678
20719
  "fixed-at-source",
@@ -20729,7 +20770,10 @@ var FindingInstance = external_exports.object({
20729
20770
  // The session that event belongs to, when it has one — the seam a
20730
20771
  // per-instance "view session" link needs. Absent for events captured
20731
20772
  // outside a session.
20732
- sessionId: external_exports.string().optional()
20773
+ sessionId: external_exports.string().optional(),
20774
+ // The delivery state of the event above (see FindingDelivery). Optional so
20775
+ // readers that do not project it stay valid.
20776
+ delivery: FindingDelivery.optional()
20733
20777
  }).meta({ id: "FindingInstance" });
20734
20778
  var FindingGroup = external_exports.object({
20735
20779
  id: external_exports.string(),
@@ -20746,13 +20790,11 @@ var FindingGroup = external_exports.object({
20746
20790
  latestDetectedAt: external_exports.iso.datetime(),
20747
20791
  instances: external_exports.array(FindingInstance),
20748
20792
  // Derived from instances' statuses with open-dominates precedence (see
20749
- // buildFindingGroups). Undefined only when no instance carries a status.
20793
+ // foldGroupStatus). Undefined only when no instance carries a status.
20750
20794
  status: FindingStatus.optional(),
20751
- // The distinct people across the WHOLE group, not just the `instances`
20752
- // preview — from the store's whole-group aggregate when it supplies one,
20753
- // else folded from the rows (see buildFindingGroups). Undefined when no
20754
- // instance carries a user, or when the store supplied whole-group folds
20755
- // without one.
20795
+ // The distinct people across the WHOLE group, not just the instances
20796
+ // carried here. Undefined when no instance carries a user, or when the
20797
+ // store supplied whole-group folds without one.
20756
20798
  users: external_exports.array(FindingUser).optional()
20757
20799
  }).meta({ id: "FindingGroup" });
20758
20800
  var FindingStats = external_exports.object({
@@ -20781,21 +20823,34 @@ var FindingFacets = external_exports.object({
20781
20823
  // counted under no value.
20782
20824
  status: external_exports.array(FindingFacetItem),
20783
20825
  // Host tool (attributes.tool_name). Present only on the instance-level
20784
- // reads, which can filter by it; the grouped read omits the dimension
20826
+ // reads, which can filter by it; the type-level read omits the dimension
20785
20827
  // because a group spans tools.
20786
- tool: external_exports.array(FindingFacetItem).optional()
20828
+ tool: external_exports.array(FindingFacetItem).optional(),
20829
+ // Delivery states (FindingDeliveryState). Present only on the
20830
+ // instance-level reads, like `tool`.
20831
+ deployment: external_exports.array(FindingFacetItem).optional()
20787
20832
  }).meta({ id: "FindingFacets" });
20788
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20789
- var ListGroupedFindingsQuery = external_exports.object({
20833
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20834
+ id: "FindingTypeSummary"
20835
+ });
20836
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20837
+ var MAX_FINDING_TYPES_LIMIT = 100;
20838
+ var ListFindingTypesQuery = external_exports.object({
20790
20839
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20791
- // FindingAction.
20840
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20841
+ // firing version carries, and this list pages types.
20842
+ //
20843
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20844
+ // definition versions at different severities, so a type kept by this filter
20845
+ // can hold findings that individually do not match — see totals.findings on
20846
+ // ListFindingTypesResponse, which counts them all.
20792
20847
  severity: external_exports.array(Severity).optional(),
20793
20848
  subtype: external_exports.array(external_exports.string()).optional(),
20794
20849
  provider: external_exports.array(FindingProvider).optional(),
20795
20850
  action: external_exports.array(FindingAction).optional(),
20796
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20797
- // individual instances' — so a filtered group's Status column always reads
20798
- // one of the requested values.
20851
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20852
+ // individual findings' — so a filtered row's status always reads one of the
20853
+ // requested values.
20799
20854
  status: external_exports.array(FindingStatus).optional(),
20800
20855
  q: external_exports.string().optional(),
20801
20856
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20805,23 +20860,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20805
20860
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20806
20861
  // means all time — this list has no default window.
20807
20862
  from: external_exports.iso.datetime().optional(),
20808
- // A group or instance id that must appear in the page even when the cursor
20809
- // has already advanced past its sort position. This is what keeps the
20810
- // Findings page's one-shot ?finding= deep link resolving once the list
20811
- // paginates: the target group is appended out of sort order rather than
20812
- // scanning forward for it. Never affects totals, facets or the cursor.
20863
+ // A RULE id that must appear in the page even when the cursor has already
20864
+ // advanced past its sort position. This is what keeps the selected type
20865
+ // visible in the list once it paginates: the target is appended out of sort
20866
+ // order rather than scanned forward for. Never affects totals, facets or the
20867
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20868
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20869
+ // and so is not bounded by what any page happens to hold.
20813
20870
  includeId: external_exports.string().optional(),
20814
- groupBy: external_exports.literal("type").optional(),
20815
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20871
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20816
20872
  cursor: external_exports.string().optional()
20817
20873
  });
20818
- var ListGroupedFindingsResponse = external_exports.object({
20874
+ var ListFindingTypesResponse = external_exports.object({
20819
20875
  totals: external_exports.object({
20876
+ // Findings belonging to the matching TYPES — not findings that each match
20877
+ // the filters. The filters here select types, so a type that survives
20878
+ // contributes its whole instanceCount.
20879
+ //
20880
+ // `status` is the one exception, narrowed per finding via
20881
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20882
+ // this can exceed what the instance read reports for the same filters: a
20883
+ // rule whose severity moved between versions is kept on its newest and
20884
+ // still counts its older findings. Narrowing the other three needs
20885
+ // per-dimension counts the aggregate does not carry today.
20820
20886
  findings: external_exports.number().int().nonnegative(),
20821
- groups: external_exports.number().int().nonnegative()
20887
+ // Counts TYPES, which is the unit this read pages. The instance read's
20888
+ // own totals count findings; the two deliberately answer different
20889
+ // questions and are never summed.
20890
+ types: external_exports.number().int().nonnegative()
20822
20891
  }),
20823
20892
  facets: FindingFacets,
20824
- items: external_exports.array(FindingGroup),
20893
+ items: external_exports.array(FindingTypeSummary),
20825
20894
  nextCursor: external_exports.string().nullable(),
20826
20895
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20827
20896
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20829,7 +20898,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20829
20898
  // every firing, so the two numbers legitimately differ — this map lets a
20830
20899
  // session-scoped view show both.
20831
20900
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20832
- }).meta({ id: "ListGroupedFindingsResponse" });
20901
+ }).meta({ id: "ListFindingTypesResponse" });
20833
20902
  var ApplyFindingActionRequest = external_exports.object({
20834
20903
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20835
20904
  // it, so it is excluded from the request contract. The mapping helper
@@ -20859,16 +20928,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20859
20928
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20860
20929
  var ListFindingInstancesQuery = external_exports.object({
20861
20930
  severity: external_exports.array(Severity).optional(),
20862
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20931
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20932
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20863
20933
  subtype: external_exports.array(external_exports.string()).optional(),
20864
20934
  provider: external_exports.array(FindingProvider).optional(),
20865
20935
  action: external_exports.array(FindingAction).optional(),
20866
20936
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20867
- // the grouped query's group-level fold.
20937
+ // the types query's type-level fold.
20868
20938
  status: external_exports.array(FindingStatus).optional(),
20869
20939
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20870
20940
  // where the free-text `q` can only match the rendered "via Bash" label.
20871
20941
  tool: external_exports.array(external_exports.string()).optional(),
20942
+ // The delivery state of each finding's event (see FindingDelivery).
20943
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20872
20944
  // Exact repository / file-path matches, for the drill-down out of the
20873
20945
  // locations view. A row whose event carries no repo/file matches neither.
20874
20946
  repo: external_exports.string().optional(),
@@ -20881,37 +20953,51 @@ var ListFindingInstancesQuery = external_exports.object({
20881
20953
  });
20882
20954
  var ListFindingInstancesResponse = external_exports.object({
20883
20955
  // Instances matching the filters across the whole scope, not just this
20884
- // page — cursor-independent, like the grouped list's totals.
20956
+ // page — cursor-independent, like the types list's totals.
20885
20957
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20886
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20958
+ // Counts in INSTANCES here, where the types response counts types. Each
20887
20959
  // dimension still excludes its own filter.
20888
20960
  facets: FindingFacets,
20889
20961
  items: external_exports.array(FindingInstanceDetail),
20890
20962
  nextCursor: external_exports.string().nullable()
20891
20963
  }).meta({ id: "ListFindingInstancesResponse" });
20892
- var FindingLocationFile = external_exports.object({
20893
- // Empty when the instances carried no file path (a prompt or a tool call
20894
- // with no file attribution).
20895
- file: external_exports.string(),
20896
- instanceCount: external_exports.number().int().nonnegative(),
20897
- maxSeverity: Severity,
20898
- latestDetectedAt: external_exports.iso.datetime(),
20899
- // Folded from the instances' derived statuses with the same
20900
- // open-dominates precedence a group uses.
20901
- status: FindingStatus.optional(),
20902
- // Distinct rules seen at this location, capped — the row shows them as
20903
- // chips, and the count is what conveys scale.
20904
- ruleIds: external_exports.array(external_exports.string())
20905
- }).meta({ id: "FindingLocationFile" });
20906
- var FindingLocationRepo = external_exports.object({
20964
+ var ListFindingInstancesPage = external_exports.object({
20965
+ items: external_exports.array(FindingInstanceDetail),
20966
+ nextCursor: external_exports.string().nullable()
20967
+ }).meta({ id: "ListFindingInstancesPage" });
20968
+ var FindingLocationSummary = external_exports.object({
20969
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20970
+ // because a location's identity is two values and a URL param carries one:
20971
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20972
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20973
+ // client's page dedupe — never decoded, and never a sort key.
20974
+ id: external_exports.string(),
20907
20975
  /** Empty when the instances carried no repo attribute. */
20908
20976
  repo: external_exports.string(),
20977
+ // Empty when the instances carried no file path (a prompt, or a tool call
20978
+ // with no file attribution). Both halves empty is a real location — usually
20979
+ // the largest one in a store — and is selectable like any other.
20980
+ file: external_exports.string(),
20909
20981
  instanceCount: external_exports.number().int().nonnegative(),
20982
+ // The WORST severity present, not the first row's. It is this list's primary
20983
+ // sort key, so it is also what explains why a row is where it is, and it is
20984
+ // how a reader decides what to open without opening everything.
20910
20985
  maxSeverity: Severity,
20911
20986
  latestDetectedAt: external_exports.iso.datetime(),
20987
+ // Folded from the instances' derived statuses with the same open-dominates
20988
+ // precedence a group uses, so it answers "is anything left to do here" and
20989
+ // not much more: a location holding 1 open among 40 resolved reads like one
20990
+ // holding 40 open. That loss is accepted — the panel beside this list
20991
+ // carries each finding's own status, and instanceCount sits next to the
20992
+ // badge.
20912
20993
  status: FindingStatus.optional(),
20913
- files: external_exports.array(FindingLocationFile)
20914
- }).meta({ id: "FindingLocationRepo" });
20994
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20995
+ // tally rather than a sample and a row can say how many there are. Bounded
20996
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20997
+ ruleIds: external_exports.array(external_exports.string())
20998
+ }).meta({ id: "FindingLocationSummary" });
20999
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
21000
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20915
21001
  var ListFindingLocationsQuery = external_exports.object({
20916
21002
  severity: external_exports.array(Severity).optional(),
20917
21003
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20921,21 +21007,47 @@ var ListFindingLocationsQuery = external_exports.object({
20921
21007
  // instances that match, and folds its status from those.
20922
21008
  status: external_exports.array(FindingStatus).optional(),
20923
21009
  tool: external_exports.array(external_exports.string()).optional(),
21010
+ // The delivery state of each finding's event (see FindingDelivery).
21011
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20924
21012
  q: external_exports.string().optional(),
20925
21013
  sessionId: external_exports.string().optional(),
20926
21014
  from: external_exports.iso.datetime().optional(),
20927
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21015
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21016
+ // even when the cursor has already advanced past its sort position — the
21017
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21018
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21019
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21020
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21021
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21022
+ includeId: external_exports.string().optional(),
21023
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21024
+ cursor: external_exports.string().optional()
20928
21025
  });
20929
21026
  var ListFindingLocationsResponse = external_exports.object({
20930
21027
  totals: external_exports.object({
21028
+ // Findings matching the filters across the whole scope. Unlike the types
21029
+ // read's same-named field this needs no caveat: the filters here narrow
21030
+ // per finding, so this is the sum of every row's instanceCount.
20931
21031
  findings: external_exports.number().int().nonnegative(),
20932
- repos: external_exports.number().int().nonnegative(),
20933
- files: external_exports.number().int().nonnegative()
21032
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21033
+ // states. The facets beside it count FINDINGS (see below); a surface
21034
+ // showing both says which is which.
21035
+ locations: external_exports.number().int().nonnegative()
20934
21036
  }),
20935
- /** Sorted by max severity, then most recent. */
20936
- items: external_exports.array(FindingLocationRepo),
20937
- /** Whether `limit` truncated the repo list. */
20938
- hasMore: external_exports.boolean()
21037
+ // Counts in FINDINGS, where the types response counts types, each dimension
21038
+ // still excluding its own filter. Deliberately not locations: counting those
21039
+ // needs a set of location keys per dimension per value — memory tracking the
21040
+ // store times the vocabulary, in a read whose scan promises flat memory —
21041
+ // and the cheap per-location version is not an approximation but WRONG. A
21042
+ // location holding {claudecode, block} and {codex, warn} would survive
21043
+ // provider=claudecode AND action=warn, under which no single finding
21044
+ // matches, so the facet would contradict the instanceCount this whole view
21045
+ // rests on. Findings also keep the toolbar in the same unit as the page
21046
+ // tally and the panel it sits above.
21047
+ facets: FindingFacets,
21048
+ /** Sorted by max severity, then most recent, then (repo, file). */
21049
+ items: external_exports.array(FindingLocationSummary),
21050
+ nextCursor: external_exports.string().nullable()
20939
21051
  }).meta({ id: "ListFindingLocationsResponse" });
20940
21052
 
20941
21053
  // ../../packages/schema/src/zod/meta.ts
@@ -21099,6 +21211,10 @@ var CaptureAttributes = external_exports.object({
21099
21211
  // to 'allow' — the enforcement audit trail's link back to the grant that
21100
21212
  // authorized the bypass.
21101
21213
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21214
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21215
+ // join back to the `llm_call` leaf for the same assistant turn.
21216
+ message_id: external_exports.string().optional(),
21217
+ conversation_id: external_exports.string().optional(),
21102
21218
  // Whole milliseconds this capture's inspection blocked its caller — the
21103
21219
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21104
21220
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21107,7 +21223,19 @@ var CaptureAttributes = external_exports.object({
21107
21223
  // inline json_extract and is not itself an optimization.
21108
21224
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21109
21225
  // before the measurement shipped — never present as a placeholder 0.
21110
- inspection_ms: external_exports.number().int().nonnegative().optional()
21226
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21227
+ // What a `redact` this capture could not carry out became instead (see
21228
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21229
+ // degrade actually happened, so absence is the ordinary case rather than a
21230
+ // reader having to distinguish it from a zero.
21231
+ //
21232
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21233
+ // so on a multi-finding row this does not say which finding degraded, and
21234
+ // its presence does not mean the fallback decided the capture's action. A
21235
+ // capture denied by another finding's own Block policy carries `block`
21236
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21237
+ // repeated rather than referenced because a store reader opens this file.
21238
+ redact_degraded_to: ActionTaken.optional()
21111
21239
  }).catchall(external_exports.unknown());
21112
21240
  var ToolCallInspection = external_exports.object({
21113
21241
  ruleId: external_exports.string().min(1),
@@ -21306,7 +21434,17 @@ var AuditEvent = external_exports.object({
21306
21434
  /** `share` to a first-party/internal destination. */
21307
21435
  internal: external_exports.boolean(),
21308
21436
  /** Event needs review (e.g. unverified egress). */
21309
- flagged: external_exports.boolean()
21437
+ flagged: external_exports.boolean(),
21438
+ /**
21439
+ * The body this event's `title` is drawn from was cleared by local body
21440
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21441
+ *
21442
+ * A separate flag rather than a sentinel written into `title`: the title is
21443
+ * rendered text, and a store-layer module that invented display copy for it
21444
+ * would be choosing words the view is supposed to choose. Additive and
21445
+ * defaulted, so an older producer still validates.
21446
+ */
21447
+ bodyExpired: external_exports.boolean().default(false)
21310
21448
  }).meta({ id: "ActivityAuditEvent" });
21311
21449
  var ActivitySessionSummary = external_exports.object({
21312
21450
  id: external_exports.string(),
@@ -22104,6 +22242,14 @@ var ControlPlaneErrorBody = external_exports.object({
22104
22242
  message: external_exports.string().optional()
22105
22243
  }).optional()
22106
22244
  });
22245
+ var RemoteFailureKind = external_exports.enum([
22246
+ "unauthorized",
22247
+ "forbidden",
22248
+ "route-absent",
22249
+ "invalid-request",
22250
+ "rejected",
22251
+ "unreachable"
22252
+ ]);
22107
22253
  var AttachDeviceRequest = external_exports.object({
22108
22254
  // This machine's own continuity id, so re-attaching ROTATES the credential
22109
22255
  // on one machine record instead of producing a second one. Client-minted
@@ -22639,6 +22785,12 @@ var EventMetadata = external_exports.object({
22639
22785
  // to 'allow' — the enforcement audit trail's link back to the grant that
22640
22786
  // authorized the bypass. Absent on captures where no exception applied.
22641
22787
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22788
+ // The assistant message this capture belongs to, and the conversation it sits
22789
+ // in — set by the browser extension's network capture so a stored `response`
22790
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22791
+ // on every other capture path, which has no such id.
22792
+ messageId: external_exports.string().optional(),
22793
+ conversationId: external_exports.string().optional(),
22642
22794
  // How long THIS capture's inspection blocked its caller, in whole
22643
22795
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22644
22796
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22651,7 +22803,37 @@ var EventMetadata = external_exports.object({
22651
22803
  // Absent is also what every pre-measurement client writes, and what a
22652
22804
  // clock failure degrades to — a reader must treat absence as "not measured"
22653
22805
  // and never as a zero, which would read as "inspection is free".
22654
- inspectionMs: external_exports.number().int().nonnegative().optional()
22806
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22807
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22808
+ // workspace's `redactFallback`, applied because the field could not be
22809
+ // masked in place (a shell command, a URL, or any argument on a host whose
22810
+ // hook contract offers no rewrite channel).
22811
+ //
22812
+ // It exists because the action alone cannot say why. A finding recorded as
22813
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22814
+ // assigned Redact on a field that could not take one — and those are
22815
+ // different facts about the same row: the first is a policy the user chose,
22816
+ // the second is a masking the host could not perform. Absent means no
22817
+ // degrade happened, which is every ordinary capture.
22818
+ //
22819
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22820
+ // is the CAPTURE while `actionTaken` is per FINDING:
22821
+ //
22822
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22823
+ // `redact` alongside a finding ASSIGNED the same action stores both
22824
+ // identically and one reason for the pair; attributing it to both
22825
+ // describes the assigned one wrongly, and to neither loses the degrade.
22826
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22827
+ // became, not the reason the capture ended as it did — a capture denied
22828
+ // by some other finding's own Block policy still carries `block` here,
22829
+ // and clearing the workspace's fallback would not have let it through.
22830
+ // Gate on the value against what a fallback can produce; never read the
22831
+ // field's presence as "this was the fallback's doing".
22832
+ //
22833
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22834
+ // Closing either means moving the reason onto the finding row, which
22835
+ // already carries its own action.
22836
+ redactDegradedTo: ActionTaken.optional()
22655
22837
  }).meta({ id: "EventMetadata" });
22656
22838
  var Event = external_exports.object({
22657
22839
  id: external_exports.guid(),
@@ -22761,7 +22943,32 @@ var RotateKeyInput = external_exports.object({
22761
22943
  confirmation: external_exports.string()
22762
22944
  });
22763
22945
 
22946
+ // ../../packages/schema/src/zod/finding-delivery.ts
22947
+ var KNOWN_REASONS = SyncFailureReason.options;
22948
+ function knownReason(value) {
22949
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22950
+ }
22951
+ function deriveFindingDelivery(row) {
22952
+ if (row.kind === "code_change") return { state: "local_scan" };
22953
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22954
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22955
+ }
22956
+ if (row.syncedAt !== null) {
22957
+ const reason = knownReason(row.syncFailure);
22958
+ return {
22959
+ state: "not_sent",
22960
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22961
+ ...reason === void 0 ? {} : { reason }
22962
+ };
22963
+ }
22964
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22965
+ return { state: "never_offered" };
22966
+ }
22967
+
22764
22968
  // ../../packages/schema/src/zod/findings-group-build.ts
22969
+ function lookupOwn(map2, key) {
22970
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22971
+ }
22765
22972
  function toApiAction(dbVal) {
22766
22973
  const map2 = {
22767
22974
  log: "monitored",
@@ -22770,7 +22977,7 @@ function toApiAction(dbVal) {
22770
22977
  warn: "warned",
22771
22978
  allow: "allowed"
22772
22979
  };
22773
- return map2[dbVal] ?? "allowed";
22980
+ return lookupOwn(map2, dbVal) ?? "allowed";
22774
22981
  }
22775
22982
  function toApiCategory(dbVal) {
22776
22983
  if (dbVal === "code_context") return "source_code";
@@ -22778,13 +22985,18 @@ function toApiCategory(dbVal) {
22778
22985
  return parsed2.success ? parsed2.data : "custom";
22779
22986
  }
22780
22987
  function toApiProvider(sourceTool) {
22781
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22988
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22782
22989
  }
22783
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22990
+ var FINDING_STATUS_PRECEDENCE = [
22991
+ "open",
22992
+ "handled",
22993
+ "dismissed",
22994
+ "resolved"
22995
+ ];
22784
22996
  function foldGroupStatus(instanceStatuses) {
22785
22997
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22786
22998
  if (statuses.size === 0) return void 0;
22787
- for (const candidate of STATUS_PRECEDENCE) {
22999
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22788
23000
  if (statuses.has(candidate)) return candidate;
22789
23001
  }
22790
23002
  return void 0;
@@ -22797,139 +23009,62 @@ function deriveFindingStatus(row) {
22797
23009
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22798
23010
  return "open";
22799
23011
  }
22800
- function distinctUsers(instances) {
22801
- const seen = /* @__PURE__ */ new Set();
22802
- const users = [];
22803
- for (const i of instances) {
22804
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22805
- seen.add(i.user.id);
22806
- users.push(i.user);
22807
- }
22808
- return users;
22809
- }
22810
23012
  function sortUsers(users) {
22811
23013
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22812
23014
  }
22813
- function buildFindingGroups(rows, opts = {}) {
22814
- const overrides = opts.overrides;
23015
+ function buildFindingTypes(aggregates, opts = {}) {
22815
23016
  const packNames = opts.packNames;
22816
- const aggregates = opts.aggregates;
22817
- const byRuleId = /* @__PURE__ */ new Map();
22818
- for (const row of rows) {
22819
- const existing = byRuleId.get(row.ruleId);
22820
- if (existing) existing.push(row);
22821
- else byRuleId.set(row.ruleId, [row]);
22822
- }
22823
- const groups = [];
22824
- for (const [ruleId, ruleRows] of byRuleId) {
22825
- const instances = ruleRows.map((r) => {
22826
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22827
- return {
22828
- id: r.id,
22829
- provider: toApiProvider(r.sourceTool),
22830
- repo: r.repo,
22831
- file: r.file,
22832
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22833
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22834
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22835
- ...r.user === void 0 ? {} : { user: r.user },
22836
- action: toApiAction(effectiveDbAction),
22837
- detectedAt: r.occurredAt,
22838
- confidence: r.confidence,
22839
- status: r.status
22840
- };
22841
- });
22842
- const agg = aggregates?.get(ruleId);
22843
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22844
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22845
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22846
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22847
- );
22848
- const seenProviders = /* @__PURE__ */ new Set();
22849
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22850
- if (seenProviders.has(p)) return false;
22851
- seenProviders.add(p);
22852
- return true;
22853
- });
22854
- const actionSet = new Set(
22855
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22856
- );
23017
+ const types = [];
23018
+ for (const [ruleId, agg] of aggregates) {
23019
+ const users = sortUsers(agg.users ?? []);
23020
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23021
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22857
23022
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22858
- const severity = ruleRows[0]?.severity ?? "low";
22859
- const detection = {
22860
- id: ruleId,
22861
- name: packNames?.get(ruleId) ?? null
22862
- };
22863
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22864
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22865
- const match = {
22866
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22867
- contextPrefix: ""
22868
- // empty (pending privacy review)
22869
- };
22870
- const status = foldGroupStatus(
22871
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22872
- );
22873
- const group = {
23023
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23024
+ const type = {
22874
23025
  id: ruleId,
22875
23026
  category: apiCategory,
22876
23027
  subtype: ruleId,
22877
23028
  // human label comes with pack metadata later
22878
- severity,
22879
- match,
22880
- detection,
22881
- policy,
22882
- instanceCount: agg?.instanceCount ?? instances.length,
23029
+ severity: agg.severity ?? "low",
23030
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23031
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23032
+ instanceCount: agg.instanceCount,
22883
23033
  providers,
22884
23034
  aggregateAction,
22885
- latestDetectedAt,
22886
- instances,
22887
- status,
23035
+ latestDetectedAt: agg.latestDetectedAt,
23036
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22888
23037
  ...users.length > 0 ? { users } : {}
22889
23038
  };
22890
- if (agg) {
22891
- actionsCache.set(group, [...actionSet]);
22892
- if (agg.searchText !== void 0) {
22893
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22894
- }
23039
+ actionsCache.set(type, [...actionSet]);
23040
+ if (agg.searchText !== void 0) {
23041
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22895
23042
  }
22896
- groups.push(group);
23043
+ types.push(type);
22897
23044
  }
22898
- return groups;
23045
+ return types;
22899
23046
  }
22900
23047
  var haystackCache = /* @__PURE__ */ new WeakMap();
22901
- function buildHaystack(g, extra) {
23048
+ function buildHaystack(t, extra) {
22902
23049
  return [
22903
- g.subtype,
22904
- g.category,
22905
- g.match.maskedValue,
22906
- g.policy.name,
22907
- g.id,
22908
- ...g.instances.map((i) => i.repo),
22909
- ...g.instances.map((i) => i.file),
22910
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22911
- ...g.instances.map((i) => i.id),
22912
- // The people: the whole group's list when the store folded one, plus the
22913
- // preview's own — the two overlap, and a haystack does not mind.
22914
- ...(g.users ?? []).map((u) => u.name),
22915
- ...g.instances.map((i) => i.user?.name ?? ""),
23050
+ t.subtype,
23051
+ t.category,
23052
+ t.policy.name,
23053
+ t.id,
23054
+ ...(t.users ?? []).map((u) => u.name),
22916
23055
  ...extra === void 0 ? [] : [extra]
22917
23056
  ].join(" ").toLowerCase();
22918
23057
  }
22919
- function groupHaystack(g) {
22920
- const cached2 = haystackCache.get(g);
23058
+ function typeHaystack(t) {
23059
+ const cached2 = haystackCache.get(t);
22921
23060
  if (cached2 !== void 0) return cached2;
22922
- const haystack = buildHaystack(g);
22923
- haystackCache.set(g, haystack);
23061
+ const haystack = buildHaystack(t);
23062
+ haystackCache.set(t, haystack);
22924
23063
  return haystack;
22925
23064
  }
22926
23065
  var actionsCache = /* @__PURE__ */ new WeakMap();
22927
- function groupActions(g) {
22928
- const cached2 = actionsCache.get(g);
22929
- if (cached2 !== void 0) return cached2;
22930
- const actions = [...new Set(g.instances.map((i) => i.action))];
22931
- actionsCache.set(g, actions);
22932
- return actions;
23066
+ function typeActions(t) {
23067
+ return actionsCache.get(t) ?? [];
22933
23068
  }
22934
23069
  function countInstancesByStatus(statusInputs, statuses) {
22935
23070
  const statusSet = new Set(statuses);
@@ -22940,8 +23075,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22940
23075
  }
22941
23076
  return sum;
22942
23077
  }
22943
- function applyFindingFilters(groups, opts) {
22944
- let filtered = groups;
23078
+ function applyFindingFilters(types, opts) {
23079
+ let filtered = types;
22945
23080
  if (opts.severity && opts.severity.length > 0) {
22946
23081
  const sevSet = new Set(opts.severity);
22947
23082
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22952,7 +23087,7 @@ function applyFindingFilters(groups, opts) {
22952
23087
  }
22953
23088
  if (opts.actions && opts.actions.length > 0) {
22954
23089
  const actionSet = new Set(opts.actions);
22955
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23090
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22956
23091
  }
22957
23092
  if (opts.subtype && opts.subtype.length > 0) {
22958
23093
  const subtypeSet = new Set(opts.subtype);
@@ -22964,26 +23099,31 @@ function applyFindingFilters(groups, opts) {
22964
23099
  }
22965
23100
  if (opts.q) {
22966
23101
  const q = opts.q.toLowerCase();
22967
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23102
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22968
23103
  }
22969
23104
  return filtered;
22970
23105
  }
22971
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22972
- var SEVERITY_RANK = SEVERITY_ORDER;
23106
+ function rankByOrder(members2) {
23107
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23108
+ }
23109
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23110
+ function severityRank(severity) {
23111
+ return lookupOwn(SEVERITY_RANK, severity);
23112
+ }
22973
23113
  function compareFindingGroupOrder(a, b) {
22974
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22975
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23114
+ const rankA = severityRank(a.severity) ?? -1;
23115
+ const rankB = severityRank(b.severity) ?? -1;
22976
23116
  const severityDiff = rankA - rankB;
22977
23117
  if (severityDiff !== 0) return severityDiff;
22978
23118
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22979
23119
  if (recencyDiff !== 0) return recencyDiff;
22980
23120
  return a.id.localeCompare(b.id);
22981
23121
  }
22982
- function sortFindingGroups(groups) {
22983
- return [...groups].sort(compareFindingGroupOrder);
23122
+ function sortFindingTypes(types) {
23123
+ return [...types].sort(compareFindingGroupOrder);
22984
23124
  }
22985
- function computeFindingFacets(allGroups, opts) {
22986
- const forSeverity = applyFindingFilters(allGroups, {
23125
+ function computeFindingFacets(allTypes, opts) {
23126
+ const forSeverity = applyFindingFilters(allTypes, {
22987
23127
  providers: opts.providers,
22988
23128
  actions: opts.actions,
22989
23129
  statuses: opts.statuses,
@@ -22994,7 +23134,7 @@ function computeFindingFacets(allGroups, opts) {
22994
23134
  for (const g of forSeverity) {
22995
23135
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22996
23136
  }
22997
- const forProvider = applyFindingFilters(allGroups, {
23137
+ const forProvider = applyFindingFilters(allTypes, {
22998
23138
  actions: opts.actions,
22999
23139
  statuses: opts.statuses,
23000
23140
  q: opts.q,
@@ -23005,7 +23145,7 @@ function computeFindingFacets(allGroups, opts) {
23005
23145
  for (const g of forProvider) {
23006
23146
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23007
23147
  }
23008
- const forAction = applyFindingFilters(allGroups, {
23148
+ const forAction = applyFindingFilters(allTypes, {
23009
23149
  providers: opts.providers,
23010
23150
  statuses: opts.statuses,
23011
23151
  q: opts.q,
@@ -23014,9 +23154,9 @@ function computeFindingFacets(allGroups, opts) {
23014
23154
  });
23015
23155
  const actionMap = /* @__PURE__ */ new Map();
23016
23156
  for (const g of forAction) {
23017
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23157
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23018
23158
  }
23019
- const forSubtype = applyFindingFilters(allGroups, {
23159
+ const forSubtype = applyFindingFilters(allTypes, {
23020
23160
  providers: opts.providers,
23021
23161
  actions: opts.actions,
23022
23162
  statuses: opts.statuses,
@@ -23025,7 +23165,7 @@ function computeFindingFacets(allGroups, opts) {
23025
23165
  });
23026
23166
  const subtypeMap = /* @__PURE__ */ new Map();
23027
23167
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23028
- const forStatus = applyFindingFilters(allGroups, {
23168
+ const forStatus = applyFindingFilters(allTypes, {
23029
23169
  providers: opts.providers,
23030
23170
  actions: opts.actions,
23031
23171
  q: opts.q,
@@ -23047,6 +23187,20 @@ function computeFindingFacets(allGroups, opts) {
23047
23187
  }
23048
23188
 
23049
23189
  // ../../packages/schema/src/zod/findings-flat-build.ts
23190
+ function compareCodePoints(a, b) {
23191
+ const aIter = a[Symbol.iterator]();
23192
+ const bIter = b[Symbol.iterator]();
23193
+ for (; ; ) {
23194
+ const aNext = aIter.next();
23195
+ const bNext = bIter.next();
23196
+ if (aNext.done && bNext.done) return 0;
23197
+ if (aNext.done) return -1;
23198
+ if (bNext.done) return 1;
23199
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23200
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23201
+ if (aPoint !== bPoint) return aPoint - bPoint;
23202
+ }
23203
+ }
23050
23204
  function rowHaystack(row) {
23051
23205
  return [
23052
23206
  row.ruleId,
@@ -23071,12 +23225,24 @@ function matchesDimension(row, opts, dimension) {
23071
23225
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23072
23226
  case "statuses":
23073
23227
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23228
+ case "deliveries":
23229
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23074
23230
  case "tools":
23075
23231
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23232
+ // An EMPTY value is a real filter here, not an absent one. The location
23233
+ // list buckets a finding whose event recorded no repo — or no file — under
23234
+ // the empty string, and selecting that bucket has to narrow the panel to
23235
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23236
+ // row omits the key, which every call site already does.
23237
+ //
23238
+ // Reading '' as unset is what this replaced, and it failed in the one place
23239
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23240
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23241
+ // — a row reading 3 findings beside a panel listing every finding there is.
23076
23242
  case "repo":
23077
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23243
+ return opts.repo === void 0 || row.repo === opts.repo;
23078
23244
  case "file":
23079
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23245
+ return opts.file === void 0 || row.file === opts.file;
23080
23246
  case "q":
23081
23247
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23082
23248
  }
@@ -23087,6 +23253,7 @@ var DIMENSIONS = [
23087
23253
  "providers",
23088
23254
  "actions",
23089
23255
  "statuses",
23256
+ "deliveries",
23090
23257
  "tools",
23091
23258
  "repo",
23092
23259
  "file",
@@ -23100,10 +23267,19 @@ function matchesInstanceFilters(row, opts, except) {
23100
23267
  return true;
23101
23268
  }
23102
23269
  function toItems(counts) {
23103
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23270
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23271
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23272
+ // NFD spelling of the same text) as equal, so a count tie between
23273
+ // them would otherwise be ordered by whichever the Map iteration
23274
+ // produced. compareCodePoints breaks that tie deterministically, which
23275
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23276
+ // which it need not: foldFacetTuples runs this same sort over grouped
23277
+ // tuples, so both paths order facets identically by construction.
23278
+ compareCodePoints(a.value, b.value)
23279
+ );
23104
23280
  }
23105
- function bump(counts, value) {
23106
- counts.set(value, (counts.get(value) ?? 0) + 1);
23281
+ function bump(counts, value, by = 1) {
23282
+ counts.set(value, (counts.get(value) ?? 0) + by);
23107
23283
  }
23108
23284
  function createInstanceFacetAccumulator(opts) {
23109
23285
  const severity = /* @__PURE__ */ new Map();
@@ -23112,6 +23288,7 @@ function createInstanceFacetAccumulator(opts) {
23112
23288
  const action = /* @__PURE__ */ new Map();
23113
23289
  const status = /* @__PURE__ */ new Map();
23114
23290
  const tool = /* @__PURE__ */ new Map();
23291
+ const deployment = /* @__PURE__ */ new Map();
23115
23292
  return {
23116
23293
  add(row) {
23117
23294
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23126,6 +23303,9 @@ function createInstanceFacetAccumulator(opts) {
23126
23303
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23127
23304
  bump(tool, row.toolName);
23128
23305
  }
23306
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23307
+ bump(deployment, row.delivery.state);
23308
+ }
23129
23309
  },
23130
23310
  facets: () => ({
23131
23311
  severity: toItems(severity),
@@ -23133,7 +23313,8 @@ function createInstanceFacetAccumulator(opts) {
23133
23313
  provider: toItems(provider),
23134
23314
  action: toItems(action),
23135
23315
  status: toItems(status),
23136
- tool: toItems(tool)
23316
+ tool: toItems(tool),
23317
+ deployment: toItems(deployment)
23137
23318
  })
23138
23319
  };
23139
23320
  }
@@ -23147,6 +23328,7 @@ function toInstanceDetail(row) {
23147
23328
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23148
23329
  eventId: row.eventId,
23149
23330
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23331
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23150
23332
  ...row.user === void 0 ? {} : { user: row.user },
23151
23333
  action: toApiAction(row.actionTaken),
23152
23334
  detectedAt: row.occurredAt,
@@ -23161,12 +23343,6 @@ function toInstanceDetail(row) {
23161
23343
  policy: { id: `category:${category}`, name: category }
23162
23344
  };
23163
23345
  }
23164
- var SEVERITY_ORDER2 = {
23165
- critical: 0,
23166
- high: 1,
23167
- medium: 2,
23168
- low: 3
23169
- };
23170
23346
  function newLocationAccumulator() {
23171
23347
  return {
23172
23348
  instanceCount: 0,
@@ -23181,7 +23357,7 @@ function newLocationAccumulator() {
23181
23357
  }
23182
23358
  function addToLocation(acc, row) {
23183
23359
  acc.instanceCount += 1;
23184
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23360
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23185
23361
  if (rank < acc.maxSeverityRank) {
23186
23362
  acc.maxSeverityRank = rank;
23187
23363
  acc.maxSeverity = row.severity;
@@ -23190,6 +23366,23 @@ function addToLocation(acc, row) {
23190
23366
  acc.statuses.push(row.status);
23191
23367
  acc.ruleIds.add(row.ruleId);
23192
23368
  }
23369
+ function compareLocationOrder(a, b) {
23370
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23371
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23372
+ if (rankA !== rankB) return rankA - rankB;
23373
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23374
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23375
+ }
23376
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23377
+ if (repoDiff !== 0) return repoDiff;
23378
+ return compareCodePoints(a.file, b.file);
23379
+ }
23380
+ function encodeLocationId(repo, file2) {
23381
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23382
+ }
23383
+ function encodePart(value) {
23384
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23385
+ }
23193
23386
 
23194
23387
  // ../../packages/schema/src/zod/installed-pack.ts
23195
23388
  var InstalledPack = external_exports.object({
@@ -23257,6 +23450,11 @@ var Policy = external_exports.object({
23257
23450
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23258
23451
  provenance: PolicyProvenance.optional()
23259
23452
  }).meta({ id: "Policy" });
23453
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23454
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23455
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23456
+ id: "RedactFallback"
23457
+ });
23260
23458
  var PolicyBundle = external_exports.object({
23261
23459
  version: external_exports.string(),
23262
23460
  policies: external_exports.array(Policy),
@@ -23304,6 +23502,16 @@ var PolicyBundle = external_exports.object({
23304
23502
  // control plane), so no name resolution stands between the decision and the
23305
23503
  // comparison.
23306
23504
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23505
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23506
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23507
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23508
+ // a control plane can tighten a machine and never loosen one — the same
23509
+ // direction `mergeRaiseOnly` enforces for policies.
23510
+ //
23511
+ // Optional so an older backend, and an older on-disk cache, still parses;
23512
+ // absent leaves the device's own setting in force, which is the behaviour
23513
+ // that predates the field and the safe direction to default.
23514
+ redactFallback: RedactFallback.optional(),
23307
23515
  customKeywords: external_exports.array(external_exports.string()),
23308
23516
  fetchedAt: external_exports.iso.datetime()
23309
23517
  }).meta({ id: "PolicyBundle" });
@@ -23333,11 +23541,6 @@ function severityFloorPolicy(category) {
23333
23541
  const peak = CATEGORY_PEAK_SEVERITY[category];
23334
23542
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23335
23543
  }
23336
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23337
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23338
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23339
- id: "RedactFallback"
23340
- });
23341
23544
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23342
23545
  var BUILTIN_POLICY_SPECS = {
23343
23546
  monitor: {
@@ -23640,7 +23843,7 @@ function isVaultConsentValid(consent) {
23640
23843
  }
23641
23844
 
23642
23845
  // ../../packages/schema/src/zod/local.ts
23643
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23846
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23644
23847
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23645
23848
  var RunMode = external_exports.enum(["standalone", "attached"]);
23646
23849
  var ControlPlaneConnection = external_exports.object({
@@ -23660,6 +23863,15 @@ var HistorySyncConsent = external_exports.object({
23660
23863
  payloadVersion: external_exports.number().int().positive(),
23661
23864
  endpoint: external_exports.string()
23662
23865
  });
23866
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23867
+ var BodyRetention = external_exports.object({
23868
+ enabled: external_exports.boolean().default(false),
23869
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23870
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23871
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23872
+ // candidate set that is already bounded by "delivered, or never owed".
23873
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23874
+ }).meta({ id: "BodyRetention" });
23663
23875
  var WorkspaceSettings = external_exports.object({
23664
23876
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23665
23877
  runMode: RunMode.default("standalone"),
@@ -23703,12 +23915,18 @@ var WorkspaceSettings = external_exports.object({
23703
23915
  // covers the current payload and must be re-granted.
23704
23916
  modelJudgeConsent: ModelJudgeConsent.optional(),
23705
23917
  // Records that the user consented to the DEFERRED send — the outbox — along
23706
- // with the payload shape and the endpoint they agreed to. Since payload v2
23707
- // that covers both the pre-attach backlog and undelivered captures (which
23708
- // carry prompt/reply text in `content`); the key name predates the widening.
23709
- // Absent until granted, and a grant for a different endpoint or an older
23710
- // payload no longer counts.
23711
- historySyncConsent: HistorySyncConsent.optional()
23918
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23919
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23920
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23921
+ // both widenings. Absent until granted, and a grant for a different endpoint
23922
+ // or an older payload no longer counts.
23923
+ historySyncConsent: HistorySyncConsent.optional(),
23924
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23925
+ // body never removes the row or its findings.
23926
+ bodyRetention: BodyRetention.default({
23927
+ enabled: false,
23928
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23929
+ })
23712
23930
  });
23713
23931
  function defaultWorkspaceSettings() {
23714
23932
  return WorkspaceSettings.parse({});
@@ -23803,12 +24021,15 @@ function toCaptureAttributes(event) {
23803
24021
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23804
24022
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23805
24023
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24024
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23806
24025
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23807
24026
  // has ever populated either), but every legacy metadata key still rides
23808
24027
  // the bag rather than being silently dropped — CaptureAttributes'
23809
24028
  // `.catchall(z.unknown())` carries the long tail.
23810
24029
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23811
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24030
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24031
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24032
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23812
24033
  };
23813
24034
  }
23814
24035
  function captureDefinitionVersion(finding) {
@@ -23836,10 +24057,22 @@ var ManagedSettingKey = external_exports.enum([
23836
24057
  "vaultInlineReveal",
23837
24058
  "modelJudgeConsent",
23838
24059
  "dataSharesInPlace",
23839
- "redactFallback"
24060
+ "redactFallback",
24061
+ // Pins the toggle and the day count together — see BodyRetention on why the
24062
+ // two are one unit. An administrator mandating a window wants the count
24063
+ // enforced with it, not one a user can widen while the toggle stays on.
24064
+ "bodyRetention"
23840
24065
  ]).meta({ id: "ManagedSettingKey" });
24066
+ function isManagedSettingKey(value) {
24067
+ return ManagedSettingKey.safeParse(value).success;
24068
+ }
23841
24069
  var ManagedSettingsValues = external_exports.object({
23842
24070
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24071
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24072
+ // plain, non-strict objects: a key under either that this build does not know
24073
+ // is stripped and nothing reports it. The unknown-value split in
24074
+ // ManagedSettings below classifies top-level names only, so it stops at
24075
+ // these boundaries.
23843
24076
  controlPlane: external_exports.object({
23844
24077
  endpoint: external_exports.string().min(1),
23845
24078
  label: external_exports.string().min(1).optional()
@@ -23850,7 +24083,8 @@ var ManagedSettingsValues = external_exports.object({
23850
24083
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23851
24084
  modelJudgeConsent: external_exports.boolean().optional(),
23852
24085
  dataSharesInPlace: external_exports.boolean().optional(),
23853
- redactFallback: RedactFallback.optional()
24086
+ redactFallback: RedactFallback.optional(),
24087
+ bodyRetention: BodyRetention.optional()
23854
24088
  }).meta({ id: "ManagedSettingsValues" });
23855
24089
  var ManagedSettings = external_exports.object({
23856
24090
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23858,11 +24092,59 @@ var ManagedSettings = external_exports.object({
23858
24092
  // decision from a bug. Absent renders as a generic "your organization".
23859
24093
  organization: external_exports.string().min(1).optional(),
23860
24094
  // What the administrator pinned.
23861
- values: ManagedSettingsValues.default({}),
24095
+ //
24096
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24097
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24098
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24099
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24100
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24101
+ // exactly the file an administrator is most likely to write while a fleet
24102
+ // is mid-upgrade.
24103
+ //
24104
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24105
+ // file, which is the outcome the lock half already rejected — an older
24106
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24107
+ // value still fails, because the nested schema is re-run over the known
24108
+ // subset and its issues are re-raised on this parse.
24109
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23862
24110
  // Which of those the user may not change. A key here with no matching value
23863
24111
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23864
24112
  // the user may still override. The two are separable on purpose.
23865
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24113
+ //
24114
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24115
+ // build does not know is dropped from the locked set and reported, never a
24116
+ // reason to refuse the file. The same shape reaches an older build whenever
24117
+ // an administrator locks a key a newer build added, and refusing it there
24118
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24119
+ // the fleets most likely to carry a version skew. A name outside the enum
24120
+ // is still never HONOURED: the lockable set stays explicit above.
24121
+ lockedFields: external_exports.array(external_exports.string()).default([])
24122
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24123
+ const known = [];
24124
+ const unknown2 = [];
24125
+ for (const name of lockedFields) {
24126
+ if (isManagedSettingKey(name)) known.push(name);
24127
+ else unknown2.push(name);
24128
+ }
24129
+ const knownValues = /* @__PURE__ */ Object.create(null);
24130
+ const unknownValues = [];
24131
+ for (const [name, value] of Object.entries(values)) {
24132
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24133
+ else unknownValues.push(name);
24134
+ }
24135
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24136
+ if (!pinned.success) {
24137
+ for (const issue2 of pinned.error.issues)
24138
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24139
+ return external_exports.NEVER;
24140
+ }
24141
+ return {
24142
+ ...rest,
24143
+ values: pinned.data,
24144
+ lockedFields: known,
24145
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24146
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24147
+ };
23866
24148
  }).meta({ id: "ManagedSettings" });
23867
24149
 
23868
24150
  // ../../packages/schema/src/zod/project-files.ts
@@ -23986,7 +24268,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23986
24268
  timestamp: external_exports.iso.date(),
23987
24269
  critical: external_exports.number().int().nonnegative(),
23988
24270
  high: external_exports.number().int().nonnegative(),
23989
- medium: external_exports.number().int().nonnegative()
24271
+ medium: external_exports.number().int().nonnegative(),
24272
+ // Optional and additive, so a producer written against the earlier
24273
+ // three-series contract keeps validating. A consumer plotting it resolves the
24274
+ // absent case itself — the chart point requires a number.
24275
+ low: external_exports.number().int().nonnegative().optional()
23990
24276
  }).meta({ id: "FindingsTimeseriesPoint" });
23991
24277
  var FindingsTimeseriesResponse = external_exports.object({
23992
24278
  range: TimeRange,
@@ -24012,6 +24298,10 @@ var ResolvedFeedItem = external_exports.object({
24012
24298
  findingKey: external_exports.string(),
24013
24299
  ruleId: external_exports.string(),
24014
24300
  severity: Severity,
24301
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24302
+ // identifies the file: a bare path matches the same name in every repo.
24303
+ // Optional and additive; empty when the event carried no repo.
24304
+ repo: external_exports.string().optional(),
24015
24305
  path: external_exports.string(),
24016
24306
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24017
24307
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24117,7 +24407,23 @@ var SaveSettingsInput = external_exports.object({
24117
24407
  modelJudgeConsent: ModelJudgeConsentChoice,
24118
24408
  historySyncConsent: HistorySyncConsentChoice,
24119
24409
  vaultConsent: external_exports.string(),
24120
- vaultInlineReveal: external_exports.string()
24410
+ vaultInlineReveal: external_exports.string(),
24411
+ // Widened to `string` like its neighbours rather than typed as
24412
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24413
+ // the call site, so the domain check receives the type it was written for.
24414
+ //
24415
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24416
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24417
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24418
+ // trade against. The real cost runs the other way and is the part worth
24419
+ // knowing: a value this schema admits and the domain enum then rejects lands
24420
+ // on the action's shared refusal, which names NO field, where a shape
24421
+ // rejection reaches `malformedInput` and names the schema key.
24422
+ redactFallback: external_exports.string(),
24423
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24424
+ // `BodyRetention`'s and the action checks it there, so there is one place
24425
+ // that decides what a legal horizon is rather than two that can drift.
24426
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24121
24427
  });
24122
24428
  var AttachInput = external_exports.object({
24123
24429
  endpoint: external_exports.string(),
@@ -24289,6 +24595,52 @@ function reviewSeverityRank(reasons) {
24289
24595
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24290
24596
  }
24291
24597
 
24598
+ // ../../packages/schema/src/zod/web-capture.ts
24599
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24600
+ var WebUsage = external_exports.object({
24601
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24602
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24603
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24604
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24605
+ });
24606
+ var WebToolCall = external_exports.object({
24607
+ toolUseId: external_exports.string().min(1),
24608
+ toolName: external_exports.string().min(1),
24609
+ target: external_exports.string().optional(),
24610
+ isError: external_exports.boolean().optional(),
24611
+ inputSize: external_exports.number().int().nonnegative().optional(),
24612
+ outputSize: external_exports.number().int().nonnegative().optional()
24613
+ });
24614
+ var WebExchange = external_exports.object({
24615
+ messageId: external_exports.string().min(1),
24616
+ startedAt: external_exports.iso.datetime(),
24617
+ model: external_exports.string().optional(),
24618
+ usage: WebUsage.optional(),
24619
+ usageSource: WebUsageSource,
24620
+ stopReason: external_exports.string().optional(),
24621
+ conversationId: external_exports.string().optional(),
24622
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24623
+ toolCalls: external_exports.array(WebToolCall).default([]),
24624
+ // Absent when the adapter recovered no text. Capped by the caller at
24625
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24626
+ // short capture is never mistaken for a short reply.
24627
+ responseText: external_exports.string().optional(),
24628
+ truncated: external_exports.boolean().default(false)
24629
+ });
24630
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24631
+ var WebCaptureStatus = external_exports.object({
24632
+ patched: external_exports.boolean(),
24633
+ live: external_exports.boolean(),
24634
+ blind: external_exports.boolean(),
24635
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24636
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24637
+ parseFailures: external_exports.number().int().nonnegative(),
24638
+ unparsedBodies: external_exports.number().int().nonnegative(),
24639
+ // The adapter-declared JSON key paths that were absent from a real payload —
24640
+ // the earliest signal that a site's contract moved.
24641
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24642
+ });
24643
+
24292
24644
  // ../../packages/persistence/src/paths.ts
24293
24645
  import {
24294
24646
  chmodSync,
@@ -24639,6 +24991,22 @@ function discardStore(file2, backup) {
24639
24991
  }
24640
24992
  }
24641
24993
 
24994
+ // ../../packages/persistence/src/internal/sql-functions.ts
24995
+ var utf8 = new TextDecoder();
24996
+ function akaLower(value) {
24997
+ if (value === null) return null;
24998
+ if (typeof value === "string") return value.toLowerCase();
24999
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25000
+ return utf8.decode(value).toLowerCase();
25001
+ }
25002
+ function registerSqlFunctions(db) {
25003
+ db.function(
25004
+ "aka_lower",
25005
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25006
+ akaLower
25007
+ );
25008
+ }
25009
+
24642
25010
  // ../../packages/persistence/src/internal/sql-text.ts
24643
25011
  function escapeLikePattern(s) {
24644
25012
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24723,6 +25091,11 @@ function schemaObjectExists(db, kind, name) {
24723
25091
  function indexExists(db, name) {
24724
25092
  return schemaObjectExists(db, "index", name);
24725
25093
  }
25094
+ function indexColumns(db, name) {
25095
+ if (!indexExists(db, name)) return [];
25096
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25097
+ return columns.map((c) => c.name).filter((c) => c !== null);
25098
+ }
24726
25099
  function columnNames(db, table, opts) {
24727
25100
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24728
25101
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24784,141 +25157,783 @@ function mapRowsTolerant(rows, map2) {
24784
25157
  return out;
24785
25158
  }
24786
25159
 
24787
- // ../../packages/persistence/src/migrations.ts
24788
- function describeObject(object2) {
24789
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24790
- }
24791
- function splitStatements(sql) {
24792
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24793
- }
24794
- function createdIndexName(statement) {
24795
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24796
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25160
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25161
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25162
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25163
+
25164
+ // ../../packages/persistence/src/sync-failure.ts
25165
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25166
+ function syncFailureRejectCondition(column = "sync_failure") {
25167
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25168
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24797
25169
  }
24798
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24799
- function applyMigrations(db, file2) {
24800
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24801
- db.exec(
24802
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24803
- );
24804
- const applied = new Set(
24805
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24806
- );
24807
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24808
- const record2 = db.prepare(
24809
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24810
- );
24811
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24812
- if (applied.has(migration.tag)) continue;
24813
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24814
- const evidence = evidenceObjects(migration.sql);
24815
- const present = evidence.filter((o) => evidenceExists(db, o));
24816
- if (present.length > 0 && present.length < evidence.length) {
24817
- const missing = evidence.filter((o) => !present.includes(o));
24818
- const message = `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.`;
24819
- akaWarn(message);
24820
- throw new Error(`[aka] ${message}`);
24821
- }
24822
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24823
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24824
- const statements = splitStatements(migration.sql);
24825
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24826
- try {
24827
- withTransaction(
24828
- db,
24829
- () => {
24830
- for (const statement of statements) {
24831
- const indexName = createdIndexName(statement);
24832
- if (indexName === void 0) {
24833
- if (alreadyApplied) continue;
24834
- } else if (indexExists(db, indexName)) {
24835
- continue;
24836
- }
24837
- db.exec(statement);
24838
- }
24839
- if (wantsFkOff && !alreadyApplied) {
24840
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24841
- if (violations.length > 0) {
24842
- throw new Error(
24843
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24844
- );
24845
- }
24846
- }
24847
- record2.run(migration.tag, Date.now());
24848
- },
24849
- "IMMEDIATE"
24850
- );
24851
- } finally {
24852
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24853
- }
25170
+
25171
+ // ../../packages/persistence/src/repositories/history-sync.ts
25172
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25173
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25174
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25175
+ var COUNTED_EVENT_TYPES = [
25176
+ ...STRUCTURAL_EVENT_TYPES,
25177
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25178
+ ];
25179
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25180
+ var PARTITION_BUCKETS = `
25181
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25182
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25183
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25184
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25185
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25186
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25187
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25188
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25189
+ -- added later lands in no bucket and fails the sum assertion, instead
25190
+ -- of silently joining this one.
25191
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25192
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25193
+ THEN 1 ELSE 0 END) AS failed,
25194
+ COUNT(*) AS total`;
25195
+ var COUNTED_SCOPE = `
25196
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25197
+ AND (
25198
+ event_type IN (${TYPE_LIST})
25199
+ OR synced_at IS NOT NULL
25200
+ OR outbox_owed = 1
25201
+ )`;
25202
+ var SKIPPED = -1;
25203
+ var ROW_COLUMNS = `id,
25204
+ parent_id AS parentId,
25205
+ root_session_id AS rootSessionId,
25206
+ event_type AS eventType,
25207
+ host_id AS hostId,
25208
+ harness_id AS harnessId,
25209
+ source_project_id AS sourceProjectId,
25210
+ started_at AS startedAt,
25211
+ ended_at AS endedAt,
25212
+ severity,
25213
+ priority,
25214
+ content,
25215
+ content_hash AS contentHash,
25216
+ attributes`;
25217
+ var SqliteHistorySyncRepository = class {
25218
+ constructor(db) {
25219
+ this.db = db;
25220
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25221
+ this.sessionsStmt = db.prepare(
25222
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25223
+ FROM audit_events
25224
+ WHERE synced_at IS NULL
25225
+ AND event_type IN (${TYPE_LIST})
25226
+ AND started_at < :before
25227
+ GROUP BY sessionId
25228
+ ORDER BY earliest
25229
+ LIMIT :limit`
25230
+ );
25231
+ this.rowsStmt = db.prepare(
25232
+ `SELECT ${ROW_COLUMNS}
25233
+ FROM audit_events
25234
+ WHERE synced_at IS NULL
25235
+ AND event_type IN (${TYPE_LIST})
25236
+ AND started_at < :before
25237
+ AND COALESCE(root_session_id, id) = :sessionId
25238
+ ORDER BY (event_type = 'session') DESC, started_at
25239
+ LIMIT :limit`
25240
+ );
25241
+ this.captureRowsStmt = db.prepare(
25242
+ `SELECT ${ROW_COLUMNS}
25243
+ FROM audit_events
25244
+ WHERE synced_at IS NULL
25245
+ AND sync_claimed_at IS NULL
25246
+ AND outbox_owed = 1
25247
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25248
+ AND started_at < :before
25249
+ ORDER BY started_at
25250
+ LIMIT :limit`
25251
+ );
25252
+ this.markOwedStmt = db.prepare(
25253
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25254
+ );
25255
+ this.markCaptureBacklogOwedStmt = db.prepare(
25256
+ `UPDATE audit_events SET outbox_owed = 1
25257
+ WHERE synced_at IS NULL
25258
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25259
+ AND started_at < :before`
25260
+ );
25261
+ this.stampStmt = db.prepare(
25262
+ `UPDATE audit_events
25263
+ SET synced_at = :at,
25264
+ sync_claimed_at = NULL,
25265
+ sync_failed_at = :failedAt,
25266
+ sync_failure = :failure
25267
+ WHERE id = :id`
25268
+ );
25269
+ this.claimRowStmt = db.prepare(
25270
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25271
+ );
25272
+ this.releaseRowStmt = db.prepare(
25273
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25274
+ );
25275
+ this.releaseStaleClaimsStmt = db.prepare(
25276
+ `UPDATE audit_events SET sync_claimed_at = NULL
25277
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25278
+ );
25279
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25280
+ FROM audit_events${COUNTED_SCOPE}`);
25281
+ this.partitionByKindStmt = db.prepare(
25282
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25283
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25284
+ GROUP BY event_type`
25285
+ );
25286
+ this.countsStmt = db.prepare(
25287
+ `SELECT
25288
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25289
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25290
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25291
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25292
+ THEN 1 ELSE 0 END) AS skipped,
25293
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25294
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25295
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25296
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25297
+ FROM audit_events
25298
+ WHERE event_type IN (${TYPE_LIST})`
25299
+ );
25300
+ this.captureSkipCountStmt = db.prepare(
25301
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25302
+ // way the structural totals are. The split exists because a refusal is
25303
+ // terminal only against the deployment that gave it, and the structural
25304
+ // re-arm frees it on a change of deployment. The capture lane has no such
25305
+ // escape: re-arming a capture would offer one deployment's undelivered
25306
+ // prompts, with their text, to a deployment that never saw them, which is
25307
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25308
+ // reasons mean the same thing — this row will not be sent — and splitting
25309
+ // them would put refused captures in a bucket nothing reads and nothing
25310
+ // frees.
25311
+ `SELECT COUNT(*) AS skipped
25312
+ FROM audit_events
25313
+ WHERE synced_at = ${String(SKIPPED)}
25314
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25315
+ );
25316
+ this.fingerprintStmt = db.prepare(
25317
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25318
+ FROM history_sync WHERE id = 1`
25319
+ );
25320
+ this.setFingerprintStmt = db.prepare(
25321
+ `UPDATE history_sync
25322
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25323
+ WHERE id = 1`
25324
+ );
25325
+ this.disownCapturesStmt = db.prepare(
25326
+ `UPDATE audit_events SET outbox_owed = NULL
25327
+ WHERE outbox_owed IS NOT NULL
25328
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25329
+ AND started_at < :attachedAt`
25330
+ );
25331
+ this.rearmStmt = db.prepare(
25332
+ `UPDATE audit_events
25333
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25334
+ WHERE (synced_at > 0
25335
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25336
+ AND event_type IN (${TYPE_LIST})`
25337
+ );
25338
+ this.claimStmt = db.prepare(
25339
+ `UPDATE history_sync
25340
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25341
+ WHERE id = 1
25342
+ AND (owner_pid IS NULL
25343
+ OR heartbeat_at IS NULL
25344
+ OR heartbeat_at < :staleBefore
25345
+ OR heartbeat_at > :now)`
25346
+ );
25347
+ this.heartbeatStmt = db.prepare(
25348
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25349
+ );
25350
+ this.releaseStmt = db.prepare(
25351
+ `UPDATE history_sync
25352
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25353
+ WHERE id = 1 AND owner_pid = :pid`
25354
+ );
25355
+ this.closeWindowStmt = db.prepare(
25356
+ `UPDATE audit_events
25357
+ SET synced_at = ${String(SKIPPED)},
25358
+ sync_failed_at = :at,
25359
+ sync_failure = 'detached_undelivered'
25360
+ WHERE synced_at IS NULL
25361
+ AND event_type IN (${TYPE_LIST})
25362
+ AND started_at >= :attachedAt`
25363
+ );
25364
+ this.releaseBoundaryStmt = db.prepare(
25365
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25366
+ );
25367
+ this.freezeBoundaryStmt = db.prepare(
25368
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25369
+ );
25370
+ this.leaseStmt = db.prepare(
25371
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25372
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25373
+ FROM history_sync WHERE id = 1`
25374
+ );
25375
+ this.inspectionsStmt = db.prepare(
25376
+ `SELECT d.rule_id AS ruleId,
25377
+ d.name AS ruleName,
25378
+ d.version AS ruleVersion,
25379
+ d.category AS category,
25380
+ d.severity AS severity,
25381
+ f.span_start AS spanStart,
25382
+ f.span_end AS spanEnd,
25383
+ f.masked_match AS maskedMatch,
25384
+ f.action_taken AS actionTaken,
25385
+ f.confidence AS confidence
25386
+ FROM inspection_findings f
25387
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25388
+ WHERE f.audit_event_id = :auditEventId
25389
+ ORDER BY f.span_start, f.id`
25390
+ );
24854
25391
  }
24855
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24856
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25392
+ db;
25393
+ ensureRowStmt;
25394
+ sessionsStmt;
25395
+ rowsStmt;
25396
+ stampStmt;
25397
+ countsStmt;
25398
+ fingerprintStmt;
25399
+ setFingerprintStmt;
25400
+ rearmStmt;
25401
+ claimStmt;
25402
+ heartbeatStmt;
25403
+ releaseStmt;
25404
+ leaseStmt;
25405
+ inspectionsStmt;
25406
+ closeWindowStmt;
25407
+ releaseBoundaryStmt;
25408
+ freezeBoundaryStmt;
25409
+ captureRowsStmt;
25410
+ markOwedStmt;
25411
+ markCaptureBacklogOwedStmt;
25412
+ captureSkipCountStmt;
25413
+ disownCapturesStmt;
25414
+ partitionStmt;
25415
+ partitionByKindStmt;
25416
+ claimRowStmt;
25417
+ releaseRowStmt;
25418
+ releaseStaleClaimsStmt;
25419
+ /**
25420
+ * The masked detections recorded against one tool call.
25421
+ *
25422
+ * These travel with the event because a tool call's target is not
25423
+ * re-inspectable from the event alone — unlike a capture, where the text
25424
+ * itself is re-scannable. What crosses is the masked match and the rule that
25425
+ * produced it, never the value.
25426
+ */
25427
+ inspectionsFor(auditEventId) {
25428
+ return allRows(this.inspectionsStmt, { auditEventId });
24857
25429
  }
24858
- ensureSyncedAtColumn(db, "audit_events");
24859
- ensureScanLedgerTable(db);
24860
- ensureHistorySyncTable(db);
24861
- ensureBlockedDetectionsTable(db);
24862
- ensureRuleProbeCacheTable(db);
24863
- ensureWriteGateTrigger(db);
24864
- ensureTokenUsageColumns(db);
24865
- reconcileSourceProjectIds(db);
24866
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24867
- const drained = runLegacyHistoryBackfill(db);
24868
- if (drained) applyLegacyDropMigration(db, file2);
25430
+ /**
25431
+ * Sessions with structural rows still to send, oldest first.
25432
+ *
25433
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25434
+ * read. Anything recorded after the machine attached is the live forward
25435
+ * path's to deliver; this drain exists for what was recorded before it, and a
25436
+ * row both paths send is at best a duplicate request and at worst — for a
25437
+ * session root — an overwrite of the inventory ids the live path resolved.
25438
+ */
25439
+ pendingSessions(limit, before) {
25440
+ return allRows(this.sessionsStmt, { limit, before }).map(
25441
+ (r) => r.sessionId
25442
+ );
24869
25443
  }
24870
- }
24871
- function readLegacyTables(db) {
24872
- let holdsRows = false;
24873
- const marks = [];
24874
- for (const table of ["events", "findings"]) {
24875
- try {
24876
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24877
- if (row === void 0) {
24878
- holdsRows = true;
24879
- marks.push(`${table}:unreadable`);
24880
- continue;
24881
- }
24882
- if (row.n > 0) holdsRows = true;
24883
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24884
- } catch {
24885
- holdsRows = true;
24886
- marks.push(`${table}:unreadable`);
24887
- }
25444
+ /** One session's undelivered structural rows within the backlog, root first. */
25445
+ pendingRows(sessionId, limit, before) {
25446
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24888
25447
  }
24889
- return { holdsRows, mark: marks.join("|") };
24890
- }
24891
- function applyLegacyDropMigration(db, file2) {
24892
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24893
- if (!migration) return;
24894
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24895
- if (file2 !== void 0 && before?.holdsRows === true) {
24896
- try {
24897
- backupBeforeLegacyDrop(db, file2);
24898
- } catch (error61) {
24899
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24900
- return;
24901
- }
25448
+ /**
25449
+ * Captures this machine still owes the deployment, oldest first.
25450
+ *
25451
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25452
+ * by a time window — see captureRowsStmt for why a window could not express
25453
+ * this. `before` is the grace window that leaves a just-recorded capture to
25454
+ * the live path.
25455
+ */
25456
+ pendingCaptureRows(limit, before) {
25457
+ return allRows(this.captureRowsStmt, { limit, before });
24902
25458
  }
24903
- try {
25459
+ /**
25460
+ * Record that a capture is OWED to the deployment.
25461
+ *
25462
+ * Written by the attached forward path when a live send did not confirm
25463
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25464
+ * a fact rather than an inference: the machine was attached, the send did not
25465
+ * land, so the row is owed — which no time window can state, because the same
25466
+ * window that holds the rows a past attachment left owed also holds every
25467
+ * capture recorded while the machine was DETACHED, and those were never
25468
+ * offered to anyone.
25469
+ *
25470
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25471
+ * out of the drain's read.
25472
+ */
25473
+ markCaptureOwed(id) {
25474
+ this.markOwedStmt.run({ id });
25475
+ }
25476
+ /**
25477
+ * Mark every capture already on disk as owed, as of `before`.
25478
+ *
25479
+ * The consent-time backfill, called once from `aka attach` when a human
25480
+ * grants existing-history consent — never from an ongoing drain pass, and
25481
+ * never inferred from a boundary that could later move. `before` is the
25482
+ * caller's own "now" at the moment consent was granted, so what this marks
25483
+ * is exactly the backlog the consent prompt already counted, not whatever a
25484
+ * later re-attach or key rotation might widen it to.
25485
+ *
25486
+ * Returns how many rows matched, for the caller to log or test against. Not a
25487
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25488
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25489
+ */
25490
+ markCaptureBacklogOwed(before) {
25491
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25492
+ }
25493
+ /**
25494
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25495
+ *
25496
+ * CLEARS any failure reason in the same statement. A row that failed against
25497
+ * one deployment and then landed is delivered, and leaving the reason behind
25498
+ * would leave the store holding two contradictory answers about one row —
25499
+ * with the surface free to render either.
25500
+ */
25501
+ markSynced(ids, atMs) {
25502
+ this.stampAll(ids, atMs, null);
25503
+ }
25504
+ /**
25505
+ * Record that THIS MACHINE cannot express the row on the wire.
25506
+ *
25507
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25508
+ * payload, or a body the client itself refused to send. It fails identically
25509
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25510
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25511
+ * is retried; marking those would turn one outage into permanent data loss.
25512
+ */
25513
+ markSkipped(ids, atMs) {
25514
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25515
+ }
25516
+ /**
25517
+ * Record that THIS DEPLOYMENT refused the row.
25518
+ *
25519
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25520
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25521
+ * row is outstanding rather than why. What separates them is the reason, and
25522
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25523
+ * on one body, so it is terminal only for as long as this machine points at
25524
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25525
+ *
25526
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25527
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25528
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25529
+ */
25530
+ markRefused(ids, atMs) {
25531
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25532
+ }
25533
+ eachInTransaction(ids, run) {
25534
+ if (ids.length === 0) return;
24904
25535
  withTransaction(
24905
- db,
25536
+ this.db,
24906
25537
  () => {
24907
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24908
- if (alreadyDropped) return;
24909
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24910
- akaWarn(
24911
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24912
- );
24913
- return;
24914
- }
24915
- for (const statement of splitStatements(migration.sql)) {
24916
- db.exec(statement);
24917
- }
24918
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24919
- migration.tag,
24920
- Date.now()
24921
- );
25538
+ for (const id of ids) run(id);
25539
+ },
25540
+ "IMMEDIATE"
25541
+ );
25542
+ }
25543
+ stampAll(ids, value, failure, failedAtMs) {
25544
+ if (ids.length === 0) return;
25545
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25546
+ withTransaction(
25547
+ this.db,
25548
+ () => {
25549
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25550
+ },
25551
+ "IMMEDIATE"
25552
+ );
25553
+ }
25554
+ /**
25555
+ * Claim rows as in-flight.
25556
+ *
25557
+ * Advisory in exactly the sense the lease is: it records that a send is in
25558
+ * progress so a surface can say so, and a lost claim costs a row showing as
25559
+ * queued while it is actually being sent. It is not exclusion — the far side
25560
+ * settles a duplicate on the row id.
25561
+ */
25562
+ claimRows(ids, atMs) {
25563
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25564
+ }
25565
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25566
+ releaseRows(ids) {
25567
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25568
+ }
25569
+ /**
25570
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25571
+ *
25572
+ * A process killed between claiming and settling leaves rows claimed with
25573
+ * nothing left to settle them. Without this they read as "sending" for ever.
25574
+ */
25575
+ releaseStaleClaims(staleBefore) {
25576
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25577
+ }
25578
+ /**
25579
+ * Every tracked row in exactly one delivery state.
25580
+ *
25581
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25582
+ * pick up now", which is a different question from "what state is this row
25583
+ * in" — and a machine that has never attached has no boundary to pass, so
25584
+ * requiring one would force a caller to invent one and report the whole store
25585
+ * as queued.
25586
+ */
25587
+ /**
25588
+ * The same partition, one row per kind that a lane carries.
25589
+ *
25590
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25591
+ * scope decides which rows exist at all, so a kind that has never been
25592
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25593
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25594
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25595
+ * different things.
25596
+ */
25597
+ partitionByKind() {
25598
+ return allRows(
25599
+ this.partitionByKindStmt,
25600
+ {}
25601
+ ).map((row) => ({
25602
+ kind: row.kind,
25603
+ queued: row.queued ?? 0,
25604
+ inProgress: row.inProgress ?? 0,
25605
+ synced: row.synced ?? 0,
25606
+ failed: row.failed ?? 0,
25607
+ refused: row.refused ?? 0,
25608
+ detached: row.detached ?? 0,
25609
+ total: row.total ?? 0
25610
+ }));
25611
+ }
25612
+ partition() {
25613
+ const row = getRow(this.partitionStmt, {});
25614
+ return {
25615
+ queued: row?.queued ?? 0,
25616
+ inProgress: row?.inProgress ?? 0,
25617
+ synced: row?.synced ?? 0,
25618
+ failed: row?.failed ?? 0,
25619
+ refused: row?.refused ?? 0,
25620
+ detached: row?.detached ?? 0,
25621
+ total: row?.total ?? 0
25622
+ };
25623
+ }
25624
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25625
+ counts(before) {
25626
+ const row = getRow(this.countsStmt, { before });
25627
+ const captures = getRow(this.captureSkipCountStmt);
25628
+ return {
25629
+ pending: row?.pending ?? 0,
25630
+ sent: row?.sent ?? 0,
25631
+ skipped: row?.skipped ?? 0,
25632
+ refused: row?.refused ?? 0,
25633
+ detached: row?.detached ?? 0,
25634
+ capturesSkipped: captures?.skipped ?? 0
25635
+ };
25636
+ }
25637
+ /**
25638
+ * The deployment the current stamps were made against, and where its backlog
25639
+ * ends.
25640
+ *
25641
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25642
+ * machine that has never drained is — and every writer below seeds the row
25643
+ * before it needs one, so nothing depends on this creating it. Keeping the
25644
+ * write off the gate path matters because the gate runs on every pass while a
25645
+ * write has to take the database's write lock.
25646
+ */
25647
+ deployment() {
25648
+ const row = getRow(
25649
+ this.fingerprintStmt
25650
+ );
25651
+ return {
25652
+ fingerprint: row?.fingerprint ?? void 0,
25653
+ backlogBefore: row?.backlogBefore ?? void 0
25654
+ };
25655
+ }
25656
+ /**
25657
+ * Point the ledger at a different deployment, discarding what it recorded
25658
+ * about the previous one.
25659
+ *
25660
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25661
+ * machine has just left are undelivered as far as the new one is concerned.
25662
+ * All four in one transaction, so a crash between them cannot leave stamps
25663
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25664
+ * a disown with no re-mark to follow it.
25665
+ *
25666
+ * The boundary is written HERE and only here, which is what freezes it: a
25667
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25668
+ * unchanged, so this never runs and the backlog does not widen back over rows
25669
+ * the live path has since delivered.
25670
+ *
25671
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25672
+ * granted existing-history consent for the deployment this call is arming —
25673
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25674
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25675
+ * apart. Passed only when that grant is valid, since this method has no way
25676
+ * to check consent itself and must not mark a row owed for a machine that
25677
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25678
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25679
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25680
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25681
+ * on the cleared side of that bound — and the re-mark in the same
25682
+ * transaction is what puts those rows back. A crash between the two cannot
25683
+ * strand the ledger disowned with nothing re-marked — the transaction either
25684
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25685
+ * committed re-enters this method on the very next pass. Omit it (the
25686
+ * structural-only tests do) to exercise the disown in isolation.
25687
+ *
25688
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25689
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25690
+ * live path can mark a capture owed from the moment `aka attach` writes the
25691
+ * descriptor, before the drain's first pass ever reaches this method, and
25692
+ * such a row sits at or after the bound rather than below it. What keeps the
25693
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25694
+ * bound — disown runs first, re-mark second, both inside the one
25695
+ * transaction above.
25696
+ */
25697
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25698
+ this.ensureRowStmt.run();
25699
+ withTransaction(
25700
+ this.db,
25701
+ () => {
25702
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25703
+ this.rearmStmt.run();
25704
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25705
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25706
+ }
25707
+ if (backfillCapturesBefore !== void 0) {
25708
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25709
+ }
25710
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25711
+ },
25712
+ "IMMEDIATE"
25713
+ );
25714
+ }
25715
+ /**
25716
+ * End the attached period: hand its rows to the live path, and release the
25717
+ * boundary so the next attachment can freeze a new one.
25718
+ *
25719
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25720
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25721
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25722
+ * during the detached period, because the machine is not attached. Rows
25723
+ * recorded in that window sit after the boundary and before the re-attach, so
25724
+ * neither path takes them, and the pending count reports none outstanding.
25725
+ *
25726
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25727
+ * closing attachment's to deliver and are no longer outstanding — that is what
25728
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25729
+ * distinction is not academic: this used to write a delivery TIME, which every
25730
+ * read treats as delivery, so one detach turned a window of undelivered rows
25731
+ * into a window of delivered ones and no surface could tell. It writes the
25732
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25733
+ * "received" stop being the same fact.
25734
+ *
25735
+ * A change of deployment still frees them (see the re-arm), because the next
25736
+ * deployment has seen none of this machine's history — so the rows reach it
25737
+ * exactly as they did when this wrote a delivery time.
25738
+ *
25739
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25740
+ * window unstamped — that half-state would re-send the whole attached period
25741
+ * on the next attach, which is the failure the boundary exists to prevent.
25742
+ */
25743
+ closeAttachedWindow(attachedAtMs, atMs) {
25744
+ this.ensureRowStmt.run();
25745
+ withTransaction(
25746
+ this.db,
25747
+ () => {
25748
+ const row = getRow(this.fingerprintStmt);
25749
+ const from = row?.backlogBefore ?? attachedAtMs;
25750
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25751
+ this.releaseBoundaryStmt.run();
25752
+ },
25753
+ "IMMEDIATE"
25754
+ );
25755
+ }
25756
+ /**
25757
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25758
+ *
25759
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25760
+ * different deployment and therefore discards what was delivered to the old
25761
+ * one: here the recipient is the same, so everything already sent to it stays
25762
+ * sent.
25763
+ */
25764
+ freezeBoundary(backlogBefore) {
25765
+ this.ensureRowStmt.run();
25766
+ this.freezeBoundaryStmt.run({ backlogBefore });
25767
+ }
25768
+ /** Take the claim, or report that someone live already holds it. */
25769
+ claim(pid, host, nowMs, staleAfterMs) {
25770
+ this.ensureRowStmt.run();
25771
+ let taken = false;
25772
+ withTransaction(
25773
+ this.db,
25774
+ () => {
25775
+ const result = this.claimStmt.run({
25776
+ pid,
25777
+ host,
25778
+ now: nowMs,
25779
+ staleBefore: nowMs - staleAfterMs
25780
+ });
25781
+ taken = result.changes === 1;
25782
+ },
25783
+ "IMMEDIATE"
25784
+ );
25785
+ return taken;
25786
+ }
25787
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25788
+ heartbeat(pid, nowMs) {
25789
+ this.heartbeatStmt.run({ now: nowMs, pid });
25790
+ }
25791
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25792
+ release(pid) {
25793
+ this.releaseStmt.run({ pid });
25794
+ }
25795
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25796
+ lease() {
25797
+ return getRow(this.leaseStmt);
25798
+ }
25799
+ };
25800
+
25801
+ // ../../packages/persistence/src/migrations.ts
25802
+ function describeObject(object2) {
25803
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25804
+ }
25805
+ function splitStatements(sql) {
25806
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25807
+ }
25808
+ function createdIndexName(statement) {
25809
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25810
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25811
+ }
25812
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25813
+ function applyMigrations(db, file2, options = {}) {
25814
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25815
+ db.exec(
25816
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25817
+ );
25818
+ const applied = new Set(
25819
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25820
+ );
25821
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25822
+ const record2 = db.prepare(
25823
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25824
+ );
25825
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25826
+ if (applied.has(migration.tag)) continue;
25827
+ if (options.skipTags?.has(migration.tag) === true) continue;
25828
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25829
+ const evidence = evidenceObjects(migration.sql);
25830
+ const present = evidence.filter((o) => evidenceExists(db, o));
25831
+ if (present.length > 0 && present.length < evidence.length) {
25832
+ const missing = evidence.filter((o) => !present.includes(o));
25833
+ const message = `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.`;
25834
+ akaWarn(message);
25835
+ throw new Error(`[aka] ${message}`);
25836
+ }
25837
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25838
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25839
+ const statements = splitStatements(migration.sql);
25840
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25841
+ try {
25842
+ withTransaction(
25843
+ db,
25844
+ () => {
25845
+ for (const statement of statements) {
25846
+ const indexName = createdIndexName(statement);
25847
+ if (indexName === void 0) {
25848
+ if (alreadyApplied) continue;
25849
+ } else if (indexExists(db, indexName)) {
25850
+ continue;
25851
+ }
25852
+ db.exec(statement);
25853
+ }
25854
+ if (wantsFkOff && !alreadyApplied) {
25855
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25856
+ if (violations.length > 0) {
25857
+ throw new Error(
25858
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25859
+ );
25860
+ }
25861
+ }
25862
+ record2.run(migration.tag, Date.now());
25863
+ },
25864
+ "IMMEDIATE"
25865
+ );
25866
+ } finally {
25867
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25868
+ }
25869
+ }
25870
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25871
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25872
+ }
25873
+ ensureSyncedAtColumn(db, "audit_events");
25874
+ ensureScanLedgerTable(db);
25875
+ ensureHistorySyncTable(db);
25876
+ ensureBlockedDetectionsTable(db);
25877
+ ensureRuleProbeCacheTable(db);
25878
+ ensureWriteGateTrigger(db);
25879
+ ensureTokenUsageColumns(db);
25880
+ reconcileSourceProjectIds(db);
25881
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25882
+ const drained = runLegacyHistoryBackfill(db);
25883
+ if (drained) applyLegacyDropMigration(db, file2);
25884
+ }
25885
+ }
25886
+ function readLegacyTables(db) {
25887
+ let holdsRows = false;
25888
+ const marks = [];
25889
+ for (const table of ["events", "findings"]) {
25890
+ try {
25891
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25892
+ if (row === void 0) {
25893
+ holdsRows = true;
25894
+ marks.push(`${table}:unreadable`);
25895
+ continue;
25896
+ }
25897
+ if (row.n > 0) holdsRows = true;
25898
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25899
+ } catch {
25900
+ holdsRows = true;
25901
+ marks.push(`${table}:unreadable`);
25902
+ }
25903
+ }
25904
+ return { holdsRows, mark: marks.join("|") };
25905
+ }
25906
+ function applyLegacyDropMigration(db, file2) {
25907
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25908
+ if (!migration) return;
25909
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25910
+ if (file2 !== void 0 && before?.holdsRows === true) {
25911
+ try {
25912
+ backupBeforeLegacyDrop(db, file2);
25913
+ } catch (error61) {
25914
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25915
+ return;
25916
+ }
25917
+ }
25918
+ try {
25919
+ withTransaction(
25920
+ db,
25921
+ () => {
25922
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25923
+ if (alreadyDropped) return;
25924
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25925
+ akaWarn(
25926
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25927
+ );
25928
+ return;
25929
+ }
25930
+ for (const statement of splitStatements(migration.sql)) {
25931
+ db.exec(statement);
25932
+ }
25933
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25934
+ migration.tag,
25935
+ Date.now()
25936
+ );
24922
25937
  },
24923
25938
  "IMMEDIATE"
24924
25939
  );
@@ -25216,10 +26231,62 @@ function ensureSyncedAtColumn(db, table) {
25216
26231
  if (!columns.includes("outbox_owed")) {
25217
26232
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25218
26233
  }
26234
+ if (!columns.includes("sync_failed_at")) {
26235
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26236
+ }
26237
+ if (!columns.includes("sync_failure")) {
26238
+ withTransaction(
26239
+ db,
26240
+ () => {
26241
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26242
+ db.exec(
26243
+ `UPDATE ${table} SET synced_at = NULL
26244
+ WHERE synced_at = -1
26245
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26246
+ );
26247
+ },
26248
+ "IMMEDIATE"
26249
+ );
26250
+ }
25219
26251
  db.exec(
25220
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25221
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26252
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26253
+ BEFORE UPDATE OF sync_failure ON ${table}
26254
+ WHEN ${syncFailureRejectCondition()}
26255
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25222
26256
  );
26257
+ const syncIndexColumns = [
26258
+ "event_type",
26259
+ "synced_at",
26260
+ "sync_claimed_at",
26261
+ "started_at",
26262
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26263
+ // has to be in the index for the read to stay covered — but putting it
26264
+ // ahead of `started_at` would reorder the prefix the structural drain's
26265
+ // reads match on.
26266
+ "sync_failure"
26267
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26268
+ //
26269
+ // The delivery-state read tests it — a capture's state depends on whether a
26270
+ // live forward marked it owed — so carrying it here makes that read covering
26271
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26272
+ // But a sixth column changes what the planner charges for this index, and
26273
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26274
+ // then stops choosing the per-session index for the token rollup and walks
26275
+ // every `llm_call` in the store through the event-type index instead. That
26276
+ // read grows with the store; this one does not.
26277
+ //
26278
+ // 40 ms on the largest store measured, once per render, is a cost worth
26279
+ // paying to leave every other read's plan where it was.
26280
+ ];
26281
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26282
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26283
+ if (!syncIndexMatches) {
26284
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26285
+ db.exec(
26286
+ `CREATE INDEX idx_audit_events_sync
26287
+ ON audit_events (${syncIndexColumns.join(", ")})`
26288
+ );
26289
+ }
25223
26290
  db.exec(
25224
26291
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25225
26292
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25441,7 +26508,11 @@ function buildAuditEvent(row) {
25441
26508
  link: linkParsed?.success ? linkParsed.data : null,
25442
26509
  targetId: row.target_id,
25443
26510
  internal: intToBool(row.internal),
25444
- flagged: intToBool(row.flagged)
26511
+ flagged: intToBool(row.flagged),
26512
+ // Only meaningful when the title came out empty — a row whose body was
26513
+ // expired but whose title fell back to `tool_name` still has something to
26514
+ // render, and flagging it would make the view apologise for nothing.
26515
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25445
26516
  };
25446
26517
  }
25447
26518
  var TIMELINE_COLUMNS = `
@@ -25449,6 +26520,7 @@ var TIMELINE_COLUMNS = `
25449
26520
  event_type,
25450
26521
  started_at,
25451
26522
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26523
+ content_expired_at,
25452
26524
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25453
26525
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25454
26526
  json_extract(attributes, '$.severity') AS severity,
@@ -25575,7 +26647,8 @@ var SqliteActivityRepository = class {
25575
26647
  SELECT 1 FROM audit_events d
25576
26648
  WHERE d.root_session_id = audit_events.id
25577
26649
  AND (d.content LIKE ? ESCAPE '\\'
25578
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26650
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26651
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25579
26652
  );
25580
26653
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25581
26654
  }
@@ -26113,6 +27186,88 @@ var SqliteAuditEventsRepository = class {
26113
27186
  }
26114
27187
  };
26115
27188
 
27189
+ // ../../packages/persistence/src/repositories/body-retention.ts
27190
+ var DEFAULT_BATCH_SIZE = 500;
27191
+ var DEFAULT_MAX_ROWS = 5e4;
27192
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27193
+ var SqliteBodyRetentionRepository = class {
27194
+ constructor(db) {
27195
+ this.db = db;
27196
+ const select = (laneClause) => `
27197
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27198
+ FROM audit_events
27199
+ WHERE content IS NOT NULL
27200
+ AND started_at < :cutoff
27201
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27202
+ ${laneClause}
27203
+ ORDER BY started_at
27204
+ LIMIT :limit`;
27205
+ this.candidatesStmt = this.db.prepare(select(""));
27206
+ this.candidatesSyncSafeStmt = this.db.prepare(
27207
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27208
+ );
27209
+ this.heldBySyncStmt = this.db.prepare(`
27210
+ SELECT COUNT(*) AS n
27211
+ FROM audit_events
27212
+ WHERE content IS NOT NULL
27213
+ AND started_at < :cutoff
27214
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27215
+ AND synced_at IS NULL`);
27216
+ this.expireStmt = this.db.prepare(
27217
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27218
+ );
27219
+ }
27220
+ db;
27221
+ candidatesStmt;
27222
+ candidatesSyncSafeStmt;
27223
+ heldBySyncStmt;
27224
+ expireStmt;
27225
+ /** How many bytes a pass with these options would free, changing nothing. */
27226
+ preview(opts) {
27227
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27228
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27229
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27230
+ return {
27231
+ rowsExpired: rows.length,
27232
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27233
+ rowsHeldBySync: this.countHeldBySync(opts)
27234
+ };
27235
+ }
27236
+ /** Clear eligible bodies, in bounded batches. */
27237
+ expire(opts) {
27238
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27239
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27240
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27241
+ let rowsExpired = 0;
27242
+ let bytesFreed = 0;
27243
+ let done = true;
27244
+ while (rowsExpired < maxRows) {
27245
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27246
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27247
+ if (batch.length === 0) break;
27248
+ withTransaction(
27249
+ this.db,
27250
+ () => {
27251
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27252
+ },
27253
+ "IMMEDIATE"
27254
+ );
27255
+ rowsExpired += batch.length;
27256
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27257
+ if (batch.length < remaining) break;
27258
+ if (rowsExpired >= maxRows) {
27259
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27260
+ }
27261
+ }
27262
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27263
+ }
27264
+ countHeldBySync(opts) {
27265
+ if (opts.sweepSyncLane) return 0;
27266
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27267
+ return row.n;
27268
+ }
27269
+ };
27270
+
26116
27271
  // ../../packages/persistence/src/repositories/classified-data.ts
26117
27272
  var SqliteClassifiedDataRepository = class {
26118
27273
  constructor(db) {
@@ -26913,23 +28068,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26913
28068
  )`;
26914
28069
 
26915
28070
  // ../../packages/persistence/src/repositories/findings.ts
26916
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26917
- var DEFAULT_LOCATIONS_LIMIT = 100;
26918
- var LOCATION_RULE_IDS_CAP = 20;
26919
- function compareLocationOrder(a, b) {
26920
- return compareFindingGroupOrder(
26921
- {
26922
- severity: a.maxSeverity,
26923
- latestDetectedAt: a.latestDetectedAt,
26924
- id: ""
26925
- },
26926
- {
26927
- severity: b.maxSeverity,
26928
- latestDetectedAt: b.latestDetectedAt,
26929
- id: ""
26930
- }
26931
- );
26932
- }
26933
28071
  var CONCAT_SEP = ",";
26934
28072
  var TUPLE_SEP = "|";
26935
28073
  function splitConcat(value) {
@@ -26958,7 +28096,15 @@ function toFlatFindingRow(r) {
26958
28096
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26959
28097
  eventId: r.event_id,
26960
28098
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26961
- status: deriveInstanceStatus(r)
28099
+ status: deriveInstanceStatus(r),
28100
+ delivery: deriveFindingDelivery({
28101
+ kind: r.kind,
28102
+ syncedAt: r.synced_at,
28103
+ syncClaimedAt: r.sync_claimed_at,
28104
+ syncFailedAt: r.sync_failed_at,
28105
+ syncFailure: r.sync_failure,
28106
+ outboxOwed: r.outbox_owed
28107
+ })
26962
28108
  };
26963
28109
  }
26964
28110
  function encodeGroupCursor(group) {
@@ -26981,13 +28127,51 @@ function decodeGroupCursor(cursor) {
26981
28127
  return null;
26982
28128
  }
26983
28129
  function firstAfter(sorted, cursor) {
26984
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28130
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26985
28131
  return index === -1 ? sorted.length : index;
26986
28132
  }
26987
28133
  function findDeepLinked(sorted, page, id) {
26988
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26989
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28134
+ if (page.some((t) => t.id === id)) return void 0;
28135
+ return sorted.find((t) => t.id === id);
28136
+ }
28137
+ function encodeLocationCursor(location) {
28138
+ const payload = {
28139
+ sev: location.maxSeverity,
28140
+ t: location.latestDetectedAt,
28141
+ r: location.repo,
28142
+ f: location.file
28143
+ };
28144
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28145
+ }
28146
+ function decodeLocationCursor(cursor) {
28147
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28148
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28149
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28150
+ }
28151
+ return null;
28152
+ }
28153
+ function firstLocationAfter(sorted, cursor) {
28154
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28155
+ return index === -1 ? sorted.length : index;
28156
+ }
28157
+ function findDeepLinkedLocation(sorted, page, id) {
28158
+ if (page.some((l) => l.id === id)) return void 0;
28159
+ return sorted.find((l) => l.id === id);
26990
28160
  }
28161
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28162
+ d.severity AS severity, f.masked_match AS masked_match,
28163
+ f.action_taken AS action_taken, f.confidence AS confidence,
28164
+ e.started_at AS occurred_at,
28165
+ e.source_tool AS source_tool,
28166
+ e.repo AS repo,
28167
+ e.file_path AS file,
28168
+ e.tool_name AS tool_name,
28169
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28170
+ e.event_type AS kind, f.finding_key AS finding_key,
28171
+ ${latestResolutionStatusSql("f")} AS latest_status,
28172
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28173
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28174
+ e.outbox_owed AS outbox_owed`;
26991
28175
  var DAY_MS3 = 864e5;
26992
28176
  var SqliteFindingsRepository = class {
26993
28177
  constructor(db) {
@@ -27108,30 +28292,26 @@ var SqliteFindingsRepository = class {
27108
28292
  );
27109
28293
  }
27110
28294
  /**
27111
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27112
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27113
- * attributes bag, rule_id/category/severity from the definition), scoped to
27114
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27115
- * rows this list must never surface), groups by ruleId, computes
27116
- * per-filter-excluded facets, applies the requested filters, and sorts by
27117
- * severity then recency. Filtering
27118
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27119
- * reflect the full filtered set; `items` is the requested
27120
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27121
- * filter, `totals.findings` counts only instances whose derived status was
27122
- * requested, and each item's instance preview is narrowed the same way.
28295
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28296
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28297
+ * list must never surface), with per-filter-excluded facets, the requested
28298
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28299
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28300
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28301
+ * Under a `status` filter, `totals.findings` counts only findings whose
28302
+ * derived status was requested.
28303
+ *
28304
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28305
+ * folding EVERY finding into the numbers a type row and the filters need
28306
+ * (count, severity, category, providers, actions, statuses, latest, search
28307
+ * text). The findings OF a type come from listFindingInstances scoped to
28308
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27123
28309
  *
27124
- * Two reads, neither of which materializes a row per finding:
27125
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27126
- * the group and the filters need (count, providers, actions, statuses,
27127
- * latest, search text);
27128
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27129
- * populate `instances` for the table's expanded rows.
27130
28310
  * The aggregates carry raw DB values and are translated by the same
27131
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27132
- * rule is ever restated in SQL.
28311
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28312
+ * status rule is ever restated in SQL.
27133
28313
  */
27134
- listGroupedFindings(query) {
28314
+ listFindingTypes(query) {
27135
28315
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27136
28316
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27137
28317
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27144,12 +28324,7 @@ var SqliteFindingsRepository = class {
27144
28324
  predicate,
27145
28325
  params: sessionParams
27146
28326
  });
27147
- const rows = this.previewRows(aggregates, {
27148
- sessionId: query.sessionId,
27149
- from: query.from
27150
- });
27151
- const groupable = rows.map(toFlatFindingRow);
27152
- const allGroups = buildFindingGroups(groupable, { aggregates });
28327
+ const allTypes = buildFindingTypes(aggregates);
27153
28328
  const filterOpts = {
27154
28329
  severity: query.severity,
27155
28330
  providers: query.provider,
@@ -27158,30 +28333,25 @@ var SqliteFindingsRepository = class {
27158
28333
  subtype: query.subtype,
27159
28334
  q: query.q
27160
28335
  };
27161
- const facets = computeFindingFacets(allGroups, filterOpts);
27162
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28336
+ const facets = computeFindingFacets(allTypes, filterOpts);
28337
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27163
28338
  const statusFilter = query.status ?? [];
27164
28339
  const totals = {
27165
- findings: sorted.reduce((acc, g) => {
27166
- if (statusFilter.length === 0) return acc + g.instanceCount;
27167
- const agg = aggregates.get(g.id);
27168
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28340
+ findings: sorted.reduce((acc, t) => {
28341
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28342
+ const agg = aggregates.get(t.id);
28343
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27169
28344
  }, 0),
27170
- groups: sorted.length
28345
+ types: sorted.length
27171
28346
  };
27172
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28347
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27173
28348
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27174
28349
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27175
28350
  const page = sorted.slice(start, start + limit);
27176
28351
  const lastOnPage = page.at(-1);
27177
28352
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27178
28353
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27179
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27180
- const narrow = (g) => statusSet ? {
27181
- ...g,
27182
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27183
- } : g;
27184
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28354
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27185
28355
  return Promise.resolve({
27186
28356
  totals,
27187
28357
  facets,
@@ -27192,7 +28362,7 @@ var SqliteFindingsRepository = class {
27192
28362
  }
27193
28363
  /**
27194
28364
  * One row per rule_id, folding EVERY instance of the group into the values
27195
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28365
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27196
28366
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27197
28367
  *
27198
28368
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27246,6 +28416,7 @@ var SqliteFindingsRepository = class {
27246
28416
  providers: query.provider,
27247
28417
  actions: query.action,
27248
28418
  statuses: query.status,
28419
+ deliveries: query.deployment,
27249
28420
  tools: query.tool,
27250
28421
  repo: query.repo,
27251
28422
  file: query.file,
@@ -27286,13 +28457,25 @@ var SqliteFindingsRepository = class {
27286
28457
  });
27287
28458
  }
27288
28459
  /**
27289
- * The same findings folded by location: repository, then file within it.
28460
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27290
28461
  *
27291
28462
  * The grouping keys come from the capturing event's attributes, which is what
27292
- * the local store relates a finding to — there is no finding↔asset row to
27293
- * group by instead. A repo or file the event did not record folds into the
27294
- * empty-string bucket, which the view renders but does not link, since no
27295
- * filter can name it.
28463
+ * the local store relates a finding to; there is no finding↔asset row to group
28464
+ * by instead. A repo or file the event did not record folds into the
28465
+ * empty-string bucket, which is a real location like any other: it is listed,
28466
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28467
+ *
28468
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28469
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28470
+ * list was rebuilt to remove — and two-level pagination inside an
28471
+ * expand/collapse table is what pushed that view to master/detail in the first
28472
+ * place.
28473
+ *
28474
+ * Every filter narrows the FINDINGS and the locations fall out of what
28475
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28476
+ * reports for the same filters scoped to that pair. The view depends on it:
28477
+ * one toolbar sits over both panels precisely because a location owns none of
28478
+ * its fields.
27296
28479
  */
27297
28480
  listFindingLocations(query) {
27298
28481
  const opts = {
@@ -27301,16 +28484,20 @@ var SqliteFindingsRepository = class {
27301
28484
  providers: query.provider,
27302
28485
  actions: query.action,
27303
28486
  statuses: query.status,
28487
+ deliveries: query.deployment,
27304
28488
  tools: query.tool,
27305
28489
  q: query.q
27306
28490
  };
27307
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28491
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28492
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27308
28493
  const byRepo = /* @__PURE__ */ new Map();
28494
+ const accumulator = createInstanceFacetAccumulator(opts);
27309
28495
  let total = 0;
27310
28496
  for (const row of this.scanFindingRows({
27311
28497
  sessionId: query.sessionId,
27312
28498
  from: query.from
27313
28499
  })) {
28500
+ accumulator.add(row);
27314
28501
  if (!matchesInstanceFilters(row, opts)) continue;
27315
28502
  total += 1;
27316
28503
  let files = byRepo.get(row.repo);
@@ -27325,103 +28512,35 @@ var SqliteFindingsRepository = class {
27325
28512
  }
27326
28513
  addToLocation(acc, row);
27327
28514
  }
27328
- let fileCount = 0;
27329
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27330
- fileCount += files.size;
27331
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27332
- file: file2,
27333
- instanceCount: acc.instanceCount,
27334
- maxSeverity: acc.maxSeverity,
27335
- latestDetectedAt: acc.latestDetectedAt,
27336
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27337
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27338
- })).sort(compareLocationOrder);
27339
- const rollup = fileRows.reduce(
27340
- (a, f) => ({
27341
- instanceCount: a.instanceCount + f.instanceCount,
27342
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27343
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27344
- }),
27345
- {
27346
- instanceCount: 0,
27347
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27348
- latestDetectedAt: ""
27349
- }
27350
- );
27351
- const statuses = fileRows.map((f) => f.status);
27352
- const folded = foldGroupStatus(statuses);
27353
- return {
27354
- repo,
27355
- instanceCount: rollup.instanceCount,
27356
- maxSeverity: rollup.maxSeverity,
27357
- latestDetectedAt: rollup.latestDetectedAt,
27358
- ...folded === void 0 ? {} : { status: folded },
27359
- files: fileRows
27360
- };
27361
- });
27362
- repos.sort(compareLocationOrder);
28515
+ const sorted = [];
28516
+ for (const [repo, files] of byRepo) {
28517
+ for (const [file2, acc] of files) {
28518
+ const status = foldGroupStatus(acc.statuses);
28519
+ sorted.push({
28520
+ id: encodeLocationId(repo, file2),
28521
+ repo,
28522
+ file: file2,
28523
+ instanceCount: acc.instanceCount,
28524
+ maxSeverity: acc.maxSeverity,
28525
+ latestDetectedAt: acc.latestDetectedAt,
28526
+ ...status === void 0 ? {} : { status },
28527
+ ruleIds: [...acc.ruleIds]
28528
+ });
28529
+ }
28530
+ }
28531
+ sorted.sort(compareLocationOrder);
28532
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28533
+ const page = sorted.slice(start, start + limit);
28534
+ const lastOnPage = page.at(-1);
28535
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28536
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27363
28537
  return Promise.resolve({
27364
- totals: { findings: total, repos: repos.length, files: fileCount },
27365
- items: repos.slice(0, limit),
27366
- hasMore: repos.length > limit
28538
+ totals: { findings: total, locations: sorted.length },
28539
+ facets: accumulator.facets(),
28540
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28541
+ nextCursor
27367
28542
  });
27368
28543
  }
27369
- /**
27370
- * Each group's newest instances, for the table's expanded rows.
27371
- *
27372
- * ONE index-ordered scan with early termination, and the shape is the point.
27373
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27374
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27375
- * through a temp B-tree to keep a bounded preview of each group, and then
27376
- * sorts the survivors again for the page order. Both sorts grow with the
27377
- * store while the answer does not.
27378
- *
27379
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27380
- * (or the session or window index the scope names — see `findingScanSql`),
27381
- * which is already the order the page wants, and keeps rows per rule until
27382
- * each rule has as many as it can show. The aggregate the caller already holds
27383
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27384
- * per rule, summed, is the number of rows this scan has to find, and it stops
27385
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27386
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27387
- * store with many firing rules widens it. The bound that DOES hold
27388
- * unconditionally is the sorted form's floor: this scan visits at most as
27389
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27390
- * sorted, and stops the moment every rule has its cap, where the sorted form
27391
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27392
- * wanted instances sitting at the tail of the scope — is one pass over
27393
- * everything in scope with a block sort of the id tie-break only, never a
27394
- * sort of the scope, which is still that floor.
27395
- *
27396
- * A row whose rule the aggregate did not see is skipped: the two statements
27397
- * run without a shared snapshot, so a capture landing between them can add a
27398
- * rule here that has no counts there, and the counts are what the group is
27399
- * built from.
27400
- */
27401
- previewRows(aggregates, scope) {
27402
- const wanted = /* @__PURE__ */ new Map();
27403
- let remaining = 0;
27404
- for (const [ruleId, agg] of aggregates) {
27405
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27406
- wanted.set(ruleId, n);
27407
- remaining += n;
27408
- }
27409
- const rows = [];
27410
- if (remaining === 0) return rows;
27411
- const { sql, params } = this.findingScanSql(scope);
27412
- const taken = /* @__PURE__ */ new Map();
27413
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27414
- const want = wanted.get(r.rule_id);
27415
- if (want === void 0) continue;
27416
- const have = taken.get(r.rule_id) ?? 0;
27417
- if (have >= want) continue;
27418
- taken.set(r.rule_id, have + 1);
27419
- rows.push(r);
27420
- remaining -= 1;
27421
- if (remaining === 0) break;
27422
- }
27423
- return rows;
27424
- }
27425
28544
  /**
27426
28545
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27427
28546
  *
@@ -27448,6 +28567,33 @@ var SqliteFindingsRepository = class {
27448
28567
  yield toFlatFindingRow(r);
27449
28568
  }
27450
28569
  }
28570
+ /**
28571
+ * One finding by its own id, or null when no such row exists.
28572
+ *
28573
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28574
+ * the store — and, unlike anything derived from a list page, it resolves a
28575
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28576
+ * deep link needs: the id it carries may name a finding thousands of rows
28577
+ * older than anything a first page holds.
28578
+ *
28579
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28580
+ * RESOLVES an id; whether that row would survive the list's current filters is
28581
+ * a different question, and hiding the target because a filter excludes it is
28582
+ * worse than showing it.
28583
+ *
28584
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28585
+ * type should the list select?" and "what does the drawer show?".
28586
+ */
28587
+ findingInstance(id) {
28588
+ const row = this.db.prepare(
28589
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28590
+ FROM inspection_findings f
28591
+ JOIN audit_events e ON e.id = f.audit_event_id
28592
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28593
+ WHERE f.id = ?`
28594
+ ).get(id);
28595
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28596
+ }
27451
28597
  /**
27452
28598
  * The one statement both instance-level scans run: every finding in scope,
27453
28599
  * joined to its event and definition, newest first.
@@ -27481,17 +28627,7 @@ var SqliteFindingsRepository = class {
27481
28627
  conditions.push("e.started_at >= ?");
27482
28628
  params.push(isoToEpochMillis(scope.from));
27483
28629
  }
27484
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27485
- d.severity AS severity, f.masked_match AS masked_match,
27486
- f.action_taken AS action_taken, f.confidence AS confidence,
27487
- e.started_at AS occurred_at,
27488
- e.source_tool AS source_tool,
27489
- e.repo AS repo,
27490
- e.file_path AS file,
27491
- e.tool_name AS tool_name,
27492
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27493
- e.event_type AS kind, f.finding_key AS finding_key,
27494
- ${latestResolutionStatusSql("f")} AS latest_status
28630
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27495
28631
  FROM audit_events e
27496
28632
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27497
28633
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27505,6 +28641,26 @@ var SqliteFindingsRepository = class {
27505
28641
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27506
28642
  const rows = this.db.prepare(
27507
28643
  `SELECT rule_id,
28644
+ -- BARE columns beside max(latest_at), which is deliberate and
28645
+ -- is SQLite's documented behaviour: with a single min()/max()
28646
+ -- in an aggregate query, every bare column takes its value from
28647
+ -- the row that produced the extremum. So these are the severity
28648
+ -- and category of the definition whose finding is NEWEST, which
28649
+ -- is what the row-based build they replaced read off its first
28650
+ -- (newest-first) row.
28651
+ --
28652
+ -- min() is WRONG here and was the defect: inspection_definitions
28653
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28654
+ -- mints a new row), so a rule whose severity moved between
28655
+ -- versions has several, and min() picks the ALPHABETICALLY
28656
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28657
+ -- That is arbitrary in direction, and it feeds the badge, the
28658
+ -- filter, the facet counts and the primary sort key.
28659
+ --
28660
+ -- Adding a second min()/max() aggregate here would make these
28661
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28662
+ severity,
28663
+ category,
27508
28664
  sum(tuple_count) AS instance_count,
27509
28665
  max(latest_at) AS latest_at,
27510
28666
  group_concat(source_tools) AS source_tools,
@@ -27515,6 +28671,14 @@ var SqliteFindingsRepository = class {
27515
28671
  group_concat(tool_names) AS tool_names
27516
28672
  FROM (
27517
28673
  SELECT d.rule_id AS rule_id,
28674
+ -- Severity and category are columns of the DEFINITION, and
28675
+ -- a rule can have SEVERAL definitions (one per version), so
28676
+ -- these are grouped on below and resolved to the newest
28677
+ -- firing version by the outer query's bare-column select.
28678
+ -- They ride the aggregate because the type build has no rows
28679
+ -- to read them off \u2014 see buildFindingTypes.
28680
+ d.severity AS severity,
28681
+ d.category AS category,
27518
28682
  e.event_type || '${TUPLE_SEP}' ||
27519
28683
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27520
28684
  coalesce(latest.status, '') AS status_tuple,
@@ -27529,7 +28693,7 @@ var SqliteFindingsRepository = class {
27529
28693
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27530
28694
  ON latest.finding_key = f.finding_key
27531
28695
  ${scope.predicate}
27532
- GROUP BY d.rule_id, status_tuple
28696
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27533
28697
  )
27534
28698
  GROUP BY rule_id`
27535
28699
  ).all(scope.params);
@@ -27538,6 +28702,8 @@ var SqliteFindingsRepository = class {
27538
28702
  r.rule_id,
27539
28703
  {
27540
28704
  instanceCount: r.instance_count,
28705
+ severity: r.severity,
28706
+ category: r.category,
27541
28707
  sourceTools: splitConcat(r.source_tools),
27542
28708
  actionsTaken: splitConcat(r.actions_taken),
27543
28709
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27554,7 +28720,7 @@ var SqliteFindingsRepository = class {
27554
28720
  latestDetectedAt: epochMillisToIso(r.latest_at),
27555
28721
  // Free text only — joined and substring-matched, so group_concat's
27556
28722
  // commas need no unpicking (a repo/path containing one still matches).
27557
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28723
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27558
28724
  // tell "no q this request" from "a group with no repo/file at all"
27559
28725
  // and skip priming a haystack nothing will read.
27560
28726
  ...withSearchText ? {
@@ -27582,7 +28748,9 @@ var SqliteFindingsRepository = class {
27582
28748
  )
27583
28749
  );
27584
28750
  for (const row of grouped) {
27585
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28751
+ if (Object.hasOwn(byAction, row.action_taken)) {
28752
+ byAction[row.action_taken] = row.c;
28753
+ }
27586
28754
  }
27587
28755
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27588
28756
  const sevRows = allRows(
@@ -27599,7 +28767,9 @@ var SqliteFindingsRepository = class {
27599
28767
  )
27600
28768
  );
27601
28769
  for (const row of sevRows) {
27602
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28770
+ if (Object.hasOwn(bySeverity, row.severity)) {
28771
+ bySeverity[row.severity] = row.c;
28772
+ }
27603
28773
  }
27604
28774
  const categories = ENFORCEABLE_CATEGORIES;
27605
28775
  const enabledRows = allRows(
@@ -27648,469 +28818,6 @@ function isoDay(ms) {
27648
28818
  return new Date(ms).toISOString().slice(0, 10);
27649
28819
  }
27650
28820
 
27651
- // ../../packages/persistence/src/repositories/history-sync.ts
27652
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27653
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27654
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27655
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27656
- var SKIPPED = -1;
27657
- var ROW_COLUMNS = `id,
27658
- parent_id AS parentId,
27659
- root_session_id AS rootSessionId,
27660
- event_type AS eventType,
27661
- host_id AS hostId,
27662
- harness_id AS harnessId,
27663
- source_project_id AS sourceProjectId,
27664
- started_at AS startedAt,
27665
- ended_at AS endedAt,
27666
- severity,
27667
- priority,
27668
- content,
27669
- content_hash AS contentHash,
27670
- attributes`;
27671
- var SqliteHistorySyncRepository = class {
27672
- constructor(db) {
27673
- this.db = db;
27674
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27675
- this.sessionsStmt = db.prepare(
27676
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27677
- FROM audit_events
27678
- WHERE synced_at IS NULL
27679
- AND event_type IN (${TYPE_LIST})
27680
- AND started_at < :before
27681
- GROUP BY sessionId
27682
- ORDER BY earliest
27683
- LIMIT :limit`
27684
- );
27685
- this.rowsStmt = db.prepare(
27686
- `SELECT ${ROW_COLUMNS}
27687
- FROM audit_events
27688
- WHERE synced_at IS NULL
27689
- AND event_type IN (${TYPE_LIST})
27690
- AND started_at < :before
27691
- AND COALESCE(root_session_id, id) = :sessionId
27692
- ORDER BY (event_type = 'session') DESC, started_at
27693
- LIMIT :limit`
27694
- );
27695
- this.captureRowsStmt = db.prepare(
27696
- `SELECT ${ROW_COLUMNS}
27697
- FROM audit_events
27698
- WHERE synced_at IS NULL
27699
- AND sync_claimed_at IS NULL
27700
- AND outbox_owed = 1
27701
- AND event_type IN (${CAPTURE_TYPE_LIST})
27702
- AND started_at < :before
27703
- ORDER BY started_at
27704
- LIMIT :limit`
27705
- );
27706
- this.markOwedStmt = db.prepare(
27707
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27708
- );
27709
- this.stampStmt = db.prepare(
27710
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27711
- );
27712
- this.claimRowStmt = db.prepare(
27713
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27714
- );
27715
- this.releaseRowStmt = db.prepare(
27716
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27717
- );
27718
- this.releaseStaleClaimsStmt = db.prepare(
27719
- `UPDATE audit_events SET sync_claimed_at = NULL
27720
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27721
- );
27722
- this.partitionStmt = db.prepare(
27723
- `SELECT
27724
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27725
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27726
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27727
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27728
- COUNT(*) AS total
27729
- FROM audit_events
27730
- WHERE event_type IN (${TYPE_LIST})`
27731
- );
27732
- this.countsStmt = db.prepare(
27733
- `SELECT
27734
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27735
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27736
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27737
- FROM audit_events
27738
- WHERE event_type IN (${TYPE_LIST})`
27739
- );
27740
- this.captureSkipCountStmt = db.prepare(
27741
- `SELECT COUNT(*) AS skipped
27742
- FROM audit_events
27743
- WHERE synced_at = ${String(SKIPPED)}
27744
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27745
- );
27746
- this.fingerprintStmt = db.prepare(
27747
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27748
- FROM history_sync WHERE id = 1`
27749
- );
27750
- this.setFingerprintStmt = db.prepare(
27751
- `UPDATE history_sync
27752
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27753
- WHERE id = 1`
27754
- );
27755
- this.disownCapturesStmt = db.prepare(
27756
- `UPDATE audit_events SET outbox_owed = NULL
27757
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27758
- );
27759
- this.rearmStmt = db.prepare(
27760
- `UPDATE audit_events SET synced_at = NULL
27761
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27762
- );
27763
- this.claimStmt = db.prepare(
27764
- `UPDATE history_sync
27765
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27766
- WHERE id = 1
27767
- AND (owner_pid IS NULL
27768
- OR heartbeat_at IS NULL
27769
- OR heartbeat_at < :staleBefore
27770
- OR heartbeat_at > :now)`
27771
- );
27772
- this.heartbeatStmt = db.prepare(
27773
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27774
- );
27775
- this.releaseStmt = db.prepare(
27776
- `UPDATE history_sync
27777
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27778
- WHERE id = 1 AND owner_pid = :pid`
27779
- );
27780
- this.closeWindowStmt = db.prepare(
27781
- `UPDATE audit_events SET synced_at = :at
27782
- WHERE synced_at IS NULL
27783
- AND event_type IN (${TYPE_LIST})
27784
- AND started_at >= :attachedAt`
27785
- );
27786
- this.releaseBoundaryStmt = db.prepare(
27787
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27788
- );
27789
- this.freezeBoundaryStmt = db.prepare(
27790
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27791
- );
27792
- this.leaseStmt = db.prepare(
27793
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27794
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27795
- FROM history_sync WHERE id = 1`
27796
- );
27797
- this.inspectionsStmt = db.prepare(
27798
- `SELECT d.rule_id AS ruleId,
27799
- d.name AS ruleName,
27800
- d.version AS ruleVersion,
27801
- d.category AS category,
27802
- d.severity AS severity,
27803
- f.span_start AS spanStart,
27804
- f.span_end AS spanEnd,
27805
- f.masked_match AS maskedMatch,
27806
- f.action_taken AS actionTaken,
27807
- f.confidence AS confidence
27808
- FROM inspection_findings f
27809
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27810
- WHERE f.audit_event_id = :auditEventId
27811
- ORDER BY f.span_start, f.id`
27812
- );
27813
- }
27814
- db;
27815
- ensureRowStmt;
27816
- sessionsStmt;
27817
- rowsStmt;
27818
- stampStmt;
27819
- countsStmt;
27820
- fingerprintStmt;
27821
- setFingerprintStmt;
27822
- rearmStmt;
27823
- claimStmt;
27824
- heartbeatStmt;
27825
- releaseStmt;
27826
- leaseStmt;
27827
- inspectionsStmt;
27828
- closeWindowStmt;
27829
- releaseBoundaryStmt;
27830
- freezeBoundaryStmt;
27831
- captureRowsStmt;
27832
- markOwedStmt;
27833
- captureSkipCountStmt;
27834
- disownCapturesStmt;
27835
- partitionStmt;
27836
- claimRowStmt;
27837
- releaseRowStmt;
27838
- releaseStaleClaimsStmt;
27839
- /**
27840
- * The masked detections recorded against one tool call.
27841
- *
27842
- * These travel with the event because a tool call's target is not
27843
- * re-inspectable from the event alone — unlike a capture, where the text
27844
- * itself is re-scannable. What crosses is the masked match and the rule that
27845
- * produced it, never the value.
27846
- */
27847
- inspectionsFor(auditEventId) {
27848
- return allRows(this.inspectionsStmt, { auditEventId });
27849
- }
27850
- /**
27851
- * Sessions with structural rows still to send, oldest first.
27852
- *
27853
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27854
- * read. Anything recorded after the machine attached is the live forward
27855
- * path's to deliver; this drain exists for what was recorded before it, and a
27856
- * row both paths send is at best a duplicate request and at worst — for a
27857
- * session root — an overwrite of the inventory ids the live path resolved.
27858
- */
27859
- pendingSessions(limit, before) {
27860
- return allRows(this.sessionsStmt, { limit, before }).map(
27861
- (r) => r.sessionId
27862
- );
27863
- }
27864
- /** One session's undelivered structural rows within the backlog, root first. */
27865
- pendingRows(sessionId, limit, before) {
27866
- return allRows(this.rowsStmt, { sessionId, limit, before });
27867
- }
27868
- /**
27869
- * Captures this machine still owes the deployment, oldest first.
27870
- *
27871
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27872
- * by a time window — see captureRowsStmt for why a window could not express
27873
- * this. `before` is the grace window that leaves a just-recorded capture to
27874
- * the live path.
27875
- */
27876
- pendingCaptureRows(limit, before) {
27877
- return allRows(this.captureRowsStmt, { limit, before });
27878
- }
27879
- /**
27880
- * Record that a capture is OWED to the deployment.
27881
- *
27882
- * Written by the attached forward path when a live send did not confirm
27883
- * delivery, and read by the drain as the whole of its eligibility test. It is
27884
- * a fact rather than an inference: the machine was attached, the send did not
27885
- * land, so the row is owed — which no time window can state, because the same
27886
- * window that holds the rows a past attachment left owed also holds every
27887
- * capture recorded while the machine was DETACHED, and those were never
27888
- * offered to anyone.
27889
- *
27890
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27891
- * out of the drain's read.
27892
- */
27893
- markCaptureOwed(id) {
27894
- this.markOwedStmt.run({ id });
27895
- }
27896
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27897
- markSynced(ids, atMs) {
27898
- this.stampAll(ids, atMs);
27899
- }
27900
- /**
27901
- * Record that a row will never be sent.
27902
- *
27903
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27904
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27905
- * is retried; marking those would turn one outage into permanent data loss.
27906
- */
27907
- markSkipped(ids) {
27908
- this.stampAll(ids, SKIPPED);
27909
- }
27910
- eachInTransaction(ids, run) {
27911
- if (ids.length === 0) return;
27912
- withTransaction(
27913
- this.db,
27914
- () => {
27915
- for (const id of ids) run(id);
27916
- },
27917
- "IMMEDIATE"
27918
- );
27919
- }
27920
- stampAll(ids, value) {
27921
- if (ids.length === 0) return;
27922
- withTransaction(
27923
- this.db,
27924
- () => {
27925
- for (const id of ids) this.stampStmt.run({ at: value, id });
27926
- },
27927
- "IMMEDIATE"
27928
- );
27929
- }
27930
- /**
27931
- * Claim rows as in-flight.
27932
- *
27933
- * Advisory in exactly the sense the lease is: it records that a send is in
27934
- * progress so a surface can say so, and a lost claim costs a row showing as
27935
- * queued while it is actually being sent. It is not exclusion — the far side
27936
- * settles a duplicate on the row id.
27937
- */
27938
- claimRows(ids, atMs) {
27939
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27940
- }
27941
- /** Give back a claim without settling — the send failed, the row is queued again. */
27942
- releaseRows(ids) {
27943
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27944
- }
27945
- /**
27946
- * Clear claims older than `staleBefore`, and report how many were cleared.
27947
- *
27948
- * A process killed between claiming and settling leaves rows claimed with
27949
- * nothing left to settle them. Without this they read as "sending" for ever.
27950
- */
27951
- releaseStaleClaims(staleBefore) {
27952
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27953
- }
27954
- /**
27955
- * Every tracked row in exactly one delivery state.
27956
- *
27957
- * Takes no boundary on purpose. The boundary answers "what should the drain
27958
- * pick up now", which is a different question from "what state is this row
27959
- * in" — and a machine that has never attached has no boundary to pass, so
27960
- * requiring one would force a caller to invent one and report the whole store
27961
- * as queued.
27962
- */
27963
- partition() {
27964
- const row = getRow(this.partitionStmt, {});
27965
- return {
27966
- queued: row?.queued ?? 0,
27967
- inProgress: row?.inProgress ?? 0,
27968
- synced: row?.synced ?? 0,
27969
- failed: row?.failed ?? 0,
27970
- total: row?.total ?? 0
27971
- };
27972
- }
27973
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27974
- counts(before) {
27975
- const row = getRow(
27976
- this.countsStmt,
27977
- { before }
27978
- );
27979
- const captures = getRow(this.captureSkipCountStmt);
27980
- return {
27981
- pending: row?.pending ?? 0,
27982
- sent: row?.sent ?? 0,
27983
- skipped: row?.skipped ?? 0,
27984
- capturesSkipped: captures?.skipped ?? 0
27985
- };
27986
- }
27987
- /**
27988
- * The deployment the current stamps were made against, and where its backlog
27989
- * ends.
27990
- *
27991
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27992
- * machine that has never drained is — and every writer below seeds the row
27993
- * before it needs one, so nothing depends on this creating it. Keeping the
27994
- * write off the gate path matters because the gate runs on every pass while a
27995
- * write has to take the database's write lock.
27996
- */
27997
- deployment() {
27998
- const row = getRow(
27999
- this.fingerprintStmt
28000
- );
28001
- return {
28002
- fingerprint: row?.fingerprint ?? void 0,
28003
- backlogBefore: row?.backlogBefore ?? void 0
28004
- };
28005
- }
28006
- /**
28007
- * Point the ledger at a different deployment, discarding what it recorded
28008
- * about the previous one.
28009
- *
28010
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28011
- * machine has just left are undelivered as far as the new one is concerned.
28012
- * All three in one transaction, so a crash between them cannot leave stamps
28013
- * attributed to the wrong deployment, or a boundary that belongs to another.
28014
- *
28015
- * The boundary is written HERE and only here, which is what freezes it: a
28016
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28017
- * unchanged, so this never runs and the backlog does not widen back over rows
28018
- * the live path has since delivered.
28019
- */
28020
- rearmFor(fingerprint, backlogBefore) {
28021
- this.ensureRowStmt.run();
28022
- withTransaction(
28023
- this.db,
28024
- () => {
28025
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28026
- this.rearmStmt.run();
28027
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28028
- this.disownCapturesStmt.run();
28029
- }
28030
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28031
- },
28032
- "IMMEDIATE"
28033
- );
28034
- }
28035
- /**
28036
- * End the attached period: hand its rows to the live path, and release the
28037
- * boundary so the next attachment can freeze a new one.
28038
- *
28039
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28040
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28041
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28042
- * during the detached period, because the machine is not attached. Rows
28043
- * recorded in that window sit after the boundary and before the re-attach, so
28044
- * neither path takes them, and the pending count reports none outstanding.
28045
- *
28046
- * Stamping the attached window is not a claim that every one of those rows
28047
- * reached the deployment — the live path drops on failure and says so
28048
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28049
- * status quo: they sit outside the frozen boundary today and are equally never
28050
- * re-sent. Making it explicit is what lets the boundary move.
28051
- *
28052
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28053
- * window unstamped — that half-state would re-send the whole attached period
28054
- * on the next attach, which is the failure the boundary exists to prevent.
28055
- */
28056
- closeAttachedWindow(attachedAtMs, atMs) {
28057
- this.ensureRowStmt.run();
28058
- withTransaction(
28059
- this.db,
28060
- () => {
28061
- const row = getRow(this.fingerprintStmt);
28062
- const from = row?.backlogBefore ?? attachedAtMs;
28063
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28064
- this.releaseBoundaryStmt.run();
28065
- },
28066
- "IMMEDIATE"
28067
- );
28068
- }
28069
- /**
28070
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28071
- *
28072
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28073
- * different deployment and therefore discards what was delivered to the old
28074
- * one: here the recipient is the same, so everything already sent to it stays
28075
- * sent.
28076
- */
28077
- freezeBoundary(backlogBefore) {
28078
- this.ensureRowStmt.run();
28079
- this.freezeBoundaryStmt.run({ backlogBefore });
28080
- }
28081
- /** Take the claim, or report that someone live already holds it. */
28082
- claim(pid, host, nowMs, staleAfterMs) {
28083
- this.ensureRowStmt.run();
28084
- let taken = false;
28085
- withTransaction(
28086
- this.db,
28087
- () => {
28088
- const result = this.claimStmt.run({
28089
- pid,
28090
- host,
28091
- now: nowMs,
28092
- staleBefore: nowMs - staleAfterMs
28093
- });
28094
- taken = result.changes === 1;
28095
- },
28096
- "IMMEDIATE"
28097
- );
28098
- return taken;
28099
- }
28100
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28101
- heartbeat(pid, nowMs) {
28102
- this.heartbeatStmt.run({ now: nowMs, pid });
28103
- }
28104
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28105
- release(pid) {
28106
- this.releaseStmt.run({ pid });
28107
- }
28108
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28109
- lease() {
28110
- return getRow(this.leaseStmt);
28111
- }
28112
- };
28113
-
28114
28821
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28115
28822
  var SqliteInspectionDefinitionsRepository = class {
28116
28823
  constructor(db) {
@@ -28305,7 +29012,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28305
29012
  }
28306
29013
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28307
29014
  }
28308
- function readManagedSettings(paths = managedSettingsPaths()) {
29015
+ var testOnlyManagedPaths = null;
29016
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28309
29017
  for (const path of paths) {
28310
29018
  let text;
28311
29019
  try {
@@ -28340,6 +29048,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28340
29048
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28341
29049
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28342
29050
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29051
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28343
29052
  if (values.vaultConsent !== void 0) {
28344
29053
  merged.vaultConsent = values.vaultConsent ? (
28345
29054
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30785,7 +31494,7 @@ function toUtcDateString(ms) {
30785
31494
  return new Date(ms).toISOString().slice(0, 10);
30786
31495
  }
30787
31496
  function isTimeseriesSeverity(s) {
30788
- return s === "critical" || s === "high" || s === "medium";
31497
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30789
31498
  }
30790
31499
  var SqliteSecurityRepository = class {
30791
31500
  constructor(db, now = () => Date.now()) {
@@ -30847,7 +31556,7 @@ var SqliteSecurityRepository = class {
30847
31556
  ELSE 0
30848
31557
  END) AS open_at_rest
30849
31558
  FROM inspection_findings f
30850
- JOIN audit_events e ON e.id = f.audit_event_id
31559
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30851
31560
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30852
31561
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30853
31562
  ON latest.finding_key = f.finding_key
@@ -30914,12 +31623,16 @@ var SqliteSecurityRepository = class {
30914
31623
  const now = this.now();
30915
31624
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30916
31625
  const rows = this.findingsInRange(windowStart, now);
30917
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30918
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30919
- critical: 0,
30920
- high: 0,
30921
- medium: 0
30922
- }));
31626
+ const points = Array.from(
31627
+ { length: numBuckets },
31628
+ (_, i) => ({
31629
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31630
+ critical: 0,
31631
+ high: 0,
31632
+ medium: 0,
31633
+ low: 0
31634
+ })
31635
+ );
30923
31636
  for (const r of rows) {
30924
31637
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30925
31638
  const bucket = points[idx];
@@ -31069,7 +31782,7 @@ var SqliteSecurityRepository = class {
31069
31782
  this.db.prepare(
31070
31783
  `SELECT e.repo AS repo, count(*) AS c
31071
31784
  FROM inspection_findings f
31072
- JOIN audit_events e ON e.id = f.audit_event_id
31785
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31073
31786
  WHERE e.started_at >= :from AND e.started_at < :to
31074
31787
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31075
31788
  AND e.repo IS NOT NULL
@@ -31137,6 +31850,7 @@ var SqliteSecurityRepository = class {
31137
31850
  `SELECT f.finding_key AS finding_key,
31138
31851
  d.rule_id AS rule_id,
31139
31852
  d.severity AS severity,
31853
+ e.repo AS repo,
31140
31854
  e.file_path AS path,
31141
31855
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31142
31856
  latest.resolved_at AS latest_resolved_at
@@ -31156,6 +31870,7 @@ var SqliteSecurityRepository = class {
31156
31870
  const items = rows.map((r) => ({
31157
31871
  findingKey: r.finding_key,
31158
31872
  ruleId: r.rule_id,
31873
+ repo: r.repo ?? "",
31159
31874
  severity: r.severity,
31160
31875
  path: r.path ?? "",
31161
31876
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31165,15 +31880,68 @@ var SqliteSecurityRepository = class {
31165
31880
  }));
31166
31881
  return Promise.resolve({ items });
31167
31882
  }
31883
+ /**
31884
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31885
+ *
31886
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31887
+ * list: a secret committed three weeks ago and never rotated is still the most
31888
+ * important thing to fix, and any window hides it. It carried a "newest N
31889
+ * findings" cap and then a range; the first meant a different span on every
31890
+ * machine, and the second reported "no recommendations" over live exposure.
31891
+ *
31892
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31893
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31894
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31895
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31896
+ * The two answer different questions and only this one has to match a link.
31897
+ *
31898
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31899
+ * whole-store scope costs a grouped scan rather than a row per finding.
31900
+ */
31901
+ recommendationInputs() {
31902
+ const rows = allRows(
31903
+ this.db.prepare(
31904
+ `SELECT d.rule_id AS rule_id,
31905
+ d.category AS category,
31906
+ d.severity AS severity,
31907
+ COUNT(*) AS count
31908
+ FROM inspection_findings f
31909
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31910
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31911
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31912
+ ON latest.finding_key = f.finding_key
31913
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31914
+ AND e.event_type = 'code_change'
31915
+ AND (
31916
+ f.finding_key IS NULL
31917
+ OR latest.status IS NULL
31918
+ OR latest.status NOT IN ('resolved', 'dismissed')
31919
+ )
31920
+ GROUP BY d.rule_id, d.category, d.severity`
31921
+ )
31922
+ );
31923
+ return Promise.resolve(
31924
+ rows.map((r) => ({
31925
+ ruleId: r.rule_id,
31926
+ category: r.category,
31927
+ severity: r.severity,
31928
+ count: r.count
31929
+ }))
31930
+ );
31931
+ }
31168
31932
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31169
31933
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31170
31934
  // numeric and the JS aggregations bucket/split on ms directly.
31171
31935
  findingsInRange(fromMs, toMs) {
31172
31936
  const rows = allRows(
31173
31937
  this.db.prepare(
31174
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31938
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31939
+ // joined for `severity`, so they are two more columns off a row this read
31940
+ // already fetches. They feed the recommended-actions rollup.
31941
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31942
+ d.rule_id AS rule_id, d.category AS category
31175
31943
  FROM inspection_findings f
31176
- JOIN audit_events e ON e.id = f.audit_event_id
31944
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31177
31945
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31178
31946
  WHERE e.started_at >= :from AND e.started_at < :to
31179
31947
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31184,7 +31952,9 @@ var SqliteSecurityRepository = class {
31184
31952
  return rows.map((r) => ({
31185
31953
  occurredAt: r.occurred_at,
31186
31954
  severity: r.severity,
31187
- actionTaken: r.action_taken
31955
+ actionTaken: r.action_taken,
31956
+ ruleId: r.rule_id,
31957
+ category: r.category
31188
31958
  }));
31189
31959
  }
31190
31960
  };
@@ -32012,6 +32782,7 @@ function openWithPragmas(file2) {
32012
32782
  db.exec("PRAGMA journal_mode = WAL");
32013
32783
  db.exec("PRAGMA busy_timeout = 2000");
32014
32784
  db.exec("PRAGMA foreign_keys = ON");
32785
+ registerSqlFunctions(db);
32015
32786
  } catch (err) {
32016
32787
  closeQuietly(db);
32017
32788
  throw err;
@@ -32041,7 +32812,7 @@ function backupLegacyStore(db, file2) {
32041
32812
  discardStore(file2, backup);
32042
32813
  return backup;
32043
32814
  }
32044
- function openAndInitialize(file2, base) {
32815
+ function openAndInitialize(file2, base, skipTags) {
32045
32816
  let db = openWithPragmas(file2);
32046
32817
  try {
32047
32818
  if (isForeignSqliteLineage(db)) {
@@ -32051,7 +32822,7 @@ function openAndInitialize(file2, base) {
32051
32822
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32052
32823
  );
32053
32824
  }
32054
- applyMigrations(db, file2);
32825
+ applyMigrations(db, file2, { skipTags });
32055
32826
  tightenPerms(file2);
32056
32827
  const policies = new SqlitePoliciesRepository(db);
32057
32828
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32066,6 +32837,7 @@ function openAndInitialize(file2, base) {
32066
32837
  exceptions: new SqliteExceptionsRepository(db),
32067
32838
  resolutions: new SqliteResolutionsRepository(db),
32068
32839
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32840
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32069
32841
  security: new SqliteSecurityRepository(db),
32070
32842
  detections: new SqliteDetectionsRepository(db),
32071
32843
  shares: new SqliteSharesRepository(db),
@@ -32088,7 +32860,8 @@ function openAndInitialize(file2, base) {
32088
32860
  throw err;
32089
32861
  }
32090
32862
  }
32091
- function openLocalDatabase(dir) {
32863
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32864
+ function openLocalDatabase(dir, options = {}) {
32092
32865
  ensureDataDirSync(dir);
32093
32866
  const file2 = join7(dir, DB_FILENAME);
32094
32867
  reapStalePartials(file2);
@@ -32100,6 +32873,7 @@ function openLocalDatabase(dir) {
32100
32873
  installedPacks,
32101
32874
  scanLedger,
32102
32875
  historySync,
32876
+ bodyRetention,
32103
32877
  secretVault,
32104
32878
  exceptions,
32105
32879
  resolutions,
@@ -32123,7 +32897,8 @@ function openLocalDatabase(dir) {
32123
32897
  // `dir` is always `<base>/data` — every caller resolves it through
32124
32898
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32125
32899
  // settings/ and data/, and the pack-policy floor needs both halves.
32126
- dirname2(dir)
32900
+ dirname2(dir),
32901
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32127
32902
  );
32128
32903
  function captureRowId(event) {
32129
32904
  return captureId(
@@ -32316,6 +33091,7 @@ function openLocalDatabase(dir) {
32316
33091
  installedPacks,
32317
33092
  scanLedger,
32318
33093
  historySync,
33094
+ bodyRetention,
32319
33095
  secretVault,
32320
33096
  exceptions,
32321
33097
  resolutions,
@@ -32354,6 +33130,70 @@ function openLocalDatabase(dir) {
32354
33130
  };
32355
33131
  }
32356
33132
 
33133
+ // ../../packages/persistence/src/egress-wire.ts
33134
+ import { createHash as createHash3 } from "crypto";
33135
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33136
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33137
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33138
+ var FILE_URL = /^file:\/\//i;
33139
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33140
+ var SLASH = "/".charCodeAt(0);
33141
+ var GIT_SUFFIX = ".git";
33142
+ function trimSlashes(path) {
33143
+ let start = 0;
33144
+ let end = path.length;
33145
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33146
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33147
+ return path.slice(start, end);
33148
+ }
33149
+ function canonicalGitUrl(url2) {
33150
+ const trimmed = url2.trim();
33151
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33152
+ const scheme = SCHEME_FORM.exec(trimmed);
33153
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33154
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33155
+ if (host === void 0) return trimmed;
33156
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33157
+ const bare = trimSlashes(path);
33158
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33159
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33160
+ }
33161
+ function hashProjectKey(projectKey) {
33162
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33163
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33164
+ }
33165
+ function toIngestHit(hit) {
33166
+ return {
33167
+ host: hit.host,
33168
+ kind: hit.kind,
33169
+ name: hit.name,
33170
+ category: hit.category,
33171
+ trust: hit.trust,
33172
+ network: hit.network,
33173
+ method: hit.method,
33174
+ transport: hit.transport,
33175
+ url: hit.url,
33176
+ template: hit.template,
33177
+ dataClass: hit.dataClass,
33178
+ site: {
33179
+ file: hit.site.file,
33180
+ line: hit.site.line,
33181
+ dynamic: hit.site.dynamic,
33182
+ vendored: hit.site.vendored
33183
+ }
33184
+ };
33185
+ }
33186
+ function toEgressIngestRequest(input2) {
33187
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33188
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33189
+ return {
33190
+ projectKey: hashProjectKey(input2.projectKey),
33191
+ project: input2.project,
33192
+ reconcile,
33193
+ hits: hits.map(toIngestHit)
33194
+ };
33195
+ }
33196
+
32357
33197
  // ../../packages/persistence/src/exception-policy.ts
32358
33198
  var UserGrantPolicyProvider = class {
32359
33199
  #exceptions;
@@ -32375,7 +33215,7 @@ var UserGrantPolicyProvider = class {
32375
33215
  };
32376
33216
 
32377
33217
  // ../../packages/persistence/src/finding-key.ts
32378
- import { createHash as createHash3 } from "crypto";
33218
+ import { createHash as createHash4 } from "crypto";
32379
33219
 
32380
33220
  // ../../packages/persistence/src/fingerprint.ts
32381
33221
  import { createHmac, randomBytes } from "crypto";
@@ -32500,14 +33340,50 @@ function fingerprintValue(key, raw) {
32500
33340
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32501
33341
  }
32502
33342
 
32503
- // ../../packages/persistence/src/history-preview.ts
32504
- import { existsSync as existsSync4 } from "fs";
33343
+ // ../../packages/persistence/src/forward-health.ts
33344
+ import { readFileSync as readFileSync7 } from "fs";
32505
33345
  import { join as join9 } from "path";
33346
+ var FAILURES = /* @__PURE__ */ new Set([
33347
+ "unauthorized",
33348
+ "forbidden",
33349
+ "unreachable"
33350
+ ]);
33351
+ var BREAKER_COOLDOWN_MS = 3e4;
33352
+ function parseForwardHealth(raw, nowMs) {
33353
+ try {
33354
+ const parsed2 = JSON.parse(raw);
33355
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33356
+ const record2 = parsed2;
33357
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33358
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33359
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33360
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33361
+ } catch {
33362
+ return null;
33363
+ }
33364
+ }
33365
+ function isForwardPaused(health, nowMs) {
33366
+ const openedAtMs = health?.openedAtMs ?? null;
33367
+ if (openedAtMs === null) return false;
33368
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33369
+ }
33370
+
33371
+ // ../../packages/persistence/src/history-backfill.ts
33372
+ import { existsSync as existsSync4 } from "fs";
33373
+ import { join as join10 } from "path";
33374
+
33375
+ // ../../packages/persistence/src/history-preview.ts
33376
+ import { existsSync as existsSync5 } from "fs";
33377
+ import { join as join11 } from "path";
32506
33378
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32507
33379
 
33380
+ // ../../packages/persistence/src/history-sync-state.ts
33381
+ import { readFileSync as readFileSync8 } from "fs";
33382
+ import { join as join12 } from "path";
33383
+
32508
33384
  // ../../packages/persistence/src/store-symlinks.ts
32509
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32510
- import { dirname as dirname3, join as join10, resolve } from "path";
33385
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33386
+ import { dirname as dirname3, join as join13, resolve } from "path";
32511
33387
 
32512
33388
  // ../../packages/persistence/src/vault/crypto.ts
32513
33389
  import {
@@ -32620,8 +33496,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32620
33496
  // ../../packages/persistence/src/vault/key-provider.ts
32621
33497
  import { execFileSync } from "child_process";
32622
33498
  import { randomBytes as randomBytes2 } from "crypto";
32623
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32624
- import { join as join11 } from "path";
33499
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33500
+ import { join as join14 } from "path";
32625
33501
  var VAULT_OCCUPANT_REASON = {
32626
33502
  symlink: "the path is a symlink; remove it so a keyring can be created",
32627
33503
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32720,7 +33596,7 @@ function claimRotationLock(lock, owner) {
32720
33596
  throw asError(err);
32721
33597
  }
32722
33598
  try {
32723
- writeFileSync3(join11(lock, LOCK_OWNER_FILE), `${owner}
33599
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32724
33600
  `, { mode: DATA_FILE_MODE });
32725
33601
  return true;
32726
33602
  } catch (err) {
@@ -32729,7 +33605,7 @@ function claimRotationLock(lock, owner) {
32729
33605
  }
32730
33606
  }
32731
33607
  function acquireRotationLock(keysDir2) {
32732
- const lock = join11(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33608
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32733
33609
  const owner = randomBytes2(16).toString("hex");
32734
33610
  if (claimRotationLock(lock, owner)) return { lock, owner };
32735
33611
  let held;
@@ -32756,7 +33632,7 @@ function acquireRotationLock(keysDir2) {
32756
33632
  }
32757
33633
  function releaseRotationLock(lease) {
32758
33634
  try {
32759
- if (readFileSync7(join11(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33635
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
32760
33636
  } catch {
32761
33637
  return;
32762
33638
  }
@@ -32777,7 +33653,7 @@ var FileKeyProvider = class {
32777
33653
  this.#keysDir = keysDir2;
32778
33654
  }
32779
33655
  get filePath() {
32780
- return join11(this.#keysDir, VAULT_KEY_FILENAME);
33656
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
32781
33657
  }
32782
33658
  loadOrCreate() {
32783
33659
  return asAsync(() => {
@@ -32807,7 +33683,7 @@ var FileKeyProvider = class {
32807
33683
  #read() {
32808
33684
  let raw;
32809
33685
  try {
32810
- raw = readFileSync7(this.filePath, "utf8");
33686
+ raw = readFileSync9(this.filePath, "utf8");
32811
33687
  } catch (err) {
32812
33688
  if (err.code === "ENOENT") return null;
32813
33689
  throw err instanceof Error ? err : new Error(String(err));
@@ -33442,13 +34318,13 @@ var SecretVault = class {
33442
34318
  };
33443
34319
 
33444
34320
  // ../../packages/persistence/src/warn-era-cap.ts
33445
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
33446
- import { join as join12 } from "path";
34321
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
34322
+ import { join as join15 } from "path";
33447
34323
  var MARKER = "warn-era-capped";
33448
34324
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33449
34325
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33450
- const marker = join12(dataDir2, MARKER);
33451
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
34326
+ const marker = join15(dataDir2, MARKER);
34327
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33452
34328
  const capped = db.policies.capCategoryActions();
33453
34329
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
33454
34330
  `, { mode: DATA_FILE_MODE });
@@ -33517,8 +34393,8 @@ function providerFromModelId(modelId) {
33517
34393
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33518
34394
  try {
33519
34395
  ensureLayoutDirSync(base);
33520
- const settingsFile = join13(settingsDir(base), "settings.json");
33521
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
34396
+ const settingsFile = join16(settingsDir(base), "settings.json");
34397
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33522
34398
  } catch {
33523
34399
  }
33524
34400
  migrateLegacyLayout(base);
@@ -33541,9 +34417,9 @@ function resolveProviderSafe(resolveProviderFn) {
33541
34417
  }
33542
34418
 
33543
34419
  // ../../packages/plugin-sdk/src/config-inventory.ts
33544
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34420
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33545
34421
  import { homedir as homedir2 } from "os";
33546
- import { basename as basename3, join as join15 } from "path";
34422
+ import { basename as basename3, join as join18 } from "path";
33547
34423
 
33548
34424
  // ../../packages/detections/src/egress/registry.ts
33549
34425
  var EXTRACTOR_VERSION = "1";
@@ -36587,8 +37463,8 @@ function scanText(text, ruleVersions) {
36587
37463
  }
36588
37464
 
36589
37465
  // ../../packages/plugin-sdk/src/repo.ts
36590
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36591
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
37466
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
37467
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
36592
37468
  function resolveRepoIdentity(cwd) {
36593
37469
  try {
36594
37470
  const root = findGitRoot(cwd);
@@ -36621,36 +37497,36 @@ function resolveRepoNwo(cwd) {
36621
37497
  function findGitRoot(start) {
36622
37498
  let dir = start;
36623
37499
  for (; ; ) {
36624
- if (existsSync8(join14(dir, ".git"))) return dir;
37500
+ if (existsSync9(join17(dir, ".git"))) return dir;
36625
37501
  const parent = dirname4(dir);
36626
37502
  if (parent === dir) return void 0;
36627
37503
  dir = parent;
36628
37504
  }
36629
37505
  }
36630
37506
  function resolveGitContext(root) {
36631
- const dotGit = join14(root, ".git");
37507
+ const dotGit = join17(root, ".git");
36632
37508
  try {
36633
37509
  if (statSync6(dotGit).isDirectory()) {
36634
- return { configPath: join14(dotGit, "config"), headRoot: root };
37510
+ return { configPath: join17(dotGit, "config"), headRoot: root };
36635
37511
  }
36636
37512
  } catch {
36637
37513
  return void 0;
36638
37514
  }
36639
37515
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36640
37516
  if (!target) return void 0;
36641
- const gitdir = isAbsolute(target) ? target : join14(root, target);
36642
- if (existsSync8(join14(gitdir, "config"))) {
36643
- return { configPath: join14(gitdir, "config"), headRoot: root };
37517
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
37518
+ if (existsSync9(join17(gitdir, "config"))) {
37519
+ return { configPath: join17(gitdir, "config"), headRoot: root };
36644
37520
  }
36645
- const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
37521
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
36646
37522
  if (!commonRaw) return void 0;
36647
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
37523
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
36648
37524
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36649
- return { configPath: join14(commonGitDir, "config"), headRoot };
37525
+ return { configPath: join17(commonGitDir, "config"), headRoot };
36650
37526
  }
36651
37527
  function safeRead(path) {
36652
37528
  try {
36653
- return readFileSync8(path, "utf8");
37529
+ return readFileSync10(path, "utf8");
36654
37530
  } catch {
36655
37531
  return void 0;
36656
37532
  }
@@ -36701,17 +37577,52 @@ function nwoFromUrl(url2) {
36701
37577
  }
36702
37578
 
36703
37579
  // ../../packages/plugin-sdk/src/events.ts
36704
- import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
37580
+ import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36705
37581
 
36706
37582
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36707
- import { existsSync as existsSync9 } from "fs";
37583
+ import { existsSync as existsSync10 } from "fs";
36708
37584
  import { fileURLToPath } from "url";
36709
37585
  import { Worker } from "worker_threads";
36710
37586
 
37587
+ // ../../packages/plugin-sdk/src/host-floor.ts
37588
+ import { readFileSync as readFileSync13 } from "fs";
37589
+ import { join as join20 } from "path";
37590
+
37591
+ // ../../packages/plugin-sdk/src/model-governance.ts
37592
+ import {
37593
+ closeSync as closeSync2,
37594
+ fstatSync,
37595
+ mkdirSync as mkdirSync2,
37596
+ openSync as openSync2,
37597
+ readFileSync as readFileSync12,
37598
+ readSync,
37599
+ writeFileSync as writeFileSync5
37600
+ } from "fs";
37601
+ import { join as join19 } from "path";
37602
+ var TAIL_BYTES = 256 * 1024;
37603
+
37604
+ // ../../packages/plugin-sdk/src/host-floor.ts
37605
+ var HOST_FEATURE = {
37606
+ ModelSwitch: "model-switch",
37607
+ VaultPointerDisplay: "vault-pointer-display"
37608
+ };
37609
+ var HOST_FLOORS = {
37610
+ [HOST_FEATURE.ModelSwitch]: {
37611
+ label: "model-switch protection",
37612
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37613
+ since: "2.1.251"
37614
+ },
37615
+ [HOST_FEATURE.VaultPointerDisplay]: {
37616
+ label: "vault pointer display",
37617
+ hookEvents: ["MessageDisplay"],
37618
+ since: "2.1.152"
37619
+ }
37620
+ };
37621
+
36711
37622
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36712
37623
  var import_ignore = __toESM(require_ignore(), 1);
36713
- import { readFileSync as readFileSync10 } from "fs";
36714
- import { join as join16 } from "path";
37624
+ import { readFileSync as readFileSync14 } from "fs";
37625
+ import { join as join21 } from "path";
36715
37626
 
36716
37627
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
36717
37628
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -36742,22 +37653,9 @@ function resolveInventoryContext(input2) {
36742
37653
  return ctx;
36743
37654
  }
36744
37655
 
36745
- // ../../packages/plugin-sdk/src/model-governance.ts
36746
- import {
36747
- closeSync as closeSync2,
36748
- fstatSync,
36749
- mkdirSync as mkdirSync2,
36750
- openSync as openSync2,
36751
- readFileSync as readFileSync11,
36752
- readSync,
36753
- writeFileSync as writeFileSync5
36754
- } from "fs";
36755
- import { join as join17 } from "path";
36756
- var TAIL_BYTES = 256 * 1024;
36757
-
36758
37656
  // ../../packages/plugin-sdk/src/nudge.ts
36759
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
36760
- import { join as join18 } from "path";
37657
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
37658
+ import { join as join22 } from "path";
36761
37659
 
36762
37660
  // ../../packages/plugin-sdk/src/paths.ts
36763
37661
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -36799,8 +37697,8 @@ function createPolicyResolver(bundle) {
36799
37697
  }
36800
37698
 
36801
37699
  // ../../packages/plugin-sdk/src/project-files.ts
36802
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36803
- import { basename as basename5, join as join19 } from "path";
37700
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37701
+ import { basename as basename5, join as join23 } from "path";
36804
37702
 
36805
37703
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36806
37704
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -36836,7 +37734,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36836
37734
 
36837
37735
  // ../../packages/plugin-sdk/src/throttle.ts
36838
37736
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36839
- import { join as join20 } from "path";
37737
+ import { join as join24 } from "path";
36840
37738
 
36841
37739
  // ../../packages/plugin-sdk/src/tokenize.ts
36842
37740
  function redactedPlaceholder(category) {
@@ -37151,43 +38049,6 @@ var UNOPENABLE_VAULT = {
37151
38049
  resolvePointerIdentity: () => Promise.resolve(null)
37152
38050
  };
37153
38051
 
37154
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
37155
- import { createHash as createHash5 } from "crypto";
37156
- function hashProjectKey(projectKey) {
37157
- return createHash5("sha256").update(projectKey, "utf8").digest("hex");
37158
- }
37159
- function toIngestHit(hit) {
37160
- return {
37161
- host: hit.host,
37162
- kind: hit.kind,
37163
- name: hit.name,
37164
- category: hit.category,
37165
- trust: hit.trust,
37166
- network: hit.network,
37167
- method: hit.method,
37168
- transport: hit.transport,
37169
- url: hit.url,
37170
- template: hit.template,
37171
- dataClass: hit.dataClass,
37172
- site: {
37173
- file: hit.site.file,
37174
- line: hit.site.line,
37175
- dynamic: hit.site.dynamic,
37176
- vendored: hit.site.vendored
37177
- }
37178
- };
37179
- }
37180
- function toEgressIngestRequest(input2) {
37181
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
37182
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
37183
- return {
37184
- projectKey: hashProjectKey(input2.projectKey),
37185
- project: input2.project,
37186
- reconcile,
37187
- hits: hits.map(toIngestHit)
37188
- };
37189
- }
37190
-
37191
38052
  // ../../packages/remote/src/http.ts
37192
38053
  import { request as httpRequest } from "http";
37193
38054
  import { request as httpsRequest } from "https";
@@ -37371,10 +38232,10 @@ function parsed(schema, body, route) {
37371
38232
  }
37372
38233
  function withoutTrailingSlashes(endpoint) {
37373
38234
  let end = endpoint.length;
37374
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
38235
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
37375
38236
  return endpoint.slice(0, end);
37376
38237
  }
37377
- var SLASH = "/".charCodeAt(0);
38238
+ var SLASH2 = "/".charCodeAt(0);
37378
38239
  function createRemoteClient(options) {
37379
38240
  const base = withoutTrailingSlashes(options.endpoint);
37380
38241
  const url2 = (route) => `${base}${route}`;
@@ -37467,6 +38328,7 @@ function createRemoteClient(options) {
37467
38328
  url: url2(ROUTES.shares),
37468
38329
  body: JSON.stringify(validated.data)
37469
38330
  });
38331
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
37470
38332
  okBody(response);
37471
38333
  },
37472
38334
  async pollCommand() {
@@ -37489,19 +38351,51 @@ function createRemoteClient(options) {
37489
38351
  };
37490
38352
  }
37491
38353
 
37492
- // ../../packages/plugin-runtime/src/attached/failure.ts
38354
+ // ../../packages/remote/src/failure-kind.ts
37493
38355
  function statusOf(err) {
37494
38356
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
37495
38357
  const { status } = err;
37496
38358
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
37497
38359
  return status >= 100 && status <= 599 ? status : null;
37498
38360
  }
37499
- function classifyFailure(err) {
37500
- switch (statusOf(err)) {
38361
+ function nameOf(err) {
38362
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
38363
+ return typeof err.name === "string" ? err.name : null;
38364
+ }
38365
+ function classifyRemoteFailure(err) {
38366
+ switch (nameOf(err)) {
38367
+ case "RemoteRouteAbsent":
38368
+ return "route-absent";
38369
+ case "RemoteRequestInvalid":
38370
+ return "invalid-request";
38371
+ case "RemoteResponseInvalid":
38372
+ return "rejected";
38373
+ default:
38374
+ break;
38375
+ }
38376
+ const status = statusOf(err);
38377
+ if (status === null) return "unreachable";
38378
+ switch (status) {
37501
38379
  case 401:
37502
38380
  return "unauthorized";
37503
38381
  case 403:
37504
38382
  return "forbidden";
38383
+ case 429:
38384
+ return "unreachable";
38385
+ case 404:
38386
+ return "unreachable";
38387
+ default:
38388
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
38389
+ }
38390
+ }
38391
+
38392
+ // ../../packages/plugin-runtime/src/attached/failure.ts
38393
+ function classifyFailure(err) {
38394
+ switch (classifyRemoteFailure(err)) {
38395
+ case "unauthorized":
38396
+ return "unauthorized";
38397
+ case "forbidden":
38398
+ return "forbidden";
37505
38399
  default:
37506
38400
  return "unreachable";
37507
38401
  }
@@ -37523,11 +38417,11 @@ function withTimeout(promise2, ms) {
37523
38417
  }
37524
38418
 
37525
38419
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
37526
- import { readFileSync as readFileSync13 } from "fs";
37527
- import { join as join21 } from "path";
38420
+ import { readFileSync as readFileSync16 } from "fs";
38421
+ import { join as join25 } from "path";
37528
38422
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
37529
38423
  function forwardDropsPath(dataDir2) {
37530
- return join21(dataDir2, FORWARD_DROPS_FILENAME);
38424
+ return join25(dataDir2, FORWARD_DROPS_FILENAME);
37531
38425
  }
37532
38426
  function recordForwardDrops(dataDir2, count, nowMs) {
37533
38427
  if (count <= 0) return;
@@ -37545,7 +38439,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
37545
38439
  }
37546
38440
  function readForwardDrops(dataDir2) {
37547
38441
  try {
37548
- const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
38442
+ const parsed2 = JSON.parse(readFileSync16(forwardDropsPath(dataDir2), "utf8"));
37549
38443
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
37550
38444
  const record2 = parsed2;
37551
38445
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -37563,9 +38457,8 @@ function readForwardDrops(dataDir2) {
37563
38457
 
37564
38458
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
37565
38459
  import { randomUUID as randomUUID15 } from "crypto";
37566
- import { readFileSync as readFileSync14 } from "fs";
37567
38460
  import { readFile, rename, writeFile } from "fs/promises";
37568
- import { join as join22 } from "path";
38461
+ import { join as join26 } from "path";
37569
38462
  function isInvalidRequest(err) {
37570
38463
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
37571
38464
  }
@@ -37579,31 +38472,12 @@ function isServerRejection(err) {
37579
38472
  var FORWARD_BUDGET_MS = 1500;
37580
38473
  var DECISION_PATH_BUDGET_MS = 800;
37581
38474
  var BREAKER_FAILURE_THRESHOLD = 3;
37582
- var BREAKER_COOLDOWN_MS = 3e4;
37583
38475
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
37584
- var FAILURES = /* @__PURE__ */ new Set([
37585
- "unauthorized",
37586
- "forbidden",
37587
- "unreachable"
37588
- ]);
37589
38476
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
37590
38477
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
37591
- function parseBreakerState(raw, nowMs) {
37592
- try {
37593
- const parsed2 = JSON.parse(raw);
37594
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
37595
- const record2 = parsed2;
37596
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
37597
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
37598
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
37599
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
37600
- } catch {
37601
- return null;
37602
- }
37603
- }
37604
38478
  function createForwardPolicy(deps) {
37605
38479
  const now = deps.now ?? (() => Date.now());
37606
- const file2 = join22(deps.dir, STATE_FILENAME);
38480
+ const file2 = join26(deps.dir, STATE_FILENAME);
37607
38481
  let state = null;
37608
38482
  let loading = null;
37609
38483
  async function readState() {
@@ -37613,7 +38487,7 @@ function createForwardPolicy(deps) {
37613
38487
  } catch {
37614
38488
  return { ...CLOSED };
37615
38489
  }
37616
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
38490
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
37617
38491
  }
37618
38492
  async function load() {
37619
38493
  if (state !== null) return state;
@@ -37659,7 +38533,7 @@ function createForwardPolicy(deps) {
37659
38533
  };
37660
38534
  const at = now();
37661
38535
  if (current.openedAtMs !== null) {
37662
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
38536
+ if (isForwardPaused(current, at)) {
37663
38537
  return { ok: false, reason: "breaker-open" };
37664
38538
  }
37665
38539
  await persist({
@@ -38196,7 +39070,18 @@ var AttachedDataGateway = class {
38196
39070
  // and the spread above would otherwise drop the field silently — which is
38197
39071
  // exactly what it did, leaving the whole control inert on every device
38198
39072
  // while every test around it stayed green.
38199
- prohibitedModels: cached2.prohibitedModels
39073
+ prohibitedModels: cached2.prohibitedModels,
39074
+ // NAMED for the same reason as the line above, and it is the same defect
39075
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
39076
+ // only the cache carries is dropped in silence. That is what left
39077
+ // `prohibitedModels` inert on every attached device with every test
39078
+ // around it green.
39079
+ //
39080
+ // Taken from the cache rather than merged here, because merging it needs
39081
+ // the device's own SETTING — which is not a bundle field and is not in
39082
+ // scope at this seam. The runtime does that merge, raise-only, where both
39083
+ // values are in hand (createPluginRuntime's ensureInitialized).
39084
+ redactFallback: cached2.redactFallback
38200
39085
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
38201
39086
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
38202
39087
  // it emits, so an 'authored' policy arriving from the control plane
@@ -38324,10 +39209,6 @@ function toolAuditEvent(input2) {
38324
39209
  };
38325
39210
  }
38326
39211
 
38327
- // ../../packages/plugin-runtime/src/attached/history-state.ts
38328
- import { readFileSync as readFileSync15 } from "fs";
38329
- import { join as join23 } from "path";
38330
-
38331
39212
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
38332
39213
  import { createHash as createHash6 } from "crypto";
38333
39214
  import { hostname as hostname5 } from "os";
@@ -38336,6 +39217,10 @@ import { hostname as hostname5 } from "os";
38336
39217
  var CORRELATION_ID = EventMetadata.shape.correlationId;
38337
39218
  var TRACE_ID = EventMetadata.shape.traceId;
38338
39219
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
39220
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
39221
+
39222
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
39223
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
38339
39224
 
38340
39225
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
38341
39226
  import { spawn } from "child_process";
@@ -38343,14 +39228,14 @@ import { fileURLToPath as fileURLToPath2 } from "url";
38343
39228
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
38344
39229
 
38345
39230
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
38346
- import { readFileSync as readFileSync16 } from "fs";
39231
+ import { readFileSync as readFileSync17 } from "fs";
38347
39232
  var manifestBuildCache = /* @__PURE__ */ new Map();
38348
39233
  function readManifestBuild(manifestUrl, packageName) {
38349
39234
  const key = manifestUrl.href;
38350
39235
  if (!manifestBuildCache.has(key)) {
38351
39236
  let build;
38352
39237
  try {
38353
- const manifest = JSON.parse(readFileSync16(manifestUrl, "utf8"));
39238
+ const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
38354
39239
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
38355
39240
  } catch {
38356
39241
  build = void 0;
@@ -38377,7 +39262,7 @@ function createPluginBlock(build, policyStore) {
38377
39262
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38378
39263
  import { randomUUID as randomUUID16 } from "crypto";
38379
39264
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38380
- import { join as join24 } from "path";
39265
+ import { join as join27 } from "path";
38381
39266
 
38382
39267
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38383
39268
  import { rename as rename2 } from "fs/promises";
@@ -38401,7 +39286,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38401
39286
 
38402
39287
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38403
39288
  function createPolicyStore(dir = dataDir()) {
38404
- const file2 = join24(dir, "policy-cache.json");
39289
+ const file2 = join27(dir, "policy-cache.json");
38405
39290
  async function read() {
38406
39291
  try {
38407
39292
  const raw = await readFile2(file2, "utf8");
@@ -38632,11 +39517,11 @@ function readStorePosture(dbPath2) {
38632
39517
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38633
39518
  import { randomUUID as randomUUID17 } from "crypto";
38634
39519
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38635
- import { join as join25 } from "path";
39520
+ import { join as join28 } from "path";
38636
39521
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38637
39522
  function createPostureStore(dir = settingsDir(), legacyDir) {
38638
- const file2 = join25(dir, "posture-state.json");
38639
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
39523
+ const file2 = join28(dir, "posture-state.json");
39524
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
38640
39525
  async function persist(state) {
38641
39526
  await ensureDataDir(dir);
38642
39527
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38704,8 +39589,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38704
39589
  }
38705
39590
 
38706
39591
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38707
- import { readFileSync as readFileSync17 } from "fs";
38708
- import { join as join26 } from "path";
39592
+ import { readFileSync as readFileSync18 } from "fs";
39593
+ import { join as join29 } from "path";
38709
39594
 
38710
39595
  // ../../packages/plugin-runtime/src/attached/status.ts
38711
39596
  var REFUSAL_LINES = {
@@ -38726,6 +39611,14 @@ import { spawn as spawn2 } from "child_process";
38726
39611
  import { fileURLToPath as fileURLToPath3 } from "url";
38727
39612
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
38728
39613
 
39614
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
39615
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39616
+
39617
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
39618
+ import { spawn as spawn3 } from "child_process";
39619
+ import { fileURLToPath as fileURLToPath4 } from "url";
39620
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
39621
+
38729
39622
  // ../../packages/plugin-runtime/src/attached/factory.ts
38730
39623
  import { hostname as hostname6 } from "os";
38731
39624
 
@@ -39186,21 +40079,21 @@ function pluginBuild() {
39186
40079
  import {
39187
40080
  lstatSync as lstatSync4,
39188
40081
  readdirSync as readdirSync6,
39189
- readFileSync as readFileSync19,
40082
+ readFileSync as readFileSync20,
39190
40083
  realpathSync as realpathSync4,
39191
40084
  renameSync as renameSync5,
39192
40085
  rmSync as rmSync7,
39193
40086
  statSync as statSync10,
39194
40087
  writeFileSync as writeFileSync8
39195
40088
  } from "fs";
39196
- import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute2, join as join28, relative, resolve as resolve2 } from "path";
40089
+ import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute2, join as join31, relative, resolve as resolve2 } from "path";
39197
40090
 
39198
40091
  // src/history/transcripts.ts
39199
- import { readdirSync as readdirSync5, readFileSync as readFileSync18 } from "fs";
40092
+ import { readdirSync as readdirSync5, readFileSync as readFileSync19 } from "fs";
39200
40093
  import { homedir as homedir3 } from "os";
39201
- import { join as join27 } from "path";
40094
+ import { join as join30 } from "path";
39202
40095
  function transcriptsDir(home) {
39203
- return join27(home ?? homedir3(), ".claude", "projects");
40096
+ return join30(home ?? homedir3(), ".claude", "projects");
39204
40097
  }
39205
40098
  function isRecord(value) {
39206
40099
  return typeof value === "object" && value !== null;
@@ -39433,13 +40326,13 @@ import {
39433
40326
  fstatSync as fstatSync2,
39434
40327
  mkdirSync as mkdirSync5,
39435
40328
  openSync as openSync3,
39436
- readFileSync as readFileSync20,
40329
+ readFileSync as readFileSync21,
39437
40330
  readSync as readSync2,
39438
40331
  writeFileSync as writeFileSync9
39439
40332
  } from "fs";
39440
- import { join as join29 } from "path";
40333
+ import { join as join32 } from "path";
39441
40334
  function offsetsDir(dataDir2) {
39442
- return join29(dataDir2, "usage-offsets");
40335
+ return join32(dataDir2, "usage-offsets");
39443
40336
  }
39444
40337
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
39445
40338
  function safeSessionId(sessionId) {
@@ -39449,11 +40342,11 @@ function safeSessionId(sessionId) {
39449
40342
  return createHash7("sha256").update(sessionId).digest("hex");
39450
40343
  }
39451
40344
  function offsetPath(dataDir2, sessionId) {
39452
- return join29(offsetsDir(dataDir2), safeSessionId(sessionId));
40345
+ return join32(offsetsDir(dataDir2), safeSessionId(sessionId));
39453
40346
  }
39454
40347
  function readOffset(dataDir2, sessionId) {
39455
40348
  try {
39456
- const raw = readFileSync20(offsetPath(dataDir2, sessionId), "utf8");
40349
+ const raw = readFileSync21(offsetPath(dataDir2, sessionId), "utf8");
39457
40350
  const parsed2 = JSON.parse(raw);
39458
40351
  if (typeof parsed2 === "object" && parsed2 !== null) {
39459
40352
  const rec = parsed2;
@@ -39511,7 +40404,7 @@ function readTail(transcriptPath, startOffset) {
39511
40404
  }
39512
40405
 
39513
40406
  // src/history/tail-scrub.ts
39514
- import { readFileSync as readFileSync21, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync11, writeFileSync as writeFileSync10 } from "fs";
40407
+ import { readFileSync as readFileSync22, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync11, writeFileSync as writeFileSync10 } from "fs";
39515
40408
  var DEFAULT_MAX_SCRUB_BYTES = 32 * 1024 * 1024;
39516
40409
  async function scrubTranscriptTail(filePath, deps) {
39517
40410
  try {
@@ -39519,7 +40412,7 @@ async function scrubTranscriptTail(filePath, deps) {
39519
40412
  if (realPath === null) return null;
39520
40413
  const statBefore = statSync11(realPath);
39521
40414
  if (statBefore.size > (deps.maxBytes ?? DEFAULT_MAX_SCRUB_BYTES)) return null;
39522
- const content = readFileSync21(realPath, "utf8");
40415
+ const content = readFileSync22(realPath, "utf8");
39523
40416
  const lines = content.split("\n");
39524
40417
  let rewritten = 0;
39525
40418
  for (const [i, line] of lines.entries()) {