@akasecurity/ai-tc-codex 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,11 +492,11 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/backfill.ts
495
- import { fileURLToPath as fileURLToPath4 } from "url";
495
+ import { fileURLToPath as fileURLToPath5 } from "url";
496
496
 
497
497
  // ../../packages/plugin-sdk/src/config.ts
498
- import { existsSync as existsSync7 } from "fs";
499
- import { join as join13 } from "path";
498
+ import { existsSync as existsSync8 } from "fs";
499
+ import { join as join16 } from "path";
500
500
 
501
501
  // ../../packages/persistence/src/attached-derived.ts
502
502
  import { rmSync } from "fs";
@@ -509,6 +509,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
509
509
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
510
510
  import { join as join2 } from "path";
511
511
 
512
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
513
+ var DEFERRED_MIGRATION_TAGS = [
514
+ "0031_audit_capture_by_time_index",
515
+ "0032_audit_capture_by_id_index",
516
+ "0033_audit_capture_location_index",
517
+ "0034_findings_read_indexes"
518
+ ];
519
+
512
520
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
513
521
  var SQLITE_MIGRATIONS = [
514
522
  {
@@ -626,6 +634,30 @@ var SQLITE_MIGRATIONS = [
626
634
  {
627
635
  tag: "0028_activity_session_probe_indexes",
628
636
  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"
637
+ },
638
+ {
639
+ tag: "0029_audit_capture_rollup_index",
640
+ 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');"
641
+ },
642
+ {
643
+ tag: "0030_audit_content_expiry",
644
+ 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;"
645
+ },
646
+ {
647
+ tag: "0031_audit_capture_by_time_index",
648
+ 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');"
649
+ },
650
+ {
651
+ tag: "0032_audit_capture_by_id_index",
652
+ 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');"
653
+ },
654
+ {
655
+ tag: "0033_audit_capture_location_index",
656
+ 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');"
657
+ },
658
+ {
659
+ tag: "0034_findings_read_indexes",
660
+ 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`);"
629
661
  }
630
662
  ];
631
663
 
@@ -20626,7 +20658,7 @@ var TOOL_TO_HARNESS = {
20626
20658
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20627
20659
  };
20628
20660
  function harnessFromTool(tool) {
20629
- return TOOL_TO_HARNESS[tool] ?? tool;
20661
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20630
20662
  }
20631
20663
 
20632
20664
  // ../../packages/schema/src/zod/finding.ts
@@ -20676,6 +20708,15 @@ var FindingCategory = external_exports.enum([
20676
20708
  ]).meta({ id: "FindingCategory" });
20677
20709
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20678
20710
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20711
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20712
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20713
+ var FindingDelivery = external_exports.object({
20714
+ state: FindingDeliveryState,
20715
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20716
+ at: external_exports.iso.datetime().optional(),
20717
+ // Only on `not_sent`, and only when a known reason was recorded.
20718
+ reason: SyncFailureReason.optional()
20719
+ }).meta({ id: "FindingDelivery" });
20679
20720
  var ResolutionMethod = external_exports.enum([
20680
20721
  "enforced-in-flight",
20681
20722
  "fixed-at-source",
@@ -20732,7 +20773,10 @@ var FindingInstance = external_exports.object({
20732
20773
  // The session that event belongs to, when it has one — the seam a
20733
20774
  // per-instance "view session" link needs. Absent for events captured
20734
20775
  // outside a session.
20735
- sessionId: external_exports.string().optional()
20776
+ sessionId: external_exports.string().optional(),
20777
+ // The delivery state of the event above (see FindingDelivery). Optional so
20778
+ // readers that do not project it stay valid.
20779
+ delivery: FindingDelivery.optional()
20736
20780
  }).meta({ id: "FindingInstance" });
20737
20781
  var FindingGroup = external_exports.object({
20738
20782
  id: external_exports.string(),
@@ -20749,13 +20793,11 @@ var FindingGroup = external_exports.object({
20749
20793
  latestDetectedAt: external_exports.iso.datetime(),
20750
20794
  instances: external_exports.array(FindingInstance),
20751
20795
  // Derived from instances' statuses with open-dominates precedence (see
20752
- // buildFindingGroups). Undefined only when no instance carries a status.
20796
+ // foldGroupStatus). Undefined only when no instance carries a status.
20753
20797
  status: FindingStatus.optional(),
20754
- // The distinct people across the WHOLE group, not just the `instances`
20755
- // preview — from the store's whole-group aggregate when it supplies one,
20756
- // else folded from the rows (see buildFindingGroups). Undefined when no
20757
- // instance carries a user, or when the store supplied whole-group folds
20758
- // without one.
20798
+ // The distinct people across the WHOLE group, not just the instances
20799
+ // carried here. Undefined when no instance carries a user, or when the
20800
+ // store supplied whole-group folds without one.
20759
20801
  users: external_exports.array(FindingUser).optional()
20760
20802
  }).meta({ id: "FindingGroup" });
20761
20803
  var FindingStats = external_exports.object({
@@ -20784,21 +20826,34 @@ var FindingFacets = external_exports.object({
20784
20826
  // counted under no value.
20785
20827
  status: external_exports.array(FindingFacetItem),
20786
20828
  // Host tool (attributes.tool_name). Present only on the instance-level
20787
- // reads, which can filter by it; the grouped read omits the dimension
20829
+ // reads, which can filter by it; the type-level read omits the dimension
20788
20830
  // because a group spans tools.
20789
- tool: external_exports.array(FindingFacetItem).optional()
20831
+ tool: external_exports.array(FindingFacetItem).optional(),
20832
+ // Delivery states (FindingDeliveryState). Present only on the
20833
+ // instance-level reads, like `tool`.
20834
+ deployment: external_exports.array(FindingFacetItem).optional()
20790
20835
  }).meta({ id: "FindingFacets" });
20791
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20792
- var ListGroupedFindingsQuery = external_exports.object({
20836
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20837
+ id: "FindingTypeSummary"
20838
+ });
20839
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20840
+ var MAX_FINDING_TYPES_LIMIT = 100;
20841
+ var ListFindingTypesQuery = external_exports.object({
20793
20842
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20794
- // FindingAction.
20843
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20844
+ // firing version carries, and this list pages types.
20845
+ //
20846
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20847
+ // definition versions at different severities, so a type kept by this filter
20848
+ // can hold findings that individually do not match — see totals.findings on
20849
+ // ListFindingTypesResponse, which counts them all.
20795
20850
  severity: external_exports.array(Severity).optional(),
20796
20851
  subtype: external_exports.array(external_exports.string()).optional(),
20797
20852
  provider: external_exports.array(FindingProvider).optional(),
20798
20853
  action: external_exports.array(FindingAction).optional(),
20799
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20800
- // individual instances' — so a filtered group's Status column always reads
20801
- // one of the requested values.
20854
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20855
+ // individual findings' — so a filtered row's status always reads one of the
20856
+ // requested values.
20802
20857
  status: external_exports.array(FindingStatus).optional(),
20803
20858
  q: external_exports.string().optional(),
20804
20859
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20808,23 +20863,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20808
20863
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20809
20864
  // means all time — this list has no default window.
20810
20865
  from: external_exports.iso.datetime().optional(),
20811
- // A group or instance id that must appear in the page even when the cursor
20812
- // has already advanced past its sort position. This is what keeps the
20813
- // Findings page's one-shot ?finding= deep link resolving once the list
20814
- // paginates: the target group is appended out of sort order rather than
20815
- // scanning forward for it. Never affects totals, facets or the cursor.
20866
+ // A RULE id that must appear in the page even when the cursor has already
20867
+ // advanced past its sort position. This is what keeps the selected type
20868
+ // visible in the list once it paginates: the target is appended out of sort
20869
+ // order rather than scanned forward for. Never affects totals, facets or the
20870
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20871
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20872
+ // and so is not bounded by what any page happens to hold.
20816
20873
  includeId: external_exports.string().optional(),
20817
- groupBy: external_exports.literal("type").optional(),
20818
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20874
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20819
20875
  cursor: external_exports.string().optional()
20820
20876
  });
20821
- var ListGroupedFindingsResponse = external_exports.object({
20877
+ var ListFindingTypesResponse = external_exports.object({
20822
20878
  totals: external_exports.object({
20879
+ // Findings belonging to the matching TYPES — not findings that each match
20880
+ // the filters. The filters here select types, so a type that survives
20881
+ // contributes its whole instanceCount.
20882
+ //
20883
+ // `status` is the one exception, narrowed per finding via
20884
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20885
+ // this can exceed what the instance read reports for the same filters: a
20886
+ // rule whose severity moved between versions is kept on its newest and
20887
+ // still counts its older findings. Narrowing the other three needs
20888
+ // per-dimension counts the aggregate does not carry today.
20823
20889
  findings: external_exports.number().int().nonnegative(),
20824
- groups: external_exports.number().int().nonnegative()
20890
+ // Counts TYPES, which is the unit this read pages. The instance read's
20891
+ // own totals count findings; the two deliberately answer different
20892
+ // questions and are never summed.
20893
+ types: external_exports.number().int().nonnegative()
20825
20894
  }),
20826
20895
  facets: FindingFacets,
20827
- items: external_exports.array(FindingGroup),
20896
+ items: external_exports.array(FindingTypeSummary),
20828
20897
  nextCursor: external_exports.string().nullable(),
20829
20898
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20830
20899
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20832,7 +20901,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20832
20901
  // every firing, so the two numbers legitimately differ — this map lets a
20833
20902
  // session-scoped view show both.
20834
20903
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20835
- }).meta({ id: "ListGroupedFindingsResponse" });
20904
+ }).meta({ id: "ListFindingTypesResponse" });
20836
20905
  var ApplyFindingActionRequest = external_exports.object({
20837
20906
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20838
20907
  // it, so it is excluded from the request contract. The mapping helper
@@ -20862,16 +20931,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20862
20931
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20863
20932
  var ListFindingInstancesQuery = external_exports.object({
20864
20933
  severity: external_exports.array(Severity).optional(),
20865
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20934
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20935
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20866
20936
  subtype: external_exports.array(external_exports.string()).optional(),
20867
20937
  provider: external_exports.array(FindingProvider).optional(),
20868
20938
  action: external_exports.array(FindingAction).optional(),
20869
20939
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20870
- // the grouped query's group-level fold.
20940
+ // the types query's type-level fold.
20871
20941
  status: external_exports.array(FindingStatus).optional(),
20872
20942
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20873
20943
  // where the free-text `q` can only match the rendered "via Bash" label.
20874
20944
  tool: external_exports.array(external_exports.string()).optional(),
20945
+ // The delivery state of each finding's event (see FindingDelivery).
20946
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20875
20947
  // Exact repository / file-path matches, for the drill-down out of the
20876
20948
  // locations view. A row whose event carries no repo/file matches neither.
20877
20949
  repo: external_exports.string().optional(),
@@ -20884,37 +20956,51 @@ var ListFindingInstancesQuery = external_exports.object({
20884
20956
  });
20885
20957
  var ListFindingInstancesResponse = external_exports.object({
20886
20958
  // Instances matching the filters across the whole scope, not just this
20887
- // page — cursor-independent, like the grouped list's totals.
20959
+ // page — cursor-independent, like the types list's totals.
20888
20960
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20889
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20961
+ // Counts in INSTANCES here, where the types response counts types. Each
20890
20962
  // dimension still excludes its own filter.
20891
20963
  facets: FindingFacets,
20892
20964
  items: external_exports.array(FindingInstanceDetail),
20893
20965
  nextCursor: external_exports.string().nullable()
20894
20966
  }).meta({ id: "ListFindingInstancesResponse" });
20895
- var FindingLocationFile = external_exports.object({
20896
- // Empty when the instances carried no file path (a prompt or a tool call
20897
- // with no file attribution).
20898
- file: external_exports.string(),
20899
- instanceCount: external_exports.number().int().nonnegative(),
20900
- maxSeverity: Severity,
20901
- latestDetectedAt: external_exports.iso.datetime(),
20902
- // Folded from the instances' derived statuses with the same
20903
- // open-dominates precedence a group uses.
20904
- status: FindingStatus.optional(),
20905
- // Distinct rules seen at this location, capped — the row shows them as
20906
- // chips, and the count is what conveys scale.
20907
- ruleIds: external_exports.array(external_exports.string())
20908
- }).meta({ id: "FindingLocationFile" });
20909
- var FindingLocationRepo = external_exports.object({
20967
+ var ListFindingInstancesPage = external_exports.object({
20968
+ items: external_exports.array(FindingInstanceDetail),
20969
+ nextCursor: external_exports.string().nullable()
20970
+ }).meta({ id: "ListFindingInstancesPage" });
20971
+ var FindingLocationSummary = external_exports.object({
20972
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20973
+ // because a location's identity is two values and a URL param carries one:
20974
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20975
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20976
+ // client's page dedupe — never decoded, and never a sort key.
20977
+ id: external_exports.string(),
20910
20978
  /** Empty when the instances carried no repo attribute. */
20911
20979
  repo: external_exports.string(),
20980
+ // Empty when the instances carried no file path (a prompt, or a tool call
20981
+ // with no file attribution). Both halves empty is a real location — usually
20982
+ // the largest one in a store — and is selectable like any other.
20983
+ file: external_exports.string(),
20912
20984
  instanceCount: external_exports.number().int().nonnegative(),
20985
+ // The WORST severity present, not the first row's. It is this list's primary
20986
+ // sort key, so it is also what explains why a row is where it is, and it is
20987
+ // how a reader decides what to open without opening everything.
20913
20988
  maxSeverity: Severity,
20914
20989
  latestDetectedAt: external_exports.iso.datetime(),
20990
+ // Folded from the instances' derived statuses with the same open-dominates
20991
+ // precedence a group uses, so it answers "is anything left to do here" and
20992
+ // not much more: a location holding 1 open among 40 resolved reads like one
20993
+ // holding 40 open. That loss is accepted — the panel beside this list
20994
+ // carries each finding's own status, and instanceCount sits next to the
20995
+ // badge.
20915
20996
  status: FindingStatus.optional(),
20916
- files: external_exports.array(FindingLocationFile)
20917
- }).meta({ id: "FindingLocationRepo" });
20997
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20998
+ // tally rather than a sample and a row can say how many there are. Bounded
20999
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
21000
+ ruleIds: external_exports.array(external_exports.string())
21001
+ }).meta({ id: "FindingLocationSummary" });
21002
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
21003
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20918
21004
  var ListFindingLocationsQuery = external_exports.object({
20919
21005
  severity: external_exports.array(Severity).optional(),
20920
21006
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20924,21 +21010,47 @@ var ListFindingLocationsQuery = external_exports.object({
20924
21010
  // instances that match, and folds its status from those.
20925
21011
  status: external_exports.array(FindingStatus).optional(),
20926
21012
  tool: external_exports.array(external_exports.string()).optional(),
21013
+ // The delivery state of each finding's event (see FindingDelivery).
21014
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20927
21015
  q: external_exports.string().optional(),
20928
21016
  sessionId: external_exports.string().optional(),
20929
21017
  from: external_exports.iso.datetime().optional(),
20930
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21018
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21019
+ // even when the cursor has already advanced past its sort position — the
21020
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21021
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21022
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21023
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21024
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21025
+ includeId: external_exports.string().optional(),
21026
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21027
+ cursor: external_exports.string().optional()
20931
21028
  });
20932
21029
  var ListFindingLocationsResponse = external_exports.object({
20933
21030
  totals: external_exports.object({
21031
+ // Findings matching the filters across the whole scope. Unlike the types
21032
+ // read's same-named field this needs no caveat: the filters here narrow
21033
+ // per finding, so this is the sum of every row's instanceCount.
20934
21034
  findings: external_exports.number().int().nonnegative(),
20935
- repos: external_exports.number().int().nonnegative(),
20936
- files: external_exports.number().int().nonnegative()
21035
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21036
+ // states. The facets beside it count FINDINGS (see below); a surface
21037
+ // showing both says which is which.
21038
+ locations: external_exports.number().int().nonnegative()
20937
21039
  }),
20938
- /** Sorted by max severity, then most recent. */
20939
- items: external_exports.array(FindingLocationRepo),
20940
- /** Whether `limit` truncated the repo list. */
20941
- hasMore: external_exports.boolean()
21040
+ // Counts in FINDINGS, where the types response counts types, each dimension
21041
+ // still excluding its own filter. Deliberately not locations: counting those
21042
+ // needs a set of location keys per dimension per value — memory tracking the
21043
+ // store times the vocabulary, in a read whose scan promises flat memory —
21044
+ // and the cheap per-location version is not an approximation but WRONG. A
21045
+ // location holding {claudecode, block} and {codex, warn} would survive
21046
+ // provider=claudecode AND action=warn, under which no single finding
21047
+ // matches, so the facet would contradict the instanceCount this whole view
21048
+ // rests on. Findings also keep the toolbar in the same unit as the page
21049
+ // tally and the panel it sits above.
21050
+ facets: FindingFacets,
21051
+ /** Sorted by max severity, then most recent, then (repo, file). */
21052
+ items: external_exports.array(FindingLocationSummary),
21053
+ nextCursor: external_exports.string().nullable()
20942
21054
  }).meta({ id: "ListFindingLocationsResponse" });
20943
21055
 
20944
21056
  // ../../packages/schema/src/zod/meta.ts
@@ -21102,6 +21214,10 @@ var CaptureAttributes = external_exports.object({
21102
21214
  // to 'allow' — the enforcement audit trail's link back to the grant that
21103
21215
  // authorized the bypass.
21104
21216
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21217
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21218
+ // join back to the `llm_call` leaf for the same assistant turn.
21219
+ message_id: external_exports.string().optional(),
21220
+ conversation_id: external_exports.string().optional(),
21105
21221
  // Whole milliseconds this capture's inspection blocked its caller — the
21106
21222
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21107
21223
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21110,7 +21226,19 @@ var CaptureAttributes = external_exports.object({
21110
21226
  // inline json_extract and is not itself an optimization.
21111
21227
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21112
21228
  // before the measurement shipped — never present as a placeholder 0.
21113
- inspection_ms: external_exports.number().int().nonnegative().optional()
21229
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21230
+ // What a `redact` this capture could not carry out became instead (see
21231
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21232
+ // degrade actually happened, so absence is the ordinary case rather than a
21233
+ // reader having to distinguish it from a zero.
21234
+ //
21235
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21236
+ // so on a multi-finding row this does not say which finding degraded, and
21237
+ // its presence does not mean the fallback decided the capture's action. A
21238
+ // capture denied by another finding's own Block policy carries `block`
21239
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21240
+ // repeated rather than referenced because a store reader opens this file.
21241
+ redact_degraded_to: ActionTaken.optional()
21114
21242
  }).catchall(external_exports.unknown());
21115
21243
  var ToolCallInspection = external_exports.object({
21116
21244
  ruleId: external_exports.string().min(1),
@@ -21309,7 +21437,17 @@ var AuditEvent = external_exports.object({
21309
21437
  /** `share` to a first-party/internal destination. */
21310
21438
  internal: external_exports.boolean(),
21311
21439
  /** Event needs review (e.g. unverified egress). */
21312
- flagged: external_exports.boolean()
21440
+ flagged: external_exports.boolean(),
21441
+ /**
21442
+ * The body this event's `title` is drawn from was cleared by local body
21443
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21444
+ *
21445
+ * A separate flag rather than a sentinel written into `title`: the title is
21446
+ * rendered text, and a store-layer module that invented display copy for it
21447
+ * would be choosing words the view is supposed to choose. Additive and
21448
+ * defaulted, so an older producer still validates.
21449
+ */
21450
+ bodyExpired: external_exports.boolean().default(false)
21313
21451
  }).meta({ id: "ActivityAuditEvent" });
21314
21452
  var ActivitySessionSummary = external_exports.object({
21315
21453
  id: external_exports.string(),
@@ -22107,6 +22245,14 @@ var ControlPlaneErrorBody = external_exports.object({
22107
22245
  message: external_exports.string().optional()
22108
22246
  }).optional()
22109
22247
  });
22248
+ var RemoteFailureKind = external_exports.enum([
22249
+ "unauthorized",
22250
+ "forbidden",
22251
+ "route-absent",
22252
+ "invalid-request",
22253
+ "rejected",
22254
+ "unreachable"
22255
+ ]);
22110
22256
  var AttachDeviceRequest = external_exports.object({
22111
22257
  // This machine's own continuity id, so re-attaching ROTATES the credential
22112
22258
  // on one machine record instead of producing a second one. Client-minted
@@ -22642,6 +22788,12 @@ var EventMetadata = external_exports.object({
22642
22788
  // to 'allow' — the enforcement audit trail's link back to the grant that
22643
22789
  // authorized the bypass. Absent on captures where no exception applied.
22644
22790
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22791
+ // The assistant message this capture belongs to, and the conversation it sits
22792
+ // in — set by the browser extension's network capture so a stored `response`
22793
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22794
+ // on every other capture path, which has no such id.
22795
+ messageId: external_exports.string().optional(),
22796
+ conversationId: external_exports.string().optional(),
22645
22797
  // How long THIS capture's inspection blocked its caller, in whole
22646
22798
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22647
22799
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22654,7 +22806,37 @@ var EventMetadata = external_exports.object({
22654
22806
  // Absent is also what every pre-measurement client writes, and what a
22655
22807
  // clock failure degrades to — a reader must treat absence as "not measured"
22656
22808
  // and never as a zero, which would read as "inspection is free".
22657
- inspectionMs: external_exports.number().int().nonnegative().optional()
22809
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22810
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22811
+ // workspace's `redactFallback`, applied because the field could not be
22812
+ // masked in place (a shell command, a URL, or any argument on a host whose
22813
+ // hook contract offers no rewrite channel).
22814
+ //
22815
+ // It exists because the action alone cannot say why. A finding recorded as
22816
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22817
+ // assigned Redact on a field that could not take one — and those are
22818
+ // different facts about the same row: the first is a policy the user chose,
22819
+ // the second is a masking the host could not perform. Absent means no
22820
+ // degrade happened, which is every ordinary capture.
22821
+ //
22822
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22823
+ // is the CAPTURE while `actionTaken` is per FINDING:
22824
+ //
22825
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22826
+ // `redact` alongside a finding ASSIGNED the same action stores both
22827
+ // identically and one reason for the pair; attributing it to both
22828
+ // describes the assigned one wrongly, and to neither loses the degrade.
22829
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22830
+ // became, not the reason the capture ended as it did — a capture denied
22831
+ // by some other finding's own Block policy still carries `block` here,
22832
+ // and clearing the workspace's fallback would not have let it through.
22833
+ // Gate on the value against what a fallback can produce; never read the
22834
+ // field's presence as "this was the fallback's doing".
22835
+ //
22836
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22837
+ // Closing either means moving the reason onto the finding row, which
22838
+ // already carries its own action.
22839
+ redactDegradedTo: ActionTaken.optional()
22658
22840
  }).meta({ id: "EventMetadata" });
22659
22841
  var Event = external_exports.object({
22660
22842
  id: external_exports.guid(),
@@ -22764,7 +22946,32 @@ var RotateKeyInput = external_exports.object({
22764
22946
  confirmation: external_exports.string()
22765
22947
  });
22766
22948
 
22949
+ // ../../packages/schema/src/zod/finding-delivery.ts
22950
+ var KNOWN_REASONS = SyncFailureReason.options;
22951
+ function knownReason(value) {
22952
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22953
+ }
22954
+ function deriveFindingDelivery(row) {
22955
+ if (row.kind === "code_change") return { state: "local_scan" };
22956
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22957
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22958
+ }
22959
+ if (row.syncedAt !== null) {
22960
+ const reason = knownReason(row.syncFailure);
22961
+ return {
22962
+ state: "not_sent",
22963
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22964
+ ...reason === void 0 ? {} : { reason }
22965
+ };
22966
+ }
22967
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22968
+ return { state: "never_offered" };
22969
+ }
22970
+
22767
22971
  // ../../packages/schema/src/zod/findings-group-build.ts
22972
+ function lookupOwn(map2, key) {
22973
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22974
+ }
22768
22975
  function toApiAction(dbVal) {
22769
22976
  const map2 = {
22770
22977
  log: "monitored",
@@ -22773,7 +22980,7 @@ function toApiAction(dbVal) {
22773
22980
  warn: "warned",
22774
22981
  allow: "allowed"
22775
22982
  };
22776
- return map2[dbVal] ?? "allowed";
22983
+ return lookupOwn(map2, dbVal) ?? "allowed";
22777
22984
  }
22778
22985
  function toApiCategory(dbVal) {
22779
22986
  if (dbVal === "code_context") return "source_code";
@@ -22781,13 +22988,18 @@ function toApiCategory(dbVal) {
22781
22988
  return parsed2.success ? parsed2.data : "custom";
22782
22989
  }
22783
22990
  function toApiProvider(sourceTool) {
22784
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22991
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22785
22992
  }
22786
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22993
+ var FINDING_STATUS_PRECEDENCE = [
22994
+ "open",
22995
+ "handled",
22996
+ "dismissed",
22997
+ "resolved"
22998
+ ];
22787
22999
  function foldGroupStatus(instanceStatuses) {
22788
23000
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22789
23001
  if (statuses.size === 0) return void 0;
22790
- for (const candidate of STATUS_PRECEDENCE) {
23002
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22791
23003
  if (statuses.has(candidate)) return candidate;
22792
23004
  }
22793
23005
  return void 0;
@@ -22800,139 +23012,62 @@ function deriveFindingStatus(row) {
22800
23012
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22801
23013
  return "open";
22802
23014
  }
22803
- function distinctUsers(instances) {
22804
- const seen = /* @__PURE__ */ new Set();
22805
- const users = [];
22806
- for (const i of instances) {
22807
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22808
- seen.add(i.user.id);
22809
- users.push(i.user);
22810
- }
22811
- return users;
22812
- }
22813
23015
  function sortUsers(users) {
22814
23016
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22815
23017
  }
22816
- function buildFindingGroups(rows, opts = {}) {
22817
- const overrides = opts.overrides;
23018
+ function buildFindingTypes(aggregates, opts = {}) {
22818
23019
  const packNames = opts.packNames;
22819
- const aggregates = opts.aggregates;
22820
- const byRuleId = /* @__PURE__ */ new Map();
22821
- for (const row of rows) {
22822
- const existing = byRuleId.get(row.ruleId);
22823
- if (existing) existing.push(row);
22824
- else byRuleId.set(row.ruleId, [row]);
22825
- }
22826
- const groups = [];
22827
- for (const [ruleId, ruleRows] of byRuleId) {
22828
- const instances = ruleRows.map((r) => {
22829
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22830
- return {
22831
- id: r.id,
22832
- provider: toApiProvider(r.sourceTool),
22833
- repo: r.repo,
22834
- file: r.file,
22835
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22836
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22837
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22838
- ...r.user === void 0 ? {} : { user: r.user },
22839
- action: toApiAction(effectiveDbAction),
22840
- detectedAt: r.occurredAt,
22841
- confidence: r.confidence,
22842
- status: r.status
22843
- };
22844
- });
22845
- const agg = aggregates?.get(ruleId);
22846
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22847
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22848
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22849
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22850
- );
22851
- const seenProviders = /* @__PURE__ */ new Set();
22852
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22853
- if (seenProviders.has(p)) return false;
22854
- seenProviders.add(p);
22855
- return true;
22856
- });
22857
- const actionSet = new Set(
22858
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22859
- );
23020
+ const types = [];
23021
+ for (const [ruleId, agg] of aggregates) {
23022
+ const users = sortUsers(agg.users ?? []);
23023
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23024
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22860
23025
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22861
- const severity = ruleRows[0]?.severity ?? "low";
22862
- const detection = {
22863
- id: ruleId,
22864
- name: packNames?.get(ruleId) ?? null
22865
- };
22866
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22867
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22868
- const match = {
22869
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22870
- contextPrefix: ""
22871
- // empty (pending privacy review)
22872
- };
22873
- const status = foldGroupStatus(
22874
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22875
- );
22876
- const group = {
23026
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23027
+ const type = {
22877
23028
  id: ruleId,
22878
23029
  category: apiCategory,
22879
23030
  subtype: ruleId,
22880
23031
  // human label comes with pack metadata later
22881
- severity,
22882
- match,
22883
- detection,
22884
- policy,
22885
- instanceCount: agg?.instanceCount ?? instances.length,
23032
+ severity: agg.severity ?? "low",
23033
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23034
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23035
+ instanceCount: agg.instanceCount,
22886
23036
  providers,
22887
23037
  aggregateAction,
22888
- latestDetectedAt,
22889
- instances,
22890
- status,
23038
+ latestDetectedAt: agg.latestDetectedAt,
23039
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22891
23040
  ...users.length > 0 ? { users } : {}
22892
23041
  };
22893
- if (agg) {
22894
- actionsCache.set(group, [...actionSet]);
22895
- if (agg.searchText !== void 0) {
22896
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22897
- }
23042
+ actionsCache.set(type, [...actionSet]);
23043
+ if (agg.searchText !== void 0) {
23044
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22898
23045
  }
22899
- groups.push(group);
23046
+ types.push(type);
22900
23047
  }
22901
- return groups;
23048
+ return types;
22902
23049
  }
22903
23050
  var haystackCache = /* @__PURE__ */ new WeakMap();
22904
- function buildHaystack(g, extra) {
23051
+ function buildHaystack(t, extra) {
22905
23052
  return [
22906
- g.subtype,
22907
- g.category,
22908
- g.match.maskedValue,
22909
- g.policy.name,
22910
- g.id,
22911
- ...g.instances.map((i) => i.repo),
22912
- ...g.instances.map((i) => i.file),
22913
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22914
- ...g.instances.map((i) => i.id),
22915
- // The people: the whole group's list when the store folded one, plus the
22916
- // preview's own — the two overlap, and a haystack does not mind.
22917
- ...(g.users ?? []).map((u) => u.name),
22918
- ...g.instances.map((i) => i.user?.name ?? ""),
23053
+ t.subtype,
23054
+ t.category,
23055
+ t.policy.name,
23056
+ t.id,
23057
+ ...(t.users ?? []).map((u) => u.name),
22919
23058
  ...extra === void 0 ? [] : [extra]
22920
23059
  ].join(" ").toLowerCase();
22921
23060
  }
22922
- function groupHaystack(g) {
22923
- const cached2 = haystackCache.get(g);
23061
+ function typeHaystack(t) {
23062
+ const cached2 = haystackCache.get(t);
22924
23063
  if (cached2 !== void 0) return cached2;
22925
- const haystack = buildHaystack(g);
22926
- haystackCache.set(g, haystack);
23064
+ const haystack = buildHaystack(t);
23065
+ haystackCache.set(t, haystack);
22927
23066
  return haystack;
22928
23067
  }
22929
23068
  var actionsCache = /* @__PURE__ */ new WeakMap();
22930
- function groupActions(g) {
22931
- const cached2 = actionsCache.get(g);
22932
- if (cached2 !== void 0) return cached2;
22933
- const actions = [...new Set(g.instances.map((i) => i.action))];
22934
- actionsCache.set(g, actions);
22935
- return actions;
23069
+ function typeActions(t) {
23070
+ return actionsCache.get(t) ?? [];
22936
23071
  }
22937
23072
  function countInstancesByStatus(statusInputs, statuses) {
22938
23073
  const statusSet = new Set(statuses);
@@ -22943,8 +23078,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22943
23078
  }
22944
23079
  return sum;
22945
23080
  }
22946
- function applyFindingFilters(groups, opts) {
22947
- let filtered = groups;
23081
+ function applyFindingFilters(types, opts) {
23082
+ let filtered = types;
22948
23083
  if (opts.severity && opts.severity.length > 0) {
22949
23084
  const sevSet = new Set(opts.severity);
22950
23085
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22955,7 +23090,7 @@ function applyFindingFilters(groups, opts) {
22955
23090
  }
22956
23091
  if (opts.actions && opts.actions.length > 0) {
22957
23092
  const actionSet = new Set(opts.actions);
22958
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23093
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22959
23094
  }
22960
23095
  if (opts.subtype && opts.subtype.length > 0) {
22961
23096
  const subtypeSet = new Set(opts.subtype);
@@ -22967,26 +23102,31 @@ function applyFindingFilters(groups, opts) {
22967
23102
  }
22968
23103
  if (opts.q) {
22969
23104
  const q = opts.q.toLowerCase();
22970
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23105
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22971
23106
  }
22972
23107
  return filtered;
22973
23108
  }
22974
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22975
- var SEVERITY_RANK = SEVERITY_ORDER;
23109
+ function rankByOrder(members2) {
23110
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23111
+ }
23112
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23113
+ function severityRank(severity) {
23114
+ return lookupOwn(SEVERITY_RANK, severity);
23115
+ }
22976
23116
  function compareFindingGroupOrder(a, b) {
22977
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22978
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23117
+ const rankA = severityRank(a.severity) ?? -1;
23118
+ const rankB = severityRank(b.severity) ?? -1;
22979
23119
  const severityDiff = rankA - rankB;
22980
23120
  if (severityDiff !== 0) return severityDiff;
22981
23121
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22982
23122
  if (recencyDiff !== 0) return recencyDiff;
22983
23123
  return a.id.localeCompare(b.id);
22984
23124
  }
22985
- function sortFindingGroups(groups) {
22986
- return [...groups].sort(compareFindingGroupOrder);
23125
+ function sortFindingTypes(types) {
23126
+ return [...types].sort(compareFindingGroupOrder);
22987
23127
  }
22988
- function computeFindingFacets(allGroups, opts) {
22989
- const forSeverity = applyFindingFilters(allGroups, {
23128
+ function computeFindingFacets(allTypes, opts) {
23129
+ const forSeverity = applyFindingFilters(allTypes, {
22990
23130
  providers: opts.providers,
22991
23131
  actions: opts.actions,
22992
23132
  statuses: opts.statuses,
@@ -22997,7 +23137,7 @@ function computeFindingFacets(allGroups, opts) {
22997
23137
  for (const g of forSeverity) {
22998
23138
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22999
23139
  }
23000
- const forProvider = applyFindingFilters(allGroups, {
23140
+ const forProvider = applyFindingFilters(allTypes, {
23001
23141
  actions: opts.actions,
23002
23142
  statuses: opts.statuses,
23003
23143
  q: opts.q,
@@ -23008,7 +23148,7 @@ function computeFindingFacets(allGroups, opts) {
23008
23148
  for (const g of forProvider) {
23009
23149
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23010
23150
  }
23011
- const forAction = applyFindingFilters(allGroups, {
23151
+ const forAction = applyFindingFilters(allTypes, {
23012
23152
  providers: opts.providers,
23013
23153
  statuses: opts.statuses,
23014
23154
  q: opts.q,
@@ -23017,9 +23157,9 @@ function computeFindingFacets(allGroups, opts) {
23017
23157
  });
23018
23158
  const actionMap = /* @__PURE__ */ new Map();
23019
23159
  for (const g of forAction) {
23020
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23160
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23021
23161
  }
23022
- const forSubtype = applyFindingFilters(allGroups, {
23162
+ const forSubtype = applyFindingFilters(allTypes, {
23023
23163
  providers: opts.providers,
23024
23164
  actions: opts.actions,
23025
23165
  statuses: opts.statuses,
@@ -23028,7 +23168,7 @@ function computeFindingFacets(allGroups, opts) {
23028
23168
  });
23029
23169
  const subtypeMap = /* @__PURE__ */ new Map();
23030
23170
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23031
- const forStatus = applyFindingFilters(allGroups, {
23171
+ const forStatus = applyFindingFilters(allTypes, {
23032
23172
  providers: opts.providers,
23033
23173
  actions: opts.actions,
23034
23174
  q: opts.q,
@@ -23050,6 +23190,20 @@ function computeFindingFacets(allGroups, opts) {
23050
23190
  }
23051
23191
 
23052
23192
  // ../../packages/schema/src/zod/findings-flat-build.ts
23193
+ function compareCodePoints(a, b) {
23194
+ const aIter = a[Symbol.iterator]();
23195
+ const bIter = b[Symbol.iterator]();
23196
+ for (; ; ) {
23197
+ const aNext = aIter.next();
23198
+ const bNext = bIter.next();
23199
+ if (aNext.done && bNext.done) return 0;
23200
+ if (aNext.done) return -1;
23201
+ if (bNext.done) return 1;
23202
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23203
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23204
+ if (aPoint !== bPoint) return aPoint - bPoint;
23205
+ }
23206
+ }
23053
23207
  function rowHaystack(row) {
23054
23208
  return [
23055
23209
  row.ruleId,
@@ -23074,12 +23228,24 @@ function matchesDimension(row, opts, dimension) {
23074
23228
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23075
23229
  case "statuses":
23076
23230
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23231
+ case "deliveries":
23232
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23077
23233
  case "tools":
23078
23234
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23235
+ // An EMPTY value is a real filter here, not an absent one. The location
23236
+ // list buckets a finding whose event recorded no repo — or no file — under
23237
+ // the empty string, and selecting that bucket has to narrow the panel to
23238
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23239
+ // row omits the key, which every call site already does.
23240
+ //
23241
+ // Reading '' as unset is what this replaced, and it failed in the one place
23242
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23243
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23244
+ // — a row reading 3 findings beside a panel listing every finding there is.
23079
23245
  case "repo":
23080
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23246
+ return opts.repo === void 0 || row.repo === opts.repo;
23081
23247
  case "file":
23082
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23248
+ return opts.file === void 0 || row.file === opts.file;
23083
23249
  case "q":
23084
23250
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23085
23251
  }
@@ -23090,6 +23256,7 @@ var DIMENSIONS = [
23090
23256
  "providers",
23091
23257
  "actions",
23092
23258
  "statuses",
23259
+ "deliveries",
23093
23260
  "tools",
23094
23261
  "repo",
23095
23262
  "file",
@@ -23103,10 +23270,19 @@ function matchesInstanceFilters(row, opts, except) {
23103
23270
  return true;
23104
23271
  }
23105
23272
  function toItems(counts) {
23106
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23273
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23274
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23275
+ // NFD spelling of the same text) as equal, so a count tie between
23276
+ // them would otherwise be ordered by whichever the Map iteration
23277
+ // produced. compareCodePoints breaks that tie deterministically, which
23278
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23279
+ // which it need not: foldFacetTuples runs this same sort over grouped
23280
+ // tuples, so both paths order facets identically by construction.
23281
+ compareCodePoints(a.value, b.value)
23282
+ );
23107
23283
  }
23108
- function bump(counts, value) {
23109
- counts.set(value, (counts.get(value) ?? 0) + 1);
23284
+ function bump(counts, value, by = 1) {
23285
+ counts.set(value, (counts.get(value) ?? 0) + by);
23110
23286
  }
23111
23287
  function createInstanceFacetAccumulator(opts) {
23112
23288
  const severity = /* @__PURE__ */ new Map();
@@ -23115,6 +23291,7 @@ function createInstanceFacetAccumulator(opts) {
23115
23291
  const action = /* @__PURE__ */ new Map();
23116
23292
  const status = /* @__PURE__ */ new Map();
23117
23293
  const tool = /* @__PURE__ */ new Map();
23294
+ const deployment = /* @__PURE__ */ new Map();
23118
23295
  return {
23119
23296
  add(row) {
23120
23297
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23129,6 +23306,9 @@ function createInstanceFacetAccumulator(opts) {
23129
23306
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23130
23307
  bump(tool, row.toolName);
23131
23308
  }
23309
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23310
+ bump(deployment, row.delivery.state);
23311
+ }
23132
23312
  },
23133
23313
  facets: () => ({
23134
23314
  severity: toItems(severity),
@@ -23136,7 +23316,8 @@ function createInstanceFacetAccumulator(opts) {
23136
23316
  provider: toItems(provider),
23137
23317
  action: toItems(action),
23138
23318
  status: toItems(status),
23139
- tool: toItems(tool)
23319
+ tool: toItems(tool),
23320
+ deployment: toItems(deployment)
23140
23321
  })
23141
23322
  };
23142
23323
  }
@@ -23150,6 +23331,7 @@ function toInstanceDetail(row) {
23150
23331
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23151
23332
  eventId: row.eventId,
23152
23333
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23334
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23153
23335
  ...row.user === void 0 ? {} : { user: row.user },
23154
23336
  action: toApiAction(row.actionTaken),
23155
23337
  detectedAt: row.occurredAt,
@@ -23164,12 +23346,6 @@ function toInstanceDetail(row) {
23164
23346
  policy: { id: `category:${category}`, name: category }
23165
23347
  };
23166
23348
  }
23167
- var SEVERITY_ORDER2 = {
23168
- critical: 0,
23169
- high: 1,
23170
- medium: 2,
23171
- low: 3
23172
- };
23173
23349
  function newLocationAccumulator() {
23174
23350
  return {
23175
23351
  instanceCount: 0,
@@ -23184,7 +23360,7 @@ function newLocationAccumulator() {
23184
23360
  }
23185
23361
  function addToLocation(acc, row) {
23186
23362
  acc.instanceCount += 1;
23187
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23363
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23188
23364
  if (rank < acc.maxSeverityRank) {
23189
23365
  acc.maxSeverityRank = rank;
23190
23366
  acc.maxSeverity = row.severity;
@@ -23193,6 +23369,23 @@ function addToLocation(acc, row) {
23193
23369
  acc.statuses.push(row.status);
23194
23370
  acc.ruleIds.add(row.ruleId);
23195
23371
  }
23372
+ function compareLocationOrder(a, b) {
23373
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23374
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23375
+ if (rankA !== rankB) return rankA - rankB;
23376
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23377
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23378
+ }
23379
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23380
+ if (repoDiff !== 0) return repoDiff;
23381
+ return compareCodePoints(a.file, b.file);
23382
+ }
23383
+ function encodeLocationId(repo, file2) {
23384
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23385
+ }
23386
+ function encodePart(value) {
23387
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23388
+ }
23196
23389
 
23197
23390
  // ../../packages/schema/src/zod/installed-pack.ts
23198
23391
  var InstalledPack = external_exports.object({
@@ -23260,6 +23453,11 @@ var Policy = external_exports.object({
23260
23453
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23261
23454
  provenance: PolicyProvenance.optional()
23262
23455
  }).meta({ id: "Policy" });
23456
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23457
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23458
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23459
+ id: "RedactFallback"
23460
+ });
23263
23461
  var PolicyBundle = external_exports.object({
23264
23462
  version: external_exports.string(),
23265
23463
  policies: external_exports.array(Policy),
@@ -23307,6 +23505,16 @@ var PolicyBundle = external_exports.object({
23307
23505
  // control plane), so no name resolution stands between the decision and the
23308
23506
  // comparison.
23309
23507
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23508
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23509
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23510
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23511
+ // a control plane can tighten a machine and never loosen one — the same
23512
+ // direction `mergeRaiseOnly` enforces for policies.
23513
+ //
23514
+ // Optional so an older backend, and an older on-disk cache, still parses;
23515
+ // absent leaves the device's own setting in force, which is the behaviour
23516
+ // that predates the field and the safe direction to default.
23517
+ redactFallback: RedactFallback.optional(),
23310
23518
  customKeywords: external_exports.array(external_exports.string()),
23311
23519
  fetchedAt: external_exports.iso.datetime()
23312
23520
  }).meta({ id: "PolicyBundle" });
@@ -23336,11 +23544,6 @@ function severityFloorPolicy(category) {
23336
23544
  const peak = CATEGORY_PEAK_SEVERITY[category];
23337
23545
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23338
23546
  }
23339
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23340
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23341
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23342
- id: "RedactFallback"
23343
- });
23344
23547
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23345
23548
  var BUILTIN_POLICY_SPECS = {
23346
23549
  monitor: {
@@ -23396,6 +23599,11 @@ function isActionAtLeast(action, floor) {
23396
23599
  function strongerAction(a, b) {
23397
23600
  return actionRank(a) >= actionRank(b) ? a : b;
23398
23601
  }
23602
+ function strongerRedactFallback(local, remote) {
23603
+ if (remote === void 0) return local;
23604
+ const localAction = builtinPolicyToAction(local);
23605
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23606
+ }
23399
23607
  function weakestBuiltinAtLeast(floor) {
23400
23608
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23401
23609
  }
@@ -23636,7 +23844,7 @@ var VaultConsent = external_exports.object({
23636
23844
  });
23637
23845
 
23638
23846
  // ../../packages/schema/src/zod/local.ts
23639
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23847
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23640
23848
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23641
23849
  var RunMode = external_exports.enum(["standalone", "attached"]);
23642
23850
  var ControlPlaneConnection = external_exports.object({
@@ -23656,6 +23864,15 @@ var HistorySyncConsent = external_exports.object({
23656
23864
  payloadVersion: external_exports.number().int().positive(),
23657
23865
  endpoint: external_exports.string()
23658
23866
  });
23867
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23868
+ var BodyRetention = external_exports.object({
23869
+ enabled: external_exports.boolean().default(false),
23870
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23871
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23872
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23873
+ // candidate set that is already bounded by "delivered, or never owed".
23874
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23875
+ }).meta({ id: "BodyRetention" });
23659
23876
  var WorkspaceSettings = external_exports.object({
23660
23877
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23661
23878
  runMode: RunMode.default("standalone"),
@@ -23699,12 +23916,18 @@ var WorkspaceSettings = external_exports.object({
23699
23916
  // covers the current payload and must be re-granted.
23700
23917
  modelJudgeConsent: ModelJudgeConsent.optional(),
23701
23918
  // Records that the user consented to the DEFERRED send — the outbox — along
23702
- // with the payload shape and the endpoint they agreed to. Since payload v2
23703
- // that covers both the pre-attach backlog and undelivered captures (which
23704
- // carry prompt/reply text in `content`); the key name predates the widening.
23705
- // Absent until granted, and a grant for a different endpoint or an older
23706
- // payload no longer counts.
23707
- historySyncConsent: HistorySyncConsent.optional()
23919
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23920
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23921
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23922
+ // both widenings. Absent until granted, and a grant for a different endpoint
23923
+ // or an older payload no longer counts.
23924
+ historySyncConsent: HistorySyncConsent.optional(),
23925
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23926
+ // body never removes the row or its findings.
23927
+ bodyRetention: BodyRetention.default({
23928
+ enabled: false,
23929
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23930
+ })
23708
23931
  });
23709
23932
  function defaultWorkspaceSettings() {
23710
23933
  return WorkspaceSettings.parse({});
@@ -23799,12 +24022,15 @@ function toCaptureAttributes(event) {
23799
24022
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23800
24023
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23801
24024
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24025
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23802
24026
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23803
24027
  // has ever populated either), but every legacy metadata key still rides
23804
24028
  // the bag rather than being silently dropped — CaptureAttributes'
23805
24029
  // `.catchall(z.unknown())` carries the long tail.
23806
24030
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23807
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24031
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24032
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24033
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23808
24034
  };
23809
24035
  }
23810
24036
  function captureDefinitionVersion(finding) {
@@ -23832,10 +24058,22 @@ var ManagedSettingKey = external_exports.enum([
23832
24058
  "vaultInlineReveal",
23833
24059
  "modelJudgeConsent",
23834
24060
  "dataSharesInPlace",
23835
- "redactFallback"
24061
+ "redactFallback",
24062
+ // Pins the toggle and the day count together — see BodyRetention on why the
24063
+ // two are one unit. An administrator mandating a window wants the count
24064
+ // enforced with it, not one a user can widen while the toggle stays on.
24065
+ "bodyRetention"
23836
24066
  ]).meta({ id: "ManagedSettingKey" });
24067
+ function isManagedSettingKey(value) {
24068
+ return ManagedSettingKey.safeParse(value).success;
24069
+ }
23837
24070
  var ManagedSettingsValues = external_exports.object({
23838
24071
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24072
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24073
+ // plain, non-strict objects: a key under either that this build does not know
24074
+ // is stripped and nothing reports it. The unknown-value split in
24075
+ // ManagedSettings below classifies top-level names only, so it stops at
24076
+ // these boundaries.
23839
24077
  controlPlane: external_exports.object({
23840
24078
  endpoint: external_exports.string().min(1),
23841
24079
  label: external_exports.string().min(1).optional()
@@ -23846,7 +24084,8 @@ var ManagedSettingsValues = external_exports.object({
23846
24084
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23847
24085
  modelJudgeConsent: external_exports.boolean().optional(),
23848
24086
  dataSharesInPlace: external_exports.boolean().optional(),
23849
- redactFallback: RedactFallback.optional()
24087
+ redactFallback: RedactFallback.optional(),
24088
+ bodyRetention: BodyRetention.optional()
23850
24089
  }).meta({ id: "ManagedSettingsValues" });
23851
24090
  var ManagedSettings = external_exports.object({
23852
24091
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23854,11 +24093,59 @@ var ManagedSettings = external_exports.object({
23854
24093
  // decision from a bug. Absent renders as a generic "your organization".
23855
24094
  organization: external_exports.string().min(1).optional(),
23856
24095
  // What the administrator pinned.
23857
- values: ManagedSettingsValues.default({}),
24096
+ //
24097
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24098
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24099
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24100
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24101
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24102
+ // exactly the file an administrator is most likely to write while a fleet
24103
+ // is mid-upgrade.
24104
+ //
24105
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24106
+ // file, which is the outcome the lock half already rejected — an older
24107
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24108
+ // value still fails, because the nested schema is re-run over the known
24109
+ // subset and its issues are re-raised on this parse.
24110
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23858
24111
  // Which of those the user may not change. A key here with no matching value
23859
24112
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23860
24113
  // the user may still override. The two are separable on purpose.
23861
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24114
+ //
24115
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24116
+ // build does not know is dropped from the locked set and reported, never a
24117
+ // reason to refuse the file. The same shape reaches an older build whenever
24118
+ // an administrator locks a key a newer build added, and refusing it there
24119
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24120
+ // the fleets most likely to carry a version skew. A name outside the enum
24121
+ // is still never HONOURED: the lockable set stays explicit above.
24122
+ lockedFields: external_exports.array(external_exports.string()).default([])
24123
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24124
+ const known = [];
24125
+ const unknown2 = [];
24126
+ for (const name of lockedFields) {
24127
+ if (isManagedSettingKey(name)) known.push(name);
24128
+ else unknown2.push(name);
24129
+ }
24130
+ const knownValues = /* @__PURE__ */ Object.create(null);
24131
+ const unknownValues = [];
24132
+ for (const [name, value] of Object.entries(values)) {
24133
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24134
+ else unknownValues.push(name);
24135
+ }
24136
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24137
+ if (!pinned.success) {
24138
+ for (const issue2 of pinned.error.issues)
24139
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24140
+ return external_exports.NEVER;
24141
+ }
24142
+ return {
24143
+ ...rest,
24144
+ values: pinned.data,
24145
+ lockedFields: known,
24146
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24147
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24148
+ };
23862
24149
  }).meta({ id: "ManagedSettings" });
23863
24150
 
23864
24151
  // ../../packages/schema/src/zod/project-files.ts
@@ -23982,7 +24269,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23982
24269
  timestamp: external_exports.iso.date(),
23983
24270
  critical: external_exports.number().int().nonnegative(),
23984
24271
  high: external_exports.number().int().nonnegative(),
23985
- medium: external_exports.number().int().nonnegative()
24272
+ medium: external_exports.number().int().nonnegative(),
24273
+ // Optional and additive, so a producer written against the earlier
24274
+ // three-series contract keeps validating. A consumer plotting it resolves the
24275
+ // absent case itself — the chart point requires a number.
24276
+ low: external_exports.number().int().nonnegative().optional()
23986
24277
  }).meta({ id: "FindingsTimeseriesPoint" });
23987
24278
  var FindingsTimeseriesResponse = external_exports.object({
23988
24279
  range: TimeRange,
@@ -24008,6 +24299,10 @@ var ResolvedFeedItem = external_exports.object({
24008
24299
  findingKey: external_exports.string(),
24009
24300
  ruleId: external_exports.string(),
24010
24301
  severity: Severity,
24302
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24303
+ // identifies the file: a bare path matches the same name in every repo.
24304
+ // Optional and additive; empty when the event carried no repo.
24305
+ repo: external_exports.string().optional(),
24011
24306
  path: external_exports.string(),
24012
24307
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24013
24308
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24113,7 +24408,23 @@ var SaveSettingsInput = external_exports.object({
24113
24408
  modelJudgeConsent: ModelJudgeConsentChoice,
24114
24409
  historySyncConsent: HistorySyncConsentChoice,
24115
24410
  vaultConsent: external_exports.string(),
24116
- vaultInlineReveal: external_exports.string()
24411
+ vaultInlineReveal: external_exports.string(),
24412
+ // Widened to `string` like its neighbours rather than typed as
24413
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24414
+ // the call site, so the domain check receives the type it was written for.
24415
+ //
24416
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24417
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24418
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24419
+ // trade against. The real cost runs the other way and is the part worth
24420
+ // knowing: a value this schema admits and the domain enum then rejects lands
24421
+ // on the action's shared refusal, which names NO field, where a shape
24422
+ // rejection reaches `malformedInput` and names the schema key.
24423
+ redactFallback: external_exports.string(),
24424
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24425
+ // `BodyRetention`'s and the action checks it there, so there is one place
24426
+ // that decides what a legal horizon is rather than two that can drift.
24427
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24117
24428
  });
24118
24429
  var AttachInput = external_exports.object({
24119
24430
  endpoint: external_exports.string(),
@@ -24285,6 +24596,52 @@ function reviewSeverityRank(reasons) {
24285
24596
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24286
24597
  }
24287
24598
 
24599
+ // ../../packages/schema/src/zod/web-capture.ts
24600
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24601
+ var WebUsage = external_exports.object({
24602
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24603
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24604
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24605
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24606
+ });
24607
+ var WebToolCall = external_exports.object({
24608
+ toolUseId: external_exports.string().min(1),
24609
+ toolName: external_exports.string().min(1),
24610
+ target: external_exports.string().optional(),
24611
+ isError: external_exports.boolean().optional(),
24612
+ inputSize: external_exports.number().int().nonnegative().optional(),
24613
+ outputSize: external_exports.number().int().nonnegative().optional()
24614
+ });
24615
+ var WebExchange = external_exports.object({
24616
+ messageId: external_exports.string().min(1),
24617
+ startedAt: external_exports.iso.datetime(),
24618
+ model: external_exports.string().optional(),
24619
+ usage: WebUsage.optional(),
24620
+ usageSource: WebUsageSource,
24621
+ stopReason: external_exports.string().optional(),
24622
+ conversationId: external_exports.string().optional(),
24623
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24624
+ toolCalls: external_exports.array(WebToolCall).default([]),
24625
+ // Absent when the adapter recovered no text. Capped by the caller at
24626
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24627
+ // short capture is never mistaken for a short reply.
24628
+ responseText: external_exports.string().optional(),
24629
+ truncated: external_exports.boolean().default(false)
24630
+ });
24631
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24632
+ var WebCaptureStatus = external_exports.object({
24633
+ patched: external_exports.boolean(),
24634
+ live: external_exports.boolean(),
24635
+ blind: external_exports.boolean(),
24636
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24637
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24638
+ parseFailures: external_exports.number().int().nonnegative(),
24639
+ unparsedBodies: external_exports.number().int().nonnegative(),
24640
+ // The adapter-declared JSON key paths that were absent from a real payload —
24641
+ // the earliest signal that a site's contract moved.
24642
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24643
+ });
24644
+
24288
24645
  // ../../packages/persistence/src/paths.ts
24289
24646
  import {
24290
24647
  chmodSync,
@@ -24645,6 +25002,22 @@ function discardStore(file2, backup) {
24645
25002
  }
24646
25003
  }
24647
25004
 
25005
+ // ../../packages/persistence/src/internal/sql-functions.ts
25006
+ var utf8 = new TextDecoder();
25007
+ function akaLower(value) {
25008
+ if (value === null) return null;
25009
+ if (typeof value === "string") return value.toLowerCase();
25010
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25011
+ return utf8.decode(value).toLowerCase();
25012
+ }
25013
+ function registerSqlFunctions(db) {
25014
+ db.function(
25015
+ "aka_lower",
25016
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25017
+ akaLower
25018
+ );
25019
+ }
25020
+
24648
25021
  // ../../packages/persistence/src/internal/sql-text.ts
24649
25022
  function escapeLikePattern(s) {
24650
25023
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24729,6 +25102,11 @@ function schemaObjectExists(db, kind, name) {
24729
25102
  function indexExists(db, name) {
24730
25103
  return schemaObjectExists(db, "index", name);
24731
25104
  }
25105
+ function indexColumns(db, name) {
25106
+ if (!indexExists(db, name)) return [];
25107
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25108
+ return columns.map((c) => c.name).filter((c) => c !== null);
25109
+ }
24732
25110
  function columnNames(db, table, opts) {
24733
25111
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24734
25112
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24790,141 +25168,783 @@ function mapRowsTolerant(rows, map2) {
24790
25168
  return out;
24791
25169
  }
24792
25170
 
24793
- // ../../packages/persistence/src/migrations.ts
24794
- function describeObject(object2) {
24795
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24796
- }
24797
- function splitStatements(sql) {
24798
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24799
- }
24800
- function createdIndexName(statement) {
24801
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24802
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25171
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25172
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25173
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25174
+
25175
+ // ../../packages/persistence/src/sync-failure.ts
25176
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25177
+ function syncFailureRejectCondition(column = "sync_failure") {
25178
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25179
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24803
25180
  }
24804
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24805
- function applyMigrations(db, file2) {
24806
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24807
- db.exec(
24808
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24809
- );
24810
- const applied = new Set(
24811
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24812
- );
24813
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24814
- const record2 = db.prepare(
24815
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24816
- );
24817
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24818
- if (applied.has(migration.tag)) continue;
24819
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24820
- const evidence = evidenceObjects(migration.sql);
24821
- const present = evidence.filter((o) => evidenceExists(db, o));
24822
- if (present.length > 0 && present.length < evidence.length) {
24823
- const missing = evidence.filter((o) => !present.includes(o));
24824
- 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.`;
24825
- akaWarn(message);
24826
- throw new Error(`[aka] ${message}`);
24827
- }
24828
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24829
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24830
- const statements = splitStatements(migration.sql);
24831
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24832
- try {
24833
- withTransaction(
24834
- db,
24835
- () => {
24836
- for (const statement of statements) {
24837
- const indexName = createdIndexName(statement);
24838
- if (indexName === void 0) {
24839
- if (alreadyApplied) continue;
24840
- } else if (indexExists(db, indexName)) {
24841
- continue;
24842
- }
24843
- db.exec(statement);
24844
- }
24845
- if (wantsFkOff && !alreadyApplied) {
24846
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24847
- if (violations.length > 0) {
24848
- throw new Error(
24849
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24850
- );
24851
- }
24852
- }
24853
- record2.run(migration.tag, Date.now());
24854
- },
24855
- "IMMEDIATE"
24856
- );
24857
- } finally {
24858
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24859
- }
25181
+
25182
+ // ../../packages/persistence/src/repositories/history-sync.ts
25183
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25184
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25185
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25186
+ var COUNTED_EVENT_TYPES = [
25187
+ ...STRUCTURAL_EVENT_TYPES,
25188
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25189
+ ];
25190
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25191
+ var PARTITION_BUCKETS = `
25192
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25193
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25194
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25195
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25196
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25197
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25198
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25199
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25200
+ -- added later lands in no bucket and fails the sum assertion, instead
25201
+ -- of silently joining this one.
25202
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25203
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25204
+ THEN 1 ELSE 0 END) AS failed,
25205
+ COUNT(*) AS total`;
25206
+ var COUNTED_SCOPE = `
25207
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25208
+ AND (
25209
+ event_type IN (${TYPE_LIST})
25210
+ OR synced_at IS NOT NULL
25211
+ OR outbox_owed = 1
25212
+ )`;
25213
+ var SKIPPED = -1;
25214
+ var ROW_COLUMNS = `id,
25215
+ parent_id AS parentId,
25216
+ root_session_id AS rootSessionId,
25217
+ event_type AS eventType,
25218
+ host_id AS hostId,
25219
+ harness_id AS harnessId,
25220
+ source_project_id AS sourceProjectId,
25221
+ started_at AS startedAt,
25222
+ ended_at AS endedAt,
25223
+ severity,
25224
+ priority,
25225
+ content,
25226
+ content_hash AS contentHash,
25227
+ attributes`;
25228
+ var SqliteHistorySyncRepository = class {
25229
+ constructor(db) {
25230
+ this.db = db;
25231
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25232
+ this.sessionsStmt = db.prepare(
25233
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25234
+ FROM audit_events
25235
+ WHERE synced_at IS NULL
25236
+ AND event_type IN (${TYPE_LIST})
25237
+ AND started_at < :before
25238
+ GROUP BY sessionId
25239
+ ORDER BY earliest
25240
+ LIMIT :limit`
25241
+ );
25242
+ this.rowsStmt = db.prepare(
25243
+ `SELECT ${ROW_COLUMNS}
25244
+ FROM audit_events
25245
+ WHERE synced_at IS NULL
25246
+ AND event_type IN (${TYPE_LIST})
25247
+ AND started_at < :before
25248
+ AND COALESCE(root_session_id, id) = :sessionId
25249
+ ORDER BY (event_type = 'session') DESC, started_at
25250
+ LIMIT :limit`
25251
+ );
25252
+ this.captureRowsStmt = db.prepare(
25253
+ `SELECT ${ROW_COLUMNS}
25254
+ FROM audit_events
25255
+ WHERE synced_at IS NULL
25256
+ AND sync_claimed_at IS NULL
25257
+ AND outbox_owed = 1
25258
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25259
+ AND started_at < :before
25260
+ ORDER BY started_at
25261
+ LIMIT :limit`
25262
+ );
25263
+ this.markOwedStmt = db.prepare(
25264
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25265
+ );
25266
+ this.markCaptureBacklogOwedStmt = db.prepare(
25267
+ `UPDATE audit_events SET outbox_owed = 1
25268
+ WHERE synced_at IS NULL
25269
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25270
+ AND started_at < :before`
25271
+ );
25272
+ this.stampStmt = db.prepare(
25273
+ `UPDATE audit_events
25274
+ SET synced_at = :at,
25275
+ sync_claimed_at = NULL,
25276
+ sync_failed_at = :failedAt,
25277
+ sync_failure = :failure
25278
+ WHERE id = :id`
25279
+ );
25280
+ this.claimRowStmt = db.prepare(
25281
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25282
+ );
25283
+ this.releaseRowStmt = db.prepare(
25284
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25285
+ );
25286
+ this.releaseStaleClaimsStmt = db.prepare(
25287
+ `UPDATE audit_events SET sync_claimed_at = NULL
25288
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25289
+ );
25290
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25291
+ FROM audit_events${COUNTED_SCOPE}`);
25292
+ this.partitionByKindStmt = db.prepare(
25293
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25294
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25295
+ GROUP BY event_type`
25296
+ );
25297
+ this.countsStmt = db.prepare(
25298
+ `SELECT
25299
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25300
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25301
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25302
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25303
+ THEN 1 ELSE 0 END) AS skipped,
25304
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25305
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25306
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25307
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25308
+ FROM audit_events
25309
+ WHERE event_type IN (${TYPE_LIST})`
25310
+ );
25311
+ this.captureSkipCountStmt = db.prepare(
25312
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25313
+ // way the structural totals are. The split exists because a refusal is
25314
+ // terminal only against the deployment that gave it, and the structural
25315
+ // re-arm frees it on a change of deployment. The capture lane has no such
25316
+ // escape: re-arming a capture would offer one deployment's undelivered
25317
+ // prompts, with their text, to a deployment that never saw them, which is
25318
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25319
+ // reasons mean the same thing — this row will not be sent — and splitting
25320
+ // them would put refused captures in a bucket nothing reads and nothing
25321
+ // frees.
25322
+ `SELECT COUNT(*) AS skipped
25323
+ FROM audit_events
25324
+ WHERE synced_at = ${String(SKIPPED)}
25325
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25326
+ );
25327
+ this.fingerprintStmt = db.prepare(
25328
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25329
+ FROM history_sync WHERE id = 1`
25330
+ );
25331
+ this.setFingerprintStmt = db.prepare(
25332
+ `UPDATE history_sync
25333
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25334
+ WHERE id = 1`
25335
+ );
25336
+ this.disownCapturesStmt = db.prepare(
25337
+ `UPDATE audit_events SET outbox_owed = NULL
25338
+ WHERE outbox_owed IS NOT NULL
25339
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25340
+ AND started_at < :attachedAt`
25341
+ );
25342
+ this.rearmStmt = db.prepare(
25343
+ `UPDATE audit_events
25344
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25345
+ WHERE (synced_at > 0
25346
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25347
+ AND event_type IN (${TYPE_LIST})`
25348
+ );
25349
+ this.claimStmt = db.prepare(
25350
+ `UPDATE history_sync
25351
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25352
+ WHERE id = 1
25353
+ AND (owner_pid IS NULL
25354
+ OR heartbeat_at IS NULL
25355
+ OR heartbeat_at < :staleBefore
25356
+ OR heartbeat_at > :now)`
25357
+ );
25358
+ this.heartbeatStmt = db.prepare(
25359
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25360
+ );
25361
+ this.releaseStmt = db.prepare(
25362
+ `UPDATE history_sync
25363
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25364
+ WHERE id = 1 AND owner_pid = :pid`
25365
+ );
25366
+ this.closeWindowStmt = db.prepare(
25367
+ `UPDATE audit_events
25368
+ SET synced_at = ${String(SKIPPED)},
25369
+ sync_failed_at = :at,
25370
+ sync_failure = 'detached_undelivered'
25371
+ WHERE synced_at IS NULL
25372
+ AND event_type IN (${TYPE_LIST})
25373
+ AND started_at >= :attachedAt`
25374
+ );
25375
+ this.releaseBoundaryStmt = db.prepare(
25376
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25377
+ );
25378
+ this.freezeBoundaryStmt = db.prepare(
25379
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25380
+ );
25381
+ this.leaseStmt = db.prepare(
25382
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25383
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25384
+ FROM history_sync WHERE id = 1`
25385
+ );
25386
+ this.inspectionsStmt = db.prepare(
25387
+ `SELECT d.rule_id AS ruleId,
25388
+ d.name AS ruleName,
25389
+ d.version AS ruleVersion,
25390
+ d.category AS category,
25391
+ d.severity AS severity,
25392
+ f.span_start AS spanStart,
25393
+ f.span_end AS spanEnd,
25394
+ f.masked_match AS maskedMatch,
25395
+ f.action_taken AS actionTaken,
25396
+ f.confidence AS confidence
25397
+ FROM inspection_findings f
25398
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25399
+ WHERE f.audit_event_id = :auditEventId
25400
+ ORDER BY f.span_start, f.id`
25401
+ );
24860
25402
  }
24861
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24862
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25403
+ db;
25404
+ ensureRowStmt;
25405
+ sessionsStmt;
25406
+ rowsStmt;
25407
+ stampStmt;
25408
+ countsStmt;
25409
+ fingerprintStmt;
25410
+ setFingerprintStmt;
25411
+ rearmStmt;
25412
+ claimStmt;
25413
+ heartbeatStmt;
25414
+ releaseStmt;
25415
+ leaseStmt;
25416
+ inspectionsStmt;
25417
+ closeWindowStmt;
25418
+ releaseBoundaryStmt;
25419
+ freezeBoundaryStmt;
25420
+ captureRowsStmt;
25421
+ markOwedStmt;
25422
+ markCaptureBacklogOwedStmt;
25423
+ captureSkipCountStmt;
25424
+ disownCapturesStmt;
25425
+ partitionStmt;
25426
+ partitionByKindStmt;
25427
+ claimRowStmt;
25428
+ releaseRowStmt;
25429
+ releaseStaleClaimsStmt;
25430
+ /**
25431
+ * The masked detections recorded against one tool call.
25432
+ *
25433
+ * These travel with the event because a tool call's target is not
25434
+ * re-inspectable from the event alone — unlike a capture, where the text
25435
+ * itself is re-scannable. What crosses is the masked match and the rule that
25436
+ * produced it, never the value.
25437
+ */
25438
+ inspectionsFor(auditEventId) {
25439
+ return allRows(this.inspectionsStmt, { auditEventId });
24863
25440
  }
24864
- ensureSyncedAtColumn(db, "audit_events");
24865
- ensureScanLedgerTable(db);
24866
- ensureHistorySyncTable(db);
24867
- ensureBlockedDetectionsTable(db);
24868
- ensureRuleProbeCacheTable(db);
24869
- ensureWriteGateTrigger(db);
24870
- ensureTokenUsageColumns(db);
24871
- reconcileSourceProjectIds(db);
24872
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24873
- const drained = runLegacyHistoryBackfill(db);
24874
- if (drained) applyLegacyDropMigration(db, file2);
25441
+ /**
25442
+ * Sessions with structural rows still to send, oldest first.
25443
+ *
25444
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25445
+ * read. Anything recorded after the machine attached is the live forward
25446
+ * path's to deliver; this drain exists for what was recorded before it, and a
25447
+ * row both paths send is at best a duplicate request and at worst — for a
25448
+ * session root — an overwrite of the inventory ids the live path resolved.
25449
+ */
25450
+ pendingSessions(limit, before) {
25451
+ return allRows(this.sessionsStmt, { limit, before }).map(
25452
+ (r) => r.sessionId
25453
+ );
24875
25454
  }
24876
- }
24877
- function readLegacyTables(db) {
24878
- let holdsRows = false;
24879
- const marks = [];
24880
- for (const table of ["events", "findings"]) {
24881
- try {
24882
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24883
- if (row === void 0) {
24884
- holdsRows = true;
24885
- marks.push(`${table}:unreadable`);
24886
- continue;
24887
- }
24888
- if (row.n > 0) holdsRows = true;
24889
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24890
- } catch {
24891
- holdsRows = true;
24892
- marks.push(`${table}:unreadable`);
24893
- }
25455
+ /** One session's undelivered structural rows within the backlog, root first. */
25456
+ pendingRows(sessionId, limit, before) {
25457
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24894
25458
  }
24895
- return { holdsRows, mark: marks.join("|") };
24896
- }
24897
- function applyLegacyDropMigration(db, file2) {
24898
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24899
- if (!migration) return;
24900
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24901
- if (file2 !== void 0 && before?.holdsRows === true) {
24902
- try {
24903
- backupBeforeLegacyDrop(db, file2);
24904
- } catch (error61) {
24905
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24906
- return;
24907
- }
25459
+ /**
25460
+ * Captures this machine still owes the deployment, oldest first.
25461
+ *
25462
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25463
+ * by a time window — see captureRowsStmt for why a window could not express
25464
+ * this. `before` is the grace window that leaves a just-recorded capture to
25465
+ * the live path.
25466
+ */
25467
+ pendingCaptureRows(limit, before) {
25468
+ return allRows(this.captureRowsStmt, { limit, before });
24908
25469
  }
24909
- try {
25470
+ /**
25471
+ * Record that a capture is OWED to the deployment.
25472
+ *
25473
+ * Written by the attached forward path when a live send did not confirm
25474
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25475
+ * a fact rather than an inference: the machine was attached, the send did not
25476
+ * land, so the row is owed — which no time window can state, because the same
25477
+ * window that holds the rows a past attachment left owed also holds every
25478
+ * capture recorded while the machine was DETACHED, and those were never
25479
+ * offered to anyone.
25480
+ *
25481
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25482
+ * out of the drain's read.
25483
+ */
25484
+ markCaptureOwed(id) {
25485
+ this.markOwedStmt.run({ id });
25486
+ }
25487
+ /**
25488
+ * Mark every capture already on disk as owed, as of `before`.
25489
+ *
25490
+ * The consent-time backfill, called once from `aka attach` when a human
25491
+ * grants existing-history consent — never from an ongoing drain pass, and
25492
+ * never inferred from a boundary that could later move. `before` is the
25493
+ * caller's own "now" at the moment consent was granted, so what this marks
25494
+ * is exactly the backlog the consent prompt already counted, not whatever a
25495
+ * later re-attach or key rotation might widen it to.
25496
+ *
25497
+ * Returns how many rows matched, for the caller to log or test against. Not a
25498
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25499
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25500
+ */
25501
+ markCaptureBacklogOwed(before) {
25502
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25503
+ }
25504
+ /**
25505
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25506
+ *
25507
+ * CLEARS any failure reason in the same statement. A row that failed against
25508
+ * one deployment and then landed is delivered, and leaving the reason behind
25509
+ * would leave the store holding two contradictory answers about one row —
25510
+ * with the surface free to render either.
25511
+ */
25512
+ markSynced(ids, atMs) {
25513
+ this.stampAll(ids, atMs, null);
25514
+ }
25515
+ /**
25516
+ * Record that THIS MACHINE cannot express the row on the wire.
25517
+ *
25518
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25519
+ * payload, or a body the client itself refused to send. It fails identically
25520
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25521
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25522
+ * is retried; marking those would turn one outage into permanent data loss.
25523
+ */
25524
+ markSkipped(ids, atMs) {
25525
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25526
+ }
25527
+ /**
25528
+ * Record that THIS DEPLOYMENT refused the row.
25529
+ *
25530
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25531
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25532
+ * row is outstanding rather than why. What separates them is the reason, and
25533
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25534
+ * on one body, so it is terminal only for as long as this machine points at
25535
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25536
+ *
25537
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25538
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25539
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25540
+ */
25541
+ markRefused(ids, atMs) {
25542
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25543
+ }
25544
+ eachInTransaction(ids, run) {
25545
+ if (ids.length === 0) return;
24910
25546
  withTransaction(
24911
- db,
25547
+ this.db,
24912
25548
  () => {
24913
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24914
- if (alreadyDropped) return;
24915
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24916
- akaWarn(
24917
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24918
- );
24919
- return;
24920
- }
24921
- for (const statement of splitStatements(migration.sql)) {
24922
- db.exec(statement);
24923
- }
24924
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24925
- migration.tag,
24926
- Date.now()
24927
- );
25549
+ for (const id of ids) run(id);
25550
+ },
25551
+ "IMMEDIATE"
25552
+ );
25553
+ }
25554
+ stampAll(ids, value, failure, failedAtMs) {
25555
+ if (ids.length === 0) return;
25556
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25557
+ withTransaction(
25558
+ this.db,
25559
+ () => {
25560
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25561
+ },
25562
+ "IMMEDIATE"
25563
+ );
25564
+ }
25565
+ /**
25566
+ * Claim rows as in-flight.
25567
+ *
25568
+ * Advisory in exactly the sense the lease is: it records that a send is in
25569
+ * progress so a surface can say so, and a lost claim costs a row showing as
25570
+ * queued while it is actually being sent. It is not exclusion — the far side
25571
+ * settles a duplicate on the row id.
25572
+ */
25573
+ claimRows(ids, atMs) {
25574
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25575
+ }
25576
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25577
+ releaseRows(ids) {
25578
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25579
+ }
25580
+ /**
25581
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25582
+ *
25583
+ * A process killed between claiming and settling leaves rows claimed with
25584
+ * nothing left to settle them. Without this they read as "sending" for ever.
25585
+ */
25586
+ releaseStaleClaims(staleBefore) {
25587
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25588
+ }
25589
+ /**
25590
+ * Every tracked row in exactly one delivery state.
25591
+ *
25592
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25593
+ * pick up now", which is a different question from "what state is this row
25594
+ * in" — and a machine that has never attached has no boundary to pass, so
25595
+ * requiring one would force a caller to invent one and report the whole store
25596
+ * as queued.
25597
+ */
25598
+ /**
25599
+ * The same partition, one row per kind that a lane carries.
25600
+ *
25601
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25602
+ * scope decides which rows exist at all, so a kind that has never been
25603
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25604
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25605
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25606
+ * different things.
25607
+ */
25608
+ partitionByKind() {
25609
+ return allRows(
25610
+ this.partitionByKindStmt,
25611
+ {}
25612
+ ).map((row) => ({
25613
+ kind: row.kind,
25614
+ queued: row.queued ?? 0,
25615
+ inProgress: row.inProgress ?? 0,
25616
+ synced: row.synced ?? 0,
25617
+ failed: row.failed ?? 0,
25618
+ refused: row.refused ?? 0,
25619
+ detached: row.detached ?? 0,
25620
+ total: row.total ?? 0
25621
+ }));
25622
+ }
25623
+ partition() {
25624
+ const row = getRow(this.partitionStmt, {});
25625
+ return {
25626
+ queued: row?.queued ?? 0,
25627
+ inProgress: row?.inProgress ?? 0,
25628
+ synced: row?.synced ?? 0,
25629
+ failed: row?.failed ?? 0,
25630
+ refused: row?.refused ?? 0,
25631
+ detached: row?.detached ?? 0,
25632
+ total: row?.total ?? 0
25633
+ };
25634
+ }
25635
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25636
+ counts(before) {
25637
+ const row = getRow(this.countsStmt, { before });
25638
+ const captures = getRow(this.captureSkipCountStmt);
25639
+ return {
25640
+ pending: row?.pending ?? 0,
25641
+ sent: row?.sent ?? 0,
25642
+ skipped: row?.skipped ?? 0,
25643
+ refused: row?.refused ?? 0,
25644
+ detached: row?.detached ?? 0,
25645
+ capturesSkipped: captures?.skipped ?? 0
25646
+ };
25647
+ }
25648
+ /**
25649
+ * The deployment the current stamps were made against, and where its backlog
25650
+ * ends.
25651
+ *
25652
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25653
+ * machine that has never drained is — and every writer below seeds the row
25654
+ * before it needs one, so nothing depends on this creating it. Keeping the
25655
+ * write off the gate path matters because the gate runs on every pass while a
25656
+ * write has to take the database's write lock.
25657
+ */
25658
+ deployment() {
25659
+ const row = getRow(
25660
+ this.fingerprintStmt
25661
+ );
25662
+ return {
25663
+ fingerprint: row?.fingerprint ?? void 0,
25664
+ backlogBefore: row?.backlogBefore ?? void 0
25665
+ };
25666
+ }
25667
+ /**
25668
+ * Point the ledger at a different deployment, discarding what it recorded
25669
+ * about the previous one.
25670
+ *
25671
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25672
+ * machine has just left are undelivered as far as the new one is concerned.
25673
+ * All four in one transaction, so a crash between them cannot leave stamps
25674
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25675
+ * a disown with no re-mark to follow it.
25676
+ *
25677
+ * The boundary is written HERE and only here, which is what freezes it: a
25678
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25679
+ * unchanged, so this never runs and the backlog does not widen back over rows
25680
+ * the live path has since delivered.
25681
+ *
25682
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25683
+ * granted existing-history consent for the deployment this call is arming —
25684
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25685
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25686
+ * apart. Passed only when that grant is valid, since this method has no way
25687
+ * to check consent itself and must not mark a row owed for a machine that
25688
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25689
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25690
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25691
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25692
+ * on the cleared side of that bound — and the re-mark in the same
25693
+ * transaction is what puts those rows back. A crash between the two cannot
25694
+ * strand the ledger disowned with nothing re-marked — the transaction either
25695
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25696
+ * committed re-enters this method on the very next pass. Omit it (the
25697
+ * structural-only tests do) to exercise the disown in isolation.
25698
+ *
25699
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25700
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25701
+ * live path can mark a capture owed from the moment `aka attach` writes the
25702
+ * descriptor, before the drain's first pass ever reaches this method, and
25703
+ * such a row sits at or after the bound rather than below it. What keeps the
25704
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25705
+ * bound — disown runs first, re-mark second, both inside the one
25706
+ * transaction above.
25707
+ */
25708
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25709
+ this.ensureRowStmt.run();
25710
+ withTransaction(
25711
+ this.db,
25712
+ () => {
25713
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25714
+ this.rearmStmt.run();
25715
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25716
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25717
+ }
25718
+ if (backfillCapturesBefore !== void 0) {
25719
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25720
+ }
25721
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25722
+ },
25723
+ "IMMEDIATE"
25724
+ );
25725
+ }
25726
+ /**
25727
+ * End the attached period: hand its rows to the live path, and release the
25728
+ * boundary so the next attachment can freeze a new one.
25729
+ *
25730
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25731
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25732
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25733
+ * during the detached period, because the machine is not attached. Rows
25734
+ * recorded in that window sit after the boundary and before the re-attach, so
25735
+ * neither path takes them, and the pending count reports none outstanding.
25736
+ *
25737
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25738
+ * closing attachment's to deliver and are no longer outstanding — that is what
25739
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25740
+ * distinction is not academic: this used to write a delivery TIME, which every
25741
+ * read treats as delivery, so one detach turned a window of undelivered rows
25742
+ * into a window of delivered ones and no surface could tell. It writes the
25743
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25744
+ * "received" stop being the same fact.
25745
+ *
25746
+ * A change of deployment still frees them (see the re-arm), because the next
25747
+ * deployment has seen none of this machine's history — so the rows reach it
25748
+ * exactly as they did when this wrote a delivery time.
25749
+ *
25750
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25751
+ * window unstamped — that half-state would re-send the whole attached period
25752
+ * on the next attach, which is the failure the boundary exists to prevent.
25753
+ */
25754
+ closeAttachedWindow(attachedAtMs, atMs) {
25755
+ this.ensureRowStmt.run();
25756
+ withTransaction(
25757
+ this.db,
25758
+ () => {
25759
+ const row = getRow(this.fingerprintStmt);
25760
+ const from = row?.backlogBefore ?? attachedAtMs;
25761
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25762
+ this.releaseBoundaryStmt.run();
25763
+ },
25764
+ "IMMEDIATE"
25765
+ );
25766
+ }
25767
+ /**
25768
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25769
+ *
25770
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25771
+ * different deployment and therefore discards what was delivered to the old
25772
+ * one: here the recipient is the same, so everything already sent to it stays
25773
+ * sent.
25774
+ */
25775
+ freezeBoundary(backlogBefore) {
25776
+ this.ensureRowStmt.run();
25777
+ this.freezeBoundaryStmt.run({ backlogBefore });
25778
+ }
25779
+ /** Take the claim, or report that someone live already holds it. */
25780
+ claim(pid, host, nowMs, staleAfterMs) {
25781
+ this.ensureRowStmt.run();
25782
+ let taken = false;
25783
+ withTransaction(
25784
+ this.db,
25785
+ () => {
25786
+ const result = this.claimStmt.run({
25787
+ pid,
25788
+ host,
25789
+ now: nowMs,
25790
+ staleBefore: nowMs - staleAfterMs
25791
+ });
25792
+ taken = result.changes === 1;
25793
+ },
25794
+ "IMMEDIATE"
25795
+ );
25796
+ return taken;
25797
+ }
25798
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25799
+ heartbeat(pid, nowMs) {
25800
+ this.heartbeatStmt.run({ now: nowMs, pid });
25801
+ }
25802
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25803
+ release(pid) {
25804
+ this.releaseStmt.run({ pid });
25805
+ }
25806
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25807
+ lease() {
25808
+ return getRow(this.leaseStmt);
25809
+ }
25810
+ };
25811
+
25812
+ // ../../packages/persistence/src/migrations.ts
25813
+ function describeObject(object2) {
25814
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25815
+ }
25816
+ function splitStatements(sql) {
25817
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25818
+ }
25819
+ function createdIndexName(statement) {
25820
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25821
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25822
+ }
25823
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25824
+ function applyMigrations(db, file2, options = {}) {
25825
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25826
+ db.exec(
25827
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25828
+ );
25829
+ const applied = new Set(
25830
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25831
+ );
25832
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25833
+ const record2 = db.prepare(
25834
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25835
+ );
25836
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25837
+ if (applied.has(migration.tag)) continue;
25838
+ if (options.skipTags?.has(migration.tag) === true) continue;
25839
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25840
+ const evidence = evidenceObjects(migration.sql);
25841
+ const present = evidence.filter((o) => evidenceExists(db, o));
25842
+ if (present.length > 0 && present.length < evidence.length) {
25843
+ const missing = evidence.filter((o) => !present.includes(o));
25844
+ 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.`;
25845
+ akaWarn(message);
25846
+ throw new Error(`[aka] ${message}`);
25847
+ }
25848
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25849
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25850
+ const statements = splitStatements(migration.sql);
25851
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25852
+ try {
25853
+ withTransaction(
25854
+ db,
25855
+ () => {
25856
+ for (const statement of statements) {
25857
+ const indexName = createdIndexName(statement);
25858
+ if (indexName === void 0) {
25859
+ if (alreadyApplied) continue;
25860
+ } else if (indexExists(db, indexName)) {
25861
+ continue;
25862
+ }
25863
+ db.exec(statement);
25864
+ }
25865
+ if (wantsFkOff && !alreadyApplied) {
25866
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25867
+ if (violations.length > 0) {
25868
+ throw new Error(
25869
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25870
+ );
25871
+ }
25872
+ }
25873
+ record2.run(migration.tag, Date.now());
25874
+ },
25875
+ "IMMEDIATE"
25876
+ );
25877
+ } finally {
25878
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25879
+ }
25880
+ }
25881
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25882
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25883
+ }
25884
+ ensureSyncedAtColumn(db, "audit_events");
25885
+ ensureScanLedgerTable(db);
25886
+ ensureHistorySyncTable(db);
25887
+ ensureBlockedDetectionsTable(db);
25888
+ ensureRuleProbeCacheTable(db);
25889
+ ensureWriteGateTrigger(db);
25890
+ ensureTokenUsageColumns(db);
25891
+ reconcileSourceProjectIds(db);
25892
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25893
+ const drained = runLegacyHistoryBackfill(db);
25894
+ if (drained) applyLegacyDropMigration(db, file2);
25895
+ }
25896
+ }
25897
+ function readLegacyTables(db) {
25898
+ let holdsRows = false;
25899
+ const marks = [];
25900
+ for (const table of ["events", "findings"]) {
25901
+ try {
25902
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25903
+ if (row === void 0) {
25904
+ holdsRows = true;
25905
+ marks.push(`${table}:unreadable`);
25906
+ continue;
25907
+ }
25908
+ if (row.n > 0) holdsRows = true;
25909
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25910
+ } catch {
25911
+ holdsRows = true;
25912
+ marks.push(`${table}:unreadable`);
25913
+ }
25914
+ }
25915
+ return { holdsRows, mark: marks.join("|") };
25916
+ }
25917
+ function applyLegacyDropMigration(db, file2) {
25918
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25919
+ if (!migration) return;
25920
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25921
+ if (file2 !== void 0 && before?.holdsRows === true) {
25922
+ try {
25923
+ backupBeforeLegacyDrop(db, file2);
25924
+ } catch (error61) {
25925
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25926
+ return;
25927
+ }
25928
+ }
25929
+ try {
25930
+ withTransaction(
25931
+ db,
25932
+ () => {
25933
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25934
+ if (alreadyDropped) return;
25935
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25936
+ akaWarn(
25937
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25938
+ );
25939
+ return;
25940
+ }
25941
+ for (const statement of splitStatements(migration.sql)) {
25942
+ db.exec(statement);
25943
+ }
25944
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25945
+ migration.tag,
25946
+ Date.now()
25947
+ );
24928
25948
  },
24929
25949
  "IMMEDIATE"
24930
25950
  );
@@ -25222,10 +26242,62 @@ function ensureSyncedAtColumn(db, table) {
25222
26242
  if (!columns.includes("outbox_owed")) {
25223
26243
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25224
26244
  }
26245
+ if (!columns.includes("sync_failed_at")) {
26246
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26247
+ }
26248
+ if (!columns.includes("sync_failure")) {
26249
+ withTransaction(
26250
+ db,
26251
+ () => {
26252
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26253
+ db.exec(
26254
+ `UPDATE ${table} SET synced_at = NULL
26255
+ WHERE synced_at = -1
26256
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26257
+ );
26258
+ },
26259
+ "IMMEDIATE"
26260
+ );
26261
+ }
25225
26262
  db.exec(
25226
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25227
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26263
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26264
+ BEFORE UPDATE OF sync_failure ON ${table}
26265
+ WHEN ${syncFailureRejectCondition()}
26266
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25228
26267
  );
26268
+ const syncIndexColumns = [
26269
+ "event_type",
26270
+ "synced_at",
26271
+ "sync_claimed_at",
26272
+ "started_at",
26273
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26274
+ // has to be in the index for the read to stay covered — but putting it
26275
+ // ahead of `started_at` would reorder the prefix the structural drain's
26276
+ // reads match on.
26277
+ "sync_failure"
26278
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26279
+ //
26280
+ // The delivery-state read tests it — a capture's state depends on whether a
26281
+ // live forward marked it owed — so carrying it here makes that read covering
26282
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26283
+ // But a sixth column changes what the planner charges for this index, and
26284
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26285
+ // then stops choosing the per-session index for the token rollup and walks
26286
+ // every `llm_call` in the store through the event-type index instead. That
26287
+ // read grows with the store; this one does not.
26288
+ //
26289
+ // 40 ms on the largest store measured, once per render, is a cost worth
26290
+ // paying to leave every other read's plan where it was.
26291
+ ];
26292
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26293
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26294
+ if (!syncIndexMatches) {
26295
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26296
+ db.exec(
26297
+ `CREATE INDEX idx_audit_events_sync
26298
+ ON audit_events (${syncIndexColumns.join(", ")})`
26299
+ );
26300
+ }
25229
26301
  db.exec(
25230
26302
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25231
26303
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25447,7 +26519,11 @@ function buildAuditEvent(row) {
25447
26519
  link: linkParsed?.success ? linkParsed.data : null,
25448
26520
  targetId: row.target_id,
25449
26521
  internal: intToBool(row.internal),
25450
- flagged: intToBool(row.flagged)
26522
+ flagged: intToBool(row.flagged),
26523
+ // Only meaningful when the title came out empty — a row whose body was
26524
+ // expired but whose title fell back to `tool_name` still has something to
26525
+ // render, and flagging it would make the view apologise for nothing.
26526
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25451
26527
  };
25452
26528
  }
25453
26529
  var TIMELINE_COLUMNS = `
@@ -25455,6 +26531,7 @@ var TIMELINE_COLUMNS = `
25455
26531
  event_type,
25456
26532
  started_at,
25457
26533
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26534
+ content_expired_at,
25458
26535
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25459
26536
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25460
26537
  json_extract(attributes, '$.severity') AS severity,
@@ -25581,7 +26658,8 @@ var SqliteActivityRepository = class {
25581
26658
  SELECT 1 FROM audit_events d
25582
26659
  WHERE d.root_session_id = audit_events.id
25583
26660
  AND (d.content LIKE ? ESCAPE '\\'
25584
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26661
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26662
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25585
26663
  );
25586
26664
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25587
26665
  }
@@ -26119,6 +27197,88 @@ var SqliteAuditEventsRepository = class {
26119
27197
  }
26120
27198
  };
26121
27199
 
27200
+ // ../../packages/persistence/src/repositories/body-retention.ts
27201
+ var DEFAULT_BATCH_SIZE = 500;
27202
+ var DEFAULT_MAX_ROWS = 5e4;
27203
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27204
+ var SqliteBodyRetentionRepository = class {
27205
+ constructor(db) {
27206
+ this.db = db;
27207
+ const select = (laneClause) => `
27208
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27209
+ FROM audit_events
27210
+ WHERE content IS NOT NULL
27211
+ AND started_at < :cutoff
27212
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27213
+ ${laneClause}
27214
+ ORDER BY started_at
27215
+ LIMIT :limit`;
27216
+ this.candidatesStmt = this.db.prepare(select(""));
27217
+ this.candidatesSyncSafeStmt = this.db.prepare(
27218
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27219
+ );
27220
+ this.heldBySyncStmt = this.db.prepare(`
27221
+ SELECT COUNT(*) AS n
27222
+ FROM audit_events
27223
+ WHERE content IS NOT NULL
27224
+ AND started_at < :cutoff
27225
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27226
+ AND synced_at IS NULL`);
27227
+ this.expireStmt = this.db.prepare(
27228
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27229
+ );
27230
+ }
27231
+ db;
27232
+ candidatesStmt;
27233
+ candidatesSyncSafeStmt;
27234
+ heldBySyncStmt;
27235
+ expireStmt;
27236
+ /** How many bytes a pass with these options would free, changing nothing. */
27237
+ preview(opts) {
27238
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27239
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27240
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27241
+ return {
27242
+ rowsExpired: rows.length,
27243
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27244
+ rowsHeldBySync: this.countHeldBySync(opts)
27245
+ };
27246
+ }
27247
+ /** Clear eligible bodies, in bounded batches. */
27248
+ expire(opts) {
27249
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27250
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27251
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27252
+ let rowsExpired = 0;
27253
+ let bytesFreed = 0;
27254
+ let done = true;
27255
+ while (rowsExpired < maxRows) {
27256
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27257
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27258
+ if (batch.length === 0) break;
27259
+ withTransaction(
27260
+ this.db,
27261
+ () => {
27262
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27263
+ },
27264
+ "IMMEDIATE"
27265
+ );
27266
+ rowsExpired += batch.length;
27267
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27268
+ if (batch.length < remaining) break;
27269
+ if (rowsExpired >= maxRows) {
27270
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27271
+ }
27272
+ }
27273
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27274
+ }
27275
+ countHeldBySync(opts) {
27276
+ if (opts.sweepSyncLane) return 0;
27277
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27278
+ return row.n;
27279
+ }
27280
+ };
27281
+
26122
27282
  // ../../packages/persistence/src/repositories/classified-data.ts
26123
27283
  var SqliteClassifiedDataRepository = class {
26124
27284
  constructor(db) {
@@ -26919,23 +28079,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26919
28079
  )`;
26920
28080
 
26921
28081
  // ../../packages/persistence/src/repositories/findings.ts
26922
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26923
- var DEFAULT_LOCATIONS_LIMIT = 100;
26924
- var LOCATION_RULE_IDS_CAP = 20;
26925
- function compareLocationOrder(a, b) {
26926
- return compareFindingGroupOrder(
26927
- {
26928
- severity: a.maxSeverity,
26929
- latestDetectedAt: a.latestDetectedAt,
26930
- id: ""
26931
- },
26932
- {
26933
- severity: b.maxSeverity,
26934
- latestDetectedAt: b.latestDetectedAt,
26935
- id: ""
26936
- }
26937
- );
26938
- }
26939
28082
  var CONCAT_SEP = ",";
26940
28083
  var TUPLE_SEP = "|";
26941
28084
  function splitConcat(value) {
@@ -26964,7 +28107,15 @@ function toFlatFindingRow(r) {
26964
28107
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26965
28108
  eventId: r.event_id,
26966
28109
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26967
- status: deriveInstanceStatus(r)
28110
+ status: deriveInstanceStatus(r),
28111
+ delivery: deriveFindingDelivery({
28112
+ kind: r.kind,
28113
+ syncedAt: r.synced_at,
28114
+ syncClaimedAt: r.sync_claimed_at,
28115
+ syncFailedAt: r.sync_failed_at,
28116
+ syncFailure: r.sync_failure,
28117
+ outboxOwed: r.outbox_owed
28118
+ })
26968
28119
  };
26969
28120
  }
26970
28121
  function encodeGroupCursor(group) {
@@ -26987,13 +28138,51 @@ function decodeGroupCursor(cursor) {
26987
28138
  return null;
26988
28139
  }
26989
28140
  function firstAfter(sorted, cursor) {
26990
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28141
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26991
28142
  return index === -1 ? sorted.length : index;
26992
28143
  }
26993
28144
  function findDeepLinked(sorted, page, id) {
26994
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26995
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28145
+ if (page.some((t) => t.id === id)) return void 0;
28146
+ return sorted.find((t) => t.id === id);
28147
+ }
28148
+ function encodeLocationCursor(location) {
28149
+ const payload = {
28150
+ sev: location.maxSeverity,
28151
+ t: location.latestDetectedAt,
28152
+ r: location.repo,
28153
+ f: location.file
28154
+ };
28155
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28156
+ }
28157
+ function decodeLocationCursor(cursor) {
28158
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28159
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28160
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28161
+ }
28162
+ return null;
28163
+ }
28164
+ function firstLocationAfter(sorted, cursor) {
28165
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28166
+ return index === -1 ? sorted.length : index;
28167
+ }
28168
+ function findDeepLinkedLocation(sorted, page, id) {
28169
+ if (page.some((l) => l.id === id)) return void 0;
28170
+ return sorted.find((l) => l.id === id);
26996
28171
  }
28172
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28173
+ d.severity AS severity, f.masked_match AS masked_match,
28174
+ f.action_taken AS action_taken, f.confidence AS confidence,
28175
+ e.started_at AS occurred_at,
28176
+ e.source_tool AS source_tool,
28177
+ e.repo AS repo,
28178
+ e.file_path AS file,
28179
+ e.tool_name AS tool_name,
28180
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28181
+ e.event_type AS kind, f.finding_key AS finding_key,
28182
+ ${latestResolutionStatusSql("f")} AS latest_status,
28183
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28184
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28185
+ e.outbox_owed AS outbox_owed`;
26997
28186
  var DAY_MS3 = 864e5;
26998
28187
  var SqliteFindingsRepository = class {
26999
28188
  constructor(db) {
@@ -27114,30 +28303,26 @@ var SqliteFindingsRepository = class {
27114
28303
  );
27115
28304
  }
27116
28305
  /**
27117
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27118
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27119
- * attributes bag, rule_id/category/severity from the definition), scoped to
27120
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27121
- * rows this list must never surface), groups by ruleId, computes
27122
- * per-filter-excluded facets, applies the requested filters, and sorts by
27123
- * severity then recency. Filtering
27124
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27125
- * reflect the full filtered set; `items` is the requested
27126
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27127
- * filter, `totals.findings` counts only instances whose derived status was
27128
- * requested, and each item's instance preview is narrowed the same way.
28306
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28307
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28308
+ * list must never surface), with per-filter-excluded facets, the requested
28309
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28310
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28311
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28312
+ * Under a `status` filter, `totals.findings` counts only findings whose
28313
+ * derived status was requested.
28314
+ *
28315
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28316
+ * folding EVERY finding into the numbers a type row and the filters need
28317
+ * (count, severity, category, providers, actions, statuses, latest, search
28318
+ * text). The findings OF a type come from listFindingInstances scoped to
28319
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27129
28320
  *
27130
- * Two reads, neither of which materializes a row per finding:
27131
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27132
- * the group and the filters need (count, providers, actions, statuses,
27133
- * latest, search text);
27134
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27135
- * populate `instances` for the table's expanded rows.
27136
28321
  * The aggregates carry raw DB values and are translated by the same
27137
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27138
- * rule is ever restated in SQL.
28322
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28323
+ * status rule is ever restated in SQL.
27139
28324
  */
27140
- listGroupedFindings(query) {
28325
+ listFindingTypes(query) {
27141
28326
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27142
28327
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27143
28328
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27150,12 +28335,7 @@ var SqliteFindingsRepository = class {
27150
28335
  predicate,
27151
28336
  params: sessionParams
27152
28337
  });
27153
- const rows = this.previewRows(aggregates, {
27154
- sessionId: query.sessionId,
27155
- from: query.from
27156
- });
27157
- const groupable = rows.map(toFlatFindingRow);
27158
- const allGroups = buildFindingGroups(groupable, { aggregates });
28338
+ const allTypes = buildFindingTypes(aggregates);
27159
28339
  const filterOpts = {
27160
28340
  severity: query.severity,
27161
28341
  providers: query.provider,
@@ -27164,30 +28344,25 @@ var SqliteFindingsRepository = class {
27164
28344
  subtype: query.subtype,
27165
28345
  q: query.q
27166
28346
  };
27167
- const facets = computeFindingFacets(allGroups, filterOpts);
27168
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28347
+ const facets = computeFindingFacets(allTypes, filterOpts);
28348
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27169
28349
  const statusFilter = query.status ?? [];
27170
28350
  const totals = {
27171
- findings: sorted.reduce((acc, g) => {
27172
- if (statusFilter.length === 0) return acc + g.instanceCount;
27173
- const agg = aggregates.get(g.id);
27174
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28351
+ findings: sorted.reduce((acc, t) => {
28352
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28353
+ const agg = aggregates.get(t.id);
28354
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27175
28355
  }, 0),
27176
- groups: sorted.length
28356
+ types: sorted.length
27177
28357
  };
27178
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28358
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27179
28359
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27180
28360
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27181
28361
  const page = sorted.slice(start, start + limit);
27182
28362
  const lastOnPage = page.at(-1);
27183
28363
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27184
28364
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27185
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27186
- const narrow = (g) => statusSet ? {
27187
- ...g,
27188
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27189
- } : g;
27190
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28365
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27191
28366
  return Promise.resolve({
27192
28367
  totals,
27193
28368
  facets,
@@ -27198,7 +28373,7 @@ var SqliteFindingsRepository = class {
27198
28373
  }
27199
28374
  /**
27200
28375
  * One row per rule_id, folding EVERY instance of the group into the values
27201
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28376
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27202
28377
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27203
28378
  *
27204
28379
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27252,6 +28427,7 @@ var SqliteFindingsRepository = class {
27252
28427
  providers: query.provider,
27253
28428
  actions: query.action,
27254
28429
  statuses: query.status,
28430
+ deliveries: query.deployment,
27255
28431
  tools: query.tool,
27256
28432
  repo: query.repo,
27257
28433
  file: query.file,
@@ -27292,13 +28468,25 @@ var SqliteFindingsRepository = class {
27292
28468
  });
27293
28469
  }
27294
28470
  /**
27295
- * The same findings folded by location: repository, then file within it.
28471
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27296
28472
  *
27297
28473
  * The grouping keys come from the capturing event's attributes, which is what
27298
- * the local store relates a finding to — there is no finding↔asset row to
27299
- * group by instead. A repo or file the event did not record folds into the
27300
- * empty-string bucket, which the view renders but does not link, since no
27301
- * filter can name it.
28474
+ * the local store relates a finding to; there is no finding↔asset row to group
28475
+ * by instead. A repo or file the event did not record folds into the
28476
+ * empty-string bucket, which is a real location like any other: it is listed,
28477
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28478
+ *
28479
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28480
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28481
+ * list was rebuilt to remove — and two-level pagination inside an
28482
+ * expand/collapse table is what pushed that view to master/detail in the first
28483
+ * place.
28484
+ *
28485
+ * Every filter narrows the FINDINGS and the locations fall out of what
28486
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28487
+ * reports for the same filters scoped to that pair. The view depends on it:
28488
+ * one toolbar sits over both panels precisely because a location owns none of
28489
+ * its fields.
27302
28490
  */
27303
28491
  listFindingLocations(query) {
27304
28492
  const opts = {
@@ -27307,16 +28495,20 @@ var SqliteFindingsRepository = class {
27307
28495
  providers: query.provider,
27308
28496
  actions: query.action,
27309
28497
  statuses: query.status,
28498
+ deliveries: query.deployment,
27310
28499
  tools: query.tool,
27311
28500
  q: query.q
27312
28501
  };
27313
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28502
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28503
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27314
28504
  const byRepo = /* @__PURE__ */ new Map();
28505
+ const accumulator = createInstanceFacetAccumulator(opts);
27315
28506
  let total = 0;
27316
28507
  for (const row of this.scanFindingRows({
27317
28508
  sessionId: query.sessionId,
27318
28509
  from: query.from
27319
28510
  })) {
28511
+ accumulator.add(row);
27320
28512
  if (!matchesInstanceFilters(row, opts)) continue;
27321
28513
  total += 1;
27322
28514
  let files = byRepo.get(row.repo);
@@ -27331,103 +28523,35 @@ var SqliteFindingsRepository = class {
27331
28523
  }
27332
28524
  addToLocation(acc, row);
27333
28525
  }
27334
- let fileCount = 0;
27335
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27336
- fileCount += files.size;
27337
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27338
- file: file2,
27339
- instanceCount: acc.instanceCount,
27340
- maxSeverity: acc.maxSeverity,
27341
- latestDetectedAt: acc.latestDetectedAt,
27342
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27343
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27344
- })).sort(compareLocationOrder);
27345
- const rollup = fileRows.reduce(
27346
- (a, f) => ({
27347
- instanceCount: a.instanceCount + f.instanceCount,
27348
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27349
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27350
- }),
27351
- {
27352
- instanceCount: 0,
27353
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27354
- latestDetectedAt: ""
27355
- }
27356
- );
27357
- const statuses = fileRows.map((f) => f.status);
27358
- const folded = foldGroupStatus(statuses);
27359
- return {
27360
- repo,
27361
- instanceCount: rollup.instanceCount,
27362
- maxSeverity: rollup.maxSeverity,
27363
- latestDetectedAt: rollup.latestDetectedAt,
27364
- ...folded === void 0 ? {} : { status: folded },
27365
- files: fileRows
27366
- };
27367
- });
27368
- repos.sort(compareLocationOrder);
28526
+ const sorted = [];
28527
+ for (const [repo, files] of byRepo) {
28528
+ for (const [file2, acc] of files) {
28529
+ const status = foldGroupStatus(acc.statuses);
28530
+ sorted.push({
28531
+ id: encodeLocationId(repo, file2),
28532
+ repo,
28533
+ file: file2,
28534
+ instanceCount: acc.instanceCount,
28535
+ maxSeverity: acc.maxSeverity,
28536
+ latestDetectedAt: acc.latestDetectedAt,
28537
+ ...status === void 0 ? {} : { status },
28538
+ ruleIds: [...acc.ruleIds]
28539
+ });
28540
+ }
28541
+ }
28542
+ sorted.sort(compareLocationOrder);
28543
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28544
+ const page = sorted.slice(start, start + limit);
28545
+ const lastOnPage = page.at(-1);
28546
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28547
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27369
28548
  return Promise.resolve({
27370
- totals: { findings: total, repos: repos.length, files: fileCount },
27371
- items: repos.slice(0, limit),
27372
- hasMore: repos.length > limit
28549
+ totals: { findings: total, locations: sorted.length },
28550
+ facets: accumulator.facets(),
28551
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28552
+ nextCursor
27373
28553
  });
27374
28554
  }
27375
- /**
27376
- * Each group's newest instances, for the table's expanded rows.
27377
- *
27378
- * ONE index-ordered scan with early termination, and the shape is the point.
27379
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27380
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27381
- * through a temp B-tree to keep a bounded preview of each group, and then
27382
- * sorts the survivors again for the page order. Both sorts grow with the
27383
- * store while the answer does not.
27384
- *
27385
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27386
- * (or the session or window index the scope names — see `findingScanSql`),
27387
- * which is already the order the page wants, and keeps rows per rule until
27388
- * each rule has as many as it can show. The aggregate the caller already holds
27389
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27390
- * per rule, summed, is the number of rows this scan has to find, and it stops
27391
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27392
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27393
- * store with many firing rules widens it. The bound that DOES hold
27394
- * unconditionally is the sorted form's floor: this scan visits at most as
27395
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27396
- * sorted, and stops the moment every rule has its cap, where the sorted form
27397
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27398
- * wanted instances sitting at the tail of the scope — is one pass over
27399
- * everything in scope with a block sort of the id tie-break only, never a
27400
- * sort of the scope, which is still that floor.
27401
- *
27402
- * A row whose rule the aggregate did not see is skipped: the two statements
27403
- * run without a shared snapshot, so a capture landing between them can add a
27404
- * rule here that has no counts there, and the counts are what the group is
27405
- * built from.
27406
- */
27407
- previewRows(aggregates, scope) {
27408
- const wanted = /* @__PURE__ */ new Map();
27409
- let remaining = 0;
27410
- for (const [ruleId, agg] of aggregates) {
27411
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27412
- wanted.set(ruleId, n);
27413
- remaining += n;
27414
- }
27415
- const rows = [];
27416
- if (remaining === 0) return rows;
27417
- const { sql, params } = this.findingScanSql(scope);
27418
- const taken = /* @__PURE__ */ new Map();
27419
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27420
- const want = wanted.get(r.rule_id);
27421
- if (want === void 0) continue;
27422
- const have = taken.get(r.rule_id) ?? 0;
27423
- if (have >= want) continue;
27424
- taken.set(r.rule_id, have + 1);
27425
- rows.push(r);
27426
- remaining -= 1;
27427
- if (remaining === 0) break;
27428
- }
27429
- return rows;
27430
- }
27431
28555
  /**
27432
28556
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27433
28557
  *
@@ -27454,6 +28578,33 @@ var SqliteFindingsRepository = class {
27454
28578
  yield toFlatFindingRow(r);
27455
28579
  }
27456
28580
  }
28581
+ /**
28582
+ * One finding by its own id, or null when no such row exists.
28583
+ *
28584
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28585
+ * the store — and, unlike anything derived from a list page, it resolves a
28586
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28587
+ * deep link needs: the id it carries may name a finding thousands of rows
28588
+ * older than anything a first page holds.
28589
+ *
28590
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28591
+ * RESOLVES an id; whether that row would survive the list's current filters is
28592
+ * a different question, and hiding the target because a filter excludes it is
28593
+ * worse than showing it.
28594
+ *
28595
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28596
+ * type should the list select?" and "what does the drawer show?".
28597
+ */
28598
+ findingInstance(id) {
28599
+ const row = this.db.prepare(
28600
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28601
+ FROM inspection_findings f
28602
+ JOIN audit_events e ON e.id = f.audit_event_id
28603
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28604
+ WHERE f.id = ?`
28605
+ ).get(id);
28606
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28607
+ }
27457
28608
  /**
27458
28609
  * The one statement both instance-level scans run: every finding in scope,
27459
28610
  * joined to its event and definition, newest first.
@@ -27487,17 +28638,7 @@ var SqliteFindingsRepository = class {
27487
28638
  conditions.push("e.started_at >= ?");
27488
28639
  params.push(isoToEpochMillis(scope.from));
27489
28640
  }
27490
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27491
- d.severity AS severity, f.masked_match AS masked_match,
27492
- f.action_taken AS action_taken, f.confidence AS confidence,
27493
- e.started_at AS occurred_at,
27494
- e.source_tool AS source_tool,
27495
- e.repo AS repo,
27496
- e.file_path AS file,
27497
- e.tool_name AS tool_name,
27498
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27499
- e.event_type AS kind, f.finding_key AS finding_key,
27500
- ${latestResolutionStatusSql("f")} AS latest_status
28641
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27501
28642
  FROM audit_events e
27502
28643
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27503
28644
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27511,6 +28652,26 @@ var SqliteFindingsRepository = class {
27511
28652
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27512
28653
  const rows = this.db.prepare(
27513
28654
  `SELECT rule_id,
28655
+ -- BARE columns beside max(latest_at), which is deliberate and
28656
+ -- is SQLite's documented behaviour: with a single min()/max()
28657
+ -- in an aggregate query, every bare column takes its value from
28658
+ -- the row that produced the extremum. So these are the severity
28659
+ -- and category of the definition whose finding is NEWEST, which
28660
+ -- is what the row-based build they replaced read off its first
28661
+ -- (newest-first) row.
28662
+ --
28663
+ -- min() is WRONG here and was the defect: inspection_definitions
28664
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28665
+ -- mints a new row), so a rule whose severity moved between
28666
+ -- versions has several, and min() picks the ALPHABETICALLY
28667
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28668
+ -- That is arbitrary in direction, and it feeds the badge, the
28669
+ -- filter, the facet counts and the primary sort key.
28670
+ --
28671
+ -- Adding a second min()/max() aggregate here would make these
28672
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28673
+ severity,
28674
+ category,
27514
28675
  sum(tuple_count) AS instance_count,
27515
28676
  max(latest_at) AS latest_at,
27516
28677
  group_concat(source_tools) AS source_tools,
@@ -27521,6 +28682,14 @@ var SqliteFindingsRepository = class {
27521
28682
  group_concat(tool_names) AS tool_names
27522
28683
  FROM (
27523
28684
  SELECT d.rule_id AS rule_id,
28685
+ -- Severity and category are columns of the DEFINITION, and
28686
+ -- a rule can have SEVERAL definitions (one per version), so
28687
+ -- these are grouped on below and resolved to the newest
28688
+ -- firing version by the outer query's bare-column select.
28689
+ -- They ride the aggregate because the type build has no rows
28690
+ -- to read them off \u2014 see buildFindingTypes.
28691
+ d.severity AS severity,
28692
+ d.category AS category,
27524
28693
  e.event_type || '${TUPLE_SEP}' ||
27525
28694
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27526
28695
  coalesce(latest.status, '') AS status_tuple,
@@ -27535,7 +28704,7 @@ var SqliteFindingsRepository = class {
27535
28704
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27536
28705
  ON latest.finding_key = f.finding_key
27537
28706
  ${scope.predicate}
27538
- GROUP BY d.rule_id, status_tuple
28707
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27539
28708
  )
27540
28709
  GROUP BY rule_id`
27541
28710
  ).all(scope.params);
@@ -27544,6 +28713,8 @@ var SqliteFindingsRepository = class {
27544
28713
  r.rule_id,
27545
28714
  {
27546
28715
  instanceCount: r.instance_count,
28716
+ severity: r.severity,
28717
+ category: r.category,
27547
28718
  sourceTools: splitConcat(r.source_tools),
27548
28719
  actionsTaken: splitConcat(r.actions_taken),
27549
28720
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27560,7 +28731,7 @@ var SqliteFindingsRepository = class {
27560
28731
  latestDetectedAt: epochMillisToIso(r.latest_at),
27561
28732
  // Free text only — joined and substring-matched, so group_concat's
27562
28733
  // commas need no unpicking (a repo/path containing one still matches).
27563
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28734
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27564
28735
  // tell "no q this request" from "a group with no repo/file at all"
27565
28736
  // and skip priming a haystack nothing will read.
27566
28737
  ...withSearchText ? {
@@ -27588,7 +28759,9 @@ var SqliteFindingsRepository = class {
27588
28759
  )
27589
28760
  );
27590
28761
  for (const row of grouped) {
27591
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28762
+ if (Object.hasOwn(byAction, row.action_taken)) {
28763
+ byAction[row.action_taken] = row.c;
28764
+ }
27592
28765
  }
27593
28766
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27594
28767
  const sevRows = allRows(
@@ -27605,7 +28778,9 @@ var SqliteFindingsRepository = class {
27605
28778
  )
27606
28779
  );
27607
28780
  for (const row of sevRows) {
27608
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28781
+ if (Object.hasOwn(bySeverity, row.severity)) {
28782
+ bySeverity[row.severity] = row.c;
28783
+ }
27609
28784
  }
27610
28785
  const categories = ENFORCEABLE_CATEGORIES;
27611
28786
  const enabledRows = allRows(
@@ -27654,469 +28829,6 @@ function isoDay(ms) {
27654
28829
  return new Date(ms).toISOString().slice(0, 10);
27655
28830
  }
27656
28831
 
27657
- // ../../packages/persistence/src/repositories/history-sync.ts
27658
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27659
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27660
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27661
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27662
- var SKIPPED = -1;
27663
- var ROW_COLUMNS = `id,
27664
- parent_id AS parentId,
27665
- root_session_id AS rootSessionId,
27666
- event_type AS eventType,
27667
- host_id AS hostId,
27668
- harness_id AS harnessId,
27669
- source_project_id AS sourceProjectId,
27670
- started_at AS startedAt,
27671
- ended_at AS endedAt,
27672
- severity,
27673
- priority,
27674
- content,
27675
- content_hash AS contentHash,
27676
- attributes`;
27677
- var SqliteHistorySyncRepository = class {
27678
- constructor(db) {
27679
- this.db = db;
27680
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27681
- this.sessionsStmt = db.prepare(
27682
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27683
- FROM audit_events
27684
- WHERE synced_at IS NULL
27685
- AND event_type IN (${TYPE_LIST})
27686
- AND started_at < :before
27687
- GROUP BY sessionId
27688
- ORDER BY earliest
27689
- LIMIT :limit`
27690
- );
27691
- this.rowsStmt = db.prepare(
27692
- `SELECT ${ROW_COLUMNS}
27693
- FROM audit_events
27694
- WHERE synced_at IS NULL
27695
- AND event_type IN (${TYPE_LIST})
27696
- AND started_at < :before
27697
- AND COALESCE(root_session_id, id) = :sessionId
27698
- ORDER BY (event_type = 'session') DESC, started_at
27699
- LIMIT :limit`
27700
- );
27701
- this.captureRowsStmt = db.prepare(
27702
- `SELECT ${ROW_COLUMNS}
27703
- FROM audit_events
27704
- WHERE synced_at IS NULL
27705
- AND sync_claimed_at IS NULL
27706
- AND outbox_owed = 1
27707
- AND event_type IN (${CAPTURE_TYPE_LIST})
27708
- AND started_at < :before
27709
- ORDER BY started_at
27710
- LIMIT :limit`
27711
- );
27712
- this.markOwedStmt = db.prepare(
27713
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27714
- );
27715
- this.stampStmt = db.prepare(
27716
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27717
- );
27718
- this.claimRowStmt = db.prepare(
27719
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27720
- );
27721
- this.releaseRowStmt = db.prepare(
27722
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27723
- );
27724
- this.releaseStaleClaimsStmt = db.prepare(
27725
- `UPDATE audit_events SET sync_claimed_at = NULL
27726
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27727
- );
27728
- this.partitionStmt = db.prepare(
27729
- `SELECT
27730
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27731
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27732
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27733
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27734
- COUNT(*) AS total
27735
- FROM audit_events
27736
- WHERE event_type IN (${TYPE_LIST})`
27737
- );
27738
- this.countsStmt = db.prepare(
27739
- `SELECT
27740
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27741
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27742
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27743
- FROM audit_events
27744
- WHERE event_type IN (${TYPE_LIST})`
27745
- );
27746
- this.captureSkipCountStmt = db.prepare(
27747
- `SELECT COUNT(*) AS skipped
27748
- FROM audit_events
27749
- WHERE synced_at = ${String(SKIPPED)}
27750
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27751
- );
27752
- this.fingerprintStmt = db.prepare(
27753
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27754
- FROM history_sync WHERE id = 1`
27755
- );
27756
- this.setFingerprintStmt = db.prepare(
27757
- `UPDATE history_sync
27758
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27759
- WHERE id = 1`
27760
- );
27761
- this.disownCapturesStmt = db.prepare(
27762
- `UPDATE audit_events SET outbox_owed = NULL
27763
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27764
- );
27765
- this.rearmStmt = db.prepare(
27766
- `UPDATE audit_events SET synced_at = NULL
27767
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27768
- );
27769
- this.claimStmt = db.prepare(
27770
- `UPDATE history_sync
27771
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27772
- WHERE id = 1
27773
- AND (owner_pid IS NULL
27774
- OR heartbeat_at IS NULL
27775
- OR heartbeat_at < :staleBefore
27776
- OR heartbeat_at > :now)`
27777
- );
27778
- this.heartbeatStmt = db.prepare(
27779
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27780
- );
27781
- this.releaseStmt = db.prepare(
27782
- `UPDATE history_sync
27783
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27784
- WHERE id = 1 AND owner_pid = :pid`
27785
- );
27786
- this.closeWindowStmt = db.prepare(
27787
- `UPDATE audit_events SET synced_at = :at
27788
- WHERE synced_at IS NULL
27789
- AND event_type IN (${TYPE_LIST})
27790
- AND started_at >= :attachedAt`
27791
- );
27792
- this.releaseBoundaryStmt = db.prepare(
27793
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27794
- );
27795
- this.freezeBoundaryStmt = db.prepare(
27796
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27797
- );
27798
- this.leaseStmt = db.prepare(
27799
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27800
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27801
- FROM history_sync WHERE id = 1`
27802
- );
27803
- this.inspectionsStmt = db.prepare(
27804
- `SELECT d.rule_id AS ruleId,
27805
- d.name AS ruleName,
27806
- d.version AS ruleVersion,
27807
- d.category AS category,
27808
- d.severity AS severity,
27809
- f.span_start AS spanStart,
27810
- f.span_end AS spanEnd,
27811
- f.masked_match AS maskedMatch,
27812
- f.action_taken AS actionTaken,
27813
- f.confidence AS confidence
27814
- FROM inspection_findings f
27815
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27816
- WHERE f.audit_event_id = :auditEventId
27817
- ORDER BY f.span_start, f.id`
27818
- );
27819
- }
27820
- db;
27821
- ensureRowStmt;
27822
- sessionsStmt;
27823
- rowsStmt;
27824
- stampStmt;
27825
- countsStmt;
27826
- fingerprintStmt;
27827
- setFingerprintStmt;
27828
- rearmStmt;
27829
- claimStmt;
27830
- heartbeatStmt;
27831
- releaseStmt;
27832
- leaseStmt;
27833
- inspectionsStmt;
27834
- closeWindowStmt;
27835
- releaseBoundaryStmt;
27836
- freezeBoundaryStmt;
27837
- captureRowsStmt;
27838
- markOwedStmt;
27839
- captureSkipCountStmt;
27840
- disownCapturesStmt;
27841
- partitionStmt;
27842
- claimRowStmt;
27843
- releaseRowStmt;
27844
- releaseStaleClaimsStmt;
27845
- /**
27846
- * The masked detections recorded against one tool call.
27847
- *
27848
- * These travel with the event because a tool call's target is not
27849
- * re-inspectable from the event alone — unlike a capture, where the text
27850
- * itself is re-scannable. What crosses is the masked match and the rule that
27851
- * produced it, never the value.
27852
- */
27853
- inspectionsFor(auditEventId) {
27854
- return allRows(this.inspectionsStmt, { auditEventId });
27855
- }
27856
- /**
27857
- * Sessions with structural rows still to send, oldest first.
27858
- *
27859
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27860
- * read. Anything recorded after the machine attached is the live forward
27861
- * path's to deliver; this drain exists for what was recorded before it, and a
27862
- * row both paths send is at best a duplicate request and at worst — for a
27863
- * session root — an overwrite of the inventory ids the live path resolved.
27864
- */
27865
- pendingSessions(limit, before) {
27866
- return allRows(this.sessionsStmt, { limit, before }).map(
27867
- (r) => r.sessionId
27868
- );
27869
- }
27870
- /** One session's undelivered structural rows within the backlog, root first. */
27871
- pendingRows(sessionId, limit, before) {
27872
- return allRows(this.rowsStmt, { sessionId, limit, before });
27873
- }
27874
- /**
27875
- * Captures this machine still owes the deployment, oldest first.
27876
- *
27877
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27878
- * by a time window — see captureRowsStmt for why a window could not express
27879
- * this. `before` is the grace window that leaves a just-recorded capture to
27880
- * the live path.
27881
- */
27882
- pendingCaptureRows(limit, before) {
27883
- return allRows(this.captureRowsStmt, { limit, before });
27884
- }
27885
- /**
27886
- * Record that a capture is OWED to the deployment.
27887
- *
27888
- * Written by the attached forward path when a live send did not confirm
27889
- * delivery, and read by the drain as the whole of its eligibility test. It is
27890
- * a fact rather than an inference: the machine was attached, the send did not
27891
- * land, so the row is owed — which no time window can state, because the same
27892
- * window that holds the rows a past attachment left owed also holds every
27893
- * capture recorded while the machine was DETACHED, and those were never
27894
- * offered to anyone.
27895
- *
27896
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27897
- * out of the drain's read.
27898
- */
27899
- markCaptureOwed(id) {
27900
- this.markOwedStmt.run({ id });
27901
- }
27902
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27903
- markSynced(ids, atMs) {
27904
- this.stampAll(ids, atMs);
27905
- }
27906
- /**
27907
- * Record that a row will never be sent.
27908
- *
27909
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27910
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27911
- * is retried; marking those would turn one outage into permanent data loss.
27912
- */
27913
- markSkipped(ids) {
27914
- this.stampAll(ids, SKIPPED);
27915
- }
27916
- eachInTransaction(ids, run) {
27917
- if (ids.length === 0) return;
27918
- withTransaction(
27919
- this.db,
27920
- () => {
27921
- for (const id of ids) run(id);
27922
- },
27923
- "IMMEDIATE"
27924
- );
27925
- }
27926
- stampAll(ids, value) {
27927
- if (ids.length === 0) return;
27928
- withTransaction(
27929
- this.db,
27930
- () => {
27931
- for (const id of ids) this.stampStmt.run({ at: value, id });
27932
- },
27933
- "IMMEDIATE"
27934
- );
27935
- }
27936
- /**
27937
- * Claim rows as in-flight.
27938
- *
27939
- * Advisory in exactly the sense the lease is: it records that a send is in
27940
- * progress so a surface can say so, and a lost claim costs a row showing as
27941
- * queued while it is actually being sent. It is not exclusion — the far side
27942
- * settles a duplicate on the row id.
27943
- */
27944
- claimRows(ids, atMs) {
27945
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27946
- }
27947
- /** Give back a claim without settling — the send failed, the row is queued again. */
27948
- releaseRows(ids) {
27949
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27950
- }
27951
- /**
27952
- * Clear claims older than `staleBefore`, and report how many were cleared.
27953
- *
27954
- * A process killed between claiming and settling leaves rows claimed with
27955
- * nothing left to settle them. Without this they read as "sending" for ever.
27956
- */
27957
- releaseStaleClaims(staleBefore) {
27958
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27959
- }
27960
- /**
27961
- * Every tracked row in exactly one delivery state.
27962
- *
27963
- * Takes no boundary on purpose. The boundary answers "what should the drain
27964
- * pick up now", which is a different question from "what state is this row
27965
- * in" — and a machine that has never attached has no boundary to pass, so
27966
- * requiring one would force a caller to invent one and report the whole store
27967
- * as queued.
27968
- */
27969
- partition() {
27970
- const row = getRow(this.partitionStmt, {});
27971
- return {
27972
- queued: row?.queued ?? 0,
27973
- inProgress: row?.inProgress ?? 0,
27974
- synced: row?.synced ?? 0,
27975
- failed: row?.failed ?? 0,
27976
- total: row?.total ?? 0
27977
- };
27978
- }
27979
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27980
- counts(before) {
27981
- const row = getRow(
27982
- this.countsStmt,
27983
- { before }
27984
- );
27985
- const captures = getRow(this.captureSkipCountStmt);
27986
- return {
27987
- pending: row?.pending ?? 0,
27988
- sent: row?.sent ?? 0,
27989
- skipped: row?.skipped ?? 0,
27990
- capturesSkipped: captures?.skipped ?? 0
27991
- };
27992
- }
27993
- /**
27994
- * The deployment the current stamps were made against, and where its backlog
27995
- * ends.
27996
- *
27997
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27998
- * machine that has never drained is — and every writer below seeds the row
27999
- * before it needs one, so nothing depends on this creating it. Keeping the
28000
- * write off the gate path matters because the gate runs on every pass while a
28001
- * write has to take the database's write lock.
28002
- */
28003
- deployment() {
28004
- const row = getRow(
28005
- this.fingerprintStmt
28006
- );
28007
- return {
28008
- fingerprint: row?.fingerprint ?? void 0,
28009
- backlogBefore: row?.backlogBefore ?? void 0
28010
- };
28011
- }
28012
- /**
28013
- * Point the ledger at a different deployment, discarding what it recorded
28014
- * about the previous one.
28015
- *
28016
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28017
- * machine has just left are undelivered as far as the new one is concerned.
28018
- * All three in one transaction, so a crash between them cannot leave stamps
28019
- * attributed to the wrong deployment, or a boundary that belongs to another.
28020
- *
28021
- * The boundary is written HERE and only here, which is what freezes it: a
28022
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28023
- * unchanged, so this never runs and the backlog does not widen back over rows
28024
- * the live path has since delivered.
28025
- */
28026
- rearmFor(fingerprint, backlogBefore) {
28027
- this.ensureRowStmt.run();
28028
- withTransaction(
28029
- this.db,
28030
- () => {
28031
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28032
- this.rearmStmt.run();
28033
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28034
- this.disownCapturesStmt.run();
28035
- }
28036
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28037
- },
28038
- "IMMEDIATE"
28039
- );
28040
- }
28041
- /**
28042
- * End the attached period: hand its rows to the live path, and release the
28043
- * boundary so the next attachment can freeze a new one.
28044
- *
28045
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28046
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28047
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28048
- * during the detached period, because the machine is not attached. Rows
28049
- * recorded in that window sit after the boundary and before the re-attach, so
28050
- * neither path takes them, and the pending count reports none outstanding.
28051
- *
28052
- * Stamping the attached window is not a claim that every one of those rows
28053
- * reached the deployment — the live path drops on failure and says so
28054
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28055
- * status quo: they sit outside the frozen boundary today and are equally never
28056
- * re-sent. Making it explicit is what lets the boundary move.
28057
- *
28058
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28059
- * window unstamped — that half-state would re-send the whole attached period
28060
- * on the next attach, which is the failure the boundary exists to prevent.
28061
- */
28062
- closeAttachedWindow(attachedAtMs, atMs) {
28063
- this.ensureRowStmt.run();
28064
- withTransaction(
28065
- this.db,
28066
- () => {
28067
- const row = getRow(this.fingerprintStmt);
28068
- const from = row?.backlogBefore ?? attachedAtMs;
28069
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28070
- this.releaseBoundaryStmt.run();
28071
- },
28072
- "IMMEDIATE"
28073
- );
28074
- }
28075
- /**
28076
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28077
- *
28078
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28079
- * different deployment and therefore discards what was delivered to the old
28080
- * one: here the recipient is the same, so everything already sent to it stays
28081
- * sent.
28082
- */
28083
- freezeBoundary(backlogBefore) {
28084
- this.ensureRowStmt.run();
28085
- this.freezeBoundaryStmt.run({ backlogBefore });
28086
- }
28087
- /** Take the claim, or report that someone live already holds it. */
28088
- claim(pid, host, nowMs, staleAfterMs) {
28089
- this.ensureRowStmt.run();
28090
- let taken = false;
28091
- withTransaction(
28092
- this.db,
28093
- () => {
28094
- const result = this.claimStmt.run({
28095
- pid,
28096
- host,
28097
- now: nowMs,
28098
- staleBefore: nowMs - staleAfterMs
28099
- });
28100
- taken = result.changes === 1;
28101
- },
28102
- "IMMEDIATE"
28103
- );
28104
- return taken;
28105
- }
28106
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28107
- heartbeat(pid, nowMs) {
28108
- this.heartbeatStmt.run({ now: nowMs, pid });
28109
- }
28110
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28111
- release(pid) {
28112
- this.releaseStmt.run({ pid });
28113
- }
28114
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28115
- lease() {
28116
- return getRow(this.leaseStmt);
28117
- }
28118
- };
28119
-
28120
28832
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28121
28833
  var SqliteInspectionDefinitionsRepository = class {
28122
28834
  constructor(db) {
@@ -28308,7 +29020,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28308
29020
  }
28309
29021
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28310
29022
  }
28311
- function readManagedSettings(paths = managedSettingsPaths()) {
29023
+ var testOnlyManagedPaths = null;
29024
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28312
29025
  for (const path of paths) {
28313
29026
  let text;
28314
29027
  try {
@@ -28343,6 +29056,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28343
29056
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28344
29057
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28345
29058
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29059
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28346
29060
  if (values.vaultConsent !== void 0) {
28347
29061
  merged.vaultConsent = values.vaultConsent ? (
28348
29062
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30788,7 +31502,7 @@ function toUtcDateString(ms) {
30788
31502
  return new Date(ms).toISOString().slice(0, 10);
30789
31503
  }
30790
31504
  function isTimeseriesSeverity(s) {
30791
- return s === "critical" || s === "high" || s === "medium";
31505
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30792
31506
  }
30793
31507
  var SqliteSecurityRepository = class {
30794
31508
  constructor(db, now = () => Date.now()) {
@@ -30850,7 +31564,7 @@ var SqliteSecurityRepository = class {
30850
31564
  ELSE 0
30851
31565
  END) AS open_at_rest
30852
31566
  FROM inspection_findings f
30853
- JOIN audit_events e ON e.id = f.audit_event_id
31567
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30854
31568
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30855
31569
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30856
31570
  ON latest.finding_key = f.finding_key
@@ -30917,12 +31631,16 @@ var SqliteSecurityRepository = class {
30917
31631
  const now = this.now();
30918
31632
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30919
31633
  const rows = this.findingsInRange(windowStart, now);
30920
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30921
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30922
- critical: 0,
30923
- high: 0,
30924
- medium: 0
30925
- }));
31634
+ const points = Array.from(
31635
+ { length: numBuckets },
31636
+ (_, i) => ({
31637
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31638
+ critical: 0,
31639
+ high: 0,
31640
+ medium: 0,
31641
+ low: 0
31642
+ })
31643
+ );
30926
31644
  for (const r of rows) {
30927
31645
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30928
31646
  const bucket = points[idx];
@@ -31072,7 +31790,7 @@ var SqliteSecurityRepository = class {
31072
31790
  this.db.prepare(
31073
31791
  `SELECT e.repo AS repo, count(*) AS c
31074
31792
  FROM inspection_findings f
31075
- JOIN audit_events e ON e.id = f.audit_event_id
31793
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31076
31794
  WHERE e.started_at >= :from AND e.started_at < :to
31077
31795
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31078
31796
  AND e.repo IS NOT NULL
@@ -31140,6 +31858,7 @@ var SqliteSecurityRepository = class {
31140
31858
  `SELECT f.finding_key AS finding_key,
31141
31859
  d.rule_id AS rule_id,
31142
31860
  d.severity AS severity,
31861
+ e.repo AS repo,
31143
31862
  e.file_path AS path,
31144
31863
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31145
31864
  latest.resolved_at AS latest_resolved_at
@@ -31159,6 +31878,7 @@ var SqliteSecurityRepository = class {
31159
31878
  const items = rows.map((r) => ({
31160
31879
  findingKey: r.finding_key,
31161
31880
  ruleId: r.rule_id,
31881
+ repo: r.repo ?? "",
31162
31882
  severity: r.severity,
31163
31883
  path: r.path ?? "",
31164
31884
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31168,15 +31888,68 @@ var SqliteSecurityRepository = class {
31168
31888
  }));
31169
31889
  return Promise.resolve({ items });
31170
31890
  }
31891
+ /**
31892
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31893
+ *
31894
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31895
+ * list: a secret committed three weeks ago and never rotated is still the most
31896
+ * important thing to fix, and any window hides it. It carried a "newest N
31897
+ * findings" cap and then a range; the first meant a different span on every
31898
+ * machine, and the second reported "no recommendations" over live exposure.
31899
+ *
31900
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31901
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31902
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31903
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31904
+ * The two answer different questions and only this one has to match a link.
31905
+ *
31906
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31907
+ * whole-store scope costs a grouped scan rather than a row per finding.
31908
+ */
31909
+ recommendationInputs() {
31910
+ const rows = allRows(
31911
+ this.db.prepare(
31912
+ `SELECT d.rule_id AS rule_id,
31913
+ d.category AS category,
31914
+ d.severity AS severity,
31915
+ COUNT(*) AS count
31916
+ FROM inspection_findings f
31917
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31918
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31919
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31920
+ ON latest.finding_key = f.finding_key
31921
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31922
+ AND e.event_type = 'code_change'
31923
+ AND (
31924
+ f.finding_key IS NULL
31925
+ OR latest.status IS NULL
31926
+ OR latest.status NOT IN ('resolved', 'dismissed')
31927
+ )
31928
+ GROUP BY d.rule_id, d.category, d.severity`
31929
+ )
31930
+ );
31931
+ return Promise.resolve(
31932
+ rows.map((r) => ({
31933
+ ruleId: r.rule_id,
31934
+ category: r.category,
31935
+ severity: r.severity,
31936
+ count: r.count
31937
+ }))
31938
+ );
31939
+ }
31171
31940
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31172
31941
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31173
31942
  // numeric and the JS aggregations bucket/split on ms directly.
31174
31943
  findingsInRange(fromMs, toMs) {
31175
31944
  const rows = allRows(
31176
31945
  this.db.prepare(
31177
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31946
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31947
+ // joined for `severity`, so they are two more columns off a row this read
31948
+ // already fetches. They feed the recommended-actions rollup.
31949
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31950
+ d.rule_id AS rule_id, d.category AS category
31178
31951
  FROM inspection_findings f
31179
- JOIN audit_events e ON e.id = f.audit_event_id
31952
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31180
31953
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31181
31954
  WHERE e.started_at >= :from AND e.started_at < :to
31182
31955
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31187,7 +31960,9 @@ var SqliteSecurityRepository = class {
31187
31960
  return rows.map((r) => ({
31188
31961
  occurredAt: r.occurred_at,
31189
31962
  severity: r.severity,
31190
- actionTaken: r.action_taken
31963
+ actionTaken: r.action_taken,
31964
+ ruleId: r.rule_id,
31965
+ category: r.category
31191
31966
  }));
31192
31967
  }
31193
31968
  };
@@ -32015,6 +32790,7 @@ function openWithPragmas(file2) {
32015
32790
  db.exec("PRAGMA journal_mode = WAL");
32016
32791
  db.exec("PRAGMA busy_timeout = 2000");
32017
32792
  db.exec("PRAGMA foreign_keys = ON");
32793
+ registerSqlFunctions(db);
32018
32794
  } catch (err) {
32019
32795
  closeQuietly(db);
32020
32796
  throw err;
@@ -32044,7 +32820,7 @@ function backupLegacyStore(db, file2) {
32044
32820
  discardStore(file2, backup);
32045
32821
  return backup;
32046
32822
  }
32047
- function openAndInitialize(file2, base) {
32823
+ function openAndInitialize(file2, base, skipTags) {
32048
32824
  let db = openWithPragmas(file2);
32049
32825
  try {
32050
32826
  if (isForeignSqliteLineage(db)) {
@@ -32054,7 +32830,7 @@ function openAndInitialize(file2, base) {
32054
32830
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32055
32831
  );
32056
32832
  }
32057
- applyMigrations(db, file2);
32833
+ applyMigrations(db, file2, { skipTags });
32058
32834
  tightenPerms(file2);
32059
32835
  const policies = new SqlitePoliciesRepository(db);
32060
32836
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32069,6 +32845,7 @@ function openAndInitialize(file2, base) {
32069
32845
  exceptions: new SqliteExceptionsRepository(db),
32070
32846
  resolutions: new SqliteResolutionsRepository(db),
32071
32847
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32848
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32072
32849
  security: new SqliteSecurityRepository(db),
32073
32850
  detections: new SqliteDetectionsRepository(db),
32074
32851
  shares: new SqliteSharesRepository(db),
@@ -32091,7 +32868,8 @@ function openAndInitialize(file2, base) {
32091
32868
  throw err;
32092
32869
  }
32093
32870
  }
32094
- function openLocalDatabase(dir) {
32871
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32872
+ function openLocalDatabase(dir, options = {}) {
32095
32873
  ensureDataDirSync(dir);
32096
32874
  const file2 = join7(dir, DB_FILENAME);
32097
32875
  reapStalePartials(file2);
@@ -32103,6 +32881,7 @@ function openLocalDatabase(dir) {
32103
32881
  installedPacks,
32104
32882
  scanLedger,
32105
32883
  historySync,
32884
+ bodyRetention,
32106
32885
  secretVault,
32107
32886
  exceptions,
32108
32887
  resolutions,
@@ -32126,7 +32905,8 @@ function openLocalDatabase(dir) {
32126
32905
  // `dir` is always `<base>/data` — every caller resolves it through
32127
32906
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32128
32907
  // settings/ and data/, and the pack-policy floor needs both halves.
32129
- dirname2(dir)
32908
+ dirname2(dir),
32909
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32130
32910
  );
32131
32911
  function captureRowId(event) {
32132
32912
  return captureId(
@@ -32319,6 +33099,7 @@ function openLocalDatabase(dir) {
32319
33099
  installedPacks,
32320
33100
  scanLedger,
32321
33101
  historySync,
33102
+ bodyRetention,
32322
33103
  secretVault,
32323
33104
  exceptions,
32324
33105
  resolutions,
@@ -32357,14 +33138,78 @@ function openLocalDatabase(dir) {
32357
33138
  };
32358
33139
  }
32359
33140
 
32360
- // ../../packages/persistence/src/finding-key.ts
33141
+ // ../../packages/persistence/src/egress-wire.ts
32361
33142
  import { createHash as createHash3 } from "crypto";
33143
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33144
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33145
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33146
+ var FILE_URL = /^file:\/\//i;
33147
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33148
+ var SLASH = "/".charCodeAt(0);
33149
+ var GIT_SUFFIX = ".git";
33150
+ function trimSlashes(path) {
33151
+ let start = 0;
33152
+ let end = path.length;
33153
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33154
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33155
+ return path.slice(start, end);
33156
+ }
33157
+ function canonicalGitUrl(url2) {
33158
+ const trimmed = url2.trim();
33159
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33160
+ const scheme = SCHEME_FORM.exec(trimmed);
33161
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33162
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33163
+ if (host === void 0) return trimmed;
33164
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33165
+ const bare = trimSlashes(path);
33166
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33167
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33168
+ }
33169
+ function hashProjectKey(projectKey) {
33170
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33171
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33172
+ }
33173
+ function toIngestHit(hit) {
33174
+ return {
33175
+ host: hit.host,
33176
+ kind: hit.kind,
33177
+ name: hit.name,
33178
+ category: hit.category,
33179
+ trust: hit.trust,
33180
+ network: hit.network,
33181
+ method: hit.method,
33182
+ transport: hit.transport,
33183
+ url: hit.url,
33184
+ template: hit.template,
33185
+ dataClass: hit.dataClass,
33186
+ site: {
33187
+ file: hit.site.file,
33188
+ line: hit.site.line,
33189
+ dynamic: hit.site.dynamic,
33190
+ vendored: hit.site.vendored
33191
+ }
33192
+ };
33193
+ }
33194
+ function toEgressIngestRequest(input2) {
33195
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33196
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33197
+ return {
33198
+ projectKey: hashProjectKey(input2.projectKey),
33199
+ project: input2.project,
33200
+ reconcile,
33201
+ hits: hits.map(toIngestHit)
33202
+ };
33203
+ }
33204
+
33205
+ // ../../packages/persistence/src/finding-key.ts
33206
+ import { createHash as createHash4 } from "crypto";
32362
33207
  function normalizeFilePath(filePath) {
32363
33208
  return filePath.replaceAll("\\", "/");
32364
33209
  }
32365
33210
  function computeFindingKey(input2) {
32366
33211
  const normalizedPath = normalizeFilePath(input2.filePath);
32367
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
33212
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32368
33213
  }
32369
33214
 
32370
33215
  // ../../packages/persistence/src/fingerprint.ts
@@ -32490,14 +33335,50 @@ function fingerprintValue(key, raw) {
32490
33335
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32491
33336
  }
32492
33337
 
32493
- // ../../packages/persistence/src/history-preview.ts
32494
- import { existsSync as existsSync4 } from "fs";
33338
+ // ../../packages/persistence/src/forward-health.ts
33339
+ import { readFileSync as readFileSync7 } from "fs";
32495
33340
  import { join as join9 } from "path";
33341
+ var FAILURES = /* @__PURE__ */ new Set([
33342
+ "unauthorized",
33343
+ "forbidden",
33344
+ "unreachable"
33345
+ ]);
33346
+ var BREAKER_COOLDOWN_MS = 3e4;
33347
+ function parseForwardHealth(raw, nowMs) {
33348
+ try {
33349
+ const parsed2 = JSON.parse(raw);
33350
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33351
+ const record2 = parsed2;
33352
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33353
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33354
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33355
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33356
+ } catch {
33357
+ return null;
33358
+ }
33359
+ }
33360
+ function isForwardPaused(health, nowMs) {
33361
+ const openedAtMs = health?.openedAtMs ?? null;
33362
+ if (openedAtMs === null) return false;
33363
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33364
+ }
33365
+
33366
+ // ../../packages/persistence/src/history-backfill.ts
33367
+ import { existsSync as existsSync4 } from "fs";
33368
+ import { join as join10 } from "path";
33369
+
33370
+ // ../../packages/persistence/src/history-preview.ts
33371
+ import { existsSync as existsSync5 } from "fs";
33372
+ import { join as join11 } from "path";
32496
33373
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32497
33374
 
33375
+ // ../../packages/persistence/src/history-sync-state.ts
33376
+ import { readFileSync as readFileSync8 } from "fs";
33377
+ import { join as join12 } from "path";
33378
+
32498
33379
  // ../../packages/persistence/src/store-symlinks.ts
32499
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32500
- import { dirname as dirname3, join as join10, resolve } from "path";
33380
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33381
+ import { dirname as dirname3, join as join13, resolve } from "path";
32501
33382
 
32502
33383
  // ../../packages/persistence/src/vault/crypto.ts
32503
33384
  import {
@@ -32511,20 +33392,20 @@ import {
32511
33392
  // ../../packages/persistence/src/vault/key-provider.ts
32512
33393
  import { execFileSync } from "child_process";
32513
33394
  import { randomBytes as randomBytes2 } from "crypto";
32514
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32515
- import { join as join11 } from "path";
33395
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33396
+ import { join as join14 } from "path";
32516
33397
 
32517
33398
  // ../../packages/persistence/src/vault/vault.ts
32518
33399
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32519
33400
 
32520
33401
  // ../../packages/persistence/src/warn-era-cap.ts
32521
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32522
- import { join as join12 } from "path";
33402
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33403
+ import { join as join15 } from "path";
32523
33404
  var MARKER = "warn-era-capped";
32524
33405
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32525
33406
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32526
- const marker = join12(dataDir2, MARKER);
32527
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33407
+ const marker = join15(dataDir2, MARKER);
33408
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32528
33409
  const capped = db.policies.capCategoryActions();
32529
33410
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32530
33411
  `, { mode: DATA_FILE_MODE });
@@ -32583,8 +33464,8 @@ function resolveProvider() {
32583
33464
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32584
33465
  try {
32585
33466
  ensureLayoutDirSync(base);
32586
- const settingsFile = join13(settingsDir(base), "settings.json");
32587
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33467
+ const settingsFile = join16(settingsDir(base), "settings.json");
33468
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
32588
33469
  } catch {
32589
33470
  }
32590
33471
  migrateLegacyLayout(base);
@@ -32607,9 +33488,9 @@ function resolveProviderSafe(resolveProviderFn) {
32607
33488
  }
32608
33489
 
32609
33490
  // ../../packages/plugin-sdk/src/config-inventory.ts
32610
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33491
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32611
33492
  import { homedir as homedir2 } from "os";
32612
- import { basename as basename3, join as join15 } from "path";
33493
+ import { basename as basename3, join as join18 } from "path";
32613
33494
 
32614
33495
  // ../../packages/detections/src/egress/registry.ts
32615
33496
  var EXTRACTOR_VERSION = "1";
@@ -35740,8 +36621,8 @@ function scanText(text, ruleVersions) {
35740
36621
  }
35741
36622
 
35742
36623
  // ../../packages/plugin-sdk/src/repo.ts
35743
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35744
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
36624
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
36625
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
35745
36626
  function resolveRepoIdentity(cwd) {
35746
36627
  try {
35747
36628
  const root = findGitRoot(cwd);
@@ -35763,36 +36644,36 @@ function resolveRepoIdentity(cwd) {
35763
36644
  function findGitRoot(start) {
35764
36645
  let dir = start;
35765
36646
  for (; ; ) {
35766
- if (existsSync8(join14(dir, ".git"))) return dir;
36647
+ if (existsSync9(join17(dir, ".git"))) return dir;
35767
36648
  const parent = dirname4(dir);
35768
36649
  if (parent === dir) return void 0;
35769
36650
  dir = parent;
35770
36651
  }
35771
36652
  }
35772
36653
  function resolveGitContext(root) {
35773
- const dotGit = join14(root, ".git");
36654
+ const dotGit = join17(root, ".git");
35774
36655
  try {
35775
36656
  if (statSync6(dotGit).isDirectory()) {
35776
- return { configPath: join14(dotGit, "config"), headRoot: root };
36657
+ return { configPath: join17(dotGit, "config"), headRoot: root };
35777
36658
  }
35778
36659
  } catch {
35779
36660
  return void 0;
35780
36661
  }
35781
36662
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
35782
36663
  if (!target) return void 0;
35783
- const gitdir = isAbsolute(target) ? target : join14(root, target);
35784
- if (existsSync8(join14(gitdir, "config"))) {
35785
- return { configPath: join14(gitdir, "config"), headRoot: root };
36664
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
36665
+ if (existsSync9(join17(gitdir, "config"))) {
36666
+ return { configPath: join17(gitdir, "config"), headRoot: root };
35786
36667
  }
35787
- const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
36668
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
35788
36669
  if (!commonRaw) return void 0;
35789
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
36670
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
35790
36671
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
35791
- return { configPath: join14(commonGitDir, "config"), headRoot };
36672
+ return { configPath: join17(commonGitDir, "config"), headRoot };
35792
36673
  }
35793
36674
  function safeRead(path) {
35794
36675
  try {
35795
- return readFileSync8(path, "utf8");
36676
+ return readFileSync10(path, "utf8");
35796
36677
  } catch {
35797
36678
  return void 0;
35798
36679
  }
@@ -35830,9 +36711,9 @@ function slugFromUrl(url2) {
35830
36711
  }
35831
36712
 
35832
36713
  // ../../packages/plugin-sdk/src/events.ts
35833
- import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
36714
+ import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
35834
36715
  function contentHashOf(text) {
35835
- return createHash4("sha256").update(text).digest("hex");
36716
+ return createHash5("sha256").update(text).digest("hex");
35836
36717
  }
35837
36718
  function buildIngestEvent(input2) {
35838
36719
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -35858,7 +36739,7 @@ function buildIngestEvent(input2) {
35858
36739
  }
35859
36740
 
35860
36741
  // ../../packages/plugin-sdk/src/isolated-scan.ts
35861
- import { existsSync as existsSync9 } from "fs";
36742
+ import { existsSync as existsSync10 } from "fs";
35862
36743
  import { fileURLToPath } from "url";
35863
36744
  import { Worker } from "worker_threads";
35864
36745
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -35872,7 +36753,7 @@ function resolveWorkerUrl() {
35872
36753
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
35873
36754
  const candidate = new URL(name, import.meta.url);
35874
36755
  try {
35875
- if (existsSync9(fileURLToPath(candidate))) {
36756
+ if (existsSync10(fileURLToPath(candidate))) {
35876
36757
  resolvedWorkerUrl = candidate;
35877
36758
  return candidate;
35878
36759
  }
@@ -36335,10 +37216,45 @@ function createGuardedScanner(partition, gateway, opts) {
36335
37216
  };
36336
37217
  }
36337
37218
 
37219
+ // ../../packages/plugin-sdk/src/host-floor.ts
37220
+ import { readFileSync as readFileSync13 } from "fs";
37221
+ import { join as join20 } from "path";
37222
+
37223
+ // ../../packages/plugin-sdk/src/model-governance.ts
37224
+ import {
37225
+ closeSync as closeSync2,
37226
+ fstatSync,
37227
+ mkdirSync as mkdirSync2,
37228
+ openSync as openSync2,
37229
+ readFileSync as readFileSync12,
37230
+ readSync,
37231
+ writeFileSync as writeFileSync5
37232
+ } from "fs";
37233
+ import { join as join19 } from "path";
37234
+ var TAIL_BYTES = 256 * 1024;
37235
+
37236
+ // ../../packages/plugin-sdk/src/host-floor.ts
37237
+ var HOST_FEATURE = {
37238
+ ModelSwitch: "model-switch",
37239
+ VaultPointerDisplay: "vault-pointer-display"
37240
+ };
37241
+ var HOST_FLOORS = {
37242
+ [HOST_FEATURE.ModelSwitch]: {
37243
+ label: "model-switch protection",
37244
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37245
+ since: "2.1.251"
37246
+ },
37247
+ [HOST_FEATURE.VaultPointerDisplay]: {
37248
+ label: "vault pointer display",
37249
+ hookEvents: ["MessageDisplay"],
37250
+ since: "2.1.152"
37251
+ }
37252
+ };
37253
+
36338
37254
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36339
37255
  var import_ignore = __toESM(require_ignore(), 1);
36340
- import { readFileSync as readFileSync10 } from "fs";
36341
- import { join as join16 } from "path";
37256
+ import { readFileSync as readFileSync14 } from "fs";
37257
+ import { join as join21 } from "path";
36342
37258
 
36343
37259
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
36344
37260
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -36369,22 +37285,9 @@ function resolveInventoryContext(input2) {
36369
37285
  return ctx;
36370
37286
  }
36371
37287
 
36372
- // ../../packages/plugin-sdk/src/model-governance.ts
36373
- import {
36374
- closeSync as closeSync2,
36375
- fstatSync,
36376
- mkdirSync as mkdirSync2,
36377
- openSync as openSync2,
36378
- readFileSync as readFileSync11,
36379
- readSync,
36380
- writeFileSync as writeFileSync5
36381
- } from "fs";
36382
- import { join as join17 } from "path";
36383
- var TAIL_BYTES = 256 * 1024;
36384
-
36385
37288
  // ../../packages/plugin-sdk/src/nudge.ts
36386
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
36387
- import { join as join18 } from "path";
37289
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
37290
+ import { join as join22 } from "path";
36388
37291
 
36389
37292
  // ../../packages/plugin-sdk/src/paths.ts
36390
37293
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -36426,8 +37329,8 @@ function createPolicyResolver(bundle) {
36426
37329
  }
36427
37330
 
36428
37331
  // ../../packages/plugin-sdk/src/project-files.ts
36429
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36430
- import { basename as basename5, join as join19 } from "path";
37332
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37333
+ import { basename as basename5, join as join23 } from "path";
36431
37334
 
36432
37335
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36433
37336
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -36508,6 +37411,14 @@ function safeMaskedMatch(rawMatch) {
36508
37411
  // ../../packages/plugin-sdk/src/runtime.ts
36509
37412
  import { randomUUID as randomUUID14 } from "crypto";
36510
37413
  var ENFORCEMENT_CEILING_ENABLED = false;
37414
+ function applyEnforcementCeiling(action, policyMode, enabled) {
37415
+ if (!enabled || policyMode !== "warn") return action;
37416
+ return action === "block" || action === "redact" ? "warn" : action;
37417
+ }
37418
+ function resolveEnforcedAction(action, opts) {
37419
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
37420
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
37421
+ }
36511
37422
  function startTiming() {
36512
37423
  try {
36513
37424
  return performance.now();
@@ -36544,7 +37455,7 @@ function createPluginRuntime(gateway, settings, opts) {
36544
37455
  bundlesPacked = true;
36545
37456
  }
36546
37457
  const policyMode = settings.policy;
36547
- const redactFallback = settings.redactFallback;
37458
+ let redactFallback = settings.redactFallback;
36548
37459
  const dataDir2 = opts?.dataDir;
36549
37460
  let rules = [];
36550
37461
  let scanner;
@@ -36588,6 +37499,7 @@ function createPluginRuntime(gateway, settings, opts) {
36588
37499
  rules = [...verified, ...unverified];
36589
37500
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
36590
37501
  bundleExceptions = bundle.exceptions ?? [];
37502
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
36591
37503
  initialized = true;
36592
37504
  }
36593
37505
  let cachedKey;
@@ -36616,21 +37528,23 @@ function createPluginRuntime(gateway, settings, opts) {
36616
37528
  }
36617
37529
  function actionForFinding(finding, excepted, rewritable = true) {
36618
37530
  if (excepted?.has(finding)) return "allow";
36619
- const action = resolveAction(finding.ruleId, finding.category);
36620
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
36621
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
36622
- return "warn";
36623
- }
36624
- return action;
37531
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
37532
+ policyMode,
37533
+ redactFallback,
37534
+ rewritable,
37535
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
37536
+ });
36625
37537
  }
36626
37538
  function decide(findings, text, excepted, rewritable = true) {
36627
37539
  if (findings.length === 0) return { action: "log", text, findings: [] };
36628
37540
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
37541
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
37542
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
36629
37543
  let worst = "log";
36630
37544
  for (const finding of findings) {
36631
37545
  worst = strongerAction(worst, actionFor(finding));
36632
37546
  }
36633
- if (worst === "block") return { action: "block", text: null, findings };
37547
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
36634
37548
  if (worst === "redact") {
36635
37549
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
36636
37550
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -36640,9 +37554,13 @@ function createPluginRuntime(gateway, settings, opts) {
36640
37554
  findings,
36641
37555
  enforcedFindings: redactFindings,
36642
37556
  reversibleFindings
37557
+ // No `degraded` here, and it is not an omission: `rewritable` is per
37558
+ // CAPTURE, so on an unrewritable field every redact has already become
37559
+ // the fallback and this branch is unreachable. Spreading it would read
37560
+ // as a case that can happen.
36643
37561
  };
36644
37562
  }
36645
- return { action: worst, text, findings };
37563
+ return { action: worst, text, findings, ...degraded };
36646
37564
  }
36647
37565
  function fingerprintOf(key, finding, cache) {
36648
37566
  let fp = cache.get(finding);
@@ -36771,8 +37689,8 @@ function createPluginRuntime(gateway, settings, opts) {
36771
37689
  };
36772
37690
  }
36773
37691
  }
36774
- async function processText(text, context) {
36775
- return (await evaluate(text, context, {})).decision;
37692
+ async function processText(text, context, opts2 = {}) {
37693
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
36776
37694
  }
36777
37695
  async function capture(input2, opts2 = {}) {
36778
37696
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -36795,10 +37713,12 @@ function createPluginRuntime(gateway, settings, opts) {
36795
37713
  );
36796
37714
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
36797
37715
  const inspectionMs = elapsedMs(timingStartedAt);
36798
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
37716
+ const redactDegradedTo = decision.redactDegradedTo;
37717
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
36799
37718
  ...input2.metadata,
36800
37719
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
36801
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
37720
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
37721
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
36802
37722
  } : input2.metadata;
36803
37723
  const event = buildIngestEvent({
36804
37724
  kind: input2.kind,
@@ -36870,11 +37790,11 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36870
37790
 
36871
37791
  // ../../packages/plugin-sdk/src/throttle.ts
36872
37792
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36873
- import { join as join20 } from "path";
37793
+ import { join as join24 } from "path";
36874
37794
 
36875
37795
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
36876
37796
  import { writeFileSync as writeFileSync8 } from "fs";
36877
- import { join as join21 } from "path";
37797
+ import { join as join25 } from "path";
36878
37798
 
36879
37799
  // ../../packages/setup-wizard/src/triage/merge.ts
36880
37800
  var RANK = Object.fromEntries(
@@ -36882,9 +37802,9 @@ var RANK = Object.fromEntries(
36882
37802
  );
36883
37803
 
36884
37804
  // ../../packages/setup-wizard/src/triage/plan-file.ts
36885
- import { mkdtempSync, readFileSync as readFileSync13, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
37805
+ import { mkdtempSync, readFileSync as readFileSync16, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
36886
37806
  import { tmpdir } from "os";
36887
- import { basename as basename6, dirname as dirname6, join as join22 } from "path";
37807
+ import { basename as basename6, dirname as dirname6, join as join26 } from "path";
36888
37808
  var SuppressionEntrySchema = external_exports.object({
36889
37809
  ruleId: external_exports.string(),
36890
37810
  category: DetectionCategory,
@@ -36928,43 +37848,6 @@ var PersistedPlanSchema = external_exports.object({
36928
37848
  // ../../packages/setup-wizard/src/triage/writeback.ts
36929
37849
  var TRIAGE_STATUSES = ["complete", "complete:no-history", "skipped:no-consent"];
36930
37850
 
36931
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
36932
- import { createHash as createHash5 } from "crypto";
36933
- function hashProjectKey(projectKey) {
36934
- return createHash5("sha256").update(projectKey, "utf8").digest("hex");
36935
- }
36936
- function toIngestHit(hit) {
36937
- return {
36938
- host: hit.host,
36939
- kind: hit.kind,
36940
- name: hit.name,
36941
- category: hit.category,
36942
- trust: hit.trust,
36943
- network: hit.network,
36944
- method: hit.method,
36945
- transport: hit.transport,
36946
- url: hit.url,
36947
- template: hit.template,
36948
- dataClass: hit.dataClass,
36949
- site: {
36950
- file: hit.site.file,
36951
- line: hit.site.line,
36952
- dynamic: hit.site.dynamic,
36953
- vendored: hit.site.vendored
36954
- }
36955
- };
36956
- }
36957
- function toEgressIngestRequest(input2) {
36958
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
36959
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
36960
- return {
36961
- projectKey: hashProjectKey(input2.projectKey),
36962
- project: input2.project,
36963
- reconcile,
36964
- hits: hits.map(toIngestHit)
36965
- };
36966
- }
36967
-
36968
37851
  // ../../packages/remote/src/http.ts
36969
37852
  import { request as httpRequest } from "http";
36970
37853
  import { request as httpsRequest } from "https";
@@ -37148,10 +38031,10 @@ function parsed(schema, body, route) {
37148
38031
  }
37149
38032
  function withoutTrailingSlashes(endpoint) {
37150
38033
  let end = endpoint.length;
37151
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
38034
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
37152
38035
  return endpoint.slice(0, end);
37153
38036
  }
37154
- var SLASH = "/".charCodeAt(0);
38037
+ var SLASH2 = "/".charCodeAt(0);
37155
38038
  function createRemoteClient(options) {
37156
38039
  const base = withoutTrailingSlashes(options.endpoint);
37157
38040
  const url2 = (route) => `${base}${route}`;
@@ -37244,6 +38127,7 @@ function createRemoteClient(options) {
37244
38127
  url: url2(ROUTES.shares),
37245
38128
  body: JSON.stringify(validated.data)
37246
38129
  });
38130
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
37247
38131
  okBody(response);
37248
38132
  },
37249
38133
  async pollCommand() {
@@ -37266,19 +38150,51 @@ function createRemoteClient(options) {
37266
38150
  };
37267
38151
  }
37268
38152
 
37269
- // ../../packages/plugin-runtime/src/attached/failure.ts
38153
+ // ../../packages/remote/src/failure-kind.ts
37270
38154
  function statusOf(err) {
37271
38155
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
37272
38156
  const { status } = err;
37273
38157
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
37274
38158
  return status >= 100 && status <= 599 ? status : null;
37275
38159
  }
37276
- function classifyFailure(err) {
37277
- switch (statusOf(err)) {
38160
+ function nameOf(err) {
38161
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
38162
+ return typeof err.name === "string" ? err.name : null;
38163
+ }
38164
+ function classifyRemoteFailure(err) {
38165
+ switch (nameOf(err)) {
38166
+ case "RemoteRouteAbsent":
38167
+ return "route-absent";
38168
+ case "RemoteRequestInvalid":
38169
+ return "invalid-request";
38170
+ case "RemoteResponseInvalid":
38171
+ return "rejected";
38172
+ default:
38173
+ break;
38174
+ }
38175
+ const status = statusOf(err);
38176
+ if (status === null) return "unreachable";
38177
+ switch (status) {
37278
38178
  case 401:
37279
38179
  return "unauthorized";
37280
38180
  case 403:
37281
38181
  return "forbidden";
38182
+ case 429:
38183
+ return "unreachable";
38184
+ case 404:
38185
+ return "unreachable";
38186
+ default:
38187
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
38188
+ }
38189
+ }
38190
+
38191
+ // ../../packages/plugin-runtime/src/attached/failure.ts
38192
+ function classifyFailure(err) {
38193
+ switch (classifyRemoteFailure(err)) {
38194
+ case "unauthorized":
38195
+ return "unauthorized";
38196
+ case "forbidden":
38197
+ return "forbidden";
37282
38198
  default:
37283
38199
  return "unreachable";
37284
38200
  }
@@ -37300,11 +38216,11 @@ function withTimeout(promise2, ms) {
37300
38216
  }
37301
38217
 
37302
38218
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
37303
- import { readFileSync as readFileSync14 } from "fs";
37304
- import { join as join23 } from "path";
38219
+ import { readFileSync as readFileSync17 } from "fs";
38220
+ import { join as join27 } from "path";
37305
38221
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
37306
38222
  function forwardDropsPath(dataDir2) {
37307
- return join23(dataDir2, FORWARD_DROPS_FILENAME);
38223
+ return join27(dataDir2, FORWARD_DROPS_FILENAME);
37308
38224
  }
37309
38225
  function recordForwardDrops(dataDir2, count, nowMs) {
37310
38226
  if (count <= 0) return;
@@ -37322,7 +38238,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
37322
38238
  }
37323
38239
  function readForwardDrops(dataDir2) {
37324
38240
  try {
37325
- const parsed2 = JSON.parse(readFileSync14(forwardDropsPath(dataDir2), "utf8"));
38241
+ const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
37326
38242
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
37327
38243
  const record2 = parsed2;
37328
38244
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -37340,9 +38256,8 @@ function readForwardDrops(dataDir2) {
37340
38256
 
37341
38257
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
37342
38258
  import { randomUUID as randomUUID15 } from "crypto";
37343
- import { readFileSync as readFileSync15 } from "fs";
37344
38259
  import { readFile, rename, writeFile } from "fs/promises";
37345
- import { join as join24 } from "path";
38260
+ import { join as join28 } from "path";
37346
38261
  function isInvalidRequest(err) {
37347
38262
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
37348
38263
  }
@@ -37356,31 +38271,12 @@ function isServerRejection(err) {
37356
38271
  var FORWARD_BUDGET_MS = 1500;
37357
38272
  var DECISION_PATH_BUDGET_MS = 800;
37358
38273
  var BREAKER_FAILURE_THRESHOLD = 3;
37359
- var BREAKER_COOLDOWN_MS = 3e4;
37360
38274
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
37361
- var FAILURES = /* @__PURE__ */ new Set([
37362
- "unauthorized",
37363
- "forbidden",
37364
- "unreachable"
37365
- ]);
37366
38275
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
37367
38276
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
37368
- function parseBreakerState(raw, nowMs) {
37369
- try {
37370
- const parsed2 = JSON.parse(raw);
37371
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
37372
- const record2 = parsed2;
37373
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
37374
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
37375
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
37376
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
37377
- } catch {
37378
- return null;
37379
- }
37380
- }
37381
38277
  function createForwardPolicy(deps) {
37382
38278
  const now = deps.now ?? (() => Date.now());
37383
- const file2 = join24(deps.dir, STATE_FILENAME);
38279
+ const file2 = join28(deps.dir, STATE_FILENAME);
37384
38280
  let state = null;
37385
38281
  let loading = null;
37386
38282
  async function readState() {
@@ -37390,7 +38286,7 @@ function createForwardPolicy(deps) {
37390
38286
  } catch {
37391
38287
  return { ...CLOSED };
37392
38288
  }
37393
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
38289
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
37394
38290
  }
37395
38291
  async function load() {
37396
38292
  if (state !== null) return state;
@@ -37436,7 +38332,7 @@ function createForwardPolicy(deps) {
37436
38332
  };
37437
38333
  const at = now();
37438
38334
  if (current.openedAtMs !== null) {
37439
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
38335
+ if (isForwardPaused(current, at)) {
37440
38336
  return { ok: false, reason: "breaker-open" };
37441
38337
  }
37442
38338
  await persist({
@@ -37973,7 +38869,18 @@ var AttachedDataGateway = class {
37973
38869
  // and the spread above would otherwise drop the field silently — which is
37974
38870
  // exactly what it did, leaving the whole control inert on every device
37975
38871
  // while every test around it stayed green.
37976
- prohibitedModels: cached2.prohibitedModels
38872
+ prohibitedModels: cached2.prohibitedModels,
38873
+ // NAMED for the same reason as the line above, and it is the same defect
38874
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
38875
+ // only the cache carries is dropped in silence. That is what left
38876
+ // `prohibitedModels` inert on every attached device with every test
38877
+ // around it green.
38878
+ //
38879
+ // Taken from the cache rather than merged here, because merging it needs
38880
+ // the device's own SETTING — which is not a bundle field and is not in
38881
+ // scope at this seam. The runtime does that merge, raise-only, where both
38882
+ // values are in hand (createPluginRuntime's ensureInitialized).
38883
+ redactFallback: cached2.redactFallback
37977
38884
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
37978
38885
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
37979
38886
  // it emits, so an 'authored' policy arriving from the control plane
@@ -38101,10 +39008,6 @@ function toolAuditEvent(input2) {
38101
39008
  };
38102
39009
  }
38103
39010
 
38104
- // ../../packages/plugin-runtime/src/attached/history-state.ts
38105
- import { readFileSync as readFileSync16 } from "fs";
38106
- import { join as join25 } from "path";
38107
-
38108
39011
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
38109
39012
  import { createHash as createHash6 } from "crypto";
38110
39013
  import { hostname as hostname5 } from "os";
@@ -38113,6 +39016,10 @@ import { hostname as hostname5 } from "os";
38113
39016
  var CORRELATION_ID = EventMetadata.shape.correlationId;
38114
39017
  var TRACE_ID = EventMetadata.shape.traceId;
38115
39018
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
39019
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
39020
+
39021
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
39022
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
38116
39023
 
38117
39024
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
38118
39025
  import { spawn } from "child_process";
@@ -38120,14 +39027,14 @@ import { fileURLToPath as fileURLToPath2 } from "url";
38120
39027
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
38121
39028
 
38122
39029
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
38123
- import { readFileSync as readFileSync17 } from "fs";
39030
+ import { readFileSync as readFileSync18 } from "fs";
38124
39031
  var manifestBuildCache = /* @__PURE__ */ new Map();
38125
39032
  function readManifestBuild(manifestUrl, packageName) {
38126
39033
  const key = manifestUrl.href;
38127
39034
  if (!manifestBuildCache.has(key)) {
38128
39035
  let build;
38129
39036
  try {
38130
- const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
39037
+ const manifest = JSON.parse(readFileSync18(manifestUrl, "utf8"));
38131
39038
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
38132
39039
  } catch {
38133
39040
  build = void 0;
@@ -38154,7 +39061,7 @@ function createPluginBlock(build, policyStore) {
38154
39061
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38155
39062
  import { randomUUID as randomUUID16 } from "crypto";
38156
39063
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38157
- import { join as join26 } from "path";
39064
+ import { join as join29 } from "path";
38158
39065
 
38159
39066
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38160
39067
  import { rename as rename2 } from "fs/promises";
@@ -38178,7 +39085,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38178
39085
 
38179
39086
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38180
39087
  function createPolicyStore(dir = dataDir()) {
38181
- const file2 = join26(dir, "policy-cache.json");
39088
+ const file2 = join29(dir, "policy-cache.json");
38182
39089
  async function read() {
38183
39090
  try {
38184
39091
  const raw = await readFile2(file2, "utf8");
@@ -38409,11 +39316,11 @@ function readStorePosture(dbPath2) {
38409
39316
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38410
39317
  import { randomUUID as randomUUID17 } from "crypto";
38411
39318
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38412
- import { join as join27 } from "path";
39319
+ import { join as join30 } from "path";
38413
39320
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38414
39321
  function createPostureStore(dir = settingsDir(), legacyDir) {
38415
- const file2 = join27(dir, "posture-state.json");
38416
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
39322
+ const file2 = join30(dir, "posture-state.json");
39323
+ const legacyFile = legacyDir === void 0 ? null : join30(legacyDir, "posture-state.json");
38417
39324
  async function persist(state) {
38418
39325
  await ensureDataDir(dir);
38419
39326
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38481,8 +39388,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38481
39388
  }
38482
39389
 
38483
39390
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38484
- import { readFileSync as readFileSync18 } from "fs";
38485
- import { join as join28 } from "path";
39391
+ import { readFileSync as readFileSync19 } from "fs";
39392
+ import { join as join31 } from "path";
38486
39393
 
38487
39394
  // ../../packages/plugin-runtime/src/attached/status.ts
38488
39395
  var REFUSAL_LINES = {
@@ -38503,6 +39410,14 @@ import { spawn as spawn2 } from "child_process";
38503
39410
  import { fileURLToPath as fileURLToPath3 } from "url";
38504
39411
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
38505
39412
 
39413
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
39414
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39415
+
39416
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
39417
+ import { spawn as spawn3 } from "child_process";
39418
+ import { fileURLToPath as fileURLToPath4 } from "url";
39419
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
39420
+
38506
39421
  // ../../packages/plugin-runtime/src/attached/factory.ts
38507
39422
  import { hostname as hostname6 } from "os";
38508
39423
 
@@ -38953,11 +39868,11 @@ import { randomUUID as randomUUID19 } from "crypto";
38953
39868
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
38954
39869
 
38955
39870
  // src/history/transcripts.ts
38956
- import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync19, readSync as readSync2, statSync as statSync10 } from "fs";
39871
+ import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync20, readSync as readSync2, statSync as statSync10 } from "fs";
38957
39872
  import { homedir as homedir3 } from "os";
38958
- import { join as join29 } from "path";
39873
+ import { join as join32 } from "path";
38959
39874
  function transcriptsDir(home) {
38960
- return join29(home ?? homedir3(), ".codex", "sessions");
39875
+ return join32(home ?? homedir3(), ".codex", "sessions");
38961
39876
  }
38962
39877
  function isRecord(value) {
38963
39878
  return typeof value === "object" && value !== null;
@@ -39196,7 +40111,7 @@ function* walkJsonlFiles(dir, depth = 0) {
39196
40111
  return;
39197
40112
  }
39198
40113
  for (const entry of entries) {
39199
- const full = join29(dir, entry.name);
40114
+ const full = join32(dir, entry.name);
39200
40115
  if (entry.isDirectory()) {
39201
40116
  yield* walkJsonlFiles(full, depth + 1);
39202
40117
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -39208,7 +40123,7 @@ function* iterateFileContents(dir) {
39208
40123
  for (const filePath of walkJsonlFiles(dir)) {
39209
40124
  try {
39210
40125
  statSync10(filePath);
39211
- yield { content: readFileSync19(filePath, "utf8"), filePath };
40126
+ yield { content: readFileSync20(filePath, "utf8"), filePath };
39212
40127
  } catch {
39213
40128
  }
39214
40129
  }
@@ -39329,11 +40244,11 @@ import {
39329
40244
  fstatSync as fstatSync2,
39330
40245
  mkdirSync as mkdirSync5,
39331
40246
  openSync as openSync4,
39332
- readFileSync as readFileSync20,
40247
+ readFileSync as readFileSync21,
39333
40248
  readSync as readSync3,
39334
40249
  writeFileSync as writeFileSync10
39335
40250
  } from "fs";
39336
- import { join as join30 } from "path";
40251
+ import { join as join33 } from "path";
39337
40252
 
39338
40253
  // src/history/usage.ts
39339
40254
  var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";
@@ -39636,7 +40551,7 @@ async function runBackfill(deps) {
39636
40551
  }
39637
40552
  }
39638
40553
  }
39639
- if (process.argv[1] && fileURLToPath4(import.meta.url) === process.argv[1]) {
40554
+ if (process.argv[1] && fileURLToPath5(import.meta.url) === process.argv[1]) {
39640
40555
  const triage = process.argv.includes("--triage");
39641
40556
  const startedAt = Date.now();
39642
40557
  await runBackfill({