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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH = "/";
53
+ var SLASH2 = "/";
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(SLASH).filter(Boolean);
425
+ const slices = path.split(SLASH2).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH) + SLASH,
429
+ slices.join(SLASH2) + SLASH2,
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(SLASH).filter(Boolean);
445
+ slices = path.split(SLASH2).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(SLASH) + SLASH,
452
+ slices.join(SLASH2) + SLASH2,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -500,6 +500,14 @@ var POLICY_CACHE_FILENAME = "policy-cache.json";
500
500
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
501
501
  import { join as join2 } from "path";
502
502
 
503
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
504
+ var DEFERRED_MIGRATION_TAGS = [
505
+ "0031_audit_capture_by_time_index",
506
+ "0032_audit_capture_by_id_index",
507
+ "0033_audit_capture_location_index",
508
+ "0034_findings_read_indexes"
509
+ ];
510
+
503
511
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
504
512
  var SQLITE_MIGRATIONS = [
505
513
  {
@@ -617,6 +625,30 @@ var SQLITE_MIGRATIONS = [
617
625
  {
618
626
  tag: "0028_activity_session_probe_indexes",
619
627
  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"
628
+ },
629
+ {
630
+ tag: "0029_audit_capture_rollup_index",
631
+ 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');"
632
+ },
633
+ {
634
+ tag: "0030_audit_content_expiry",
635
+ 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;"
636
+ },
637
+ {
638
+ tag: "0031_audit_capture_by_time_index",
639
+ 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');"
640
+ },
641
+ {
642
+ tag: "0032_audit_capture_by_id_index",
643
+ 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');"
644
+ },
645
+ {
646
+ tag: "0033_audit_capture_location_index",
647
+ 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');"
648
+ },
649
+ {
650
+ tag: "0034_findings_read_indexes",
651
+ 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`);"
620
652
  }
621
653
  ];
622
654
 
@@ -20664,6 +20696,15 @@ var FindingCategory = external_exports.enum([
20664
20696
  ]).meta({ id: "FindingCategory" });
20665
20697
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20666
20698
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20699
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20700
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20701
+ var FindingDelivery = external_exports.object({
20702
+ state: FindingDeliveryState,
20703
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20704
+ at: external_exports.iso.datetime().optional(),
20705
+ // Only on `not_sent`, and only when a known reason was recorded.
20706
+ reason: SyncFailureReason.optional()
20707
+ }).meta({ id: "FindingDelivery" });
20667
20708
  var ResolutionMethod = external_exports.enum([
20668
20709
  "enforced-in-flight",
20669
20710
  "fixed-at-source",
@@ -20720,7 +20761,10 @@ var FindingInstance = external_exports.object({
20720
20761
  // The session that event belongs to, when it has one — the seam a
20721
20762
  // per-instance "view session" link needs. Absent for events captured
20722
20763
  // outside a session.
20723
- sessionId: external_exports.string().optional()
20764
+ sessionId: external_exports.string().optional(),
20765
+ // The delivery state of the event above (see FindingDelivery). Optional so
20766
+ // readers that do not project it stay valid.
20767
+ delivery: FindingDelivery.optional()
20724
20768
  }).meta({ id: "FindingInstance" });
20725
20769
  var FindingGroup = external_exports.object({
20726
20770
  id: external_exports.string(),
@@ -20737,13 +20781,11 @@ var FindingGroup = external_exports.object({
20737
20781
  latestDetectedAt: external_exports.iso.datetime(),
20738
20782
  instances: external_exports.array(FindingInstance),
20739
20783
  // Derived from instances' statuses with open-dominates precedence (see
20740
- // buildFindingGroups). Undefined only when no instance carries a status.
20784
+ // foldGroupStatus). Undefined only when no instance carries a status.
20741
20785
  status: FindingStatus.optional(),
20742
- // The distinct people across the WHOLE group, not just the `instances`
20743
- // preview — from the store's whole-group aggregate when it supplies one,
20744
- // else folded from the rows (see buildFindingGroups). Undefined when no
20745
- // instance carries a user, or when the store supplied whole-group folds
20746
- // without one.
20786
+ // The distinct people across the WHOLE group, not just the instances
20787
+ // carried here. Undefined when no instance carries a user, or when the
20788
+ // store supplied whole-group folds without one.
20747
20789
  users: external_exports.array(FindingUser).optional()
20748
20790
  }).meta({ id: "FindingGroup" });
20749
20791
  var FindingStats = external_exports.object({
@@ -20772,21 +20814,34 @@ var FindingFacets = external_exports.object({
20772
20814
  // counted under no value.
20773
20815
  status: external_exports.array(FindingFacetItem),
20774
20816
  // Host tool (attributes.tool_name). Present only on the instance-level
20775
- // reads, which can filter by it; the grouped read omits the dimension
20817
+ // reads, which can filter by it; the type-level read omits the dimension
20776
20818
  // because a group spans tools.
20777
- tool: external_exports.array(FindingFacetItem).optional()
20819
+ tool: external_exports.array(FindingFacetItem).optional(),
20820
+ // Delivery states (FindingDeliveryState). Present only on the
20821
+ // instance-level reads, like `tool`.
20822
+ deployment: external_exports.array(FindingFacetItem).optional()
20778
20823
  }).meta({ id: "FindingFacets" });
20779
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20780
- var ListGroupedFindingsQuery = external_exports.object({
20824
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20825
+ id: "FindingTypeSummary"
20826
+ });
20827
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20828
+ var MAX_FINDING_TYPES_LIMIT = 100;
20829
+ var ListFindingTypesQuery = external_exports.object({
20781
20830
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20782
- // FindingAction.
20831
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20832
+ // firing version carries, and this list pages types.
20833
+ //
20834
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20835
+ // definition versions at different severities, so a type kept by this filter
20836
+ // can hold findings that individually do not match — see totals.findings on
20837
+ // ListFindingTypesResponse, which counts them all.
20783
20838
  severity: external_exports.array(Severity).optional(),
20784
20839
  subtype: external_exports.array(external_exports.string()).optional(),
20785
20840
  provider: external_exports.array(FindingProvider).optional(),
20786
20841
  action: external_exports.array(FindingAction).optional(),
20787
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20788
- // individual instances' — so a filtered group's Status column always reads
20789
- // one of the requested values.
20842
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20843
+ // individual findings' — so a filtered row's status always reads one of the
20844
+ // requested values.
20790
20845
  status: external_exports.array(FindingStatus).optional(),
20791
20846
  q: external_exports.string().optional(),
20792
20847
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20796,23 +20851,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20796
20851
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20797
20852
  // means all time — this list has no default window.
20798
20853
  from: external_exports.iso.datetime().optional(),
20799
- // A group or instance id that must appear in the page even when the cursor
20800
- // has already advanced past its sort position. This is what keeps the
20801
- // Findings page's one-shot ?finding= deep link resolving once the list
20802
- // paginates: the target group is appended out of sort order rather than
20803
- // scanning forward for it. Never affects totals, facets or the cursor.
20854
+ // A RULE id that must appear in the page even when the cursor has already
20855
+ // advanced past its sort position. This is what keeps the selected type
20856
+ // visible in the list once it paginates: the target is appended out of sort
20857
+ // order rather than scanned forward for. Never affects totals, facets or the
20858
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20859
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20860
+ // and so is not bounded by what any page happens to hold.
20804
20861
  includeId: external_exports.string().optional(),
20805
- groupBy: external_exports.literal("type").optional(),
20806
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20862
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20807
20863
  cursor: external_exports.string().optional()
20808
20864
  });
20809
- var ListGroupedFindingsResponse = external_exports.object({
20865
+ var ListFindingTypesResponse = external_exports.object({
20810
20866
  totals: external_exports.object({
20867
+ // Findings belonging to the matching TYPES — not findings that each match
20868
+ // the filters. The filters here select types, so a type that survives
20869
+ // contributes its whole instanceCount.
20870
+ //
20871
+ // `status` is the one exception, narrowed per finding via
20872
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20873
+ // this can exceed what the instance read reports for the same filters: a
20874
+ // rule whose severity moved between versions is kept on its newest and
20875
+ // still counts its older findings. Narrowing the other three needs
20876
+ // per-dimension counts the aggregate does not carry today.
20811
20877
  findings: external_exports.number().int().nonnegative(),
20812
- groups: external_exports.number().int().nonnegative()
20878
+ // Counts TYPES, which is the unit this read pages. The instance read's
20879
+ // own totals count findings; the two deliberately answer different
20880
+ // questions and are never summed.
20881
+ types: external_exports.number().int().nonnegative()
20813
20882
  }),
20814
20883
  facets: FindingFacets,
20815
- items: external_exports.array(FindingGroup),
20884
+ items: external_exports.array(FindingTypeSummary),
20816
20885
  nextCursor: external_exports.string().nullable(),
20817
20886
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20818
20887
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20820,7 +20889,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20820
20889
  // every firing, so the two numbers legitimately differ — this map lets a
20821
20890
  // session-scoped view show both.
20822
20891
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20823
- }).meta({ id: "ListGroupedFindingsResponse" });
20892
+ }).meta({ id: "ListFindingTypesResponse" });
20824
20893
  var ApplyFindingActionRequest = external_exports.object({
20825
20894
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20826
20895
  // it, so it is excluded from the request contract. The mapping helper
@@ -20850,16 +20919,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20850
20919
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20851
20920
  var ListFindingInstancesQuery = external_exports.object({
20852
20921
  severity: external_exports.array(Severity).optional(),
20853
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20922
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20923
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20854
20924
  subtype: external_exports.array(external_exports.string()).optional(),
20855
20925
  provider: external_exports.array(FindingProvider).optional(),
20856
20926
  action: external_exports.array(FindingAction).optional(),
20857
20927
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20858
- // the grouped query's group-level fold.
20928
+ // the types query's type-level fold.
20859
20929
  status: external_exports.array(FindingStatus).optional(),
20860
20930
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20861
20931
  // where the free-text `q` can only match the rendered "via Bash" label.
20862
20932
  tool: external_exports.array(external_exports.string()).optional(),
20933
+ // The delivery state of each finding's event (see FindingDelivery).
20934
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20863
20935
  // Exact repository / file-path matches, for the drill-down out of the
20864
20936
  // locations view. A row whose event carries no repo/file matches neither.
20865
20937
  repo: external_exports.string().optional(),
@@ -20872,37 +20944,51 @@ var ListFindingInstancesQuery = external_exports.object({
20872
20944
  });
20873
20945
  var ListFindingInstancesResponse = external_exports.object({
20874
20946
  // Instances matching the filters across the whole scope, not just this
20875
- // page — cursor-independent, like the grouped list's totals.
20947
+ // page — cursor-independent, like the types list's totals.
20876
20948
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20877
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20949
+ // Counts in INSTANCES here, where the types response counts types. Each
20878
20950
  // dimension still excludes its own filter.
20879
20951
  facets: FindingFacets,
20880
20952
  items: external_exports.array(FindingInstanceDetail),
20881
20953
  nextCursor: external_exports.string().nullable()
20882
20954
  }).meta({ id: "ListFindingInstancesResponse" });
20883
- var FindingLocationFile = external_exports.object({
20884
- // Empty when the instances carried no file path (a prompt or a tool call
20885
- // with no file attribution).
20886
- file: external_exports.string(),
20887
- instanceCount: external_exports.number().int().nonnegative(),
20888
- maxSeverity: Severity,
20889
- latestDetectedAt: external_exports.iso.datetime(),
20890
- // Folded from the instances' derived statuses with the same
20891
- // open-dominates precedence a group uses.
20892
- status: FindingStatus.optional(),
20893
- // Distinct rules seen at this location, capped — the row shows them as
20894
- // chips, and the count is what conveys scale.
20895
- ruleIds: external_exports.array(external_exports.string())
20896
- }).meta({ id: "FindingLocationFile" });
20897
- var FindingLocationRepo = external_exports.object({
20955
+ var ListFindingInstancesPage = external_exports.object({
20956
+ items: external_exports.array(FindingInstanceDetail),
20957
+ nextCursor: external_exports.string().nullable()
20958
+ }).meta({ id: "ListFindingInstancesPage" });
20959
+ var FindingLocationSummary = external_exports.object({
20960
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20961
+ // because a location's identity is two values and a URL param carries one:
20962
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20963
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20964
+ // client's page dedupe — never decoded, and never a sort key.
20965
+ id: external_exports.string(),
20898
20966
  /** Empty when the instances carried no repo attribute. */
20899
20967
  repo: external_exports.string(),
20968
+ // Empty when the instances carried no file path (a prompt, or a tool call
20969
+ // with no file attribution). Both halves empty is a real location — usually
20970
+ // the largest one in a store — and is selectable like any other.
20971
+ file: external_exports.string(),
20900
20972
  instanceCount: external_exports.number().int().nonnegative(),
20973
+ // The WORST severity present, not the first row's. It is this list's primary
20974
+ // sort key, so it is also what explains why a row is where it is, and it is
20975
+ // how a reader decides what to open without opening everything.
20901
20976
  maxSeverity: Severity,
20902
20977
  latestDetectedAt: external_exports.iso.datetime(),
20978
+ // Folded from the instances' derived statuses with the same open-dominates
20979
+ // precedence a group uses, so it answers "is anything left to do here" and
20980
+ // not much more: a location holding 1 open among 40 resolved reads like one
20981
+ // holding 40 open. That loss is accepted — the panel beside this list
20982
+ // carries each finding's own status, and instanceCount sits next to the
20983
+ // badge.
20903
20984
  status: FindingStatus.optional(),
20904
- files: external_exports.array(FindingLocationFile)
20905
- }).meta({ id: "FindingLocationRepo" });
20985
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20986
+ // tally rather than a sample and a row can say how many there are. Bounded
20987
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20988
+ ruleIds: external_exports.array(external_exports.string())
20989
+ }).meta({ id: "FindingLocationSummary" });
20990
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20991
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20906
20992
  var ListFindingLocationsQuery = external_exports.object({
20907
20993
  severity: external_exports.array(Severity).optional(),
20908
20994
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20912,21 +20998,47 @@ var ListFindingLocationsQuery = external_exports.object({
20912
20998
  // instances that match, and folds its status from those.
20913
20999
  status: external_exports.array(FindingStatus).optional(),
20914
21000
  tool: external_exports.array(external_exports.string()).optional(),
21001
+ // The delivery state of each finding's event (see FindingDelivery).
21002
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20915
21003
  q: external_exports.string().optional(),
20916
21004
  sessionId: external_exports.string().optional(),
20917
21005
  from: external_exports.iso.datetime().optional(),
20918
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21006
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21007
+ // even when the cursor has already advanced past its sort position — the
21008
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21009
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21010
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21011
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21012
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21013
+ includeId: external_exports.string().optional(),
21014
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21015
+ cursor: external_exports.string().optional()
20919
21016
  });
20920
21017
  var ListFindingLocationsResponse = external_exports.object({
20921
21018
  totals: external_exports.object({
21019
+ // Findings matching the filters across the whole scope. Unlike the types
21020
+ // read's same-named field this needs no caveat: the filters here narrow
21021
+ // per finding, so this is the sum of every row's instanceCount.
20922
21022
  findings: external_exports.number().int().nonnegative(),
20923
- repos: external_exports.number().int().nonnegative(),
20924
- files: external_exports.number().int().nonnegative()
21023
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21024
+ // states. The facets beside it count FINDINGS (see below); a surface
21025
+ // showing both says which is which.
21026
+ locations: external_exports.number().int().nonnegative()
20925
21027
  }),
20926
- /** Sorted by max severity, then most recent. */
20927
- items: external_exports.array(FindingLocationRepo),
20928
- /** Whether `limit` truncated the repo list. */
20929
- hasMore: external_exports.boolean()
21028
+ // Counts in FINDINGS, where the types response counts types, each dimension
21029
+ // still excluding its own filter. Deliberately not locations: counting those
21030
+ // needs a set of location keys per dimension per value — memory tracking the
21031
+ // store times the vocabulary, in a read whose scan promises flat memory —
21032
+ // and the cheap per-location version is not an approximation but WRONG. A
21033
+ // location holding {claudecode, block} and {codex, warn} would survive
21034
+ // provider=claudecode AND action=warn, under which no single finding
21035
+ // matches, so the facet would contradict the instanceCount this whole view
21036
+ // rests on. Findings also keep the toolbar in the same unit as the page
21037
+ // tally and the panel it sits above.
21038
+ facets: FindingFacets,
21039
+ /** Sorted by max severity, then most recent, then (repo, file). */
21040
+ items: external_exports.array(FindingLocationSummary),
21041
+ nextCursor: external_exports.string().nullable()
20930
21042
  }).meta({ id: "ListFindingLocationsResponse" });
20931
21043
 
20932
21044
  // ../../packages/schema/src/zod/meta.ts
@@ -21090,6 +21202,10 @@ var CaptureAttributes = external_exports.object({
21090
21202
  // to 'allow' — the enforcement audit trail's link back to the grant that
21091
21203
  // authorized the bypass.
21092
21204
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21205
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21206
+ // join back to the `llm_call` leaf for the same assistant turn.
21207
+ message_id: external_exports.string().optional(),
21208
+ conversation_id: external_exports.string().optional(),
21093
21209
  // Whole milliseconds this capture's inspection blocked its caller — the
21094
21210
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21095
21211
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21098,7 +21214,19 @@ var CaptureAttributes = external_exports.object({
21098
21214
  // inline json_extract and is not itself an optimization.
21099
21215
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21100
21216
  // before the measurement shipped — never present as a placeholder 0.
21101
- inspection_ms: external_exports.number().int().nonnegative().optional()
21217
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21218
+ // What a `redact` this capture could not carry out became instead (see
21219
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21220
+ // degrade actually happened, so absence is the ordinary case rather than a
21221
+ // reader having to distinguish it from a zero.
21222
+ //
21223
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21224
+ // so on a multi-finding row this does not say which finding degraded, and
21225
+ // its presence does not mean the fallback decided the capture's action. A
21226
+ // capture denied by another finding's own Block policy carries `block`
21227
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21228
+ // repeated rather than referenced because a store reader opens this file.
21229
+ redact_degraded_to: ActionTaken.optional()
21102
21230
  }).catchall(external_exports.unknown());
21103
21231
  var ToolCallInspection = external_exports.object({
21104
21232
  ruleId: external_exports.string().min(1),
@@ -21297,7 +21425,17 @@ var AuditEvent = external_exports.object({
21297
21425
  /** `share` to a first-party/internal destination. */
21298
21426
  internal: external_exports.boolean(),
21299
21427
  /** Event needs review (e.g. unverified egress). */
21300
- flagged: external_exports.boolean()
21428
+ flagged: external_exports.boolean(),
21429
+ /**
21430
+ * The body this event's `title` is drawn from was cleared by local body
21431
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21432
+ *
21433
+ * A separate flag rather than a sentinel written into `title`: the title is
21434
+ * rendered text, and a store-layer module that invented display copy for it
21435
+ * would be choosing words the view is supposed to choose. Additive and
21436
+ * defaulted, so an older producer still validates.
21437
+ */
21438
+ bodyExpired: external_exports.boolean().default(false)
21301
21439
  }).meta({ id: "ActivityAuditEvent" });
21302
21440
  var ActivitySessionSummary = external_exports.object({
21303
21441
  id: external_exports.string(),
@@ -22094,6 +22232,14 @@ var ControlPlaneErrorBody = external_exports.object({
22094
22232
  message: external_exports.string().optional()
22095
22233
  }).optional()
22096
22234
  });
22235
+ var RemoteFailureKind = external_exports.enum([
22236
+ "unauthorized",
22237
+ "forbidden",
22238
+ "route-absent",
22239
+ "invalid-request",
22240
+ "rejected",
22241
+ "unreachable"
22242
+ ]);
22097
22243
  var AttachDeviceRequest = external_exports.object({
22098
22244
  // This machine's own continuity id, so re-attaching ROTATES the credential
22099
22245
  // on one machine record instead of producing a second one. Client-minted
@@ -22629,6 +22775,12 @@ var EventMetadata = external_exports.object({
22629
22775
  // to 'allow' — the enforcement audit trail's link back to the grant that
22630
22776
  // authorized the bypass. Absent on captures where no exception applied.
22631
22777
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22778
+ // The assistant message this capture belongs to, and the conversation it sits
22779
+ // in — set by the browser extension's network capture so a stored `response`
22780
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22781
+ // on every other capture path, which has no such id.
22782
+ messageId: external_exports.string().optional(),
22783
+ conversationId: external_exports.string().optional(),
22632
22784
  // How long THIS capture's inspection blocked its caller, in whole
22633
22785
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22634
22786
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22641,7 +22793,37 @@ var EventMetadata = external_exports.object({
22641
22793
  // Absent is also what every pre-measurement client writes, and what a
22642
22794
  // clock failure degrades to — a reader must treat absence as "not measured"
22643
22795
  // and never as a zero, which would read as "inspection is free".
22644
- inspectionMs: external_exports.number().int().nonnegative().optional()
22796
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22797
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22798
+ // workspace's `redactFallback`, applied because the field could not be
22799
+ // masked in place (a shell command, a URL, or any argument on a host whose
22800
+ // hook contract offers no rewrite channel).
22801
+ //
22802
+ // It exists because the action alone cannot say why. A finding recorded as
22803
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22804
+ // assigned Redact on a field that could not take one — and those are
22805
+ // different facts about the same row: the first is a policy the user chose,
22806
+ // the second is a masking the host could not perform. Absent means no
22807
+ // degrade happened, which is every ordinary capture.
22808
+ //
22809
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22810
+ // is the CAPTURE while `actionTaken` is per FINDING:
22811
+ //
22812
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22813
+ // `redact` alongside a finding ASSIGNED the same action stores both
22814
+ // identically and one reason for the pair; attributing it to both
22815
+ // describes the assigned one wrongly, and to neither loses the degrade.
22816
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22817
+ // became, not the reason the capture ended as it did — a capture denied
22818
+ // by some other finding's own Block policy still carries `block` here,
22819
+ // and clearing the workspace's fallback would not have let it through.
22820
+ // Gate on the value against what a fallback can produce; never read the
22821
+ // field's presence as "this was the fallback's doing".
22822
+ //
22823
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22824
+ // Closing either means moving the reason onto the finding row, which
22825
+ // already carries its own action.
22826
+ redactDegradedTo: ActionTaken.optional()
22645
22827
  }).meta({ id: "EventMetadata" });
22646
22828
  var Event = external_exports.object({
22647
22829
  id: external_exports.guid(),
@@ -22751,7 +22933,32 @@ var RotateKeyInput = external_exports.object({
22751
22933
  confirmation: external_exports.string()
22752
22934
  });
22753
22935
 
22936
+ // ../../packages/schema/src/zod/finding-delivery.ts
22937
+ var KNOWN_REASONS = SyncFailureReason.options;
22938
+ function knownReason(value) {
22939
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22940
+ }
22941
+ function deriveFindingDelivery(row) {
22942
+ if (row.kind === "code_change") return { state: "local_scan" };
22943
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22944
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22945
+ }
22946
+ if (row.syncedAt !== null) {
22947
+ const reason = knownReason(row.syncFailure);
22948
+ return {
22949
+ state: "not_sent",
22950
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22951
+ ...reason === void 0 ? {} : { reason }
22952
+ };
22953
+ }
22954
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22955
+ return { state: "never_offered" };
22956
+ }
22957
+
22754
22958
  // ../../packages/schema/src/zod/findings-group-build.ts
22959
+ function lookupOwn(map2, key) {
22960
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22961
+ }
22755
22962
  function toApiAction(dbVal) {
22756
22963
  const map2 = {
22757
22964
  log: "monitored",
@@ -22760,7 +22967,7 @@ function toApiAction(dbVal) {
22760
22967
  warn: "warned",
22761
22968
  allow: "allowed"
22762
22969
  };
22763
- return map2[dbVal] ?? "allowed";
22970
+ return lookupOwn(map2, dbVal) ?? "allowed";
22764
22971
  }
22765
22972
  function toApiCategory(dbVal) {
22766
22973
  if (dbVal === "code_context") return "source_code";
@@ -22768,13 +22975,18 @@ function toApiCategory(dbVal) {
22768
22975
  return parsed.success ? parsed.data : "custom";
22769
22976
  }
22770
22977
  function toApiProvider(sourceTool) {
22771
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22978
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22772
22979
  }
22773
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22980
+ var FINDING_STATUS_PRECEDENCE = [
22981
+ "open",
22982
+ "handled",
22983
+ "dismissed",
22984
+ "resolved"
22985
+ ];
22774
22986
  function foldGroupStatus(instanceStatuses) {
22775
22987
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22776
22988
  if (statuses.size === 0) return void 0;
22777
- for (const candidate of STATUS_PRECEDENCE) {
22989
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22778
22990
  if (statuses.has(candidate)) return candidate;
22779
22991
  }
22780
22992
  return void 0;
@@ -22787,139 +22999,62 @@ function deriveFindingStatus(row) {
22787
22999
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22788
23000
  return "open";
22789
23001
  }
22790
- function distinctUsers(instances) {
22791
- const seen = /* @__PURE__ */ new Set();
22792
- const users = [];
22793
- for (const i of instances) {
22794
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22795
- seen.add(i.user.id);
22796
- users.push(i.user);
22797
- }
22798
- return users;
22799
- }
22800
23002
  function sortUsers(users) {
22801
23003
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22802
23004
  }
22803
- function buildFindingGroups(rows, opts = {}) {
22804
- const overrides = opts.overrides;
23005
+ function buildFindingTypes(aggregates, opts = {}) {
22805
23006
  const packNames = opts.packNames;
22806
- const aggregates = opts.aggregates;
22807
- const byRuleId = /* @__PURE__ */ new Map();
22808
- for (const row of rows) {
22809
- const existing = byRuleId.get(row.ruleId);
22810
- if (existing) existing.push(row);
22811
- else byRuleId.set(row.ruleId, [row]);
22812
- }
22813
- const groups = [];
22814
- for (const [ruleId, ruleRows] of byRuleId) {
22815
- const instances = ruleRows.map((r) => {
22816
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22817
- return {
22818
- id: r.id,
22819
- provider: toApiProvider(r.sourceTool),
22820
- repo: r.repo,
22821
- file: r.file,
22822
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22823
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22824
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22825
- ...r.user === void 0 ? {} : { user: r.user },
22826
- action: toApiAction(effectiveDbAction),
22827
- detectedAt: r.occurredAt,
22828
- confidence: r.confidence,
22829
- status: r.status
22830
- };
22831
- });
22832
- const agg = aggregates?.get(ruleId);
22833
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22834
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22835
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22836
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22837
- );
22838
- const seenProviders = /* @__PURE__ */ new Set();
22839
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22840
- if (seenProviders.has(p)) return false;
22841
- seenProviders.add(p);
22842
- return true;
22843
- });
22844
- const actionSet = new Set(
22845
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22846
- );
23007
+ const types = [];
23008
+ for (const [ruleId, agg] of aggregates) {
23009
+ const users = sortUsers(agg.users ?? []);
23010
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23011
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22847
23012
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22848
- const severity = ruleRows[0]?.severity ?? "low";
22849
- const detection = {
22850
- id: ruleId,
22851
- name: packNames?.get(ruleId) ?? null
22852
- };
22853
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22854
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22855
- const match = {
22856
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22857
- contextPrefix: ""
22858
- // empty (pending privacy review)
22859
- };
22860
- const status = foldGroupStatus(
22861
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22862
- );
22863
- const group = {
23013
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23014
+ const type = {
22864
23015
  id: ruleId,
22865
23016
  category: apiCategory,
22866
23017
  subtype: ruleId,
22867
23018
  // human label comes with pack metadata later
22868
- severity,
22869
- match,
22870
- detection,
22871
- policy,
22872
- instanceCount: agg?.instanceCount ?? instances.length,
23019
+ severity: agg.severity ?? "low",
23020
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23021
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23022
+ instanceCount: agg.instanceCount,
22873
23023
  providers,
22874
23024
  aggregateAction,
22875
- latestDetectedAt,
22876
- instances,
22877
- status,
23025
+ latestDetectedAt: agg.latestDetectedAt,
23026
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22878
23027
  ...users.length > 0 ? { users } : {}
22879
23028
  };
22880
- if (agg) {
22881
- actionsCache.set(group, [...actionSet]);
22882
- if (agg.searchText !== void 0) {
22883
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22884
- }
23029
+ actionsCache.set(type, [...actionSet]);
23030
+ if (agg.searchText !== void 0) {
23031
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22885
23032
  }
22886
- groups.push(group);
23033
+ types.push(type);
22887
23034
  }
22888
- return groups;
23035
+ return types;
22889
23036
  }
22890
23037
  var haystackCache = /* @__PURE__ */ new WeakMap();
22891
- function buildHaystack(g, extra) {
23038
+ function buildHaystack(t, extra) {
22892
23039
  return [
22893
- g.subtype,
22894
- g.category,
22895
- g.match.maskedValue,
22896
- g.policy.name,
22897
- g.id,
22898
- ...g.instances.map((i) => i.repo),
22899
- ...g.instances.map((i) => i.file),
22900
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22901
- ...g.instances.map((i) => i.id),
22902
- // The people: the whole group's list when the store folded one, plus the
22903
- // preview's own — the two overlap, and a haystack does not mind.
22904
- ...(g.users ?? []).map((u) => u.name),
22905
- ...g.instances.map((i) => i.user?.name ?? ""),
23040
+ t.subtype,
23041
+ t.category,
23042
+ t.policy.name,
23043
+ t.id,
23044
+ ...(t.users ?? []).map((u) => u.name),
22906
23045
  ...extra === void 0 ? [] : [extra]
22907
23046
  ].join(" ").toLowerCase();
22908
23047
  }
22909
- function groupHaystack(g) {
22910
- const cached2 = haystackCache.get(g);
23048
+ function typeHaystack(t) {
23049
+ const cached2 = haystackCache.get(t);
22911
23050
  if (cached2 !== void 0) return cached2;
22912
- const haystack = buildHaystack(g);
22913
- haystackCache.set(g, haystack);
23051
+ const haystack = buildHaystack(t);
23052
+ haystackCache.set(t, haystack);
22914
23053
  return haystack;
22915
23054
  }
22916
23055
  var actionsCache = /* @__PURE__ */ new WeakMap();
22917
- function groupActions(g) {
22918
- const cached2 = actionsCache.get(g);
22919
- if (cached2 !== void 0) return cached2;
22920
- const actions = [...new Set(g.instances.map((i) => i.action))];
22921
- actionsCache.set(g, actions);
22922
- return actions;
23056
+ function typeActions(t) {
23057
+ return actionsCache.get(t) ?? [];
22923
23058
  }
22924
23059
  function countInstancesByStatus(statusInputs, statuses) {
22925
23060
  const statusSet = new Set(statuses);
@@ -22930,8 +23065,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22930
23065
  }
22931
23066
  return sum;
22932
23067
  }
22933
- function applyFindingFilters(groups, opts) {
22934
- let filtered = groups;
23068
+ function applyFindingFilters(types, opts) {
23069
+ let filtered = types;
22935
23070
  if (opts.severity && opts.severity.length > 0) {
22936
23071
  const sevSet = new Set(opts.severity);
22937
23072
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22942,7 +23077,7 @@ function applyFindingFilters(groups, opts) {
22942
23077
  }
22943
23078
  if (opts.actions && opts.actions.length > 0) {
22944
23079
  const actionSet = new Set(opts.actions);
22945
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23080
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22946
23081
  }
22947
23082
  if (opts.subtype && opts.subtype.length > 0) {
22948
23083
  const subtypeSet = new Set(opts.subtype);
@@ -22954,26 +23089,31 @@ function applyFindingFilters(groups, opts) {
22954
23089
  }
22955
23090
  if (opts.q) {
22956
23091
  const q = opts.q.toLowerCase();
22957
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23092
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22958
23093
  }
22959
23094
  return filtered;
22960
23095
  }
22961
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22962
- var SEVERITY_RANK = SEVERITY_ORDER;
23096
+ function rankByOrder(members2) {
23097
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23098
+ }
23099
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23100
+ function severityRank(severity) {
23101
+ return lookupOwn(SEVERITY_RANK, severity);
23102
+ }
22963
23103
  function compareFindingGroupOrder(a, b) {
22964
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22965
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23104
+ const rankA = severityRank(a.severity) ?? -1;
23105
+ const rankB = severityRank(b.severity) ?? -1;
22966
23106
  const severityDiff = rankA - rankB;
22967
23107
  if (severityDiff !== 0) return severityDiff;
22968
23108
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22969
23109
  if (recencyDiff !== 0) return recencyDiff;
22970
23110
  return a.id.localeCompare(b.id);
22971
23111
  }
22972
- function sortFindingGroups(groups) {
22973
- return [...groups].sort(compareFindingGroupOrder);
23112
+ function sortFindingTypes(types) {
23113
+ return [...types].sort(compareFindingGroupOrder);
22974
23114
  }
22975
- function computeFindingFacets(allGroups, opts) {
22976
- const forSeverity = applyFindingFilters(allGroups, {
23115
+ function computeFindingFacets(allTypes, opts) {
23116
+ const forSeverity = applyFindingFilters(allTypes, {
22977
23117
  providers: opts.providers,
22978
23118
  actions: opts.actions,
22979
23119
  statuses: opts.statuses,
@@ -22984,7 +23124,7 @@ function computeFindingFacets(allGroups, opts) {
22984
23124
  for (const g of forSeverity) {
22985
23125
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22986
23126
  }
22987
- const forProvider = applyFindingFilters(allGroups, {
23127
+ const forProvider = applyFindingFilters(allTypes, {
22988
23128
  actions: opts.actions,
22989
23129
  statuses: opts.statuses,
22990
23130
  q: opts.q,
@@ -22995,7 +23135,7 @@ function computeFindingFacets(allGroups, opts) {
22995
23135
  for (const g of forProvider) {
22996
23136
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
22997
23137
  }
22998
- const forAction = applyFindingFilters(allGroups, {
23138
+ const forAction = applyFindingFilters(allTypes, {
22999
23139
  providers: opts.providers,
23000
23140
  statuses: opts.statuses,
23001
23141
  q: opts.q,
@@ -23004,9 +23144,9 @@ function computeFindingFacets(allGroups, opts) {
23004
23144
  });
23005
23145
  const actionMap = /* @__PURE__ */ new Map();
23006
23146
  for (const g of forAction) {
23007
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23147
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23008
23148
  }
23009
- const forSubtype = applyFindingFilters(allGroups, {
23149
+ const forSubtype = applyFindingFilters(allTypes, {
23010
23150
  providers: opts.providers,
23011
23151
  actions: opts.actions,
23012
23152
  statuses: opts.statuses,
@@ -23015,7 +23155,7 @@ function computeFindingFacets(allGroups, opts) {
23015
23155
  });
23016
23156
  const subtypeMap = /* @__PURE__ */ new Map();
23017
23157
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23018
- const forStatus = applyFindingFilters(allGroups, {
23158
+ const forStatus = applyFindingFilters(allTypes, {
23019
23159
  providers: opts.providers,
23020
23160
  actions: opts.actions,
23021
23161
  q: opts.q,
@@ -23037,6 +23177,20 @@ function computeFindingFacets(allGroups, opts) {
23037
23177
  }
23038
23178
 
23039
23179
  // ../../packages/schema/src/zod/findings-flat-build.ts
23180
+ function compareCodePoints(a, b) {
23181
+ const aIter = a[Symbol.iterator]();
23182
+ const bIter = b[Symbol.iterator]();
23183
+ for (; ; ) {
23184
+ const aNext = aIter.next();
23185
+ const bNext = bIter.next();
23186
+ if (aNext.done && bNext.done) return 0;
23187
+ if (aNext.done) return -1;
23188
+ if (bNext.done) return 1;
23189
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23190
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23191
+ if (aPoint !== bPoint) return aPoint - bPoint;
23192
+ }
23193
+ }
23040
23194
  function rowHaystack(row) {
23041
23195
  return [
23042
23196
  row.ruleId,
@@ -23061,12 +23215,24 @@ function matchesDimension(row, opts, dimension) {
23061
23215
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23062
23216
  case "statuses":
23063
23217
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23218
+ case "deliveries":
23219
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23064
23220
  case "tools":
23065
23221
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23222
+ // An EMPTY value is a real filter here, not an absent one. The location
23223
+ // list buckets a finding whose event recorded no repo — or no file — under
23224
+ // the empty string, and selecting that bucket has to narrow the panel to
23225
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23226
+ // row omits the key, which every call site already does.
23227
+ //
23228
+ // Reading '' as unset is what this replaced, and it failed in the one place
23229
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23230
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23231
+ // — a row reading 3 findings beside a panel listing every finding there is.
23066
23232
  case "repo":
23067
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23233
+ return opts.repo === void 0 || row.repo === opts.repo;
23068
23234
  case "file":
23069
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23235
+ return opts.file === void 0 || row.file === opts.file;
23070
23236
  case "q":
23071
23237
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23072
23238
  }
@@ -23077,6 +23243,7 @@ var DIMENSIONS = [
23077
23243
  "providers",
23078
23244
  "actions",
23079
23245
  "statuses",
23246
+ "deliveries",
23080
23247
  "tools",
23081
23248
  "repo",
23082
23249
  "file",
@@ -23090,10 +23257,19 @@ function matchesInstanceFilters(row, opts, except) {
23090
23257
  return true;
23091
23258
  }
23092
23259
  function toItems(counts) {
23093
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23260
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23261
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23262
+ // NFD spelling of the same text) as equal, so a count tie between
23263
+ // them would otherwise be ordered by whichever the Map iteration
23264
+ // produced. compareCodePoints breaks that tie deterministically, which
23265
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23266
+ // which it need not: foldFacetTuples runs this same sort over grouped
23267
+ // tuples, so both paths order facets identically by construction.
23268
+ compareCodePoints(a.value, b.value)
23269
+ );
23094
23270
  }
23095
- function bump(counts, value) {
23096
- counts.set(value, (counts.get(value) ?? 0) + 1);
23271
+ function bump(counts, value, by = 1) {
23272
+ counts.set(value, (counts.get(value) ?? 0) + by);
23097
23273
  }
23098
23274
  function createInstanceFacetAccumulator(opts) {
23099
23275
  const severity = /* @__PURE__ */ new Map();
@@ -23102,6 +23278,7 @@ function createInstanceFacetAccumulator(opts) {
23102
23278
  const action = /* @__PURE__ */ new Map();
23103
23279
  const status = /* @__PURE__ */ new Map();
23104
23280
  const tool = /* @__PURE__ */ new Map();
23281
+ const deployment = /* @__PURE__ */ new Map();
23105
23282
  return {
23106
23283
  add(row) {
23107
23284
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23116,6 +23293,9 @@ function createInstanceFacetAccumulator(opts) {
23116
23293
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23117
23294
  bump(tool, row.toolName);
23118
23295
  }
23296
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23297
+ bump(deployment, row.delivery.state);
23298
+ }
23119
23299
  },
23120
23300
  facets: () => ({
23121
23301
  severity: toItems(severity),
@@ -23123,7 +23303,8 @@ function createInstanceFacetAccumulator(opts) {
23123
23303
  provider: toItems(provider),
23124
23304
  action: toItems(action),
23125
23305
  status: toItems(status),
23126
- tool: toItems(tool)
23306
+ tool: toItems(tool),
23307
+ deployment: toItems(deployment)
23127
23308
  })
23128
23309
  };
23129
23310
  }
@@ -23137,6 +23318,7 @@ function toInstanceDetail(row) {
23137
23318
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23138
23319
  eventId: row.eventId,
23139
23320
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23321
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23140
23322
  ...row.user === void 0 ? {} : { user: row.user },
23141
23323
  action: toApiAction(row.actionTaken),
23142
23324
  detectedAt: row.occurredAt,
@@ -23151,12 +23333,6 @@ function toInstanceDetail(row) {
23151
23333
  policy: { id: `category:${category}`, name: category }
23152
23334
  };
23153
23335
  }
23154
- var SEVERITY_ORDER2 = {
23155
- critical: 0,
23156
- high: 1,
23157
- medium: 2,
23158
- low: 3
23159
- };
23160
23336
  function newLocationAccumulator() {
23161
23337
  return {
23162
23338
  instanceCount: 0,
@@ -23171,7 +23347,7 @@ function newLocationAccumulator() {
23171
23347
  }
23172
23348
  function addToLocation(acc, row) {
23173
23349
  acc.instanceCount += 1;
23174
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23350
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23175
23351
  if (rank < acc.maxSeverityRank) {
23176
23352
  acc.maxSeverityRank = rank;
23177
23353
  acc.maxSeverity = row.severity;
@@ -23180,6 +23356,23 @@ function addToLocation(acc, row) {
23180
23356
  acc.statuses.push(row.status);
23181
23357
  acc.ruleIds.add(row.ruleId);
23182
23358
  }
23359
+ function compareLocationOrder(a, b) {
23360
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23361
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23362
+ if (rankA !== rankB) return rankA - rankB;
23363
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23364
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23365
+ }
23366
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23367
+ if (repoDiff !== 0) return repoDiff;
23368
+ return compareCodePoints(a.file, b.file);
23369
+ }
23370
+ function encodeLocationId(repo, file2) {
23371
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23372
+ }
23373
+ function encodePart(value) {
23374
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23375
+ }
23183
23376
 
23184
23377
  // ../../packages/schema/src/zod/installed-pack.ts
23185
23378
  var InstalledPack = external_exports.object({
@@ -23247,6 +23440,11 @@ var Policy = external_exports.object({
23247
23440
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23248
23441
  provenance: PolicyProvenance.optional()
23249
23442
  }).meta({ id: "Policy" });
23443
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23444
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23445
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23446
+ id: "RedactFallback"
23447
+ });
23250
23448
  var PolicyBundle = external_exports.object({
23251
23449
  version: external_exports.string(),
23252
23450
  policies: external_exports.array(Policy),
@@ -23294,6 +23492,16 @@ var PolicyBundle = external_exports.object({
23294
23492
  // control plane), so no name resolution stands between the decision and the
23295
23493
  // comparison.
23296
23494
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23495
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23496
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23497
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23498
+ // a control plane can tighten a machine and never loosen one — the same
23499
+ // direction `mergeRaiseOnly` enforces for policies.
23500
+ //
23501
+ // Optional so an older backend, and an older on-disk cache, still parses;
23502
+ // absent leaves the device's own setting in force, which is the behaviour
23503
+ // that predates the field and the safe direction to default.
23504
+ redactFallback: RedactFallback.optional(),
23297
23505
  customKeywords: external_exports.array(external_exports.string()),
23298
23506
  fetchedAt: external_exports.iso.datetime()
23299
23507
  }).meta({ id: "PolicyBundle" });
@@ -23328,11 +23536,6 @@ function severityFloorPosture() {
23328
23536
  for (const c of DetectionCategory.options) out[c] = severityFloorPolicy(c);
23329
23537
  return out;
23330
23538
  }
23331
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23332
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23333
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23334
- id: "RedactFallback"
23335
- });
23336
23539
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23337
23540
  var BUILTIN_POLICY_SPECS = {
23338
23541
  monitor: {
@@ -23628,7 +23831,7 @@ function isVaultConsentValid(consent) {
23628
23831
  }
23629
23832
 
23630
23833
  // ../../packages/schema/src/zod/local.ts
23631
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23834
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23632
23835
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23633
23836
  var RunMode = external_exports.enum(["standalone", "attached"]);
23634
23837
  var ControlPlaneConnection = external_exports.object({
@@ -23651,6 +23854,15 @@ var HistorySyncConsent = external_exports.object({
23651
23854
  payloadVersion: external_exports.number().int().positive(),
23652
23855
  endpoint: external_exports.string()
23653
23856
  });
23857
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23858
+ var BodyRetention = external_exports.object({
23859
+ enabled: external_exports.boolean().default(false),
23860
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23861
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23862
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23863
+ // candidate set that is already bounded by "delivered, or never owed".
23864
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23865
+ }).meta({ id: "BodyRetention" });
23654
23866
  var WorkspaceSettings = external_exports.object({
23655
23867
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23656
23868
  runMode: RunMode.default("standalone"),
@@ -23694,12 +23906,18 @@ var WorkspaceSettings = external_exports.object({
23694
23906
  // covers the current payload and must be re-granted.
23695
23907
  modelJudgeConsent: ModelJudgeConsent.optional(),
23696
23908
  // Records that the user consented to the DEFERRED send — the outbox — along
23697
- // with the payload shape and the endpoint they agreed to. Since payload v2
23698
- // that covers both the pre-attach backlog and undelivered captures (which
23699
- // carry prompt/reply text in `content`); the key name predates the widening.
23700
- // Absent until granted, and a grant for a different endpoint or an older
23701
- // payload no longer counts.
23702
- historySyncConsent: HistorySyncConsent.optional()
23909
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23910
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23911
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23912
+ // both widenings. Absent until granted, and a grant for a different endpoint
23913
+ // or an older payload no longer counts.
23914
+ historySyncConsent: HistorySyncConsent.optional(),
23915
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23916
+ // body never removes the row or its findings.
23917
+ bodyRetention: BodyRetention.default({
23918
+ enabled: false,
23919
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23920
+ })
23703
23921
  });
23704
23922
  function defaultWorkspaceSettings() {
23705
23923
  return WorkspaceSettings.parse({});
@@ -23794,12 +24012,15 @@ function toCaptureAttributes(event) {
23794
24012
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23795
24013
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23796
24014
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24015
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23797
24016
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23798
24017
  // has ever populated either), but every legacy metadata key still rides
23799
24018
  // the bag rather than being silently dropped — CaptureAttributes'
23800
24019
  // `.catchall(z.unknown())` carries the long tail.
23801
24020
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23802
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24021
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24022
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24023
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23803
24024
  };
23804
24025
  }
23805
24026
  function captureDefinitionVersion(finding) {
@@ -23827,10 +24048,22 @@ var ManagedSettingKey = external_exports.enum([
23827
24048
  "vaultInlineReveal",
23828
24049
  "modelJudgeConsent",
23829
24050
  "dataSharesInPlace",
23830
- "redactFallback"
24051
+ "redactFallback",
24052
+ // Pins the toggle and the day count together — see BodyRetention on why the
24053
+ // two are one unit. An administrator mandating a window wants the count
24054
+ // enforced with it, not one a user can widen while the toggle stays on.
24055
+ "bodyRetention"
23831
24056
  ]).meta({ id: "ManagedSettingKey" });
24057
+ function isManagedSettingKey(value) {
24058
+ return ManagedSettingKey.safeParse(value).success;
24059
+ }
23832
24060
  var ManagedSettingsValues = external_exports.object({
23833
24061
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24062
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24063
+ // plain, non-strict objects: a key under either that this build does not know
24064
+ // is stripped and nothing reports it. The unknown-value split in
24065
+ // ManagedSettings below classifies top-level names only, so it stops at
24066
+ // these boundaries.
23834
24067
  controlPlane: external_exports.object({
23835
24068
  endpoint: external_exports.string().min(1),
23836
24069
  label: external_exports.string().min(1).optional()
@@ -23841,7 +24074,8 @@ var ManagedSettingsValues = external_exports.object({
23841
24074
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23842
24075
  modelJudgeConsent: external_exports.boolean().optional(),
23843
24076
  dataSharesInPlace: external_exports.boolean().optional(),
23844
- redactFallback: RedactFallback.optional()
24077
+ redactFallback: RedactFallback.optional(),
24078
+ bodyRetention: BodyRetention.optional()
23845
24079
  }).meta({ id: "ManagedSettingsValues" });
23846
24080
  var ManagedSettings = external_exports.object({
23847
24081
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23849,11 +24083,59 @@ var ManagedSettings = external_exports.object({
23849
24083
  // decision from a bug. Absent renders as a generic "your organization".
23850
24084
  organization: external_exports.string().min(1).optional(),
23851
24085
  // What the administrator pinned.
23852
- values: ManagedSettingsValues.default({}),
24086
+ //
24087
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24088
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24089
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24090
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24091
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24092
+ // exactly the file an administrator is most likely to write while a fleet
24093
+ // is mid-upgrade.
24094
+ //
24095
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24096
+ // file, which is the outcome the lock half already rejected — an older
24097
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24098
+ // value still fails, because the nested schema is re-run over the known
24099
+ // subset and its issues are re-raised on this parse.
24100
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23853
24101
  // Which of those the user may not change. A key here with no matching value
23854
24102
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23855
24103
  // the user may still override. The two are separable on purpose.
23856
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24104
+ //
24105
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24106
+ // build does not know is dropped from the locked set and reported, never a
24107
+ // reason to refuse the file. The same shape reaches an older build whenever
24108
+ // an administrator locks a key a newer build added, and refusing it there
24109
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24110
+ // the fleets most likely to carry a version skew. A name outside the enum
24111
+ // is still never HONOURED: the lockable set stays explicit above.
24112
+ lockedFields: external_exports.array(external_exports.string()).default([])
24113
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24114
+ const known = [];
24115
+ const unknown2 = [];
24116
+ for (const name of lockedFields) {
24117
+ if (isManagedSettingKey(name)) known.push(name);
24118
+ else unknown2.push(name);
24119
+ }
24120
+ const knownValues = /* @__PURE__ */ Object.create(null);
24121
+ const unknownValues = [];
24122
+ for (const [name, value] of Object.entries(values)) {
24123
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24124
+ else unknownValues.push(name);
24125
+ }
24126
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24127
+ if (!pinned.success) {
24128
+ for (const issue2 of pinned.error.issues)
24129
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24130
+ return external_exports.NEVER;
24131
+ }
24132
+ return {
24133
+ ...rest,
24134
+ values: pinned.data,
24135
+ lockedFields: known,
24136
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24137
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24138
+ };
23857
24139
  }).meta({ id: "ManagedSettings" });
23858
24140
  var NO_MANAGED_CONTEXT = { present: false, lockedFields: [] };
23859
24141
 
@@ -23978,7 +24260,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23978
24260
  timestamp: external_exports.iso.date(),
23979
24261
  critical: external_exports.number().int().nonnegative(),
23980
24262
  high: external_exports.number().int().nonnegative(),
23981
- medium: external_exports.number().int().nonnegative()
24263
+ medium: external_exports.number().int().nonnegative(),
24264
+ // Optional and additive, so a producer written against the earlier
24265
+ // three-series contract keeps validating. A consumer plotting it resolves the
24266
+ // absent case itself — the chart point requires a number.
24267
+ low: external_exports.number().int().nonnegative().optional()
23982
24268
  }).meta({ id: "FindingsTimeseriesPoint" });
23983
24269
  var FindingsTimeseriesResponse = external_exports.object({
23984
24270
  range: TimeRange,
@@ -24004,6 +24290,10 @@ var ResolvedFeedItem = external_exports.object({
24004
24290
  findingKey: external_exports.string(),
24005
24291
  ruleId: external_exports.string(),
24006
24292
  severity: Severity,
24293
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24294
+ // identifies the file: a bare path matches the same name in every repo.
24295
+ // Optional and additive; empty when the event carried no repo.
24296
+ repo: external_exports.string().optional(),
24007
24297
  path: external_exports.string(),
24008
24298
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24009
24299
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24109,7 +24399,23 @@ var SaveSettingsInput = external_exports.object({
24109
24399
  modelJudgeConsent: ModelJudgeConsentChoice,
24110
24400
  historySyncConsent: HistorySyncConsentChoice,
24111
24401
  vaultConsent: external_exports.string(),
24112
- vaultInlineReveal: external_exports.string()
24402
+ vaultInlineReveal: external_exports.string(),
24403
+ // Widened to `string` like its neighbours rather than typed as
24404
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24405
+ // the call site, so the domain check receives the type it was written for.
24406
+ //
24407
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24408
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24409
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24410
+ // trade against. The real cost runs the other way and is the part worth
24411
+ // knowing: a value this schema admits and the domain enum then rejects lands
24412
+ // on the action's shared refusal, which names NO field, where a shape
24413
+ // rejection reaches `malformedInput` and names the schema key.
24414
+ redactFallback: external_exports.string(),
24415
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24416
+ // `BodyRetention`'s and the action checks it there, so there is one place
24417
+ // that decides what a legal horizon is rather than two that can drift.
24418
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24113
24419
  });
24114
24420
  var AttachInput = external_exports.object({
24115
24421
  endpoint: external_exports.string(),
@@ -24281,6 +24587,52 @@ function reviewSeverityRank(reasons) {
24281
24587
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24282
24588
  }
24283
24589
 
24590
+ // ../../packages/schema/src/zod/web-capture.ts
24591
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24592
+ var WebUsage = external_exports.object({
24593
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24594
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24595
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24596
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24597
+ });
24598
+ var WebToolCall = external_exports.object({
24599
+ toolUseId: external_exports.string().min(1),
24600
+ toolName: external_exports.string().min(1),
24601
+ target: external_exports.string().optional(),
24602
+ isError: external_exports.boolean().optional(),
24603
+ inputSize: external_exports.number().int().nonnegative().optional(),
24604
+ outputSize: external_exports.number().int().nonnegative().optional()
24605
+ });
24606
+ var WebExchange = external_exports.object({
24607
+ messageId: external_exports.string().min(1),
24608
+ startedAt: external_exports.iso.datetime(),
24609
+ model: external_exports.string().optional(),
24610
+ usage: WebUsage.optional(),
24611
+ usageSource: WebUsageSource,
24612
+ stopReason: external_exports.string().optional(),
24613
+ conversationId: external_exports.string().optional(),
24614
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24615
+ toolCalls: external_exports.array(WebToolCall).default([]),
24616
+ // Absent when the adapter recovered no text. Capped by the caller at
24617
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24618
+ // short capture is never mistaken for a short reply.
24619
+ responseText: external_exports.string().optional(),
24620
+ truncated: external_exports.boolean().default(false)
24621
+ });
24622
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24623
+ var WebCaptureStatus = external_exports.object({
24624
+ patched: external_exports.boolean(),
24625
+ live: external_exports.boolean(),
24626
+ blind: external_exports.boolean(),
24627
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24628
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24629
+ parseFailures: external_exports.number().int().nonnegative(),
24630
+ unparsedBodies: external_exports.number().int().nonnegative(),
24631
+ // The adapter-declared JSON key paths that were absent from a real payload —
24632
+ // the earliest signal that a site's contract moved.
24633
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24634
+ });
24635
+
24284
24636
  // ../../packages/persistence/src/paths.ts
24285
24637
  import {
24286
24638
  chmodSync,
@@ -24493,6 +24845,22 @@ function discardStore(file2, backup) {
24493
24845
  }
24494
24846
  }
24495
24847
 
24848
+ // ../../packages/persistence/src/internal/sql-functions.ts
24849
+ var utf8 = new TextDecoder();
24850
+ function akaLower(value) {
24851
+ if (value === null) return null;
24852
+ if (typeof value === "string") return value.toLowerCase();
24853
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
24854
+ return utf8.decode(value).toLowerCase();
24855
+ }
24856
+ function registerSqlFunctions(db) {
24857
+ db.function(
24858
+ "aka_lower",
24859
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
24860
+ akaLower
24861
+ );
24862
+ }
24863
+
24496
24864
  // ../../packages/persistence/src/internal/sql-text.ts
24497
24865
  function escapeLikePattern(s) {
24498
24866
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24577,6 +24945,11 @@ function schemaObjectExists(db, kind, name) {
24577
24945
  function indexExists(db, name) {
24578
24946
  return schemaObjectExists(db, "index", name);
24579
24947
  }
24948
+ function indexColumns(db, name) {
24949
+ if (!indexExists(db, name)) return [];
24950
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
24951
+ return columns.map((c) => c.name).filter((c) => c !== null);
24952
+ }
24580
24953
  function columnNames(db, table2, opts) {
24581
24954
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24582
24955
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24638,6 +25011,647 @@ function mapRowsTolerant(rows, map2) {
24638
25011
  return out;
24639
25012
  }
24640
25013
 
25014
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25015
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25016
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25017
+
25018
+ // ../../packages/persistence/src/sync-failure.ts
25019
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25020
+ function syncFailureRejectCondition(column = "sync_failure") {
25021
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25022
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
25023
+ }
25024
+
25025
+ // ../../packages/persistence/src/repositories/history-sync.ts
25026
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25027
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25028
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25029
+ var COUNTED_EVENT_TYPES = [
25030
+ ...STRUCTURAL_EVENT_TYPES,
25031
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25032
+ ];
25033
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25034
+ var PARTITION_BUCKETS = `
25035
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25036
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25037
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25038
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25039
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25040
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25041
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25042
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25043
+ -- added later lands in no bucket and fails the sum assertion, instead
25044
+ -- of silently joining this one.
25045
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25046
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25047
+ THEN 1 ELSE 0 END) AS failed,
25048
+ COUNT(*) AS total`;
25049
+ var COUNTED_SCOPE = `
25050
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25051
+ AND (
25052
+ event_type IN (${TYPE_LIST})
25053
+ OR synced_at IS NOT NULL
25054
+ OR outbox_owed = 1
25055
+ )`;
25056
+ var SKIPPED = -1;
25057
+ var ROW_COLUMNS = `id,
25058
+ parent_id AS parentId,
25059
+ root_session_id AS rootSessionId,
25060
+ event_type AS eventType,
25061
+ host_id AS hostId,
25062
+ harness_id AS harnessId,
25063
+ source_project_id AS sourceProjectId,
25064
+ started_at AS startedAt,
25065
+ ended_at AS endedAt,
25066
+ severity,
25067
+ priority,
25068
+ content,
25069
+ content_hash AS contentHash,
25070
+ attributes`;
25071
+ var SqliteHistorySyncRepository = class {
25072
+ constructor(db) {
25073
+ this.db = db;
25074
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25075
+ this.sessionsStmt = db.prepare(
25076
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25077
+ FROM audit_events
25078
+ WHERE synced_at IS NULL
25079
+ AND event_type IN (${TYPE_LIST})
25080
+ AND started_at < :before
25081
+ GROUP BY sessionId
25082
+ ORDER BY earliest
25083
+ LIMIT :limit`
25084
+ );
25085
+ this.rowsStmt = db.prepare(
25086
+ `SELECT ${ROW_COLUMNS}
25087
+ FROM audit_events
25088
+ WHERE synced_at IS NULL
25089
+ AND event_type IN (${TYPE_LIST})
25090
+ AND started_at < :before
25091
+ AND COALESCE(root_session_id, id) = :sessionId
25092
+ ORDER BY (event_type = 'session') DESC, started_at
25093
+ LIMIT :limit`
25094
+ );
25095
+ this.captureRowsStmt = db.prepare(
25096
+ `SELECT ${ROW_COLUMNS}
25097
+ FROM audit_events
25098
+ WHERE synced_at IS NULL
25099
+ AND sync_claimed_at IS NULL
25100
+ AND outbox_owed = 1
25101
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25102
+ AND started_at < :before
25103
+ ORDER BY started_at
25104
+ LIMIT :limit`
25105
+ );
25106
+ this.markOwedStmt = db.prepare(
25107
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25108
+ );
25109
+ this.markCaptureBacklogOwedStmt = db.prepare(
25110
+ `UPDATE audit_events SET outbox_owed = 1
25111
+ WHERE synced_at IS NULL
25112
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25113
+ AND started_at < :before`
25114
+ );
25115
+ this.stampStmt = db.prepare(
25116
+ `UPDATE audit_events
25117
+ SET synced_at = :at,
25118
+ sync_claimed_at = NULL,
25119
+ sync_failed_at = :failedAt,
25120
+ sync_failure = :failure
25121
+ WHERE id = :id`
25122
+ );
25123
+ this.claimRowStmt = db.prepare(
25124
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25125
+ );
25126
+ this.releaseRowStmt = db.prepare(
25127
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25128
+ );
25129
+ this.releaseStaleClaimsStmt = db.prepare(
25130
+ `UPDATE audit_events SET sync_claimed_at = NULL
25131
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25132
+ );
25133
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25134
+ FROM audit_events${COUNTED_SCOPE}`);
25135
+ this.partitionByKindStmt = db.prepare(
25136
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25137
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25138
+ GROUP BY event_type`
25139
+ );
25140
+ this.countsStmt = db.prepare(
25141
+ `SELECT
25142
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25143
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25144
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25145
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25146
+ THEN 1 ELSE 0 END) AS skipped,
25147
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25148
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25149
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25150
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25151
+ FROM audit_events
25152
+ WHERE event_type IN (${TYPE_LIST})`
25153
+ );
25154
+ this.captureSkipCountStmt = db.prepare(
25155
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25156
+ // way the structural totals are. The split exists because a refusal is
25157
+ // terminal only against the deployment that gave it, and the structural
25158
+ // re-arm frees it on a change of deployment. The capture lane has no such
25159
+ // escape: re-arming a capture would offer one deployment's undelivered
25160
+ // prompts, with their text, to a deployment that never saw them, which is
25161
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25162
+ // reasons mean the same thing — this row will not be sent — and splitting
25163
+ // them would put refused captures in a bucket nothing reads and nothing
25164
+ // frees.
25165
+ `SELECT COUNT(*) AS skipped
25166
+ FROM audit_events
25167
+ WHERE synced_at = ${String(SKIPPED)}
25168
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25169
+ );
25170
+ this.fingerprintStmt = db.prepare(
25171
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25172
+ FROM history_sync WHERE id = 1`
25173
+ );
25174
+ this.setFingerprintStmt = db.prepare(
25175
+ `UPDATE history_sync
25176
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25177
+ WHERE id = 1`
25178
+ );
25179
+ this.disownCapturesStmt = db.prepare(
25180
+ `UPDATE audit_events SET outbox_owed = NULL
25181
+ WHERE outbox_owed IS NOT NULL
25182
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25183
+ AND started_at < :attachedAt`
25184
+ );
25185
+ this.rearmStmt = db.prepare(
25186
+ `UPDATE audit_events
25187
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25188
+ WHERE (synced_at > 0
25189
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25190
+ AND event_type IN (${TYPE_LIST})`
25191
+ );
25192
+ this.claimStmt = db.prepare(
25193
+ `UPDATE history_sync
25194
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25195
+ WHERE id = 1
25196
+ AND (owner_pid IS NULL
25197
+ OR heartbeat_at IS NULL
25198
+ OR heartbeat_at < :staleBefore
25199
+ OR heartbeat_at > :now)`
25200
+ );
25201
+ this.heartbeatStmt = db.prepare(
25202
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25203
+ );
25204
+ this.releaseStmt = db.prepare(
25205
+ `UPDATE history_sync
25206
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25207
+ WHERE id = 1 AND owner_pid = :pid`
25208
+ );
25209
+ this.closeWindowStmt = db.prepare(
25210
+ `UPDATE audit_events
25211
+ SET synced_at = ${String(SKIPPED)},
25212
+ sync_failed_at = :at,
25213
+ sync_failure = 'detached_undelivered'
25214
+ WHERE synced_at IS NULL
25215
+ AND event_type IN (${TYPE_LIST})
25216
+ AND started_at >= :attachedAt`
25217
+ );
25218
+ this.releaseBoundaryStmt = db.prepare(
25219
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25220
+ );
25221
+ this.freezeBoundaryStmt = db.prepare(
25222
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25223
+ );
25224
+ this.leaseStmt = db.prepare(
25225
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25226
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25227
+ FROM history_sync WHERE id = 1`
25228
+ );
25229
+ this.inspectionsStmt = db.prepare(
25230
+ `SELECT d.rule_id AS ruleId,
25231
+ d.name AS ruleName,
25232
+ d.version AS ruleVersion,
25233
+ d.category AS category,
25234
+ d.severity AS severity,
25235
+ f.span_start AS spanStart,
25236
+ f.span_end AS spanEnd,
25237
+ f.masked_match AS maskedMatch,
25238
+ f.action_taken AS actionTaken,
25239
+ f.confidence AS confidence
25240
+ FROM inspection_findings f
25241
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25242
+ WHERE f.audit_event_id = :auditEventId
25243
+ ORDER BY f.span_start, f.id`
25244
+ );
25245
+ }
25246
+ db;
25247
+ ensureRowStmt;
25248
+ sessionsStmt;
25249
+ rowsStmt;
25250
+ stampStmt;
25251
+ countsStmt;
25252
+ fingerprintStmt;
25253
+ setFingerprintStmt;
25254
+ rearmStmt;
25255
+ claimStmt;
25256
+ heartbeatStmt;
25257
+ releaseStmt;
25258
+ leaseStmt;
25259
+ inspectionsStmt;
25260
+ closeWindowStmt;
25261
+ releaseBoundaryStmt;
25262
+ freezeBoundaryStmt;
25263
+ captureRowsStmt;
25264
+ markOwedStmt;
25265
+ markCaptureBacklogOwedStmt;
25266
+ captureSkipCountStmt;
25267
+ disownCapturesStmt;
25268
+ partitionStmt;
25269
+ partitionByKindStmt;
25270
+ claimRowStmt;
25271
+ releaseRowStmt;
25272
+ releaseStaleClaimsStmt;
25273
+ /**
25274
+ * The masked detections recorded against one tool call.
25275
+ *
25276
+ * These travel with the event because a tool call's target is not
25277
+ * re-inspectable from the event alone — unlike a capture, where the text
25278
+ * itself is re-scannable. What crosses is the masked match and the rule that
25279
+ * produced it, never the value.
25280
+ */
25281
+ inspectionsFor(auditEventId) {
25282
+ return allRows(this.inspectionsStmt, { auditEventId });
25283
+ }
25284
+ /**
25285
+ * Sessions with structural rows still to send, oldest first.
25286
+ *
25287
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25288
+ * read. Anything recorded after the machine attached is the live forward
25289
+ * path's to deliver; this drain exists for what was recorded before it, and a
25290
+ * row both paths send is at best a duplicate request and at worst — for a
25291
+ * session root — an overwrite of the inventory ids the live path resolved.
25292
+ */
25293
+ pendingSessions(limit, before) {
25294
+ return allRows(this.sessionsStmt, { limit, before }).map(
25295
+ (r) => r.sessionId
25296
+ );
25297
+ }
25298
+ /** One session's undelivered structural rows within the backlog, root first. */
25299
+ pendingRows(sessionId, limit, before) {
25300
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25301
+ }
25302
+ /**
25303
+ * Captures this machine still owes the deployment, oldest first.
25304
+ *
25305
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25306
+ * by a time window — see captureRowsStmt for why a window could not express
25307
+ * this. `before` is the grace window that leaves a just-recorded capture to
25308
+ * the live path.
25309
+ */
25310
+ pendingCaptureRows(limit, before) {
25311
+ return allRows(this.captureRowsStmt, { limit, before });
25312
+ }
25313
+ /**
25314
+ * Record that a capture is OWED to the deployment.
25315
+ *
25316
+ * Written by the attached forward path when a live send did not confirm
25317
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25318
+ * a fact rather than an inference: the machine was attached, the send did not
25319
+ * land, so the row is owed — which no time window can state, because the same
25320
+ * window that holds the rows a past attachment left owed also holds every
25321
+ * capture recorded while the machine was DETACHED, and those were never
25322
+ * offered to anyone.
25323
+ *
25324
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25325
+ * out of the drain's read.
25326
+ */
25327
+ markCaptureOwed(id) {
25328
+ this.markOwedStmt.run({ id });
25329
+ }
25330
+ /**
25331
+ * Mark every capture already on disk as owed, as of `before`.
25332
+ *
25333
+ * The consent-time backfill, called once from `aka attach` when a human
25334
+ * grants existing-history consent — never from an ongoing drain pass, and
25335
+ * never inferred from a boundary that could later move. `before` is the
25336
+ * caller's own "now" at the moment consent was granted, so what this marks
25337
+ * is exactly the backlog the consent prompt already counted, not whatever a
25338
+ * later re-attach or key rotation might widen it to.
25339
+ *
25340
+ * Returns how many rows matched, for the caller to log or test against. Not a
25341
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25342
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25343
+ */
25344
+ markCaptureBacklogOwed(before) {
25345
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25346
+ }
25347
+ /**
25348
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25349
+ *
25350
+ * CLEARS any failure reason in the same statement. A row that failed against
25351
+ * one deployment and then landed is delivered, and leaving the reason behind
25352
+ * would leave the store holding two contradictory answers about one row —
25353
+ * with the surface free to render either.
25354
+ */
25355
+ markSynced(ids, atMs) {
25356
+ this.stampAll(ids, atMs, null);
25357
+ }
25358
+ /**
25359
+ * Record that THIS MACHINE cannot express the row on the wire.
25360
+ *
25361
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25362
+ * payload, or a body the client itself refused to send. It fails identically
25363
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25364
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25365
+ * is retried; marking those would turn one outage into permanent data loss.
25366
+ */
25367
+ markSkipped(ids, atMs) {
25368
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25369
+ }
25370
+ /**
25371
+ * Record that THIS DEPLOYMENT refused the row.
25372
+ *
25373
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25374
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25375
+ * row is outstanding rather than why. What separates them is the reason, and
25376
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25377
+ * on one body, so it is terminal only for as long as this machine points at
25378
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25379
+ *
25380
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25381
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25382
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25383
+ */
25384
+ markRefused(ids, atMs) {
25385
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25386
+ }
25387
+ eachInTransaction(ids, run) {
25388
+ if (ids.length === 0) return;
25389
+ withTransaction(
25390
+ this.db,
25391
+ () => {
25392
+ for (const id of ids) run(id);
25393
+ },
25394
+ "IMMEDIATE"
25395
+ );
25396
+ }
25397
+ stampAll(ids, value, failure, failedAtMs) {
25398
+ if (ids.length === 0) return;
25399
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25400
+ withTransaction(
25401
+ this.db,
25402
+ () => {
25403
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25404
+ },
25405
+ "IMMEDIATE"
25406
+ );
25407
+ }
25408
+ /**
25409
+ * Claim rows as in-flight.
25410
+ *
25411
+ * Advisory in exactly the sense the lease is: it records that a send is in
25412
+ * progress so a surface can say so, and a lost claim costs a row showing as
25413
+ * queued while it is actually being sent. It is not exclusion — the far side
25414
+ * settles a duplicate on the row id.
25415
+ */
25416
+ claimRows(ids, atMs) {
25417
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25418
+ }
25419
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25420
+ releaseRows(ids) {
25421
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25422
+ }
25423
+ /**
25424
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25425
+ *
25426
+ * A process killed between claiming and settling leaves rows claimed with
25427
+ * nothing left to settle them. Without this they read as "sending" for ever.
25428
+ */
25429
+ releaseStaleClaims(staleBefore) {
25430
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25431
+ }
25432
+ /**
25433
+ * Every tracked row in exactly one delivery state.
25434
+ *
25435
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25436
+ * pick up now", which is a different question from "what state is this row
25437
+ * in" — and a machine that has never attached has no boundary to pass, so
25438
+ * requiring one would force a caller to invent one and report the whole store
25439
+ * as queued.
25440
+ */
25441
+ /**
25442
+ * The same partition, one row per kind that a lane carries.
25443
+ *
25444
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25445
+ * scope decides which rows exist at all, so a kind that has never been
25446
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25447
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25448
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25449
+ * different things.
25450
+ */
25451
+ partitionByKind() {
25452
+ return allRows(
25453
+ this.partitionByKindStmt,
25454
+ {}
25455
+ ).map((row) => ({
25456
+ kind: row.kind,
25457
+ queued: row.queued ?? 0,
25458
+ inProgress: row.inProgress ?? 0,
25459
+ synced: row.synced ?? 0,
25460
+ failed: row.failed ?? 0,
25461
+ refused: row.refused ?? 0,
25462
+ detached: row.detached ?? 0,
25463
+ total: row.total ?? 0
25464
+ }));
25465
+ }
25466
+ partition() {
25467
+ const row = getRow(this.partitionStmt, {});
25468
+ return {
25469
+ queued: row?.queued ?? 0,
25470
+ inProgress: row?.inProgress ?? 0,
25471
+ synced: row?.synced ?? 0,
25472
+ failed: row?.failed ?? 0,
25473
+ refused: row?.refused ?? 0,
25474
+ detached: row?.detached ?? 0,
25475
+ total: row?.total ?? 0
25476
+ };
25477
+ }
25478
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25479
+ counts(before) {
25480
+ const row = getRow(this.countsStmt, { before });
25481
+ const captures = getRow(this.captureSkipCountStmt);
25482
+ return {
25483
+ pending: row?.pending ?? 0,
25484
+ sent: row?.sent ?? 0,
25485
+ skipped: row?.skipped ?? 0,
25486
+ refused: row?.refused ?? 0,
25487
+ detached: row?.detached ?? 0,
25488
+ capturesSkipped: captures?.skipped ?? 0
25489
+ };
25490
+ }
25491
+ /**
25492
+ * The deployment the current stamps were made against, and where its backlog
25493
+ * ends.
25494
+ *
25495
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25496
+ * machine that has never drained is — and every writer below seeds the row
25497
+ * before it needs one, so nothing depends on this creating it. Keeping the
25498
+ * write off the gate path matters because the gate runs on every pass while a
25499
+ * write has to take the database's write lock.
25500
+ */
25501
+ deployment() {
25502
+ const row = getRow(
25503
+ this.fingerprintStmt
25504
+ );
25505
+ return {
25506
+ fingerprint: row?.fingerprint ?? void 0,
25507
+ backlogBefore: row?.backlogBefore ?? void 0
25508
+ };
25509
+ }
25510
+ /**
25511
+ * Point the ledger at a different deployment, discarding what it recorded
25512
+ * about the previous one.
25513
+ *
25514
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25515
+ * machine has just left are undelivered as far as the new one is concerned.
25516
+ * All four in one transaction, so a crash between them cannot leave stamps
25517
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25518
+ * a disown with no re-mark to follow it.
25519
+ *
25520
+ * The boundary is written HERE and only here, which is what freezes it: a
25521
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25522
+ * unchanged, so this never runs and the backlog does not widen back over rows
25523
+ * the live path has since delivered.
25524
+ *
25525
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25526
+ * granted existing-history consent for the deployment this call is arming —
25527
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25528
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25529
+ * apart. Passed only when that grant is valid, since this method has no way
25530
+ * to check consent itself and must not mark a row owed for a machine that
25531
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25532
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25533
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25534
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25535
+ * on the cleared side of that bound — and the re-mark in the same
25536
+ * transaction is what puts those rows back. A crash between the two cannot
25537
+ * strand the ledger disowned with nothing re-marked — the transaction either
25538
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25539
+ * committed re-enters this method on the very next pass. Omit it (the
25540
+ * structural-only tests do) to exercise the disown in isolation.
25541
+ *
25542
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25543
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25544
+ * live path can mark a capture owed from the moment `aka attach` writes the
25545
+ * descriptor, before the drain's first pass ever reaches this method, and
25546
+ * such a row sits at or after the bound rather than below it. What keeps the
25547
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25548
+ * bound — disown runs first, re-mark second, both inside the one
25549
+ * transaction above.
25550
+ */
25551
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25552
+ this.ensureRowStmt.run();
25553
+ withTransaction(
25554
+ this.db,
25555
+ () => {
25556
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25557
+ this.rearmStmt.run();
25558
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25559
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25560
+ }
25561
+ if (backfillCapturesBefore !== void 0) {
25562
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25563
+ }
25564
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25565
+ },
25566
+ "IMMEDIATE"
25567
+ );
25568
+ }
25569
+ /**
25570
+ * End the attached period: hand its rows to the live path, and release the
25571
+ * boundary so the next attachment can freeze a new one.
25572
+ *
25573
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25574
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25575
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25576
+ * during the detached period, because the machine is not attached. Rows
25577
+ * recorded in that window sit after the boundary and before the re-attach, so
25578
+ * neither path takes them, and the pending count reports none outstanding.
25579
+ *
25580
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25581
+ * closing attachment's to deliver and are no longer outstanding — that is what
25582
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25583
+ * distinction is not academic: this used to write a delivery TIME, which every
25584
+ * read treats as delivery, so one detach turned a window of undelivered rows
25585
+ * into a window of delivered ones and no surface could tell. It writes the
25586
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25587
+ * "received" stop being the same fact.
25588
+ *
25589
+ * A change of deployment still frees them (see the re-arm), because the next
25590
+ * deployment has seen none of this machine's history — so the rows reach it
25591
+ * exactly as they did when this wrote a delivery time.
25592
+ *
25593
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25594
+ * window unstamped — that half-state would re-send the whole attached period
25595
+ * on the next attach, which is the failure the boundary exists to prevent.
25596
+ */
25597
+ closeAttachedWindow(attachedAtMs, atMs) {
25598
+ this.ensureRowStmt.run();
25599
+ withTransaction(
25600
+ this.db,
25601
+ () => {
25602
+ const row = getRow(this.fingerprintStmt);
25603
+ const from = row?.backlogBefore ?? attachedAtMs;
25604
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25605
+ this.releaseBoundaryStmt.run();
25606
+ },
25607
+ "IMMEDIATE"
25608
+ );
25609
+ }
25610
+ /**
25611
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25612
+ *
25613
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25614
+ * different deployment and therefore discards what was delivered to the old
25615
+ * one: here the recipient is the same, so everything already sent to it stays
25616
+ * sent.
25617
+ */
25618
+ freezeBoundary(backlogBefore) {
25619
+ this.ensureRowStmt.run();
25620
+ this.freezeBoundaryStmt.run({ backlogBefore });
25621
+ }
25622
+ /** Take the claim, or report that someone live already holds it. */
25623
+ claim(pid, host, nowMs, staleAfterMs) {
25624
+ this.ensureRowStmt.run();
25625
+ let taken = false;
25626
+ withTransaction(
25627
+ this.db,
25628
+ () => {
25629
+ const result = this.claimStmt.run({
25630
+ pid,
25631
+ host,
25632
+ now: nowMs,
25633
+ staleBefore: nowMs - staleAfterMs
25634
+ });
25635
+ taken = result.changes === 1;
25636
+ },
25637
+ "IMMEDIATE"
25638
+ );
25639
+ return taken;
25640
+ }
25641
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25642
+ heartbeat(pid, nowMs) {
25643
+ this.heartbeatStmt.run({ now: nowMs, pid });
25644
+ }
25645
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25646
+ release(pid) {
25647
+ this.releaseStmt.run({ pid });
25648
+ }
25649
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25650
+ lease() {
25651
+ return getRow(this.leaseStmt);
25652
+ }
25653
+ };
25654
+
24641
25655
  // ../../packages/persistence/src/migrations.ts
24642
25656
  function describeObject(object2) {
24643
25657
  return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
@@ -24650,7 +25664,7 @@ function createdIndexName(statement) {
24650
25664
  return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
24651
25665
  }
24652
25666
  var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24653
- function applyMigrations(db, file2) {
25667
+ function applyMigrations(db, file2, options = {}) {
24654
25668
  const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24655
25669
  db.exec(
24656
25670
  "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
@@ -24664,6 +25678,7 @@ function applyMigrations(db, file2) {
24664
25678
  );
24665
25679
  for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24666
25680
  if (applied.has(migration.tag)) continue;
25681
+ if (options.skipTags?.has(migration.tag) === true) continue;
24667
25682
  if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24668
25683
  const evidence = evidenceObjects(migration.sql);
24669
25684
  const present = evidence.filter((o) => evidenceExists(db, o));
@@ -25070,10 +26085,62 @@ function ensureSyncedAtColumn(db, table2) {
25070
26085
  if (!columns.includes("outbox_owed")) {
25071
26086
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25072
26087
  }
26088
+ if (!columns.includes("sync_failed_at")) {
26089
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26090
+ }
26091
+ if (!columns.includes("sync_failure")) {
26092
+ withTransaction(
26093
+ db,
26094
+ () => {
26095
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26096
+ db.exec(
26097
+ `UPDATE ${table2} SET synced_at = NULL
26098
+ WHERE synced_at = -1
26099
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26100
+ );
26101
+ },
26102
+ "IMMEDIATE"
26103
+ );
26104
+ }
25073
26105
  db.exec(
25074
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25075
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26106
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26107
+ BEFORE UPDATE OF sync_failure ON ${table2}
26108
+ WHEN ${syncFailureRejectCondition()}
26109
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25076
26110
  );
26111
+ const syncIndexColumns = [
26112
+ "event_type",
26113
+ "synced_at",
26114
+ "sync_claimed_at",
26115
+ "started_at",
26116
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26117
+ // has to be in the index for the read to stay covered — but putting it
26118
+ // ahead of `started_at` would reorder the prefix the structural drain's
26119
+ // reads match on.
26120
+ "sync_failure"
26121
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26122
+ //
26123
+ // The delivery-state read tests it — a capture's state depends on whether a
26124
+ // live forward marked it owed — so carrying it here makes that read covering
26125
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26126
+ // But a sixth column changes what the planner charges for this index, and
26127
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26128
+ // then stops choosing the per-session index for the token rollup and walks
26129
+ // every `llm_call` in the store through the event-type index instead. That
26130
+ // read grows with the store; this one does not.
26131
+ //
26132
+ // 40 ms on the largest store measured, once per render, is a cost worth
26133
+ // paying to leave every other read's plan where it was.
26134
+ ];
26135
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26136
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26137
+ if (!syncIndexMatches) {
26138
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26139
+ db.exec(
26140
+ `CREATE INDEX idx_audit_events_sync
26141
+ ON audit_events (${syncIndexColumns.join(", ")})`
26142
+ );
26143
+ }
25077
26144
  db.exec(
25078
26145
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25079
26146
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25295,7 +26362,11 @@ function buildAuditEvent(row) {
25295
26362
  link: linkParsed?.success ? linkParsed.data : null,
25296
26363
  targetId: row.target_id,
25297
26364
  internal: intToBool(row.internal),
25298
- flagged: intToBool(row.flagged)
26365
+ flagged: intToBool(row.flagged),
26366
+ // Only meaningful when the title came out empty — a row whose body was
26367
+ // expired but whose title fell back to `tool_name` still has something to
26368
+ // render, and flagging it would make the view apologise for nothing.
26369
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25299
26370
  };
25300
26371
  }
25301
26372
  var TIMELINE_COLUMNS = `
@@ -25303,6 +26374,7 @@ var TIMELINE_COLUMNS = `
25303
26374
  event_type,
25304
26375
  started_at,
25305
26376
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26377
+ content_expired_at,
25306
26378
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25307
26379
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25308
26380
  json_extract(attributes, '$.severity') AS severity,
@@ -25429,7 +26501,8 @@ var SqliteActivityRepository = class {
25429
26501
  SELECT 1 FROM audit_events d
25430
26502
  WHERE d.root_session_id = audit_events.id
25431
26503
  AND (d.content LIKE ? ESCAPE '\\'
25432
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26504
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26505
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25433
26506
  );
25434
26507
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25435
26508
  }
@@ -25967,6 +27040,88 @@ var SqliteAuditEventsRepository = class {
25967
27040
  }
25968
27041
  };
25969
27042
 
27043
+ // ../../packages/persistence/src/repositories/body-retention.ts
27044
+ var DEFAULT_BATCH_SIZE = 500;
27045
+ var DEFAULT_MAX_ROWS = 5e4;
27046
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27047
+ var SqliteBodyRetentionRepository = class {
27048
+ constructor(db) {
27049
+ this.db = db;
27050
+ const select = (laneClause) => `
27051
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27052
+ FROM audit_events
27053
+ WHERE content IS NOT NULL
27054
+ AND started_at < :cutoff
27055
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27056
+ ${laneClause}
27057
+ ORDER BY started_at
27058
+ LIMIT :limit`;
27059
+ this.candidatesStmt = this.db.prepare(select(""));
27060
+ this.candidatesSyncSafeStmt = this.db.prepare(
27061
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27062
+ );
27063
+ this.heldBySyncStmt = this.db.prepare(`
27064
+ SELECT COUNT(*) AS n
27065
+ FROM audit_events
27066
+ WHERE content IS NOT NULL
27067
+ AND started_at < :cutoff
27068
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27069
+ AND synced_at IS NULL`);
27070
+ this.expireStmt = this.db.prepare(
27071
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27072
+ );
27073
+ }
27074
+ db;
27075
+ candidatesStmt;
27076
+ candidatesSyncSafeStmt;
27077
+ heldBySyncStmt;
27078
+ expireStmt;
27079
+ /** How many bytes a pass with these options would free, changing nothing. */
27080
+ preview(opts) {
27081
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27082
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27083
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27084
+ return {
27085
+ rowsExpired: rows.length,
27086
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27087
+ rowsHeldBySync: this.countHeldBySync(opts)
27088
+ };
27089
+ }
27090
+ /** Clear eligible bodies, in bounded batches. */
27091
+ expire(opts) {
27092
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27093
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27094
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27095
+ let rowsExpired = 0;
27096
+ let bytesFreed = 0;
27097
+ let done = true;
27098
+ while (rowsExpired < maxRows) {
27099
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27100
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27101
+ if (batch.length === 0) break;
27102
+ withTransaction(
27103
+ this.db,
27104
+ () => {
27105
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27106
+ },
27107
+ "IMMEDIATE"
27108
+ );
27109
+ rowsExpired += batch.length;
27110
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27111
+ if (batch.length < remaining) break;
27112
+ if (rowsExpired >= maxRows) {
27113
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27114
+ }
27115
+ }
27116
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27117
+ }
27118
+ countHeldBySync(opts) {
27119
+ if (opts.sweepSyncLane) return 0;
27120
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27121
+ return row.n;
27122
+ }
27123
+ };
27124
+
25970
27125
  // ../../packages/persistence/src/repositories/classified-data.ts
25971
27126
  var SqliteClassifiedDataRepository = class {
25972
27127
  constructor(db) {
@@ -26767,23 +27922,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26767
27922
  )`;
26768
27923
 
26769
27924
  // ../../packages/persistence/src/repositories/findings.ts
26770
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26771
- var DEFAULT_LOCATIONS_LIMIT = 100;
26772
- var LOCATION_RULE_IDS_CAP = 20;
26773
- function compareLocationOrder(a, b) {
26774
- return compareFindingGroupOrder(
26775
- {
26776
- severity: a.maxSeverity,
26777
- latestDetectedAt: a.latestDetectedAt,
26778
- id: ""
26779
- },
26780
- {
26781
- severity: b.maxSeverity,
26782
- latestDetectedAt: b.latestDetectedAt,
26783
- id: ""
26784
- }
26785
- );
26786
- }
26787
27925
  var CONCAT_SEP = ",";
26788
27926
  var TUPLE_SEP = "|";
26789
27927
  function splitConcat(value) {
@@ -26812,7 +27950,15 @@ function toFlatFindingRow(r) {
26812
27950
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26813
27951
  eventId: r.event_id,
26814
27952
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26815
- status: deriveInstanceStatus(r)
27953
+ status: deriveInstanceStatus(r),
27954
+ delivery: deriveFindingDelivery({
27955
+ kind: r.kind,
27956
+ syncedAt: r.synced_at,
27957
+ syncClaimedAt: r.sync_claimed_at,
27958
+ syncFailedAt: r.sync_failed_at,
27959
+ syncFailure: r.sync_failure,
27960
+ outboxOwed: r.outbox_owed
27961
+ })
26816
27962
  };
26817
27963
  }
26818
27964
  function encodeGroupCursor(group) {
@@ -26835,13 +27981,51 @@ function decodeGroupCursor(cursor) {
26835
27981
  return null;
26836
27982
  }
26837
27983
  function firstAfter(sorted, cursor) {
26838
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
27984
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26839
27985
  return index === -1 ? sorted.length : index;
26840
27986
  }
26841
27987
  function findDeepLinked(sorted, page, id) {
26842
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26843
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
27988
+ if (page.some((t) => t.id === id)) return void 0;
27989
+ return sorted.find((t) => t.id === id);
27990
+ }
27991
+ function encodeLocationCursor(location) {
27992
+ const payload = {
27993
+ sev: location.maxSeverity,
27994
+ t: location.latestDetectedAt,
27995
+ r: location.repo,
27996
+ f: location.file
27997
+ };
27998
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
26844
27999
  }
28000
+ function decodeLocationCursor(cursor) {
28001
+ const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28002
+ if (parsed !== void 0 && typeof parsed.sev === "string" && typeof parsed.t === "string" && typeof parsed.r === "string" && typeof parsed.f === "string") {
28003
+ return { maxSeverity: parsed.sev, latestDetectedAt: parsed.t, repo: parsed.r, file: parsed.f };
28004
+ }
28005
+ return null;
28006
+ }
28007
+ function firstLocationAfter(sorted, cursor) {
28008
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28009
+ return index === -1 ? sorted.length : index;
28010
+ }
28011
+ function findDeepLinkedLocation(sorted, page, id) {
28012
+ if (page.some((l) => l.id === id)) return void 0;
28013
+ return sorted.find((l) => l.id === id);
28014
+ }
28015
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28016
+ d.severity AS severity, f.masked_match AS masked_match,
28017
+ f.action_taken AS action_taken, f.confidence AS confidence,
28018
+ e.started_at AS occurred_at,
28019
+ e.source_tool AS source_tool,
28020
+ e.repo AS repo,
28021
+ e.file_path AS file,
28022
+ e.tool_name AS tool_name,
28023
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28024
+ e.event_type AS kind, f.finding_key AS finding_key,
28025
+ ${latestResolutionStatusSql("f")} AS latest_status,
28026
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28027
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28028
+ e.outbox_owed AS outbox_owed`;
26845
28029
  var DAY_MS3 = 864e5;
26846
28030
  var SqliteFindingsRepository = class {
26847
28031
  constructor(db) {
@@ -26962,30 +28146,26 @@ var SqliteFindingsRepository = class {
26962
28146
  );
26963
28147
  }
26964
28148
  /**
26965
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
26966
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
26967
- * attributes bag, rule_id/category/severity from the definition), scoped to
26968
- * the four capture kinds (audit_events also holds structural/reconciler/scan
26969
- * rows this list must never surface), groups by ruleId, computes
26970
- * per-filter-excluded facets, applies the requested filters, and sorts by
26971
- * severity then recency. Filtering
26972
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
26973
- * reflect the full filtered set; `items` is the requested
26974
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
26975
- * filter, `totals.findings` counts only instances whose derived status was
26976
- * requested, and each item's instance preview is narrowed the same way.
28149
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28150
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28151
+ * list must never surface), with per-filter-excluded facets, the requested
28152
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28153
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28154
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28155
+ * Under a `status` filter, `totals.findings` counts only findings whose
28156
+ * derived status was requested.
28157
+ *
28158
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28159
+ * folding EVERY finding into the numbers a type row and the filters need
28160
+ * (count, severity, category, providers, actions, statuses, latest, search
28161
+ * text). The findings OF a type come from listFindingInstances scoped to
28162
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
26977
28163
  *
26978
- * Two reads, neither of which materializes a row per finding:
26979
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
26980
- * the group and the filters need (count, providers, actions, statuses,
26981
- * latest, search text);
26982
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
26983
- * populate `instances` for the table's expanded rows.
26984
28164
  * The aggregates carry raw DB values and are translated by the same
26985
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
26986
- * rule is ever restated in SQL.
28165
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28166
+ * status rule is ever restated in SQL.
26987
28167
  */
26988
- listGroupedFindings(query) {
28168
+ listFindingTypes(query) {
26989
28169
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
26990
28170
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
26991
28171
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -26998,12 +28178,7 @@ var SqliteFindingsRepository = class {
26998
28178
  predicate,
26999
28179
  params: sessionParams
27000
28180
  });
27001
- const rows = this.previewRows(aggregates, {
27002
- sessionId: query.sessionId,
27003
- from: query.from
27004
- });
27005
- const groupable = rows.map(toFlatFindingRow);
27006
- const allGroups = buildFindingGroups(groupable, { aggregates });
28181
+ const allTypes = buildFindingTypes(aggregates);
27007
28182
  const filterOpts = {
27008
28183
  severity: query.severity,
27009
28184
  providers: query.provider,
@@ -27012,30 +28187,25 @@ var SqliteFindingsRepository = class {
27012
28187
  subtype: query.subtype,
27013
28188
  q: query.q
27014
28189
  };
27015
- const facets = computeFindingFacets(allGroups, filterOpts);
27016
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28190
+ const facets = computeFindingFacets(allTypes, filterOpts);
28191
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27017
28192
  const statusFilter = query.status ?? [];
27018
28193
  const totals = {
27019
- findings: sorted.reduce((acc, g) => {
27020
- if (statusFilter.length === 0) return acc + g.instanceCount;
27021
- const agg = aggregates.get(g.id);
27022
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28194
+ findings: sorted.reduce((acc, t) => {
28195
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28196
+ const agg = aggregates.get(t.id);
28197
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27023
28198
  }, 0),
27024
- groups: sorted.length
28199
+ types: sorted.length
27025
28200
  };
27026
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28201
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27027
28202
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27028
28203
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27029
28204
  const page = sorted.slice(start, start + limit);
27030
28205
  const lastOnPage = page.at(-1);
27031
28206
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27032
28207
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27033
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27034
- const narrow = (g) => statusSet ? {
27035
- ...g,
27036
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27037
- } : g;
27038
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28208
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27039
28209
  return Promise.resolve({
27040
28210
  totals,
27041
28211
  facets,
@@ -27046,7 +28216,7 @@ var SqliteFindingsRepository = class {
27046
28216
  }
27047
28217
  /**
27048
28218
  * One row per rule_id, folding EVERY instance of the group into the values
27049
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28219
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27050
28220
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27051
28221
  *
27052
28222
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27100,6 +28270,7 @@ var SqliteFindingsRepository = class {
27100
28270
  providers: query.provider,
27101
28271
  actions: query.action,
27102
28272
  statuses: query.status,
28273
+ deliveries: query.deployment,
27103
28274
  tools: query.tool,
27104
28275
  repo: query.repo,
27105
28276
  file: query.file,
@@ -27140,13 +28311,25 @@ var SqliteFindingsRepository = class {
27140
28311
  });
27141
28312
  }
27142
28313
  /**
27143
- * The same findings folded by location: repository, then file within it.
28314
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27144
28315
  *
27145
28316
  * The grouping keys come from the capturing event's attributes, which is what
27146
- * the local store relates a finding to — there is no finding↔asset row to
27147
- * group by instead. A repo or file the event did not record folds into the
27148
- * empty-string bucket, which the view renders but does not link, since no
27149
- * filter can name it.
28317
+ * the local store relates a finding to; there is no finding↔asset row to group
28318
+ * by instead. A repo or file the event did not record folds into the
28319
+ * empty-string bucket, which is a real location like any other: it is listed,
28320
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28321
+ *
28322
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28323
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28324
+ * list was rebuilt to remove — and two-level pagination inside an
28325
+ * expand/collapse table is what pushed that view to master/detail in the first
28326
+ * place.
28327
+ *
28328
+ * Every filter narrows the FINDINGS and the locations fall out of what
28329
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28330
+ * reports for the same filters scoped to that pair. The view depends on it:
28331
+ * one toolbar sits over both panels precisely because a location owns none of
28332
+ * its fields.
27150
28333
  */
27151
28334
  listFindingLocations(query) {
27152
28335
  const opts = {
@@ -27155,16 +28338,20 @@ var SqliteFindingsRepository = class {
27155
28338
  providers: query.provider,
27156
28339
  actions: query.action,
27157
28340
  statuses: query.status,
28341
+ deliveries: query.deployment,
27158
28342
  tools: query.tool,
27159
28343
  q: query.q
27160
28344
  };
27161
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28345
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28346
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27162
28347
  const byRepo = /* @__PURE__ */ new Map();
28348
+ const accumulator = createInstanceFacetAccumulator(opts);
27163
28349
  let total = 0;
27164
28350
  for (const row of this.scanFindingRows({
27165
28351
  sessionId: query.sessionId,
27166
28352
  from: query.from
27167
28353
  })) {
28354
+ accumulator.add(row);
27168
28355
  if (!matchesInstanceFilters(row, opts)) continue;
27169
28356
  total += 1;
27170
28357
  let files = byRepo.get(row.repo);
@@ -27179,103 +28366,35 @@ var SqliteFindingsRepository = class {
27179
28366
  }
27180
28367
  addToLocation(acc, row);
27181
28368
  }
27182
- let fileCount = 0;
27183
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27184
- fileCount += files.size;
27185
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27186
- file: file2,
27187
- instanceCount: acc.instanceCount,
27188
- maxSeverity: acc.maxSeverity,
27189
- latestDetectedAt: acc.latestDetectedAt,
27190
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27191
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27192
- })).sort(compareLocationOrder);
27193
- const rollup = fileRows.reduce(
27194
- (a, f) => ({
27195
- instanceCount: a.instanceCount + f.instanceCount,
27196
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27197
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27198
- }),
27199
- {
27200
- instanceCount: 0,
27201
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27202
- latestDetectedAt: ""
27203
- }
27204
- );
27205
- const statuses = fileRows.map((f) => f.status);
27206
- const folded = foldGroupStatus(statuses);
27207
- return {
27208
- repo,
27209
- instanceCount: rollup.instanceCount,
27210
- maxSeverity: rollup.maxSeverity,
27211
- latestDetectedAt: rollup.latestDetectedAt,
27212
- ...folded === void 0 ? {} : { status: folded },
27213
- files: fileRows
27214
- };
27215
- });
27216
- repos.sort(compareLocationOrder);
28369
+ const sorted = [];
28370
+ for (const [repo, files] of byRepo) {
28371
+ for (const [file2, acc] of files) {
28372
+ const status = foldGroupStatus(acc.statuses);
28373
+ sorted.push({
28374
+ id: encodeLocationId(repo, file2),
28375
+ repo,
28376
+ file: file2,
28377
+ instanceCount: acc.instanceCount,
28378
+ maxSeverity: acc.maxSeverity,
28379
+ latestDetectedAt: acc.latestDetectedAt,
28380
+ ...status === void 0 ? {} : { status },
28381
+ ruleIds: [...acc.ruleIds]
28382
+ });
28383
+ }
28384
+ }
28385
+ sorted.sort(compareLocationOrder);
28386
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28387
+ const page = sorted.slice(start, start + limit);
28388
+ const lastOnPage = page.at(-1);
28389
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28390
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27217
28391
  return Promise.resolve({
27218
- totals: { findings: total, repos: repos.length, files: fileCount },
27219
- items: repos.slice(0, limit),
27220
- hasMore: repos.length > limit
28392
+ totals: { findings: total, locations: sorted.length },
28393
+ facets: accumulator.facets(),
28394
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28395
+ nextCursor
27221
28396
  });
27222
28397
  }
27223
- /**
27224
- * Each group's newest instances, for the table's expanded rows.
27225
- *
27226
- * ONE index-ordered scan with early termination, and the shape is the point.
27227
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27228
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27229
- * through a temp B-tree to keep a bounded preview of each group, and then
27230
- * sorts the survivors again for the page order. Both sorts grow with the
27231
- * store while the answer does not.
27232
- *
27233
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27234
- * (or the session or window index the scope names — see `findingScanSql`),
27235
- * which is already the order the page wants, and keeps rows per rule until
27236
- * each rule has as many as it can show. The aggregate the caller already holds
27237
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27238
- * per rule, summed, is the number of rows this scan has to find, and it stops
27239
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27240
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27241
- * store with many firing rules widens it. The bound that DOES hold
27242
- * unconditionally is the sorted form's floor: this scan visits at most as
27243
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27244
- * sorted, and stops the moment every rule has its cap, where the sorted form
27245
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27246
- * wanted instances sitting at the tail of the scope — is one pass over
27247
- * everything in scope with a block sort of the id tie-break only, never a
27248
- * sort of the scope, which is still that floor.
27249
- *
27250
- * A row whose rule the aggregate did not see is skipped: the two statements
27251
- * run without a shared snapshot, so a capture landing between them can add a
27252
- * rule here that has no counts there, and the counts are what the group is
27253
- * built from.
27254
- */
27255
- previewRows(aggregates, scope) {
27256
- const wanted = /* @__PURE__ */ new Map();
27257
- let remaining = 0;
27258
- for (const [ruleId, agg] of aggregates) {
27259
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27260
- wanted.set(ruleId, n);
27261
- remaining += n;
27262
- }
27263
- const rows = [];
27264
- if (remaining === 0) return rows;
27265
- const { sql, params } = this.findingScanSql(scope);
27266
- const taken = /* @__PURE__ */ new Map();
27267
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27268
- const want = wanted.get(r.rule_id);
27269
- if (want === void 0) continue;
27270
- const have = taken.get(r.rule_id) ?? 0;
27271
- if (have >= want) continue;
27272
- taken.set(r.rule_id, have + 1);
27273
- rows.push(r);
27274
- remaining -= 1;
27275
- if (remaining === 0) break;
27276
- }
27277
- return rows;
27278
- }
27279
28398
  /**
27280
28399
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27281
28400
  *
@@ -27302,6 +28421,33 @@ var SqliteFindingsRepository = class {
27302
28421
  yield toFlatFindingRow(r);
27303
28422
  }
27304
28423
  }
28424
+ /**
28425
+ * One finding by its own id, or null when no such row exists.
28426
+ *
28427
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28428
+ * the store — and, unlike anything derived from a list page, it resolves a
28429
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28430
+ * deep link needs: the id it carries may name a finding thousands of rows
28431
+ * older than anything a first page holds.
28432
+ *
28433
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28434
+ * RESOLVES an id; whether that row would survive the list's current filters is
28435
+ * a different question, and hiding the target because a filter excludes it is
28436
+ * worse than showing it.
28437
+ *
28438
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28439
+ * type should the list select?" and "what does the drawer show?".
28440
+ */
28441
+ findingInstance(id) {
28442
+ const row = this.db.prepare(
28443
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28444
+ FROM inspection_findings f
28445
+ JOIN audit_events e ON e.id = f.audit_event_id
28446
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28447
+ WHERE f.id = ?`
28448
+ ).get(id);
28449
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28450
+ }
27305
28451
  /**
27306
28452
  * The one statement both instance-level scans run: every finding in scope,
27307
28453
  * joined to its event and definition, newest first.
@@ -27335,17 +28481,7 @@ var SqliteFindingsRepository = class {
27335
28481
  conditions.push("e.started_at >= ?");
27336
28482
  params.push(isoToEpochMillis(scope.from));
27337
28483
  }
27338
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27339
- d.severity AS severity, f.masked_match AS masked_match,
27340
- f.action_taken AS action_taken, f.confidence AS confidence,
27341
- e.started_at AS occurred_at,
27342
- e.source_tool AS source_tool,
27343
- e.repo AS repo,
27344
- e.file_path AS file,
27345
- e.tool_name AS tool_name,
27346
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27347
- e.event_type AS kind, f.finding_key AS finding_key,
27348
- ${latestResolutionStatusSql("f")} AS latest_status
28484
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27349
28485
  FROM audit_events e
27350
28486
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27351
28487
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27359,6 +28495,26 @@ var SqliteFindingsRepository = class {
27359
28495
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27360
28496
  const rows = this.db.prepare(
27361
28497
  `SELECT rule_id,
28498
+ -- BARE columns beside max(latest_at), which is deliberate and
28499
+ -- is SQLite's documented behaviour: with a single min()/max()
28500
+ -- in an aggregate query, every bare column takes its value from
28501
+ -- the row that produced the extremum. So these are the severity
28502
+ -- and category of the definition whose finding is NEWEST, which
28503
+ -- is what the row-based build they replaced read off its first
28504
+ -- (newest-first) row.
28505
+ --
28506
+ -- min() is WRONG here and was the defect: inspection_definitions
28507
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28508
+ -- mints a new row), so a rule whose severity moved between
28509
+ -- versions has several, and min() picks the ALPHABETICALLY
28510
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28511
+ -- That is arbitrary in direction, and it feeds the badge, the
28512
+ -- filter, the facet counts and the primary sort key.
28513
+ --
28514
+ -- Adding a second min()/max() aggregate here would make these
28515
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28516
+ severity,
28517
+ category,
27362
28518
  sum(tuple_count) AS instance_count,
27363
28519
  max(latest_at) AS latest_at,
27364
28520
  group_concat(source_tools) AS source_tools,
@@ -27369,6 +28525,14 @@ var SqliteFindingsRepository = class {
27369
28525
  group_concat(tool_names) AS tool_names
27370
28526
  FROM (
27371
28527
  SELECT d.rule_id AS rule_id,
28528
+ -- Severity and category are columns of the DEFINITION, and
28529
+ -- a rule can have SEVERAL definitions (one per version), so
28530
+ -- these are grouped on below and resolved to the newest
28531
+ -- firing version by the outer query's bare-column select.
28532
+ -- They ride the aggregate because the type build has no rows
28533
+ -- to read them off \u2014 see buildFindingTypes.
28534
+ d.severity AS severity,
28535
+ d.category AS category,
27372
28536
  e.event_type || '${TUPLE_SEP}' ||
27373
28537
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27374
28538
  coalesce(latest.status, '') AS status_tuple,
@@ -27383,7 +28547,7 @@ var SqliteFindingsRepository = class {
27383
28547
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27384
28548
  ON latest.finding_key = f.finding_key
27385
28549
  ${scope.predicate}
27386
- GROUP BY d.rule_id, status_tuple
28550
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27387
28551
  )
27388
28552
  GROUP BY rule_id`
27389
28553
  ).all(scope.params);
@@ -27392,6 +28556,8 @@ var SqliteFindingsRepository = class {
27392
28556
  r.rule_id,
27393
28557
  {
27394
28558
  instanceCount: r.instance_count,
28559
+ severity: r.severity,
28560
+ category: r.category,
27395
28561
  sourceTools: splitConcat(r.source_tools),
27396
28562
  actionsTaken: splitConcat(r.actions_taken),
27397
28563
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27408,7 +28574,7 @@ var SqliteFindingsRepository = class {
27408
28574
  latestDetectedAt: epochMillisToIso(r.latest_at),
27409
28575
  // Free text only — joined and substring-matched, so group_concat's
27410
28576
  // commas need no unpicking (a repo/path containing one still matches).
27411
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28577
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27412
28578
  // tell "no q this request" from "a group with no repo/file at all"
27413
28579
  // and skip priming a haystack nothing will read.
27414
28580
  ...withSearchText ? {
@@ -27436,7 +28602,9 @@ var SqliteFindingsRepository = class {
27436
28602
  )
27437
28603
  );
27438
28604
  for (const row of grouped) {
27439
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28605
+ if (Object.hasOwn(byAction, row.action_taken)) {
28606
+ byAction[row.action_taken] = row.c;
28607
+ }
27440
28608
  }
27441
28609
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27442
28610
  const sevRows = allRows(
@@ -27453,7 +28621,9 @@ var SqliteFindingsRepository = class {
27453
28621
  )
27454
28622
  );
27455
28623
  for (const row of sevRows) {
27456
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28624
+ if (Object.hasOwn(bySeverity, row.severity)) {
28625
+ bySeverity[row.severity] = row.c;
28626
+ }
27457
28627
  }
27458
28628
  const categories = ENFORCEABLE_CATEGORIES;
27459
28629
  const enabledRows = allRows(
@@ -27502,469 +28672,6 @@ function isoDay(ms) {
27502
28672
  return new Date(ms).toISOString().slice(0, 10);
27503
28673
  }
27504
28674
 
27505
- // ../../packages/persistence/src/repositories/history-sync.ts
27506
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27507
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27508
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27509
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27510
- var SKIPPED = -1;
27511
- var ROW_COLUMNS = `id,
27512
- parent_id AS parentId,
27513
- root_session_id AS rootSessionId,
27514
- event_type AS eventType,
27515
- host_id AS hostId,
27516
- harness_id AS harnessId,
27517
- source_project_id AS sourceProjectId,
27518
- started_at AS startedAt,
27519
- ended_at AS endedAt,
27520
- severity,
27521
- priority,
27522
- content,
27523
- content_hash AS contentHash,
27524
- attributes`;
27525
- var SqliteHistorySyncRepository = class {
27526
- constructor(db) {
27527
- this.db = db;
27528
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27529
- this.sessionsStmt = db.prepare(
27530
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27531
- FROM audit_events
27532
- WHERE synced_at IS NULL
27533
- AND event_type IN (${TYPE_LIST})
27534
- AND started_at < :before
27535
- GROUP BY sessionId
27536
- ORDER BY earliest
27537
- LIMIT :limit`
27538
- );
27539
- this.rowsStmt = db.prepare(
27540
- `SELECT ${ROW_COLUMNS}
27541
- FROM audit_events
27542
- WHERE synced_at IS NULL
27543
- AND event_type IN (${TYPE_LIST})
27544
- AND started_at < :before
27545
- AND COALESCE(root_session_id, id) = :sessionId
27546
- ORDER BY (event_type = 'session') DESC, started_at
27547
- LIMIT :limit`
27548
- );
27549
- this.captureRowsStmt = db.prepare(
27550
- `SELECT ${ROW_COLUMNS}
27551
- FROM audit_events
27552
- WHERE synced_at IS NULL
27553
- AND sync_claimed_at IS NULL
27554
- AND outbox_owed = 1
27555
- AND event_type IN (${CAPTURE_TYPE_LIST})
27556
- AND started_at < :before
27557
- ORDER BY started_at
27558
- LIMIT :limit`
27559
- );
27560
- this.markOwedStmt = db.prepare(
27561
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27562
- );
27563
- this.stampStmt = db.prepare(
27564
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27565
- );
27566
- this.claimRowStmt = db.prepare(
27567
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27568
- );
27569
- this.releaseRowStmt = db.prepare(
27570
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27571
- );
27572
- this.releaseStaleClaimsStmt = db.prepare(
27573
- `UPDATE audit_events SET sync_claimed_at = NULL
27574
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27575
- );
27576
- this.partitionStmt = db.prepare(
27577
- `SELECT
27578
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27579
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27580
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27581
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27582
- COUNT(*) AS total
27583
- FROM audit_events
27584
- WHERE event_type IN (${TYPE_LIST})`
27585
- );
27586
- this.countsStmt = db.prepare(
27587
- `SELECT
27588
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27589
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27590
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27591
- FROM audit_events
27592
- WHERE event_type IN (${TYPE_LIST})`
27593
- );
27594
- this.captureSkipCountStmt = db.prepare(
27595
- `SELECT COUNT(*) AS skipped
27596
- FROM audit_events
27597
- WHERE synced_at = ${String(SKIPPED)}
27598
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27599
- );
27600
- this.fingerprintStmt = db.prepare(
27601
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27602
- FROM history_sync WHERE id = 1`
27603
- );
27604
- this.setFingerprintStmt = db.prepare(
27605
- `UPDATE history_sync
27606
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27607
- WHERE id = 1`
27608
- );
27609
- this.disownCapturesStmt = db.prepare(
27610
- `UPDATE audit_events SET outbox_owed = NULL
27611
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27612
- );
27613
- this.rearmStmt = db.prepare(
27614
- `UPDATE audit_events SET synced_at = NULL
27615
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27616
- );
27617
- this.claimStmt = db.prepare(
27618
- `UPDATE history_sync
27619
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27620
- WHERE id = 1
27621
- AND (owner_pid IS NULL
27622
- OR heartbeat_at IS NULL
27623
- OR heartbeat_at < :staleBefore
27624
- OR heartbeat_at > :now)`
27625
- );
27626
- this.heartbeatStmt = db.prepare(
27627
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27628
- );
27629
- this.releaseStmt = db.prepare(
27630
- `UPDATE history_sync
27631
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27632
- WHERE id = 1 AND owner_pid = :pid`
27633
- );
27634
- this.closeWindowStmt = db.prepare(
27635
- `UPDATE audit_events SET synced_at = :at
27636
- WHERE synced_at IS NULL
27637
- AND event_type IN (${TYPE_LIST})
27638
- AND started_at >= :attachedAt`
27639
- );
27640
- this.releaseBoundaryStmt = db.prepare(
27641
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27642
- );
27643
- this.freezeBoundaryStmt = db.prepare(
27644
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27645
- );
27646
- this.leaseStmt = db.prepare(
27647
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27648
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27649
- FROM history_sync WHERE id = 1`
27650
- );
27651
- this.inspectionsStmt = db.prepare(
27652
- `SELECT d.rule_id AS ruleId,
27653
- d.name AS ruleName,
27654
- d.version AS ruleVersion,
27655
- d.category AS category,
27656
- d.severity AS severity,
27657
- f.span_start AS spanStart,
27658
- f.span_end AS spanEnd,
27659
- f.masked_match AS maskedMatch,
27660
- f.action_taken AS actionTaken,
27661
- f.confidence AS confidence
27662
- FROM inspection_findings f
27663
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27664
- WHERE f.audit_event_id = :auditEventId
27665
- ORDER BY f.span_start, f.id`
27666
- );
27667
- }
27668
- db;
27669
- ensureRowStmt;
27670
- sessionsStmt;
27671
- rowsStmt;
27672
- stampStmt;
27673
- countsStmt;
27674
- fingerprintStmt;
27675
- setFingerprintStmt;
27676
- rearmStmt;
27677
- claimStmt;
27678
- heartbeatStmt;
27679
- releaseStmt;
27680
- leaseStmt;
27681
- inspectionsStmt;
27682
- closeWindowStmt;
27683
- releaseBoundaryStmt;
27684
- freezeBoundaryStmt;
27685
- captureRowsStmt;
27686
- markOwedStmt;
27687
- captureSkipCountStmt;
27688
- disownCapturesStmt;
27689
- partitionStmt;
27690
- claimRowStmt;
27691
- releaseRowStmt;
27692
- releaseStaleClaimsStmt;
27693
- /**
27694
- * The masked detections recorded against one tool call.
27695
- *
27696
- * These travel with the event because a tool call's target is not
27697
- * re-inspectable from the event alone — unlike a capture, where the text
27698
- * itself is re-scannable. What crosses is the masked match and the rule that
27699
- * produced it, never the value.
27700
- */
27701
- inspectionsFor(auditEventId) {
27702
- return allRows(this.inspectionsStmt, { auditEventId });
27703
- }
27704
- /**
27705
- * Sessions with structural rows still to send, oldest first.
27706
- *
27707
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27708
- * read. Anything recorded after the machine attached is the live forward
27709
- * path's to deliver; this drain exists for what was recorded before it, and a
27710
- * row both paths send is at best a duplicate request and at worst — for a
27711
- * session root — an overwrite of the inventory ids the live path resolved.
27712
- */
27713
- pendingSessions(limit, before) {
27714
- return allRows(this.sessionsStmt, { limit, before }).map(
27715
- (r) => r.sessionId
27716
- );
27717
- }
27718
- /** One session's undelivered structural rows within the backlog, root first. */
27719
- pendingRows(sessionId, limit, before) {
27720
- return allRows(this.rowsStmt, { sessionId, limit, before });
27721
- }
27722
- /**
27723
- * Captures this machine still owes the deployment, oldest first.
27724
- *
27725
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27726
- * by a time window — see captureRowsStmt for why a window could not express
27727
- * this. `before` is the grace window that leaves a just-recorded capture to
27728
- * the live path.
27729
- */
27730
- pendingCaptureRows(limit, before) {
27731
- return allRows(this.captureRowsStmt, { limit, before });
27732
- }
27733
- /**
27734
- * Record that a capture is OWED to the deployment.
27735
- *
27736
- * Written by the attached forward path when a live send did not confirm
27737
- * delivery, and read by the drain as the whole of its eligibility test. It is
27738
- * a fact rather than an inference: the machine was attached, the send did not
27739
- * land, so the row is owed — which no time window can state, because the same
27740
- * window that holds the rows a past attachment left owed also holds every
27741
- * capture recorded while the machine was DETACHED, and those were never
27742
- * offered to anyone.
27743
- *
27744
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27745
- * out of the drain's read.
27746
- */
27747
- markCaptureOwed(id) {
27748
- this.markOwedStmt.run({ id });
27749
- }
27750
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27751
- markSynced(ids, atMs) {
27752
- this.stampAll(ids, atMs);
27753
- }
27754
- /**
27755
- * Record that a row will never be sent.
27756
- *
27757
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27758
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27759
- * is retried; marking those would turn one outage into permanent data loss.
27760
- */
27761
- markSkipped(ids) {
27762
- this.stampAll(ids, SKIPPED);
27763
- }
27764
- eachInTransaction(ids, run) {
27765
- if (ids.length === 0) return;
27766
- withTransaction(
27767
- this.db,
27768
- () => {
27769
- for (const id of ids) run(id);
27770
- },
27771
- "IMMEDIATE"
27772
- );
27773
- }
27774
- stampAll(ids, value) {
27775
- if (ids.length === 0) return;
27776
- withTransaction(
27777
- this.db,
27778
- () => {
27779
- for (const id of ids) this.stampStmt.run({ at: value, id });
27780
- },
27781
- "IMMEDIATE"
27782
- );
27783
- }
27784
- /**
27785
- * Claim rows as in-flight.
27786
- *
27787
- * Advisory in exactly the sense the lease is: it records that a send is in
27788
- * progress so a surface can say so, and a lost claim costs a row showing as
27789
- * queued while it is actually being sent. It is not exclusion — the far side
27790
- * settles a duplicate on the row id.
27791
- */
27792
- claimRows(ids, atMs) {
27793
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27794
- }
27795
- /** Give back a claim without settling — the send failed, the row is queued again. */
27796
- releaseRows(ids) {
27797
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27798
- }
27799
- /**
27800
- * Clear claims older than `staleBefore`, and report how many were cleared.
27801
- *
27802
- * A process killed between claiming and settling leaves rows claimed with
27803
- * nothing left to settle them. Without this they read as "sending" for ever.
27804
- */
27805
- releaseStaleClaims(staleBefore) {
27806
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27807
- }
27808
- /**
27809
- * Every tracked row in exactly one delivery state.
27810
- *
27811
- * Takes no boundary on purpose. The boundary answers "what should the drain
27812
- * pick up now", which is a different question from "what state is this row
27813
- * in" — and a machine that has never attached has no boundary to pass, so
27814
- * requiring one would force a caller to invent one and report the whole store
27815
- * as queued.
27816
- */
27817
- partition() {
27818
- const row = getRow(this.partitionStmt, {});
27819
- return {
27820
- queued: row?.queued ?? 0,
27821
- inProgress: row?.inProgress ?? 0,
27822
- synced: row?.synced ?? 0,
27823
- failed: row?.failed ?? 0,
27824
- total: row?.total ?? 0
27825
- };
27826
- }
27827
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27828
- counts(before) {
27829
- const row = getRow(
27830
- this.countsStmt,
27831
- { before }
27832
- );
27833
- const captures = getRow(this.captureSkipCountStmt);
27834
- return {
27835
- pending: row?.pending ?? 0,
27836
- sent: row?.sent ?? 0,
27837
- skipped: row?.skipped ?? 0,
27838
- capturesSkipped: captures?.skipped ?? 0
27839
- };
27840
- }
27841
- /**
27842
- * The deployment the current stamps were made against, and where its backlog
27843
- * ends.
27844
- *
27845
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27846
- * machine that has never drained is — and every writer below seeds the row
27847
- * before it needs one, so nothing depends on this creating it. Keeping the
27848
- * write off the gate path matters because the gate runs on every pass while a
27849
- * write has to take the database's write lock.
27850
- */
27851
- deployment() {
27852
- const row = getRow(
27853
- this.fingerprintStmt
27854
- );
27855
- return {
27856
- fingerprint: row?.fingerprint ?? void 0,
27857
- backlogBefore: row?.backlogBefore ?? void 0
27858
- };
27859
- }
27860
- /**
27861
- * Point the ledger at a different deployment, discarding what it recorded
27862
- * about the previous one.
27863
- *
27864
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
27865
- * machine has just left are undelivered as far as the new one is concerned.
27866
- * All three in one transaction, so a crash between them cannot leave stamps
27867
- * attributed to the wrong deployment, or a boundary that belongs to another.
27868
- *
27869
- * The boundary is written HERE and only here, which is what freezes it: a
27870
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
27871
- * unchanged, so this never runs and the backlog does not widen back over rows
27872
- * the live path has since delivered.
27873
- */
27874
- rearmFor(fingerprint, backlogBefore) {
27875
- this.ensureRowStmt.run();
27876
- withTransaction(
27877
- this.db,
27878
- () => {
27879
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
27880
- this.rearmStmt.run();
27881
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
27882
- this.disownCapturesStmt.run();
27883
- }
27884
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27885
- },
27886
- "IMMEDIATE"
27887
- );
27888
- }
27889
- /**
27890
- * End the attached period: hand its rows to the live path, and release the
27891
- * boundary so the next attachment can freeze a new one.
27892
- *
27893
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
27894
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
27895
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
27896
- * during the detached period, because the machine is not attached. Rows
27897
- * recorded in that window sit after the boundary and before the re-attach, so
27898
- * neither path takes them, and the pending count reports none outstanding.
27899
- *
27900
- * Stamping the attached window is not a claim that every one of those rows
27901
- * reached the deployment — the live path drops on failure and says so
27902
- * elsewhere. It records that they were ITS to deliver, which is exactly the
27903
- * status quo: they sit outside the frozen boundary today and are equally never
27904
- * re-sent. Making it explicit is what lets the boundary move.
27905
- *
27906
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
27907
- * window unstamped — that half-state would re-send the whole attached period
27908
- * on the next attach, which is the failure the boundary exists to prevent.
27909
- */
27910
- closeAttachedWindow(attachedAtMs, atMs) {
27911
- this.ensureRowStmt.run();
27912
- withTransaction(
27913
- this.db,
27914
- () => {
27915
- const row = getRow(this.fingerprintStmt);
27916
- const from = row?.backlogBefore ?? attachedAtMs;
27917
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
27918
- this.releaseBoundaryStmt.run();
27919
- },
27920
- "IMMEDIATE"
27921
- );
27922
- }
27923
- /**
27924
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
27925
- *
27926
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
27927
- * different deployment and therefore discards what was delivered to the old
27928
- * one: here the recipient is the same, so everything already sent to it stays
27929
- * sent.
27930
- */
27931
- freezeBoundary(backlogBefore) {
27932
- this.ensureRowStmt.run();
27933
- this.freezeBoundaryStmt.run({ backlogBefore });
27934
- }
27935
- /** Take the claim, or report that someone live already holds it. */
27936
- claim(pid, host, nowMs, staleAfterMs) {
27937
- this.ensureRowStmt.run();
27938
- let taken = false;
27939
- withTransaction(
27940
- this.db,
27941
- () => {
27942
- const result = this.claimStmt.run({
27943
- pid,
27944
- host,
27945
- now: nowMs,
27946
- staleBefore: nowMs - staleAfterMs
27947
- });
27948
- taken = result.changes === 1;
27949
- },
27950
- "IMMEDIATE"
27951
- );
27952
- return taken;
27953
- }
27954
- /** Say the holder is still alive. A no-op once the claim has moved on. */
27955
- heartbeat(pid, nowMs) {
27956
- this.heartbeatStmt.run({ now: nowMs, pid });
27957
- }
27958
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
27959
- release(pid) {
27960
- this.releaseStmt.run({ pid });
27961
- }
27962
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
27963
- lease() {
27964
- return getRow(this.leaseStmt);
27965
- }
27966
- };
27967
-
27968
28675
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
27969
28676
  var SqliteInspectionDefinitionsRepository = class {
27970
28677
  constructor(db) {
@@ -28352,7 +29059,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28352
29059
  }
28353
29060
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28354
29061
  }
28355
- function readManagedSettings(paths = managedSettingsPaths()) {
29062
+ var testOnlyManagedPaths = null;
29063
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28356
29064
  for (const path of paths) {
28357
29065
  let text;
28358
29066
  try {
@@ -28372,7 +29080,11 @@ function managedContextOf(managed) {
28372
29080
  return {
28373
29081
  present: true,
28374
29082
  ...managed.organization === void 0 ? {} : { organization: managed.organization },
28375
- lockedFields: managed.lockedFields
29083
+ lockedFields: managed.lockedFields,
29084
+ // The COUNT crosses to the dashboard, not the names — see ManagedContext.
29085
+ // The names remain on `managed` for any caller that wants to list them.
29086
+ ...managed.unknownLockedFields === void 0 ? {} : { unknownLockedCount: managed.unknownLockedFields.length },
29087
+ ...managed.unknownValueFields === void 0 ? {} : { unknownValueCount: managed.unknownValueFields.length }
28376
29088
  };
28377
29089
  }
28378
29090
  function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
@@ -28395,6 +29107,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28395
29107
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28396
29108
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28397
29109
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29110
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28398
29111
  if (values.vaultConsent !== void 0) {
28399
29112
  merged.vaultConsent = values.vaultConsent ? (
28400
29113
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -28447,6 +29160,9 @@ function lockableKeysTouched(current, applied) {
28447
29160
  if (changed("vaultInlineReveal")) keys.push("vaultInlineReveal");
28448
29161
  if (changed("dataSharesInPlace")) keys.push("dataSharesInPlace");
28449
29162
  if (changed("redactFallback")) keys.push("redactFallback");
29163
+ const appliedRetention = applied.bodyRetention;
29164
+ const retentionChanged = appliedRetention !== void 0 && (appliedRetention.enabled !== current.bodyRetention.enabled || appliedRetention.retainDays !== current.bodyRetention.retainDays);
29165
+ if (retentionChanged) keys.push("bodyRetention");
28450
29166
  if ("vaultConsent" in applied && isVaultConsentValid(applied.vaultConsent) !== isVaultConsentValid(current.vaultConsent)) {
28451
29167
  keys.push("vaultConsent");
28452
29168
  }
@@ -28467,6 +29183,7 @@ function pinnedKeys(managed) {
28467
29183
  if (values.modelJudgeConsent !== void 0) keys.push("modelJudgeConsent");
28468
29184
  if (values.dataSharesInPlace !== void 0) keys.push("dataSharesInPlace");
28469
29185
  if (values.redactFallback !== void 0) keys.push("redactFallback");
29186
+ if (values.bodyRetention !== void 0) keys.push("bodyRetention");
28470
29187
  return keys;
28471
29188
  }
28472
29189
  function withoutManagedKeys(applied, managed, pinned, touched) {
@@ -28484,6 +29201,7 @@ function withoutManagedKeys(applied, managed, pinned, touched) {
28484
29201
  if (strip("modelJudgeConsent")) delete out.modelJudgeConsent;
28485
29202
  if (strip("dataSharesInPlace")) delete out.dataSharesInPlace;
28486
29203
  if (strip("redactFallback")) delete out.redactFallback;
29204
+ if (strip("bodyRetention")) delete out.bodyRetention;
28487
29205
  return out;
28488
29206
  }
28489
29207
  function applyOnboarding(answers2, base = defaultDataDir(), managedOverride) {
@@ -30930,7 +31648,7 @@ function toUtcDateString(ms) {
30930
31648
  return new Date(ms).toISOString().slice(0, 10);
30931
31649
  }
30932
31650
  function isTimeseriesSeverity(s) {
30933
- return s === "critical" || s === "high" || s === "medium";
31651
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30934
31652
  }
30935
31653
  var SqliteSecurityRepository = class {
30936
31654
  constructor(db, now = () => Date.now()) {
@@ -30992,7 +31710,7 @@ var SqliteSecurityRepository = class {
30992
31710
  ELSE 0
30993
31711
  END) AS open_at_rest
30994
31712
  FROM inspection_findings f
30995
- JOIN audit_events e ON e.id = f.audit_event_id
31713
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30996
31714
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30997
31715
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30998
31716
  ON latest.finding_key = f.finding_key
@@ -31059,12 +31777,16 @@ var SqliteSecurityRepository = class {
31059
31777
  const now = this.now();
31060
31778
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
31061
31779
  const rows = this.findingsInRange(windowStart, now);
31062
- const points = Array.from({ length: numBuckets }, (_, i) => ({
31063
- timestamp: toUtcDateString(windowStart + i * bucketMs),
31064
- critical: 0,
31065
- high: 0,
31066
- medium: 0
31067
- }));
31780
+ const points = Array.from(
31781
+ { length: numBuckets },
31782
+ (_, i) => ({
31783
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31784
+ critical: 0,
31785
+ high: 0,
31786
+ medium: 0,
31787
+ low: 0
31788
+ })
31789
+ );
31068
31790
  for (const r of rows) {
31069
31791
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
31070
31792
  const bucket = points[idx];
@@ -31214,7 +31936,7 @@ var SqliteSecurityRepository = class {
31214
31936
  this.db.prepare(
31215
31937
  `SELECT e.repo AS repo, count(*) AS c
31216
31938
  FROM inspection_findings f
31217
- JOIN audit_events e ON e.id = f.audit_event_id
31939
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31218
31940
  WHERE e.started_at >= :from AND e.started_at < :to
31219
31941
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31220
31942
  AND e.repo IS NOT NULL
@@ -31282,6 +32004,7 @@ var SqliteSecurityRepository = class {
31282
32004
  `SELECT f.finding_key AS finding_key,
31283
32005
  d.rule_id AS rule_id,
31284
32006
  d.severity AS severity,
32007
+ e.repo AS repo,
31285
32008
  e.file_path AS path,
31286
32009
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31287
32010
  latest.resolved_at AS latest_resolved_at
@@ -31301,6 +32024,7 @@ var SqliteSecurityRepository = class {
31301
32024
  const items = rows.map((r) => ({
31302
32025
  findingKey: r.finding_key,
31303
32026
  ruleId: r.rule_id,
32027
+ repo: r.repo ?? "",
31304
32028
  severity: r.severity,
31305
32029
  path: r.path ?? "",
31306
32030
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31310,15 +32034,68 @@ var SqliteSecurityRepository = class {
31310
32034
  }));
31311
32035
  return Promise.resolve({ items });
31312
32036
  }
32037
+ /**
32038
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
32039
+ *
32040
+ * Scoped by status rather than by time, because the card this feeds is a to-do
32041
+ * list: a secret committed three weeks ago and never rotated is still the most
32042
+ * important thing to fix, and any window hides it. It carried a "newest N
32043
+ * findings" cap and then a range; the first meant a different span on every
32044
+ * machine, and the second reported "no recommendations" over live exposure.
32045
+ *
32046
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
32047
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
32048
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
32049
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
32050
+ * The two answer different questions and only this one has to match a link.
32051
+ *
32052
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
32053
+ * whole-store scope costs a grouped scan rather than a row per finding.
32054
+ */
32055
+ recommendationInputs() {
32056
+ const rows = allRows(
32057
+ this.db.prepare(
32058
+ `SELECT d.rule_id AS rule_id,
32059
+ d.category AS category,
32060
+ d.severity AS severity,
32061
+ COUNT(*) AS count
32062
+ FROM inspection_findings f
32063
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
32064
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
32065
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
32066
+ ON latest.finding_key = f.finding_key
32067
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
32068
+ AND e.event_type = 'code_change'
32069
+ AND (
32070
+ f.finding_key IS NULL
32071
+ OR latest.status IS NULL
32072
+ OR latest.status NOT IN ('resolved', 'dismissed')
32073
+ )
32074
+ GROUP BY d.rule_id, d.category, d.severity`
32075
+ )
32076
+ );
32077
+ return Promise.resolve(
32078
+ rows.map((r) => ({
32079
+ ruleId: r.rule_id,
32080
+ category: r.category,
32081
+ severity: r.severity,
32082
+ count: r.count
32083
+ }))
32084
+ );
32085
+ }
31313
32086
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31314
32087
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31315
32088
  // numeric and the JS aggregations bucket/split on ms directly.
31316
32089
  findingsInRange(fromMs, toMs) {
31317
32090
  const rows = allRows(
31318
32091
  this.db.prepare(
31319
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
32092
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
32093
+ // joined for `severity`, so they are two more columns off a row this read
32094
+ // already fetches. They feed the recommended-actions rollup.
32095
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
32096
+ d.rule_id AS rule_id, d.category AS category
31320
32097
  FROM inspection_findings f
31321
- JOIN audit_events e ON e.id = f.audit_event_id
32098
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31322
32099
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31323
32100
  WHERE e.started_at >= :from AND e.started_at < :to
31324
32101
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31329,7 +32106,9 @@ var SqliteSecurityRepository = class {
31329
32106
  return rows.map((r) => ({
31330
32107
  occurredAt: r.occurred_at,
31331
32108
  severity: r.severity,
31332
- actionTaken: r.action_taken
32109
+ actionTaken: r.action_taken,
32110
+ ruleId: r.rule_id,
32111
+ category: r.category
31333
32112
  }));
31334
32113
  }
31335
32114
  };
@@ -32157,6 +32936,7 @@ function openWithPragmas(file2) {
32157
32936
  db.exec("PRAGMA journal_mode = WAL");
32158
32937
  db.exec("PRAGMA busy_timeout = 2000");
32159
32938
  db.exec("PRAGMA foreign_keys = ON");
32939
+ registerSqlFunctions(db);
32160
32940
  } catch (err) {
32161
32941
  closeQuietly(db);
32162
32942
  throw err;
@@ -32186,7 +32966,7 @@ function backupLegacyStore(db, file2) {
32186
32966
  discardStore(file2, backup);
32187
32967
  return backup;
32188
32968
  }
32189
- function openAndInitialize(file2, base) {
32969
+ function openAndInitialize(file2, base, skipTags) {
32190
32970
  let db = openWithPragmas(file2);
32191
32971
  try {
32192
32972
  if (isForeignSqliteLineage(db)) {
@@ -32196,7 +32976,7 @@ function openAndInitialize(file2, base) {
32196
32976
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32197
32977
  );
32198
32978
  }
32199
- applyMigrations(db, file2);
32979
+ applyMigrations(db, file2, { skipTags });
32200
32980
  tightenPerms(file2);
32201
32981
  const policies = new SqlitePoliciesRepository(db);
32202
32982
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32211,6 +32991,7 @@ function openAndInitialize(file2, base) {
32211
32991
  exceptions: new SqliteExceptionsRepository(db),
32212
32992
  resolutions: new SqliteResolutionsRepository(db),
32213
32993
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32994
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32214
32995
  security: new SqliteSecurityRepository(db),
32215
32996
  detections: new SqliteDetectionsRepository(db),
32216
32997
  shares: new SqliteSharesRepository(db),
@@ -32233,7 +33014,8 @@ function openAndInitialize(file2, base) {
32233
33014
  throw err;
32234
33015
  }
32235
33016
  }
32236
- function openLocalDatabase(dir) {
33017
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
33018
+ function openLocalDatabase(dir, options = {}) {
32237
33019
  ensureDataDirSync(dir);
32238
33020
  const file2 = join7(dir, DB_FILENAME);
32239
33021
  reapStalePartials(file2);
@@ -32245,6 +33027,7 @@ function openLocalDatabase(dir) {
32245
33027
  installedPacks,
32246
33028
  scanLedger,
32247
33029
  historySync,
33030
+ bodyRetention,
32248
33031
  secretVault,
32249
33032
  exceptions,
32250
33033
  resolutions,
@@ -32268,7 +33051,8 @@ function openLocalDatabase(dir) {
32268
33051
  // `dir` is always `<base>/data` — every caller resolves it through
32269
33052
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32270
33053
  // settings/ and data/, and the pack-policy floor needs both halves.
32271
- dirname2(dir)
33054
+ dirname2(dir),
33055
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32272
33056
  );
32273
33057
  function captureRowId(event) {
32274
33058
  return captureId(
@@ -32461,6 +33245,7 @@ function openLocalDatabase(dir) {
32461
33245
  installedPacks,
32462
33246
  scanLedger,
32463
33247
  historySync,
33248
+ bodyRetention,
32464
33249
  secretVault,
32465
33250
  exceptions,
32466
33251
  resolutions,
@@ -32499,8 +33284,12 @@ function openLocalDatabase(dir) {
32499
33284
  };
32500
33285
  }
32501
33286
 
32502
- // ../../packages/persistence/src/finding-key.ts
33287
+ // ../../packages/persistence/src/egress-wire.ts
32503
33288
  import { createHash as createHash3 } from "crypto";
33289
+ var SLASH = "/".charCodeAt(0);
33290
+
33291
+ // ../../packages/persistence/src/finding-key.ts
33292
+ import { createHash as createHash4 } from "crypto";
32504
33293
 
32505
33294
  // ../../packages/persistence/src/fingerprint.ts
32506
33295
  import { createHmac, randomBytes } from "crypto";
@@ -32508,14 +33297,26 @@ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32508
33297
  import { join as join8 } from "path";
32509
33298
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
32510
33299
 
32511
- // ../../packages/persistence/src/history-preview.ts
32512
- import { existsSync as existsSync4 } from "fs";
33300
+ // ../../packages/persistence/src/forward-health.ts
33301
+ import { readFileSync as readFileSync7 } from "fs";
32513
33302
  import { join as join9 } from "path";
33303
+
33304
+ // ../../packages/persistence/src/history-backfill.ts
33305
+ import { existsSync as existsSync4 } from "fs";
33306
+ import { join as join10 } from "path";
33307
+
33308
+ // ../../packages/persistence/src/history-preview.ts
33309
+ import { existsSync as existsSync5 } from "fs";
33310
+ import { join as join11 } from "path";
32514
33311
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32515
33312
 
33313
+ // ../../packages/persistence/src/history-sync-state.ts
33314
+ import { readFileSync as readFileSync8 } from "fs";
33315
+ import { join as join12 } from "path";
33316
+
32516
33317
  // ../../packages/persistence/src/store-symlinks.ts
32517
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32518
- import { dirname as dirname3, join as join10, resolve } from "path";
33318
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33319
+ import { dirname as dirname3, join as join13, resolve } from "path";
32519
33320
 
32520
33321
  // ../../packages/persistence/src/vault/crypto.ts
32521
33322
  import {
@@ -32529,20 +33330,20 @@ import {
32529
33330
  // ../../packages/persistence/src/vault/key-provider.ts
32530
33331
  import { execFileSync } from "child_process";
32531
33332
  import { randomBytes as randomBytes2 } from "crypto";
32532
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32533
- import { join as join11 } from "path";
33333
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33334
+ import { join as join14 } from "path";
32534
33335
 
32535
33336
  // ../../packages/persistence/src/vault/vault.ts
32536
33337
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32537
33338
 
32538
33339
  // ../../packages/persistence/src/warn-era-cap.ts
32539
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32540
- import { join as join12 } from "path";
33340
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33341
+ import { join as join15 } from "path";
32541
33342
  var MARKER = "warn-era-capped";
32542
33343
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32543
33344
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32544
- const marker = join12(dataDir2, MARKER);
32545
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33345
+ const marker = join15(dataDir2, MARKER);
33346
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32546
33347
  const capped = db.policies.capCategoryActions();
32547
33348
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32548
33349
  `, { mode: DATA_FILE_MODE });
@@ -32550,8 +33351,8 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32550
33351
  }
32551
33352
 
32552
33353
  // ../../packages/plugin-sdk/src/config.ts
32553
- import { existsSync as existsSync7 } from "fs";
32554
- import { join as join13 } from "path";
33354
+ import { existsSync as existsSync8 } from "fs";
33355
+ import { join as join16 } from "path";
32555
33356
 
32556
33357
  // ../../packages/plugin-sdk/src/provider-env.ts
32557
33358
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -32605,8 +33406,8 @@ function resolveProvider() {
32605
33406
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32606
33407
  try {
32607
33408
  ensureLayoutDirSync(base);
32608
- const settingsFile = join13(settingsDir(base), "settings.json");
32609
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33409
+ const settingsFile = join16(settingsDir(base), "settings.json");
33410
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
32610
33411
  } catch {
32611
33412
  }
32612
33413
  migrateLegacyLayout(base);
@@ -32629,9 +33430,9 @@ function resolveProviderSafe(resolveProviderFn) {
32629
33430
  }
32630
33431
 
32631
33432
  // ../../packages/plugin-sdk/src/config-inventory.ts
32632
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33433
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32633
33434
  import { homedir as homedir2 } from "os";
32634
- import { basename as basename3, join as join15 } from "path";
33435
+ import { basename as basename3, join as join18 } from "path";
32635
33436
 
32636
33437
  // ../../packages/detections/src/egress/registry.ts
32637
33438
  var EXTRACTOR_VERSION = "1";
@@ -33389,24 +34190,20 @@ var CPU_CORROBORATION_SHARE = 0.2;
33389
34190
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
33390
34191
 
33391
34192
  // ../../packages/plugin-sdk/src/repo.ts
33392
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
33393
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
34193
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
34194
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
33394
34195
 
33395
34196
  // ../../packages/plugin-sdk/src/events.ts
33396
- import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
34197
+ import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
33397
34198
 
33398
34199
  // ../../packages/plugin-sdk/src/isolated-scan.ts
33399
- import { existsSync as existsSync9 } from "fs";
34200
+ import { existsSync as existsSync10 } from "fs";
33400
34201
  import { fileURLToPath } from "url";
33401
34202
  import { Worker } from "worker_threads";
33402
34203
 
33403
- // ../../packages/plugin-sdk/src/ignore-layers.ts
33404
- var import_ignore = __toESM(require_ignore(), 1);
33405
- import { readFileSync as readFileSync10 } from "fs";
33406
- import { join as join16 } from "path";
33407
-
33408
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
33409
- import { arch, hostname as hostname4, platform, release as release2 } from "os";
34204
+ // ../../packages/plugin-sdk/src/host-floor.ts
34205
+ import { readFileSync as readFileSync13 } from "fs";
34206
+ import { join as join20 } from "path";
33410
34207
 
33411
34208
  // ../../packages/plugin-sdk/src/model-governance.ts
33412
34209
  import {
@@ -33414,16 +34211,42 @@ import {
33414
34211
  fstatSync,
33415
34212
  mkdirSync as mkdirSync2,
33416
34213
  openSync as openSync2,
33417
- readFileSync as readFileSync11,
34214
+ readFileSync as readFileSync12,
33418
34215
  readSync,
33419
34216
  writeFileSync as writeFileSync5
33420
34217
  } from "fs";
33421
- import { join as join17 } from "path";
34218
+ import { join as join19 } from "path";
33422
34219
  var TAIL_BYTES = 256 * 1024;
33423
34220
 
34221
+ // ../../packages/plugin-sdk/src/host-floor.ts
34222
+ var HOST_FEATURE = {
34223
+ ModelSwitch: "model-switch",
34224
+ VaultPointerDisplay: "vault-pointer-display"
34225
+ };
34226
+ var HOST_FLOORS = {
34227
+ [HOST_FEATURE.ModelSwitch]: {
34228
+ label: "model-switch protection",
34229
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
34230
+ since: "2.1.251"
34231
+ },
34232
+ [HOST_FEATURE.VaultPointerDisplay]: {
34233
+ label: "vault pointer display",
34234
+ hookEvents: ["MessageDisplay"],
34235
+ since: "2.1.152"
34236
+ }
34237
+ };
34238
+
34239
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
34240
+ var import_ignore = __toESM(require_ignore(), 1);
34241
+ import { readFileSync as readFileSync14 } from "fs";
34242
+ import { join as join21 } from "path";
34243
+
34244
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
34245
+ import { arch, hostname as hostname4, platform, release as release2 } from "os";
34246
+
33424
34247
  // ../../packages/plugin-sdk/src/nudge.ts
33425
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
33426
- import { join as join18 } from "path";
34248
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
34249
+ import { join as join22 } from "path";
33427
34250
 
33428
34251
  // ../../packages/plugin-sdk/src/paths.ts
33429
34252
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -33440,8 +34263,8 @@ function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
33440
34263
  }
33441
34264
 
33442
34265
  // ../../packages/plugin-sdk/src/project-files.ts
33443
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
33444
- import { basename as basename5, join as join19 } from "path";
34266
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
34267
+ import { basename as basename5, join as join23 } from "path";
33445
34268
 
33446
34269
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
33447
34270
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -33477,7 +34300,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
33477
34300
 
33478
34301
  // ../../packages/plugin-sdk/src/throttle.ts
33479
34302
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
33480
- import { join as join20 } from "path";
34303
+ import { join as join24 } from "path";
33481
34304
 
33482
34305
  // ../../packages/setup-wizard/src/onboard-posture.ts
33483
34306
  function parsePosture(json2) {
@@ -33500,7 +34323,7 @@ function parsePosture(json2) {
33500
34323
 
33501
34324
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
33502
34325
  import { writeFileSync as writeFileSync8 } from "fs";
33503
- import { join as join21 } from "path";
34326
+ import { join as join25 } from "path";
33504
34327
 
33505
34328
  // ../../packages/setup-wizard/src/triage/merge.ts
33506
34329
  var RANK = Object.fromEntries(
@@ -33508,9 +34331,9 @@ var RANK = Object.fromEntries(
33508
34331
  );
33509
34332
 
33510
34333
  // ../../packages/setup-wizard/src/triage/plan-file.ts
33511
- import { mkdtempSync, readFileSync as readFileSync13, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
34334
+ import { mkdtempSync, readFileSync as readFileSync16, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
33512
34335
  import { tmpdir } from "os";
33513
- import { basename as basename6, dirname as dirname6, join as join22 } from "path";
34336
+ import { basename as basename6, dirname as dirname6, join as join26 } from "path";
33514
34337
  var SuppressionEntrySchema = external_exports.object({
33515
34338
  ruleId: external_exports.string(),
33516
34339
  category: DetectionCategory,