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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,8 +492,8 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync7 } from "fs";
496
- import { join as join13 } from "path";
495
+ import { existsSync as existsSync8 } from "fs";
496
+ import { join as join16 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20670,6 +20702,15 @@ var FindingCategory = external_exports.enum([
20670
20702
  ]).meta({ id: "FindingCategory" });
20671
20703
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20672
20704
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20705
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20706
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20707
+ var FindingDelivery = external_exports.object({
20708
+ state: FindingDeliveryState,
20709
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20710
+ at: external_exports.iso.datetime().optional(),
20711
+ // Only on `not_sent`, and only when a known reason was recorded.
20712
+ reason: SyncFailureReason.optional()
20713
+ }).meta({ id: "FindingDelivery" });
20673
20714
  var ResolutionMethod = external_exports.enum([
20674
20715
  "enforced-in-flight",
20675
20716
  "fixed-at-source",
@@ -20726,7 +20767,10 @@ var FindingInstance = external_exports.object({
20726
20767
  // The session that event belongs to, when it has one — the seam a
20727
20768
  // per-instance "view session" link needs. Absent for events captured
20728
20769
  // outside a session.
20729
- sessionId: external_exports.string().optional()
20770
+ sessionId: external_exports.string().optional(),
20771
+ // The delivery state of the event above (see FindingDelivery). Optional so
20772
+ // readers that do not project it stay valid.
20773
+ delivery: FindingDelivery.optional()
20730
20774
  }).meta({ id: "FindingInstance" });
20731
20775
  var FindingGroup = external_exports.object({
20732
20776
  id: external_exports.string(),
@@ -20743,13 +20787,11 @@ var FindingGroup = external_exports.object({
20743
20787
  latestDetectedAt: external_exports.iso.datetime(),
20744
20788
  instances: external_exports.array(FindingInstance),
20745
20789
  // Derived from instances' statuses with open-dominates precedence (see
20746
- // buildFindingGroups). Undefined only when no instance carries a status.
20790
+ // foldGroupStatus). Undefined only when no instance carries a status.
20747
20791
  status: FindingStatus.optional(),
20748
- // The distinct people across the WHOLE group, not just the `instances`
20749
- // preview — from the store's whole-group aggregate when it supplies one,
20750
- // else folded from the rows (see buildFindingGroups). Undefined when no
20751
- // instance carries a user, or when the store supplied whole-group folds
20752
- // without one.
20792
+ // The distinct people across the WHOLE group, not just the instances
20793
+ // carried here. Undefined when no instance carries a user, or when the
20794
+ // store supplied whole-group folds without one.
20753
20795
  users: external_exports.array(FindingUser).optional()
20754
20796
  }).meta({ id: "FindingGroup" });
20755
20797
  var FindingStats = external_exports.object({
@@ -20778,21 +20820,34 @@ var FindingFacets = external_exports.object({
20778
20820
  // counted under no value.
20779
20821
  status: external_exports.array(FindingFacetItem),
20780
20822
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
- // reads, which can filter by it; the grouped read omits the dimension
20823
+ // reads, which can filter by it; the type-level read omits the dimension
20782
20824
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20825
+ tool: external_exports.array(FindingFacetItem).optional(),
20826
+ // Delivery states (FindingDeliveryState). Present only on the
20827
+ // instance-level reads, like `tool`.
20828
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20829
  }).meta({ id: "FindingFacets" });
20785
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20786
- var ListGroupedFindingsQuery = external_exports.object({
20830
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20831
+ id: "FindingTypeSummary"
20832
+ });
20833
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20834
+ var MAX_FINDING_TYPES_LIMIT = 100;
20835
+ var ListFindingTypesQuery = external_exports.object({
20787
20836
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20788
- // FindingAction.
20837
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20838
+ // firing version carries, and this list pages types.
20839
+ //
20840
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20841
+ // definition versions at different severities, so a type kept by this filter
20842
+ // can hold findings that individually do not match — see totals.findings on
20843
+ // ListFindingTypesResponse, which counts them all.
20789
20844
  severity: external_exports.array(Severity).optional(),
20790
20845
  subtype: external_exports.array(external_exports.string()).optional(),
20791
20846
  provider: external_exports.array(FindingProvider).optional(),
20792
20847
  action: external_exports.array(FindingAction).optional(),
20793
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20794
- // individual instances' — so a filtered group's Status column always reads
20795
- // one of the requested values.
20848
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20849
+ // individual findings' — so a filtered row's status always reads one of the
20850
+ // requested values.
20796
20851
  status: external_exports.array(FindingStatus).optional(),
20797
20852
  q: external_exports.string().optional(),
20798
20853
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20802,23 +20857,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20802
20857
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20803
20858
  // means all time — this list has no default window.
20804
20859
  from: external_exports.iso.datetime().optional(),
20805
- // A group or instance id that must appear in the page even when the cursor
20806
- // has already advanced past its sort position. This is what keeps the
20807
- // Findings page's one-shot ?finding= deep link resolving once the list
20808
- // paginates: the target group is appended out of sort order rather than
20809
- // scanning forward for it. Never affects totals, facets or the cursor.
20860
+ // A RULE id that must appear in the page even when the cursor has already
20861
+ // advanced past its sort position. This is what keeps the selected type
20862
+ // visible in the list once it paginates: the target is appended out of sort
20863
+ // order rather than scanned forward for. Never affects totals, facets or the
20864
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20865
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20866
+ // and so is not bounded by what any page happens to hold.
20810
20867
  includeId: external_exports.string().optional(),
20811
- groupBy: external_exports.literal("type").optional(),
20812
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20868
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20813
20869
  cursor: external_exports.string().optional()
20814
20870
  });
20815
- var ListGroupedFindingsResponse = external_exports.object({
20871
+ var ListFindingTypesResponse = external_exports.object({
20816
20872
  totals: external_exports.object({
20873
+ // Findings belonging to the matching TYPES — not findings that each match
20874
+ // the filters. The filters here select types, so a type that survives
20875
+ // contributes its whole instanceCount.
20876
+ //
20877
+ // `status` is the one exception, narrowed per finding via
20878
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20879
+ // this can exceed what the instance read reports for the same filters: a
20880
+ // rule whose severity moved between versions is kept on its newest and
20881
+ // still counts its older findings. Narrowing the other three needs
20882
+ // per-dimension counts the aggregate does not carry today.
20817
20883
  findings: external_exports.number().int().nonnegative(),
20818
- groups: external_exports.number().int().nonnegative()
20884
+ // Counts TYPES, which is the unit this read pages. The instance read's
20885
+ // own totals count findings; the two deliberately answer different
20886
+ // questions and are never summed.
20887
+ types: external_exports.number().int().nonnegative()
20819
20888
  }),
20820
20889
  facets: FindingFacets,
20821
- items: external_exports.array(FindingGroup),
20890
+ items: external_exports.array(FindingTypeSummary),
20822
20891
  nextCursor: external_exports.string().nullable(),
20823
20892
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20824
20893
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20826,7 +20895,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20826
20895
  // every firing, so the two numbers legitimately differ — this map lets a
20827
20896
  // session-scoped view show both.
20828
20897
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20829
- }).meta({ id: "ListGroupedFindingsResponse" });
20898
+ }).meta({ id: "ListFindingTypesResponse" });
20830
20899
  var ApplyFindingActionRequest = external_exports.object({
20831
20900
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20832
20901
  // it, so it is excluded from the request contract. The mapping helper
@@ -20856,16 +20925,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20856
20925
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20857
20926
  var ListFindingInstancesQuery = external_exports.object({
20858
20927
  severity: external_exports.array(Severity).optional(),
20859
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20928
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20929
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20860
20930
  subtype: external_exports.array(external_exports.string()).optional(),
20861
20931
  provider: external_exports.array(FindingProvider).optional(),
20862
20932
  action: external_exports.array(FindingAction).optional(),
20863
20933
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20864
- // the grouped query's group-level fold.
20934
+ // the types query's type-level fold.
20865
20935
  status: external_exports.array(FindingStatus).optional(),
20866
20936
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20867
20937
  // where the free-text `q` can only match the rendered "via Bash" label.
20868
20938
  tool: external_exports.array(external_exports.string()).optional(),
20939
+ // The delivery state of each finding's event (see FindingDelivery).
20940
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20869
20941
  // Exact repository / file-path matches, for the drill-down out of the
20870
20942
  // locations view. A row whose event carries no repo/file matches neither.
20871
20943
  repo: external_exports.string().optional(),
@@ -20878,37 +20950,51 @@ var ListFindingInstancesQuery = external_exports.object({
20878
20950
  });
20879
20951
  var ListFindingInstancesResponse = external_exports.object({
20880
20952
  // Instances matching the filters across the whole scope, not just this
20881
- // page — cursor-independent, like the grouped list's totals.
20953
+ // page — cursor-independent, like the types list's totals.
20882
20954
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20883
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20955
+ // Counts in INSTANCES here, where the types response counts types. Each
20884
20956
  // dimension still excludes its own filter.
20885
20957
  facets: FindingFacets,
20886
20958
  items: external_exports.array(FindingInstanceDetail),
20887
20959
  nextCursor: external_exports.string().nullable()
20888
20960
  }).meta({ id: "ListFindingInstancesResponse" });
20889
- var FindingLocationFile = external_exports.object({
20890
- // Empty when the instances carried no file path (a prompt or a tool call
20891
- // with no file attribution).
20892
- file: external_exports.string(),
20893
- instanceCount: external_exports.number().int().nonnegative(),
20894
- maxSeverity: Severity,
20895
- latestDetectedAt: external_exports.iso.datetime(),
20896
- // Folded from the instances' derived statuses with the same
20897
- // open-dominates precedence a group uses.
20898
- status: FindingStatus.optional(),
20899
- // Distinct rules seen at this location, capped — the row shows them as
20900
- // chips, and the count is what conveys scale.
20901
- ruleIds: external_exports.array(external_exports.string())
20902
- }).meta({ id: "FindingLocationFile" });
20903
- var FindingLocationRepo = external_exports.object({
20961
+ var ListFindingInstancesPage = external_exports.object({
20962
+ items: external_exports.array(FindingInstanceDetail),
20963
+ nextCursor: external_exports.string().nullable()
20964
+ }).meta({ id: "ListFindingInstancesPage" });
20965
+ var FindingLocationSummary = external_exports.object({
20966
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20967
+ // because a location's identity is two values and a URL param carries one:
20968
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20969
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20970
+ // client's page dedupe — never decoded, and never a sort key.
20971
+ id: external_exports.string(),
20904
20972
  /** Empty when the instances carried no repo attribute. */
20905
20973
  repo: external_exports.string(),
20974
+ // Empty when the instances carried no file path (a prompt, or a tool call
20975
+ // with no file attribution). Both halves empty is a real location — usually
20976
+ // the largest one in a store — and is selectable like any other.
20977
+ file: external_exports.string(),
20906
20978
  instanceCount: external_exports.number().int().nonnegative(),
20979
+ // The WORST severity present, not the first row's. It is this list's primary
20980
+ // sort key, so it is also what explains why a row is where it is, and it is
20981
+ // how a reader decides what to open without opening everything.
20907
20982
  maxSeverity: Severity,
20908
20983
  latestDetectedAt: external_exports.iso.datetime(),
20984
+ // Folded from the instances' derived statuses with the same open-dominates
20985
+ // precedence a group uses, so it answers "is anything left to do here" and
20986
+ // not much more: a location holding 1 open among 40 resolved reads like one
20987
+ // holding 40 open. That loss is accepted — the panel beside this list
20988
+ // carries each finding's own status, and instanceCount sits next to the
20989
+ // badge.
20909
20990
  status: FindingStatus.optional(),
20910
- files: external_exports.array(FindingLocationFile)
20911
- }).meta({ id: "FindingLocationRepo" });
20991
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20992
+ // tally rather than a sample and a row can say how many there are. Bounded
20993
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20994
+ ruleIds: external_exports.array(external_exports.string())
20995
+ }).meta({ id: "FindingLocationSummary" });
20996
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20997
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20912
20998
  var ListFindingLocationsQuery = external_exports.object({
20913
20999
  severity: external_exports.array(Severity).optional(),
20914
21000
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20918,21 +21004,47 @@ var ListFindingLocationsQuery = external_exports.object({
20918
21004
  // instances that match, and folds its status from those.
20919
21005
  status: external_exports.array(FindingStatus).optional(),
20920
21006
  tool: external_exports.array(external_exports.string()).optional(),
21007
+ // The delivery state of each finding's event (see FindingDelivery).
21008
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20921
21009
  q: external_exports.string().optional(),
20922
21010
  sessionId: external_exports.string().optional(),
20923
21011
  from: external_exports.iso.datetime().optional(),
20924
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21012
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21013
+ // even when the cursor has already advanced past its sort position — the
21014
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21015
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21016
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21017
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21018
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21019
+ includeId: external_exports.string().optional(),
21020
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21021
+ cursor: external_exports.string().optional()
20925
21022
  });
20926
21023
  var ListFindingLocationsResponse = external_exports.object({
20927
21024
  totals: external_exports.object({
21025
+ // Findings matching the filters across the whole scope. Unlike the types
21026
+ // read's same-named field this needs no caveat: the filters here narrow
21027
+ // per finding, so this is the sum of every row's instanceCount.
20928
21028
  findings: external_exports.number().int().nonnegative(),
20929
- repos: external_exports.number().int().nonnegative(),
20930
- files: external_exports.number().int().nonnegative()
21029
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21030
+ // states. The facets beside it count FINDINGS (see below); a surface
21031
+ // showing both says which is which.
21032
+ locations: external_exports.number().int().nonnegative()
20931
21033
  }),
20932
- /** Sorted by max severity, then most recent. */
20933
- items: external_exports.array(FindingLocationRepo),
20934
- /** Whether `limit` truncated the repo list. */
20935
- hasMore: external_exports.boolean()
21034
+ // Counts in FINDINGS, where the types response counts types, each dimension
21035
+ // still excluding its own filter. Deliberately not locations: counting those
21036
+ // needs a set of location keys per dimension per value — memory tracking the
21037
+ // store times the vocabulary, in a read whose scan promises flat memory —
21038
+ // and the cheap per-location version is not an approximation but WRONG. A
21039
+ // location holding {claudecode, block} and {codex, warn} would survive
21040
+ // provider=claudecode AND action=warn, under which no single finding
21041
+ // matches, so the facet would contradict the instanceCount this whole view
21042
+ // rests on. Findings also keep the toolbar in the same unit as the page
21043
+ // tally and the panel it sits above.
21044
+ facets: FindingFacets,
21045
+ /** Sorted by max severity, then most recent, then (repo, file). */
21046
+ items: external_exports.array(FindingLocationSummary),
21047
+ nextCursor: external_exports.string().nullable()
20936
21048
  }).meta({ id: "ListFindingLocationsResponse" });
20937
21049
 
20938
21050
  // ../../packages/schema/src/zod/meta.ts
@@ -21096,6 +21208,10 @@ var CaptureAttributes = external_exports.object({
21096
21208
  // to 'allow' — the enforcement audit trail's link back to the grant that
21097
21209
  // authorized the bypass.
21098
21210
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21211
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21212
+ // join back to the `llm_call` leaf for the same assistant turn.
21213
+ message_id: external_exports.string().optional(),
21214
+ conversation_id: external_exports.string().optional(),
21099
21215
  // Whole milliseconds this capture's inspection blocked its caller — the
21100
21216
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21101
21217
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21104,7 +21220,19 @@ var CaptureAttributes = external_exports.object({
21104
21220
  // inline json_extract and is not itself an optimization.
21105
21221
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21106
21222
  // before the measurement shipped — never present as a placeholder 0.
21107
- inspection_ms: external_exports.number().int().nonnegative().optional()
21223
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21224
+ // What a `redact` this capture could not carry out became instead (see
21225
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21226
+ // degrade actually happened, so absence is the ordinary case rather than a
21227
+ // reader having to distinguish it from a zero.
21228
+ //
21229
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21230
+ // so on a multi-finding row this does not say which finding degraded, and
21231
+ // its presence does not mean the fallback decided the capture's action. A
21232
+ // capture denied by another finding's own Block policy carries `block`
21233
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21234
+ // repeated rather than referenced because a store reader opens this file.
21235
+ redact_degraded_to: ActionTaken.optional()
21108
21236
  }).catchall(external_exports.unknown());
21109
21237
  var ToolCallInspection = external_exports.object({
21110
21238
  ruleId: external_exports.string().min(1),
@@ -21303,7 +21431,17 @@ var AuditEvent = external_exports.object({
21303
21431
  /** `share` to a first-party/internal destination. */
21304
21432
  internal: external_exports.boolean(),
21305
21433
  /** Event needs review (e.g. unverified egress). */
21306
- flagged: external_exports.boolean()
21434
+ flagged: external_exports.boolean(),
21435
+ /**
21436
+ * The body this event's `title` is drawn from was cleared by local body
21437
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21438
+ *
21439
+ * A separate flag rather than a sentinel written into `title`: the title is
21440
+ * rendered text, and a store-layer module that invented display copy for it
21441
+ * would be choosing words the view is supposed to choose. Additive and
21442
+ * defaulted, so an older producer still validates.
21443
+ */
21444
+ bodyExpired: external_exports.boolean().default(false)
21307
21445
  }).meta({ id: "ActivityAuditEvent" });
21308
21446
  var ActivitySessionSummary = external_exports.object({
21309
21447
  id: external_exports.string(),
@@ -22101,6 +22239,14 @@ var ControlPlaneErrorBody = external_exports.object({
22101
22239
  message: external_exports.string().optional()
22102
22240
  }).optional()
22103
22241
  });
22242
+ var RemoteFailureKind = external_exports.enum([
22243
+ "unauthorized",
22244
+ "forbidden",
22245
+ "route-absent",
22246
+ "invalid-request",
22247
+ "rejected",
22248
+ "unreachable"
22249
+ ]);
22104
22250
  var AttachDeviceRequest = external_exports.object({
22105
22251
  // This machine's own continuity id, so re-attaching ROTATES the credential
22106
22252
  // on one machine record instead of producing a second one. Client-minted
@@ -22636,6 +22782,12 @@ var EventMetadata = external_exports.object({
22636
22782
  // to 'allow' — the enforcement audit trail's link back to the grant that
22637
22783
  // authorized the bypass. Absent on captures where no exception applied.
22638
22784
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22785
+ // The assistant message this capture belongs to, and the conversation it sits
22786
+ // in — set by the browser extension's network capture so a stored `response`
22787
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22788
+ // on every other capture path, which has no such id.
22789
+ messageId: external_exports.string().optional(),
22790
+ conversationId: external_exports.string().optional(),
22639
22791
  // How long THIS capture's inspection blocked its caller, in whole
22640
22792
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22641
22793
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22648,7 +22800,37 @@ var EventMetadata = external_exports.object({
22648
22800
  // Absent is also what every pre-measurement client writes, and what a
22649
22801
  // clock failure degrades to — a reader must treat absence as "not measured"
22650
22802
  // and never as a zero, which would read as "inspection is free".
22651
- inspectionMs: external_exports.number().int().nonnegative().optional()
22803
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22804
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22805
+ // workspace's `redactFallback`, applied because the field could not be
22806
+ // masked in place (a shell command, a URL, or any argument on a host whose
22807
+ // hook contract offers no rewrite channel).
22808
+ //
22809
+ // It exists because the action alone cannot say why. A finding recorded as
22810
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22811
+ // assigned Redact on a field that could not take one — and those are
22812
+ // different facts about the same row: the first is a policy the user chose,
22813
+ // the second is a masking the host could not perform. Absent means no
22814
+ // degrade happened, which is every ordinary capture.
22815
+ //
22816
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22817
+ // is the CAPTURE while `actionTaken` is per FINDING:
22818
+ //
22819
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22820
+ // `redact` alongside a finding ASSIGNED the same action stores both
22821
+ // identically and one reason for the pair; attributing it to both
22822
+ // describes the assigned one wrongly, and to neither loses the degrade.
22823
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22824
+ // became, not the reason the capture ended as it did — a capture denied
22825
+ // by some other finding's own Block policy still carries `block` here,
22826
+ // and clearing the workspace's fallback would not have let it through.
22827
+ // Gate on the value against what a fallback can produce; never read the
22828
+ // field's presence as "this was the fallback's doing".
22829
+ //
22830
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22831
+ // Closing either means moving the reason onto the finding row, which
22832
+ // already carries its own action.
22833
+ redactDegradedTo: ActionTaken.optional()
22652
22834
  }).meta({ id: "EventMetadata" });
22653
22835
  var Event = external_exports.object({
22654
22836
  id: external_exports.guid(),
@@ -22758,7 +22940,32 @@ var RotateKeyInput = external_exports.object({
22758
22940
  confirmation: external_exports.string()
22759
22941
  });
22760
22942
 
22943
+ // ../../packages/schema/src/zod/finding-delivery.ts
22944
+ var KNOWN_REASONS = SyncFailureReason.options;
22945
+ function knownReason(value) {
22946
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22947
+ }
22948
+ function deriveFindingDelivery(row) {
22949
+ if (row.kind === "code_change") return { state: "local_scan" };
22950
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22951
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22952
+ }
22953
+ if (row.syncedAt !== null) {
22954
+ const reason = knownReason(row.syncFailure);
22955
+ return {
22956
+ state: "not_sent",
22957
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22958
+ ...reason === void 0 ? {} : { reason }
22959
+ };
22960
+ }
22961
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22962
+ return { state: "never_offered" };
22963
+ }
22964
+
22761
22965
  // ../../packages/schema/src/zod/findings-group-build.ts
22966
+ function lookupOwn(map2, key) {
22967
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22968
+ }
22762
22969
  function toApiAction(dbVal) {
22763
22970
  const map2 = {
22764
22971
  log: "monitored",
@@ -22767,7 +22974,7 @@ function toApiAction(dbVal) {
22767
22974
  warn: "warned",
22768
22975
  allow: "allowed"
22769
22976
  };
22770
- return map2[dbVal] ?? "allowed";
22977
+ return lookupOwn(map2, dbVal) ?? "allowed";
22771
22978
  }
22772
22979
  function toApiCategory(dbVal) {
22773
22980
  if (dbVal === "code_context") return "source_code";
@@ -22775,13 +22982,18 @@ function toApiCategory(dbVal) {
22775
22982
  return parsed2.success ? parsed2.data : "custom";
22776
22983
  }
22777
22984
  function toApiProvider(sourceTool) {
22778
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22985
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22779
22986
  }
22780
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22987
+ var FINDING_STATUS_PRECEDENCE = [
22988
+ "open",
22989
+ "handled",
22990
+ "dismissed",
22991
+ "resolved"
22992
+ ];
22781
22993
  function foldGroupStatus(instanceStatuses) {
22782
22994
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22783
22995
  if (statuses.size === 0) return void 0;
22784
- for (const candidate of STATUS_PRECEDENCE) {
22996
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22785
22997
  if (statuses.has(candidate)) return candidate;
22786
22998
  }
22787
22999
  return void 0;
@@ -22794,139 +23006,62 @@ function deriveFindingStatus(row) {
22794
23006
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22795
23007
  return "open";
22796
23008
  }
22797
- function distinctUsers(instances) {
22798
- const seen = /* @__PURE__ */ new Set();
22799
- const users = [];
22800
- for (const i of instances) {
22801
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22802
- seen.add(i.user.id);
22803
- users.push(i.user);
22804
- }
22805
- return users;
22806
- }
22807
23009
  function sortUsers(users) {
22808
23010
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22809
23011
  }
22810
- function buildFindingGroups(rows, opts = {}) {
22811
- const overrides = opts.overrides;
23012
+ function buildFindingTypes(aggregates, opts = {}) {
22812
23013
  const packNames = opts.packNames;
22813
- const aggregates = opts.aggregates;
22814
- const byRuleId = /* @__PURE__ */ new Map();
22815
- for (const row of rows) {
22816
- const existing = byRuleId.get(row.ruleId);
22817
- if (existing) existing.push(row);
22818
- else byRuleId.set(row.ruleId, [row]);
22819
- }
22820
- const groups = [];
22821
- for (const [ruleId, ruleRows] of byRuleId) {
22822
- const instances = ruleRows.map((r) => {
22823
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22824
- return {
22825
- id: r.id,
22826
- provider: toApiProvider(r.sourceTool),
22827
- repo: r.repo,
22828
- file: r.file,
22829
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22830
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22831
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22832
- ...r.user === void 0 ? {} : { user: r.user },
22833
- action: toApiAction(effectiveDbAction),
22834
- detectedAt: r.occurredAt,
22835
- confidence: r.confidence,
22836
- status: r.status
22837
- };
22838
- });
22839
- const agg = aggregates?.get(ruleId);
22840
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22841
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22842
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22843
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22844
- );
22845
- const seenProviders = /* @__PURE__ */ new Set();
22846
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22847
- if (seenProviders.has(p)) return false;
22848
- seenProviders.add(p);
22849
- return true;
22850
- });
22851
- const actionSet = new Set(
22852
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22853
- );
23014
+ const types = [];
23015
+ for (const [ruleId, agg] of aggregates) {
23016
+ const users = sortUsers(agg.users ?? []);
23017
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23018
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22854
23019
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22855
- const severity = ruleRows[0]?.severity ?? "low";
22856
- const detection = {
22857
- id: ruleId,
22858
- name: packNames?.get(ruleId) ?? null
22859
- };
22860
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22861
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22862
- const match = {
22863
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22864
- contextPrefix: ""
22865
- // empty (pending privacy review)
22866
- };
22867
- const status = foldGroupStatus(
22868
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22869
- );
22870
- const group = {
23020
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23021
+ const type = {
22871
23022
  id: ruleId,
22872
23023
  category: apiCategory,
22873
23024
  subtype: ruleId,
22874
23025
  // human label comes with pack metadata later
22875
- severity,
22876
- match,
22877
- detection,
22878
- policy,
22879
- instanceCount: agg?.instanceCount ?? instances.length,
23026
+ severity: agg.severity ?? "low",
23027
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23028
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23029
+ instanceCount: agg.instanceCount,
22880
23030
  providers,
22881
23031
  aggregateAction,
22882
- latestDetectedAt,
22883
- instances,
22884
- status,
23032
+ latestDetectedAt: agg.latestDetectedAt,
23033
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22885
23034
  ...users.length > 0 ? { users } : {}
22886
23035
  };
22887
- if (agg) {
22888
- actionsCache.set(group, [...actionSet]);
22889
- if (agg.searchText !== void 0) {
22890
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22891
- }
23036
+ actionsCache.set(type, [...actionSet]);
23037
+ if (agg.searchText !== void 0) {
23038
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22892
23039
  }
22893
- groups.push(group);
23040
+ types.push(type);
22894
23041
  }
22895
- return groups;
23042
+ return types;
22896
23043
  }
22897
23044
  var haystackCache = /* @__PURE__ */ new WeakMap();
22898
- function buildHaystack(g, extra) {
23045
+ function buildHaystack(t, extra) {
22899
23046
  return [
22900
- g.subtype,
22901
- g.category,
22902
- g.match.maskedValue,
22903
- g.policy.name,
22904
- g.id,
22905
- ...g.instances.map((i) => i.repo),
22906
- ...g.instances.map((i) => i.file),
22907
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22908
- ...g.instances.map((i) => i.id),
22909
- // The people: the whole group's list when the store folded one, plus the
22910
- // preview's own — the two overlap, and a haystack does not mind.
22911
- ...(g.users ?? []).map((u) => u.name),
22912
- ...g.instances.map((i) => i.user?.name ?? ""),
23047
+ t.subtype,
23048
+ t.category,
23049
+ t.policy.name,
23050
+ t.id,
23051
+ ...(t.users ?? []).map((u) => u.name),
22913
23052
  ...extra === void 0 ? [] : [extra]
22914
23053
  ].join(" ").toLowerCase();
22915
23054
  }
22916
- function groupHaystack(g) {
22917
- const cached2 = haystackCache.get(g);
23055
+ function typeHaystack(t) {
23056
+ const cached2 = haystackCache.get(t);
22918
23057
  if (cached2 !== void 0) return cached2;
22919
- const haystack = buildHaystack(g);
22920
- haystackCache.set(g, haystack);
23058
+ const haystack = buildHaystack(t);
23059
+ haystackCache.set(t, haystack);
22921
23060
  return haystack;
22922
23061
  }
22923
23062
  var actionsCache = /* @__PURE__ */ new WeakMap();
22924
- function groupActions(g) {
22925
- const cached2 = actionsCache.get(g);
22926
- if (cached2 !== void 0) return cached2;
22927
- const actions = [...new Set(g.instances.map((i) => i.action))];
22928
- actionsCache.set(g, actions);
22929
- return actions;
23063
+ function typeActions(t) {
23064
+ return actionsCache.get(t) ?? [];
22930
23065
  }
22931
23066
  function countInstancesByStatus(statusInputs, statuses) {
22932
23067
  const statusSet = new Set(statuses);
@@ -22937,8 +23072,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22937
23072
  }
22938
23073
  return sum;
22939
23074
  }
22940
- function applyFindingFilters(groups, opts) {
22941
- let filtered = groups;
23075
+ function applyFindingFilters(types, opts) {
23076
+ let filtered = types;
22942
23077
  if (opts.severity && opts.severity.length > 0) {
22943
23078
  const sevSet = new Set(opts.severity);
22944
23079
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22949,7 +23084,7 @@ function applyFindingFilters(groups, opts) {
22949
23084
  }
22950
23085
  if (opts.actions && opts.actions.length > 0) {
22951
23086
  const actionSet = new Set(opts.actions);
22952
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23087
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22953
23088
  }
22954
23089
  if (opts.subtype && opts.subtype.length > 0) {
22955
23090
  const subtypeSet = new Set(opts.subtype);
@@ -22961,26 +23096,31 @@ function applyFindingFilters(groups, opts) {
22961
23096
  }
22962
23097
  if (opts.q) {
22963
23098
  const q = opts.q.toLowerCase();
22964
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23099
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22965
23100
  }
22966
23101
  return filtered;
22967
23102
  }
22968
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22969
- var SEVERITY_RANK = SEVERITY_ORDER;
23103
+ function rankByOrder(members2) {
23104
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23105
+ }
23106
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23107
+ function severityRank(severity) {
23108
+ return lookupOwn(SEVERITY_RANK, severity);
23109
+ }
22970
23110
  function compareFindingGroupOrder(a, b) {
22971
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22972
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23111
+ const rankA = severityRank(a.severity) ?? -1;
23112
+ const rankB = severityRank(b.severity) ?? -1;
22973
23113
  const severityDiff = rankA - rankB;
22974
23114
  if (severityDiff !== 0) return severityDiff;
22975
23115
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22976
23116
  if (recencyDiff !== 0) return recencyDiff;
22977
23117
  return a.id.localeCompare(b.id);
22978
23118
  }
22979
- function sortFindingGroups(groups) {
22980
- return [...groups].sort(compareFindingGroupOrder);
23119
+ function sortFindingTypes(types) {
23120
+ return [...types].sort(compareFindingGroupOrder);
22981
23121
  }
22982
- function computeFindingFacets(allGroups, opts) {
22983
- const forSeverity = applyFindingFilters(allGroups, {
23122
+ function computeFindingFacets(allTypes, opts) {
23123
+ const forSeverity = applyFindingFilters(allTypes, {
22984
23124
  providers: opts.providers,
22985
23125
  actions: opts.actions,
22986
23126
  statuses: opts.statuses,
@@ -22991,7 +23131,7 @@ function computeFindingFacets(allGroups, opts) {
22991
23131
  for (const g of forSeverity) {
22992
23132
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22993
23133
  }
22994
- const forProvider = applyFindingFilters(allGroups, {
23134
+ const forProvider = applyFindingFilters(allTypes, {
22995
23135
  actions: opts.actions,
22996
23136
  statuses: opts.statuses,
22997
23137
  q: opts.q,
@@ -23002,7 +23142,7 @@ function computeFindingFacets(allGroups, opts) {
23002
23142
  for (const g of forProvider) {
23003
23143
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23004
23144
  }
23005
- const forAction = applyFindingFilters(allGroups, {
23145
+ const forAction = applyFindingFilters(allTypes, {
23006
23146
  providers: opts.providers,
23007
23147
  statuses: opts.statuses,
23008
23148
  q: opts.q,
@@ -23011,9 +23151,9 @@ function computeFindingFacets(allGroups, opts) {
23011
23151
  });
23012
23152
  const actionMap = /* @__PURE__ */ new Map();
23013
23153
  for (const g of forAction) {
23014
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23154
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23015
23155
  }
23016
- const forSubtype = applyFindingFilters(allGroups, {
23156
+ const forSubtype = applyFindingFilters(allTypes, {
23017
23157
  providers: opts.providers,
23018
23158
  actions: opts.actions,
23019
23159
  statuses: opts.statuses,
@@ -23022,7 +23162,7 @@ function computeFindingFacets(allGroups, opts) {
23022
23162
  });
23023
23163
  const subtypeMap = /* @__PURE__ */ new Map();
23024
23164
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23025
- const forStatus = applyFindingFilters(allGroups, {
23165
+ const forStatus = applyFindingFilters(allTypes, {
23026
23166
  providers: opts.providers,
23027
23167
  actions: opts.actions,
23028
23168
  q: opts.q,
@@ -23044,6 +23184,20 @@ function computeFindingFacets(allGroups, opts) {
23044
23184
  }
23045
23185
 
23046
23186
  // ../../packages/schema/src/zod/findings-flat-build.ts
23187
+ function compareCodePoints(a, b) {
23188
+ const aIter = a[Symbol.iterator]();
23189
+ const bIter = b[Symbol.iterator]();
23190
+ for (; ; ) {
23191
+ const aNext = aIter.next();
23192
+ const bNext = bIter.next();
23193
+ if (aNext.done && bNext.done) return 0;
23194
+ if (aNext.done) return -1;
23195
+ if (bNext.done) return 1;
23196
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23197
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23198
+ if (aPoint !== bPoint) return aPoint - bPoint;
23199
+ }
23200
+ }
23047
23201
  function rowHaystack(row) {
23048
23202
  return [
23049
23203
  row.ruleId,
@@ -23068,12 +23222,24 @@ function matchesDimension(row, opts, dimension) {
23068
23222
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23069
23223
  case "statuses":
23070
23224
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23225
+ case "deliveries":
23226
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23071
23227
  case "tools":
23072
23228
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23229
+ // An EMPTY value is a real filter here, not an absent one. The location
23230
+ // list buckets a finding whose event recorded no repo — or no file — under
23231
+ // the empty string, and selecting that bucket has to narrow the panel to
23232
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23233
+ // row omits the key, which every call site already does.
23234
+ //
23235
+ // Reading '' as unset is what this replaced, and it failed in the one place
23236
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23237
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23238
+ // — a row reading 3 findings beside a panel listing every finding there is.
23073
23239
  case "repo":
23074
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23240
+ return opts.repo === void 0 || row.repo === opts.repo;
23075
23241
  case "file":
23076
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23242
+ return opts.file === void 0 || row.file === opts.file;
23077
23243
  case "q":
23078
23244
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23079
23245
  }
@@ -23084,6 +23250,7 @@ var DIMENSIONS = [
23084
23250
  "providers",
23085
23251
  "actions",
23086
23252
  "statuses",
23253
+ "deliveries",
23087
23254
  "tools",
23088
23255
  "repo",
23089
23256
  "file",
@@ -23097,10 +23264,19 @@ function matchesInstanceFilters(row, opts, except) {
23097
23264
  return true;
23098
23265
  }
23099
23266
  function toItems(counts) {
23100
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23267
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23268
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23269
+ // NFD spelling of the same text) as equal, so a count tie between
23270
+ // them would otherwise be ordered by whichever the Map iteration
23271
+ // produced. compareCodePoints breaks that tie deterministically, which
23272
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23273
+ // which it need not: foldFacetTuples runs this same sort over grouped
23274
+ // tuples, so both paths order facets identically by construction.
23275
+ compareCodePoints(a.value, b.value)
23276
+ );
23101
23277
  }
23102
- function bump(counts, value) {
23103
- counts.set(value, (counts.get(value) ?? 0) + 1);
23278
+ function bump(counts, value, by = 1) {
23279
+ counts.set(value, (counts.get(value) ?? 0) + by);
23104
23280
  }
23105
23281
  function createInstanceFacetAccumulator(opts) {
23106
23282
  const severity = /* @__PURE__ */ new Map();
@@ -23109,6 +23285,7 @@ function createInstanceFacetAccumulator(opts) {
23109
23285
  const action = /* @__PURE__ */ new Map();
23110
23286
  const status = /* @__PURE__ */ new Map();
23111
23287
  const tool = /* @__PURE__ */ new Map();
23288
+ const deployment = /* @__PURE__ */ new Map();
23112
23289
  return {
23113
23290
  add(row) {
23114
23291
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23123,6 +23300,9 @@ function createInstanceFacetAccumulator(opts) {
23123
23300
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23124
23301
  bump(tool, row.toolName);
23125
23302
  }
23303
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23304
+ bump(deployment, row.delivery.state);
23305
+ }
23126
23306
  },
23127
23307
  facets: () => ({
23128
23308
  severity: toItems(severity),
@@ -23130,7 +23310,8 @@ function createInstanceFacetAccumulator(opts) {
23130
23310
  provider: toItems(provider),
23131
23311
  action: toItems(action),
23132
23312
  status: toItems(status),
23133
- tool: toItems(tool)
23313
+ tool: toItems(tool),
23314
+ deployment: toItems(deployment)
23134
23315
  })
23135
23316
  };
23136
23317
  }
@@ -23144,6 +23325,7 @@ function toInstanceDetail(row) {
23144
23325
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23145
23326
  eventId: row.eventId,
23146
23327
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23328
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23147
23329
  ...row.user === void 0 ? {} : { user: row.user },
23148
23330
  action: toApiAction(row.actionTaken),
23149
23331
  detectedAt: row.occurredAt,
@@ -23158,12 +23340,6 @@ function toInstanceDetail(row) {
23158
23340
  policy: { id: `category:${category}`, name: category }
23159
23341
  };
23160
23342
  }
23161
- var SEVERITY_ORDER2 = {
23162
- critical: 0,
23163
- high: 1,
23164
- medium: 2,
23165
- low: 3
23166
- };
23167
23343
  function newLocationAccumulator() {
23168
23344
  return {
23169
23345
  instanceCount: 0,
@@ -23178,7 +23354,7 @@ function newLocationAccumulator() {
23178
23354
  }
23179
23355
  function addToLocation(acc, row) {
23180
23356
  acc.instanceCount += 1;
23181
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23357
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23182
23358
  if (rank < acc.maxSeverityRank) {
23183
23359
  acc.maxSeverityRank = rank;
23184
23360
  acc.maxSeverity = row.severity;
@@ -23187,6 +23363,23 @@ function addToLocation(acc, row) {
23187
23363
  acc.statuses.push(row.status);
23188
23364
  acc.ruleIds.add(row.ruleId);
23189
23365
  }
23366
+ function compareLocationOrder(a, b) {
23367
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23368
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23369
+ if (rankA !== rankB) return rankA - rankB;
23370
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23371
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23372
+ }
23373
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23374
+ if (repoDiff !== 0) return repoDiff;
23375
+ return compareCodePoints(a.file, b.file);
23376
+ }
23377
+ function encodeLocationId(repo, file2) {
23378
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23379
+ }
23380
+ function encodePart(value) {
23381
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23382
+ }
23190
23383
 
23191
23384
  // ../../packages/schema/src/zod/installed-pack.ts
23192
23385
  var InstalledPack = external_exports.object({
@@ -23254,6 +23447,11 @@ var Policy = external_exports.object({
23254
23447
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23255
23448
  provenance: PolicyProvenance.optional()
23256
23449
  }).meta({ id: "Policy" });
23450
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23451
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23452
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23453
+ id: "RedactFallback"
23454
+ });
23257
23455
  var PolicyBundle = external_exports.object({
23258
23456
  version: external_exports.string(),
23259
23457
  policies: external_exports.array(Policy),
@@ -23301,6 +23499,16 @@ var PolicyBundle = external_exports.object({
23301
23499
  // control plane), so no name resolution stands between the decision and the
23302
23500
  // comparison.
23303
23501
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23502
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23503
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23504
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23505
+ // a control plane can tighten a machine and never loosen one — the same
23506
+ // direction `mergeRaiseOnly` enforces for policies.
23507
+ //
23508
+ // Optional so an older backend, and an older on-disk cache, still parses;
23509
+ // absent leaves the device's own setting in force, which is the behaviour
23510
+ // that predates the field and the safe direction to default.
23511
+ redactFallback: RedactFallback.optional(),
23304
23512
  customKeywords: external_exports.array(external_exports.string()),
23305
23513
  fetchedAt: external_exports.iso.datetime()
23306
23514
  }).meta({ id: "PolicyBundle" });
@@ -23330,11 +23538,6 @@ function severityFloorPolicy(category) {
23330
23538
  const peak = CATEGORY_PEAK_SEVERITY[category];
23331
23539
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23332
23540
  }
23333
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23334
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23335
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23336
- id: "RedactFallback"
23337
- });
23338
23541
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23339
23542
  var BUILTIN_POLICY_SPECS = {
23340
23543
  monitor: {
@@ -23627,7 +23830,7 @@ var VaultConsent = external_exports.object({
23627
23830
  });
23628
23831
 
23629
23832
  // ../../packages/schema/src/zod/local.ts
23630
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23833
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23631
23834
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23632
23835
  var RunMode = external_exports.enum(["standalone", "attached"]);
23633
23836
  var ControlPlaneConnection = external_exports.object({
@@ -23647,6 +23850,15 @@ var HistorySyncConsent = external_exports.object({
23647
23850
  payloadVersion: external_exports.number().int().positive(),
23648
23851
  endpoint: external_exports.string()
23649
23852
  });
23853
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23854
+ var BodyRetention = external_exports.object({
23855
+ enabled: external_exports.boolean().default(false),
23856
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23857
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23858
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23859
+ // candidate set that is already bounded by "delivered, or never owed".
23860
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23861
+ }).meta({ id: "BodyRetention" });
23650
23862
  var WorkspaceSettings = external_exports.object({
23651
23863
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23652
23864
  runMode: RunMode.default("standalone"),
@@ -23690,12 +23902,18 @@ var WorkspaceSettings = external_exports.object({
23690
23902
  // covers the current payload and must be re-granted.
23691
23903
  modelJudgeConsent: ModelJudgeConsent.optional(),
23692
23904
  // Records that the user consented to the DEFERRED send — the outbox — along
23693
- // with the payload shape and the endpoint they agreed to. Since payload v2
23694
- // that covers both the pre-attach backlog and undelivered captures (which
23695
- // carry prompt/reply text in `content`); the key name predates the widening.
23696
- // Absent until granted, and a grant for a different endpoint or an older
23697
- // payload no longer counts.
23698
- historySyncConsent: HistorySyncConsent.optional()
23905
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23906
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23907
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23908
+ // both widenings. Absent until granted, and a grant for a different endpoint
23909
+ // or an older payload no longer counts.
23910
+ historySyncConsent: HistorySyncConsent.optional(),
23911
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23912
+ // body never removes the row or its findings.
23913
+ bodyRetention: BodyRetention.default({
23914
+ enabled: false,
23915
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23916
+ })
23699
23917
  });
23700
23918
  function defaultWorkspaceSettings() {
23701
23919
  return WorkspaceSettings.parse({});
@@ -23790,12 +24008,15 @@ function toCaptureAttributes(event) {
23790
24008
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23791
24009
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23792
24010
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24011
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23793
24012
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23794
24013
  // has ever populated either), but every legacy metadata key still rides
23795
24014
  // the bag rather than being silently dropped — CaptureAttributes'
23796
24015
  // `.catchall(z.unknown())` carries the long tail.
23797
24016
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23798
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24017
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24018
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24019
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23799
24020
  };
23800
24021
  }
23801
24022
  function captureDefinitionVersion(finding) {
@@ -23823,10 +24044,22 @@ var ManagedSettingKey = external_exports.enum([
23823
24044
  "vaultInlineReveal",
23824
24045
  "modelJudgeConsent",
23825
24046
  "dataSharesInPlace",
23826
- "redactFallback"
24047
+ "redactFallback",
24048
+ // Pins the toggle and the day count together — see BodyRetention on why the
24049
+ // two are one unit. An administrator mandating a window wants the count
24050
+ // enforced with it, not one a user can widen while the toggle stays on.
24051
+ "bodyRetention"
23827
24052
  ]).meta({ id: "ManagedSettingKey" });
24053
+ function isManagedSettingKey(value) {
24054
+ return ManagedSettingKey.safeParse(value).success;
24055
+ }
23828
24056
  var ManagedSettingsValues = external_exports.object({
23829
24057
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24058
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24059
+ // plain, non-strict objects: a key under either that this build does not know
24060
+ // is stripped and nothing reports it. The unknown-value split in
24061
+ // ManagedSettings below classifies top-level names only, so it stops at
24062
+ // these boundaries.
23830
24063
  controlPlane: external_exports.object({
23831
24064
  endpoint: external_exports.string().min(1),
23832
24065
  label: external_exports.string().min(1).optional()
@@ -23837,7 +24070,8 @@ var ManagedSettingsValues = external_exports.object({
23837
24070
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23838
24071
  modelJudgeConsent: external_exports.boolean().optional(),
23839
24072
  dataSharesInPlace: external_exports.boolean().optional(),
23840
- redactFallback: RedactFallback.optional()
24073
+ redactFallback: RedactFallback.optional(),
24074
+ bodyRetention: BodyRetention.optional()
23841
24075
  }).meta({ id: "ManagedSettingsValues" });
23842
24076
  var ManagedSettings = external_exports.object({
23843
24077
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23845,11 +24079,59 @@ var ManagedSettings = external_exports.object({
23845
24079
  // decision from a bug. Absent renders as a generic "your organization".
23846
24080
  organization: external_exports.string().min(1).optional(),
23847
24081
  // What the administrator pinned.
23848
- values: ManagedSettingsValues.default({}),
24082
+ //
24083
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24084
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24085
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24086
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24087
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24088
+ // exactly the file an administrator is most likely to write while a fleet
24089
+ // is mid-upgrade.
24090
+ //
24091
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24092
+ // file, which is the outcome the lock half already rejected — an older
24093
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24094
+ // value still fails, because the nested schema is re-run over the known
24095
+ // subset and its issues are re-raised on this parse.
24096
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23849
24097
  // Which of those the user may not change. A key here with no matching value
23850
24098
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23851
24099
  // the user may still override. The two are separable on purpose.
23852
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24100
+ //
24101
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24102
+ // build does not know is dropped from the locked set and reported, never a
24103
+ // reason to refuse the file. The same shape reaches an older build whenever
24104
+ // an administrator locks a key a newer build added, and refusing it there
24105
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24106
+ // the fleets most likely to carry a version skew. A name outside the enum
24107
+ // is still never HONOURED: the lockable set stays explicit above.
24108
+ lockedFields: external_exports.array(external_exports.string()).default([])
24109
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24110
+ const known = [];
24111
+ const unknown2 = [];
24112
+ for (const name of lockedFields) {
24113
+ if (isManagedSettingKey(name)) known.push(name);
24114
+ else unknown2.push(name);
24115
+ }
24116
+ const knownValues = /* @__PURE__ */ Object.create(null);
24117
+ const unknownValues = [];
24118
+ for (const [name, value] of Object.entries(values)) {
24119
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24120
+ else unknownValues.push(name);
24121
+ }
24122
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24123
+ if (!pinned.success) {
24124
+ for (const issue2 of pinned.error.issues)
24125
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24126
+ return external_exports.NEVER;
24127
+ }
24128
+ return {
24129
+ ...rest,
24130
+ values: pinned.data,
24131
+ lockedFields: known,
24132
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24133
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24134
+ };
23853
24135
  }).meta({ id: "ManagedSettings" });
23854
24136
 
23855
24137
  // ../../packages/schema/src/zod/project-files.ts
@@ -23973,7 +24255,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23973
24255
  timestamp: external_exports.iso.date(),
23974
24256
  critical: external_exports.number().int().nonnegative(),
23975
24257
  high: external_exports.number().int().nonnegative(),
23976
- medium: external_exports.number().int().nonnegative()
24258
+ medium: external_exports.number().int().nonnegative(),
24259
+ // Optional and additive, so a producer written against the earlier
24260
+ // three-series contract keeps validating. A consumer plotting it resolves the
24261
+ // absent case itself — the chart point requires a number.
24262
+ low: external_exports.number().int().nonnegative().optional()
23977
24263
  }).meta({ id: "FindingsTimeseriesPoint" });
23978
24264
  var FindingsTimeseriesResponse = external_exports.object({
23979
24265
  range: TimeRange,
@@ -23999,6 +24285,10 @@ var ResolvedFeedItem = external_exports.object({
23999
24285
  findingKey: external_exports.string(),
24000
24286
  ruleId: external_exports.string(),
24001
24287
  severity: Severity,
24288
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24289
+ // identifies the file: a bare path matches the same name in every repo.
24290
+ // Optional and additive; empty when the event carried no repo.
24291
+ repo: external_exports.string().optional(),
24002
24292
  path: external_exports.string(),
24003
24293
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24004
24294
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24104,7 +24394,23 @@ var SaveSettingsInput = external_exports.object({
24104
24394
  modelJudgeConsent: ModelJudgeConsentChoice,
24105
24395
  historySyncConsent: HistorySyncConsentChoice,
24106
24396
  vaultConsent: external_exports.string(),
24107
- vaultInlineReveal: external_exports.string()
24397
+ vaultInlineReveal: external_exports.string(),
24398
+ // Widened to `string` like its neighbours rather than typed as
24399
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24400
+ // the call site, so the domain check receives the type it was written for.
24401
+ //
24402
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24403
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24404
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24405
+ // trade against. The real cost runs the other way and is the part worth
24406
+ // knowing: a value this schema admits and the domain enum then rejects lands
24407
+ // on the action's shared refusal, which names NO field, where a shape
24408
+ // rejection reaches `malformedInput` and names the schema key.
24409
+ redactFallback: external_exports.string(),
24410
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24411
+ // `BodyRetention`'s and the action checks it there, so there is one place
24412
+ // that decides what a legal horizon is rather than two that can drift.
24413
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24108
24414
  });
24109
24415
  var AttachInput = external_exports.object({
24110
24416
  endpoint: external_exports.string(),
@@ -24276,6 +24582,52 @@ function reviewSeverityRank(reasons) {
24276
24582
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24277
24583
  }
24278
24584
 
24585
+ // ../../packages/schema/src/zod/web-capture.ts
24586
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24587
+ var WebUsage = external_exports.object({
24588
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24589
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24590
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24591
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24592
+ });
24593
+ var WebToolCall = external_exports.object({
24594
+ toolUseId: external_exports.string().min(1),
24595
+ toolName: external_exports.string().min(1),
24596
+ target: external_exports.string().optional(),
24597
+ isError: external_exports.boolean().optional(),
24598
+ inputSize: external_exports.number().int().nonnegative().optional(),
24599
+ outputSize: external_exports.number().int().nonnegative().optional()
24600
+ });
24601
+ var WebExchange = external_exports.object({
24602
+ messageId: external_exports.string().min(1),
24603
+ startedAt: external_exports.iso.datetime(),
24604
+ model: external_exports.string().optional(),
24605
+ usage: WebUsage.optional(),
24606
+ usageSource: WebUsageSource,
24607
+ stopReason: external_exports.string().optional(),
24608
+ conversationId: external_exports.string().optional(),
24609
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24610
+ toolCalls: external_exports.array(WebToolCall).default([]),
24611
+ // Absent when the adapter recovered no text. Capped by the caller at
24612
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24613
+ // short capture is never mistaken for a short reply.
24614
+ responseText: external_exports.string().optional(),
24615
+ truncated: external_exports.boolean().default(false)
24616
+ });
24617
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24618
+ var WebCaptureStatus = external_exports.object({
24619
+ patched: external_exports.boolean(),
24620
+ live: external_exports.boolean(),
24621
+ blind: external_exports.boolean(),
24622
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24623
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24624
+ parseFailures: external_exports.number().int().nonnegative(),
24625
+ unparsedBodies: external_exports.number().int().nonnegative(),
24626
+ // The adapter-declared JSON key paths that were absent from a real payload —
24627
+ // the earliest signal that a site's contract moved.
24628
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24629
+ });
24630
+
24279
24631
  // ../../packages/persistence/src/paths.ts
24280
24632
  import {
24281
24633
  chmodSync,
@@ -24606,6 +24958,22 @@ function discardStore(file2, backup) {
24606
24958
  }
24607
24959
  }
24608
24960
 
24961
+ // ../../packages/persistence/src/internal/sql-functions.ts
24962
+ var utf8 = new TextDecoder();
24963
+ function akaLower(value) {
24964
+ if (value === null) return null;
24965
+ if (typeof value === "string") return value.toLowerCase();
24966
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
24967
+ return utf8.decode(value).toLowerCase();
24968
+ }
24969
+ function registerSqlFunctions(db) {
24970
+ db.function(
24971
+ "aka_lower",
24972
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
24973
+ akaLower
24974
+ );
24975
+ }
24976
+
24609
24977
  // ../../packages/persistence/src/internal/sql-text.ts
24610
24978
  function escapeLikePattern(s) {
24611
24979
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24690,6 +25058,11 @@ function schemaObjectExists(db, kind, name) {
24690
25058
  function indexExists(db, name) {
24691
25059
  return schemaObjectExists(db, "index", name);
24692
25060
  }
25061
+ function indexColumns(db, name) {
25062
+ if (!indexExists(db, name)) return [];
25063
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25064
+ return columns.map((c) => c.name).filter((c) => c !== null);
25065
+ }
24693
25066
  function columnNames(db, table, opts) {
24694
25067
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24695
25068
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24751,148 +25124,790 @@ function mapRowsTolerant(rows, map2) {
24751
25124
  return out;
24752
25125
  }
24753
25126
 
24754
- // ../../packages/persistence/src/migrations.ts
24755
- function describeObject(object2) {
24756
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24757
- }
24758
- function splitStatements(sql) {
24759
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24760
- }
24761
- function createdIndexName(statement) {
24762
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24763
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25127
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25128
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25129
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25130
+
25131
+ // ../../packages/persistence/src/sync-failure.ts
25132
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25133
+ function syncFailureRejectCondition(column = "sync_failure") {
25134
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25135
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24764
25136
  }
24765
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24766
- function applyMigrations(db, file2) {
24767
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24768
- db.exec(
24769
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24770
- );
24771
- const applied = new Set(
24772
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24773
- );
24774
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24775
- const record2 = db.prepare(
24776
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24777
- );
24778
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24779
- if (applied.has(migration.tag)) continue;
24780
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24781
- const evidence = evidenceObjects(migration.sql);
24782
- const present = evidence.filter((o) => evidenceExists(db, o));
24783
- if (present.length > 0 && present.length < evidence.length) {
24784
- const missing = evidence.filter((o) => !present.includes(o));
24785
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24786
- akaWarn(message);
24787
- throw new Error(`[aka] ${message}`);
24788
- }
24789
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24790
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24791
- const statements = splitStatements(migration.sql);
24792
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24793
- try {
24794
- withTransaction(
24795
- db,
24796
- () => {
24797
- for (const statement of statements) {
24798
- const indexName = createdIndexName(statement);
24799
- if (indexName === void 0) {
24800
- if (alreadyApplied) continue;
24801
- } else if (indexExists(db, indexName)) {
24802
- continue;
24803
- }
24804
- db.exec(statement);
24805
- }
24806
- if (wantsFkOff && !alreadyApplied) {
24807
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24808
- if (violations.length > 0) {
24809
- throw new Error(
24810
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24811
- );
24812
- }
24813
- }
24814
- record2.run(migration.tag, Date.now());
24815
- },
24816
- "IMMEDIATE"
24817
- );
24818
- } finally {
24819
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24820
- }
25137
+
25138
+ // ../../packages/persistence/src/repositories/history-sync.ts
25139
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25140
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25141
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25142
+ var COUNTED_EVENT_TYPES = [
25143
+ ...STRUCTURAL_EVENT_TYPES,
25144
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25145
+ ];
25146
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25147
+ var PARTITION_BUCKETS = `
25148
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25149
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25150
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25151
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25152
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25153
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25154
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25155
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25156
+ -- added later lands in no bucket and fails the sum assertion, instead
25157
+ -- of silently joining this one.
25158
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25159
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25160
+ THEN 1 ELSE 0 END) AS failed,
25161
+ COUNT(*) AS total`;
25162
+ var COUNTED_SCOPE = `
25163
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25164
+ AND (
25165
+ event_type IN (${TYPE_LIST})
25166
+ OR synced_at IS NOT NULL
25167
+ OR outbox_owed = 1
25168
+ )`;
25169
+ var SKIPPED = -1;
25170
+ var ROW_COLUMNS = `id,
25171
+ parent_id AS parentId,
25172
+ root_session_id AS rootSessionId,
25173
+ event_type AS eventType,
25174
+ host_id AS hostId,
25175
+ harness_id AS harnessId,
25176
+ source_project_id AS sourceProjectId,
25177
+ started_at AS startedAt,
25178
+ ended_at AS endedAt,
25179
+ severity,
25180
+ priority,
25181
+ content,
25182
+ content_hash AS contentHash,
25183
+ attributes`;
25184
+ var SqliteHistorySyncRepository = class {
25185
+ constructor(db) {
25186
+ this.db = db;
25187
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25188
+ this.sessionsStmt = db.prepare(
25189
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25190
+ FROM audit_events
25191
+ WHERE synced_at IS NULL
25192
+ AND event_type IN (${TYPE_LIST})
25193
+ AND started_at < :before
25194
+ GROUP BY sessionId
25195
+ ORDER BY earliest
25196
+ LIMIT :limit`
25197
+ );
25198
+ this.rowsStmt = db.prepare(
25199
+ `SELECT ${ROW_COLUMNS}
25200
+ FROM audit_events
25201
+ WHERE synced_at IS NULL
25202
+ AND event_type IN (${TYPE_LIST})
25203
+ AND started_at < :before
25204
+ AND COALESCE(root_session_id, id) = :sessionId
25205
+ ORDER BY (event_type = 'session') DESC, started_at
25206
+ LIMIT :limit`
25207
+ );
25208
+ this.captureRowsStmt = db.prepare(
25209
+ `SELECT ${ROW_COLUMNS}
25210
+ FROM audit_events
25211
+ WHERE synced_at IS NULL
25212
+ AND sync_claimed_at IS NULL
25213
+ AND outbox_owed = 1
25214
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25215
+ AND started_at < :before
25216
+ ORDER BY started_at
25217
+ LIMIT :limit`
25218
+ );
25219
+ this.markOwedStmt = db.prepare(
25220
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25221
+ );
25222
+ this.markCaptureBacklogOwedStmt = db.prepare(
25223
+ `UPDATE audit_events SET outbox_owed = 1
25224
+ WHERE synced_at IS NULL
25225
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25226
+ AND started_at < :before`
25227
+ );
25228
+ this.stampStmt = db.prepare(
25229
+ `UPDATE audit_events
25230
+ SET synced_at = :at,
25231
+ sync_claimed_at = NULL,
25232
+ sync_failed_at = :failedAt,
25233
+ sync_failure = :failure
25234
+ WHERE id = :id`
25235
+ );
25236
+ this.claimRowStmt = db.prepare(
25237
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25238
+ );
25239
+ this.releaseRowStmt = db.prepare(
25240
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25241
+ );
25242
+ this.releaseStaleClaimsStmt = db.prepare(
25243
+ `UPDATE audit_events SET sync_claimed_at = NULL
25244
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25245
+ );
25246
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25247
+ FROM audit_events${COUNTED_SCOPE}`);
25248
+ this.partitionByKindStmt = db.prepare(
25249
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25250
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25251
+ GROUP BY event_type`
25252
+ );
25253
+ this.countsStmt = db.prepare(
25254
+ `SELECT
25255
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25256
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25257
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25258
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25259
+ THEN 1 ELSE 0 END) AS skipped,
25260
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25261
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25262
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25263
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25264
+ FROM audit_events
25265
+ WHERE event_type IN (${TYPE_LIST})`
25266
+ );
25267
+ this.captureSkipCountStmt = db.prepare(
25268
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25269
+ // way the structural totals are. The split exists because a refusal is
25270
+ // terminal only against the deployment that gave it, and the structural
25271
+ // re-arm frees it on a change of deployment. The capture lane has no such
25272
+ // escape: re-arming a capture would offer one deployment's undelivered
25273
+ // prompts, with their text, to a deployment that never saw them, which is
25274
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25275
+ // reasons mean the same thing — this row will not be sent — and splitting
25276
+ // them would put refused captures in a bucket nothing reads and nothing
25277
+ // frees.
25278
+ `SELECT COUNT(*) AS skipped
25279
+ FROM audit_events
25280
+ WHERE synced_at = ${String(SKIPPED)}
25281
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25282
+ );
25283
+ this.fingerprintStmt = db.prepare(
25284
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25285
+ FROM history_sync WHERE id = 1`
25286
+ );
25287
+ this.setFingerprintStmt = db.prepare(
25288
+ `UPDATE history_sync
25289
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25290
+ WHERE id = 1`
25291
+ );
25292
+ this.disownCapturesStmt = db.prepare(
25293
+ `UPDATE audit_events SET outbox_owed = NULL
25294
+ WHERE outbox_owed IS NOT NULL
25295
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25296
+ AND started_at < :attachedAt`
25297
+ );
25298
+ this.rearmStmt = db.prepare(
25299
+ `UPDATE audit_events
25300
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25301
+ WHERE (synced_at > 0
25302
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25303
+ AND event_type IN (${TYPE_LIST})`
25304
+ );
25305
+ this.claimStmt = db.prepare(
25306
+ `UPDATE history_sync
25307
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25308
+ WHERE id = 1
25309
+ AND (owner_pid IS NULL
25310
+ OR heartbeat_at IS NULL
25311
+ OR heartbeat_at < :staleBefore
25312
+ OR heartbeat_at > :now)`
25313
+ );
25314
+ this.heartbeatStmt = db.prepare(
25315
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25316
+ );
25317
+ this.releaseStmt = db.prepare(
25318
+ `UPDATE history_sync
25319
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25320
+ WHERE id = 1 AND owner_pid = :pid`
25321
+ );
25322
+ this.closeWindowStmt = db.prepare(
25323
+ `UPDATE audit_events
25324
+ SET synced_at = ${String(SKIPPED)},
25325
+ sync_failed_at = :at,
25326
+ sync_failure = 'detached_undelivered'
25327
+ WHERE synced_at IS NULL
25328
+ AND event_type IN (${TYPE_LIST})
25329
+ AND started_at >= :attachedAt`
25330
+ );
25331
+ this.releaseBoundaryStmt = db.prepare(
25332
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25333
+ );
25334
+ this.freezeBoundaryStmt = db.prepare(
25335
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25336
+ );
25337
+ this.leaseStmt = db.prepare(
25338
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25339
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25340
+ FROM history_sync WHERE id = 1`
25341
+ );
25342
+ this.inspectionsStmt = db.prepare(
25343
+ `SELECT d.rule_id AS ruleId,
25344
+ d.name AS ruleName,
25345
+ d.version AS ruleVersion,
25346
+ d.category AS category,
25347
+ d.severity AS severity,
25348
+ f.span_start AS spanStart,
25349
+ f.span_end AS spanEnd,
25350
+ f.masked_match AS maskedMatch,
25351
+ f.action_taken AS actionTaken,
25352
+ f.confidence AS confidence
25353
+ FROM inspection_findings f
25354
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25355
+ WHERE f.audit_event_id = :auditEventId
25356
+ ORDER BY f.span_start, f.id`
25357
+ );
24821
25358
  }
24822
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24823
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25359
+ db;
25360
+ ensureRowStmt;
25361
+ sessionsStmt;
25362
+ rowsStmt;
25363
+ stampStmt;
25364
+ countsStmt;
25365
+ fingerprintStmt;
25366
+ setFingerprintStmt;
25367
+ rearmStmt;
25368
+ claimStmt;
25369
+ heartbeatStmt;
25370
+ releaseStmt;
25371
+ leaseStmt;
25372
+ inspectionsStmt;
25373
+ closeWindowStmt;
25374
+ releaseBoundaryStmt;
25375
+ freezeBoundaryStmt;
25376
+ captureRowsStmt;
25377
+ markOwedStmt;
25378
+ markCaptureBacklogOwedStmt;
25379
+ captureSkipCountStmt;
25380
+ disownCapturesStmt;
25381
+ partitionStmt;
25382
+ partitionByKindStmt;
25383
+ claimRowStmt;
25384
+ releaseRowStmt;
25385
+ releaseStaleClaimsStmt;
25386
+ /**
25387
+ * The masked detections recorded against one tool call.
25388
+ *
25389
+ * These travel with the event because a tool call's target is not
25390
+ * re-inspectable from the event alone — unlike a capture, where the text
25391
+ * itself is re-scannable. What crosses is the masked match and the rule that
25392
+ * produced it, never the value.
25393
+ */
25394
+ inspectionsFor(auditEventId) {
25395
+ return allRows(this.inspectionsStmt, { auditEventId });
24824
25396
  }
24825
- ensureSyncedAtColumn(db, "audit_events");
24826
- ensureScanLedgerTable(db);
24827
- ensureHistorySyncTable(db);
24828
- ensureBlockedDetectionsTable(db);
24829
- ensureRuleProbeCacheTable(db);
24830
- ensureWriteGateTrigger(db);
24831
- ensureTokenUsageColumns(db);
24832
- reconcileSourceProjectIds(db);
24833
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24834
- const drained = runLegacyHistoryBackfill(db);
24835
- if (drained) applyLegacyDropMigration(db, file2);
25397
+ /**
25398
+ * Sessions with structural rows still to send, oldest first.
25399
+ *
25400
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25401
+ * read. Anything recorded after the machine attached is the live forward
25402
+ * path's to deliver; this drain exists for what was recorded before it, and a
25403
+ * row both paths send is at best a duplicate request and at worst — for a
25404
+ * session root — an overwrite of the inventory ids the live path resolved.
25405
+ */
25406
+ pendingSessions(limit, before) {
25407
+ return allRows(this.sessionsStmt, { limit, before }).map(
25408
+ (r) => r.sessionId
25409
+ );
24836
25410
  }
24837
- }
24838
- function readLegacyTables(db) {
24839
- let holdsRows = false;
24840
- const marks = [];
24841
- for (const table of ["events", "findings"]) {
24842
- try {
24843
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24844
- if (row === void 0) {
24845
- holdsRows = true;
24846
- marks.push(`${table}:unreadable`);
24847
- continue;
24848
- }
24849
- if (row.n > 0) holdsRows = true;
24850
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24851
- } catch {
24852
- holdsRows = true;
24853
- marks.push(`${table}:unreadable`);
24854
- }
25411
+ /** One session's undelivered structural rows within the backlog, root first. */
25412
+ pendingRows(sessionId, limit, before) {
25413
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24855
25414
  }
24856
- return { holdsRows, mark: marks.join("|") };
24857
- }
24858
- function applyLegacyDropMigration(db, file2) {
24859
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24860
- if (!migration) return;
24861
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24862
- if (file2 !== void 0 && before?.holdsRows === true) {
24863
- try {
24864
- backupBeforeLegacyDrop(db, file2);
24865
- } catch (error61) {
24866
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24867
- return;
24868
- }
25415
+ /**
25416
+ * Captures this machine still owes the deployment, oldest first.
25417
+ *
25418
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25419
+ * by a time window — see captureRowsStmt for why a window could not express
25420
+ * this. `before` is the grace window that leaves a just-recorded capture to
25421
+ * the live path.
25422
+ */
25423
+ pendingCaptureRows(limit, before) {
25424
+ return allRows(this.captureRowsStmt, { limit, before });
24869
25425
  }
24870
- try {
25426
+ /**
25427
+ * Record that a capture is OWED to the deployment.
25428
+ *
25429
+ * Written by the attached forward path when a live send did not confirm
25430
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25431
+ * a fact rather than an inference: the machine was attached, the send did not
25432
+ * land, so the row is owed — which no time window can state, because the same
25433
+ * window that holds the rows a past attachment left owed also holds every
25434
+ * capture recorded while the machine was DETACHED, and those were never
25435
+ * offered to anyone.
25436
+ *
25437
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25438
+ * out of the drain's read.
25439
+ */
25440
+ markCaptureOwed(id) {
25441
+ this.markOwedStmt.run({ id });
25442
+ }
25443
+ /**
25444
+ * Mark every capture already on disk as owed, as of `before`.
25445
+ *
25446
+ * The consent-time backfill, called once from `aka attach` when a human
25447
+ * grants existing-history consent — never from an ongoing drain pass, and
25448
+ * never inferred from a boundary that could later move. `before` is the
25449
+ * caller's own "now" at the moment consent was granted, so what this marks
25450
+ * is exactly the backlog the consent prompt already counted, not whatever a
25451
+ * later re-attach or key rotation might widen it to.
25452
+ *
25453
+ * Returns how many rows matched, for the caller to log or test against. Not a
25454
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25455
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25456
+ */
25457
+ markCaptureBacklogOwed(before) {
25458
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25459
+ }
25460
+ /**
25461
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25462
+ *
25463
+ * CLEARS any failure reason in the same statement. A row that failed against
25464
+ * one deployment and then landed is delivered, and leaving the reason behind
25465
+ * would leave the store holding two contradictory answers about one row —
25466
+ * with the surface free to render either.
25467
+ */
25468
+ markSynced(ids, atMs) {
25469
+ this.stampAll(ids, atMs, null);
25470
+ }
25471
+ /**
25472
+ * Record that THIS MACHINE cannot express the row on the wire.
25473
+ *
25474
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25475
+ * payload, or a body the client itself refused to send. It fails identically
25476
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25477
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25478
+ * is retried; marking those would turn one outage into permanent data loss.
25479
+ */
25480
+ markSkipped(ids, atMs) {
25481
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25482
+ }
25483
+ /**
25484
+ * Record that THIS DEPLOYMENT refused the row.
25485
+ *
25486
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25487
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25488
+ * row is outstanding rather than why. What separates them is the reason, and
25489
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25490
+ * on one body, so it is terminal only for as long as this machine points at
25491
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25492
+ *
25493
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25494
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25495
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25496
+ */
25497
+ markRefused(ids, atMs) {
25498
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25499
+ }
25500
+ eachInTransaction(ids, run) {
25501
+ if (ids.length === 0) return;
24871
25502
  withTransaction(
24872
- db,
25503
+ this.db,
24873
25504
  () => {
24874
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24875
- if (alreadyDropped) return;
24876
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24877
- akaWarn(
24878
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24879
- );
24880
- return;
24881
- }
24882
- for (const statement of splitStatements(migration.sql)) {
24883
- db.exec(statement);
24884
- }
24885
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24886
- migration.tag,
24887
- Date.now()
24888
- );
25505
+ for (const id of ids) run(id);
24889
25506
  },
24890
25507
  "IMMEDIATE"
24891
25508
  );
24892
- } catch (error61) {
24893
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24894
25509
  }
24895
- }
25510
+ stampAll(ids, value, failure, failedAtMs) {
25511
+ if (ids.length === 0) return;
25512
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25513
+ withTransaction(
25514
+ this.db,
25515
+ () => {
25516
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25517
+ },
25518
+ "IMMEDIATE"
25519
+ );
25520
+ }
25521
+ /**
25522
+ * Claim rows as in-flight.
25523
+ *
25524
+ * Advisory in exactly the sense the lease is: it records that a send is in
25525
+ * progress so a surface can say so, and a lost claim costs a row showing as
25526
+ * queued while it is actually being sent. It is not exclusion — the far side
25527
+ * settles a duplicate on the row id.
25528
+ */
25529
+ claimRows(ids, atMs) {
25530
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25531
+ }
25532
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25533
+ releaseRows(ids) {
25534
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25535
+ }
25536
+ /**
25537
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25538
+ *
25539
+ * A process killed between claiming and settling leaves rows claimed with
25540
+ * nothing left to settle them. Without this they read as "sending" for ever.
25541
+ */
25542
+ releaseStaleClaims(staleBefore) {
25543
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25544
+ }
25545
+ /**
25546
+ * Every tracked row in exactly one delivery state.
25547
+ *
25548
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25549
+ * pick up now", which is a different question from "what state is this row
25550
+ * in" — and a machine that has never attached has no boundary to pass, so
25551
+ * requiring one would force a caller to invent one and report the whole store
25552
+ * as queued.
25553
+ */
25554
+ /**
25555
+ * The same partition, one row per kind that a lane carries.
25556
+ *
25557
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25558
+ * scope decides which rows exist at all, so a kind that has never been
25559
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25560
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25561
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25562
+ * different things.
25563
+ */
25564
+ partitionByKind() {
25565
+ return allRows(
25566
+ this.partitionByKindStmt,
25567
+ {}
25568
+ ).map((row) => ({
25569
+ kind: row.kind,
25570
+ queued: row.queued ?? 0,
25571
+ inProgress: row.inProgress ?? 0,
25572
+ synced: row.synced ?? 0,
25573
+ failed: row.failed ?? 0,
25574
+ refused: row.refused ?? 0,
25575
+ detached: row.detached ?? 0,
25576
+ total: row.total ?? 0
25577
+ }));
25578
+ }
25579
+ partition() {
25580
+ const row = getRow(this.partitionStmt, {});
25581
+ return {
25582
+ queued: row?.queued ?? 0,
25583
+ inProgress: row?.inProgress ?? 0,
25584
+ synced: row?.synced ?? 0,
25585
+ failed: row?.failed ?? 0,
25586
+ refused: row?.refused ?? 0,
25587
+ detached: row?.detached ?? 0,
25588
+ total: row?.total ?? 0
25589
+ };
25590
+ }
25591
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25592
+ counts(before) {
25593
+ const row = getRow(this.countsStmt, { before });
25594
+ const captures = getRow(this.captureSkipCountStmt);
25595
+ return {
25596
+ pending: row?.pending ?? 0,
25597
+ sent: row?.sent ?? 0,
25598
+ skipped: row?.skipped ?? 0,
25599
+ refused: row?.refused ?? 0,
25600
+ detached: row?.detached ?? 0,
25601
+ capturesSkipped: captures?.skipped ?? 0
25602
+ };
25603
+ }
25604
+ /**
25605
+ * The deployment the current stamps were made against, and where its backlog
25606
+ * ends.
25607
+ *
25608
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25609
+ * machine that has never drained is — and every writer below seeds the row
25610
+ * before it needs one, so nothing depends on this creating it. Keeping the
25611
+ * write off the gate path matters because the gate runs on every pass while a
25612
+ * write has to take the database's write lock.
25613
+ */
25614
+ deployment() {
25615
+ const row = getRow(
25616
+ this.fingerprintStmt
25617
+ );
25618
+ return {
25619
+ fingerprint: row?.fingerprint ?? void 0,
25620
+ backlogBefore: row?.backlogBefore ?? void 0
25621
+ };
25622
+ }
25623
+ /**
25624
+ * Point the ledger at a different deployment, discarding what it recorded
25625
+ * about the previous one.
25626
+ *
25627
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25628
+ * machine has just left are undelivered as far as the new one is concerned.
25629
+ * All four in one transaction, so a crash between them cannot leave stamps
25630
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25631
+ * a disown with no re-mark to follow it.
25632
+ *
25633
+ * The boundary is written HERE and only here, which is what freezes it: a
25634
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25635
+ * unchanged, so this never runs and the backlog does not widen back over rows
25636
+ * the live path has since delivered.
25637
+ *
25638
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25639
+ * granted existing-history consent for the deployment this call is arming —
25640
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25641
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25642
+ * apart. Passed only when that grant is valid, since this method has no way
25643
+ * to check consent itself and must not mark a row owed for a machine that
25644
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25645
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25646
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25647
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25648
+ * on the cleared side of that bound — and the re-mark in the same
25649
+ * transaction is what puts those rows back. A crash between the two cannot
25650
+ * strand the ledger disowned with nothing re-marked — the transaction either
25651
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25652
+ * committed re-enters this method on the very next pass. Omit it (the
25653
+ * structural-only tests do) to exercise the disown in isolation.
25654
+ *
25655
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25656
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25657
+ * live path can mark a capture owed from the moment `aka attach` writes the
25658
+ * descriptor, before the drain's first pass ever reaches this method, and
25659
+ * such a row sits at or after the bound rather than below it. What keeps the
25660
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25661
+ * bound — disown runs first, re-mark second, both inside the one
25662
+ * transaction above.
25663
+ */
25664
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25665
+ this.ensureRowStmt.run();
25666
+ withTransaction(
25667
+ this.db,
25668
+ () => {
25669
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25670
+ this.rearmStmt.run();
25671
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25672
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25673
+ }
25674
+ if (backfillCapturesBefore !== void 0) {
25675
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25676
+ }
25677
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25678
+ },
25679
+ "IMMEDIATE"
25680
+ );
25681
+ }
25682
+ /**
25683
+ * End the attached period: hand its rows to the live path, and release the
25684
+ * boundary so the next attachment can freeze a new one.
25685
+ *
25686
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25687
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25688
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25689
+ * during the detached period, because the machine is not attached. Rows
25690
+ * recorded in that window sit after the boundary and before the re-attach, so
25691
+ * neither path takes them, and the pending count reports none outstanding.
25692
+ *
25693
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25694
+ * closing attachment's to deliver and are no longer outstanding — that is what
25695
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25696
+ * distinction is not academic: this used to write a delivery TIME, which every
25697
+ * read treats as delivery, so one detach turned a window of undelivered rows
25698
+ * into a window of delivered ones and no surface could tell. It writes the
25699
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25700
+ * "received" stop being the same fact.
25701
+ *
25702
+ * A change of deployment still frees them (see the re-arm), because the next
25703
+ * deployment has seen none of this machine's history — so the rows reach it
25704
+ * exactly as they did when this wrote a delivery time.
25705
+ *
25706
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25707
+ * window unstamped — that half-state would re-send the whole attached period
25708
+ * on the next attach, which is the failure the boundary exists to prevent.
25709
+ */
25710
+ closeAttachedWindow(attachedAtMs, atMs) {
25711
+ this.ensureRowStmt.run();
25712
+ withTransaction(
25713
+ this.db,
25714
+ () => {
25715
+ const row = getRow(this.fingerprintStmt);
25716
+ const from = row?.backlogBefore ?? attachedAtMs;
25717
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25718
+ this.releaseBoundaryStmt.run();
25719
+ },
25720
+ "IMMEDIATE"
25721
+ );
25722
+ }
25723
+ /**
25724
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25725
+ *
25726
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25727
+ * different deployment and therefore discards what was delivered to the old
25728
+ * one: here the recipient is the same, so everything already sent to it stays
25729
+ * sent.
25730
+ */
25731
+ freezeBoundary(backlogBefore) {
25732
+ this.ensureRowStmt.run();
25733
+ this.freezeBoundaryStmt.run({ backlogBefore });
25734
+ }
25735
+ /** Take the claim, or report that someone live already holds it. */
25736
+ claim(pid, host, nowMs, staleAfterMs) {
25737
+ this.ensureRowStmt.run();
25738
+ let taken = false;
25739
+ withTransaction(
25740
+ this.db,
25741
+ () => {
25742
+ const result = this.claimStmt.run({
25743
+ pid,
25744
+ host,
25745
+ now: nowMs,
25746
+ staleBefore: nowMs - staleAfterMs
25747
+ });
25748
+ taken = result.changes === 1;
25749
+ },
25750
+ "IMMEDIATE"
25751
+ );
25752
+ return taken;
25753
+ }
25754
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25755
+ heartbeat(pid, nowMs) {
25756
+ this.heartbeatStmt.run({ now: nowMs, pid });
25757
+ }
25758
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25759
+ release(pid) {
25760
+ this.releaseStmt.run({ pid });
25761
+ }
25762
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25763
+ lease() {
25764
+ return getRow(this.leaseStmt);
25765
+ }
25766
+ };
25767
+
25768
+ // ../../packages/persistence/src/migrations.ts
25769
+ function describeObject(object2) {
25770
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25771
+ }
25772
+ function splitStatements(sql) {
25773
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25774
+ }
25775
+ function createdIndexName(statement) {
25776
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25777
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25778
+ }
25779
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25780
+ function applyMigrations(db, file2, options = {}) {
25781
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25782
+ db.exec(
25783
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25784
+ );
25785
+ const applied = new Set(
25786
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25787
+ );
25788
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25789
+ const record2 = db.prepare(
25790
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25791
+ );
25792
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25793
+ if (applied.has(migration.tag)) continue;
25794
+ if (options.skipTags?.has(migration.tag) === true) continue;
25795
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25796
+ const evidence = evidenceObjects(migration.sql);
25797
+ const present = evidence.filter((o) => evidenceExists(db, o));
25798
+ if (present.length > 0 && present.length < evidence.length) {
25799
+ const missing = evidence.filter((o) => !present.includes(o));
25800
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25801
+ akaWarn(message);
25802
+ throw new Error(`[aka] ${message}`);
25803
+ }
25804
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25805
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25806
+ const statements = splitStatements(migration.sql);
25807
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25808
+ try {
25809
+ withTransaction(
25810
+ db,
25811
+ () => {
25812
+ for (const statement of statements) {
25813
+ const indexName = createdIndexName(statement);
25814
+ if (indexName === void 0) {
25815
+ if (alreadyApplied) continue;
25816
+ } else if (indexExists(db, indexName)) {
25817
+ continue;
25818
+ }
25819
+ db.exec(statement);
25820
+ }
25821
+ if (wantsFkOff && !alreadyApplied) {
25822
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25823
+ if (violations.length > 0) {
25824
+ throw new Error(
25825
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25826
+ );
25827
+ }
25828
+ }
25829
+ record2.run(migration.tag, Date.now());
25830
+ },
25831
+ "IMMEDIATE"
25832
+ );
25833
+ } finally {
25834
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25835
+ }
25836
+ }
25837
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25838
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25839
+ }
25840
+ ensureSyncedAtColumn(db, "audit_events");
25841
+ ensureScanLedgerTable(db);
25842
+ ensureHistorySyncTable(db);
25843
+ ensureBlockedDetectionsTable(db);
25844
+ ensureRuleProbeCacheTable(db);
25845
+ ensureWriteGateTrigger(db);
25846
+ ensureTokenUsageColumns(db);
25847
+ reconcileSourceProjectIds(db);
25848
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25849
+ const drained = runLegacyHistoryBackfill(db);
25850
+ if (drained) applyLegacyDropMigration(db, file2);
25851
+ }
25852
+ }
25853
+ function readLegacyTables(db) {
25854
+ let holdsRows = false;
25855
+ const marks = [];
25856
+ for (const table of ["events", "findings"]) {
25857
+ try {
25858
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25859
+ if (row === void 0) {
25860
+ holdsRows = true;
25861
+ marks.push(`${table}:unreadable`);
25862
+ continue;
25863
+ }
25864
+ if (row.n > 0) holdsRows = true;
25865
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25866
+ } catch {
25867
+ holdsRows = true;
25868
+ marks.push(`${table}:unreadable`);
25869
+ }
25870
+ }
25871
+ return { holdsRows, mark: marks.join("|") };
25872
+ }
25873
+ function applyLegacyDropMigration(db, file2) {
25874
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25875
+ if (!migration) return;
25876
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25877
+ if (file2 !== void 0 && before?.holdsRows === true) {
25878
+ try {
25879
+ backupBeforeLegacyDrop(db, file2);
25880
+ } catch (error61) {
25881
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25882
+ return;
25883
+ }
25884
+ }
25885
+ try {
25886
+ withTransaction(
25887
+ db,
25888
+ () => {
25889
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25890
+ if (alreadyDropped) return;
25891
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25892
+ akaWarn(
25893
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25894
+ );
25895
+ return;
25896
+ }
25897
+ for (const statement of splitStatements(migration.sql)) {
25898
+ db.exec(statement);
25899
+ }
25900
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25901
+ migration.tag,
25902
+ Date.now()
25903
+ );
25904
+ },
25905
+ "IMMEDIATE"
25906
+ );
25907
+ } catch (error61) {
25908
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25909
+ }
25910
+ }
24896
25911
  function backupBeforeLegacyDrop(db, file2) {
24897
25912
  reapStalePartials(file2);
24898
25913
  const backup = backupPath(file2, "pre-drop");
@@ -25183,10 +26198,62 @@ function ensureSyncedAtColumn(db, table) {
25183
26198
  if (!columns.includes("outbox_owed")) {
25184
26199
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25185
26200
  }
26201
+ if (!columns.includes("sync_failed_at")) {
26202
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26203
+ }
26204
+ if (!columns.includes("sync_failure")) {
26205
+ withTransaction(
26206
+ db,
26207
+ () => {
26208
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26209
+ db.exec(
26210
+ `UPDATE ${table} SET synced_at = NULL
26211
+ WHERE synced_at = -1
26212
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26213
+ );
26214
+ },
26215
+ "IMMEDIATE"
26216
+ );
26217
+ }
25186
26218
  db.exec(
25187
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25188
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26219
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26220
+ BEFORE UPDATE OF sync_failure ON ${table}
26221
+ WHEN ${syncFailureRejectCondition()}
26222
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25189
26223
  );
26224
+ const syncIndexColumns = [
26225
+ "event_type",
26226
+ "synced_at",
26227
+ "sync_claimed_at",
26228
+ "started_at",
26229
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26230
+ // has to be in the index for the read to stay covered — but putting it
26231
+ // ahead of `started_at` would reorder the prefix the structural drain's
26232
+ // reads match on.
26233
+ "sync_failure"
26234
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26235
+ //
26236
+ // The delivery-state read tests it — a capture's state depends on whether a
26237
+ // live forward marked it owed — so carrying it here makes that read covering
26238
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26239
+ // But a sixth column changes what the planner charges for this index, and
26240
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26241
+ // then stops choosing the per-session index for the token rollup and walks
26242
+ // every `llm_call` in the store through the event-type index instead. That
26243
+ // read grows with the store; this one does not.
26244
+ //
26245
+ // 40 ms on the largest store measured, once per render, is a cost worth
26246
+ // paying to leave every other read's plan where it was.
26247
+ ];
26248
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26249
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26250
+ if (!syncIndexMatches) {
26251
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26252
+ db.exec(
26253
+ `CREATE INDEX idx_audit_events_sync
26254
+ ON audit_events (${syncIndexColumns.join(", ")})`
26255
+ );
26256
+ }
25190
26257
  db.exec(
25191
26258
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25192
26259
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25408,7 +26475,11 @@ function buildAuditEvent(row) {
25408
26475
  link: linkParsed?.success ? linkParsed.data : null,
25409
26476
  targetId: row.target_id,
25410
26477
  internal: intToBool(row.internal),
25411
- flagged: intToBool(row.flagged)
26478
+ flagged: intToBool(row.flagged),
26479
+ // Only meaningful when the title came out empty — a row whose body was
26480
+ // expired but whose title fell back to `tool_name` still has something to
26481
+ // render, and flagging it would make the view apologise for nothing.
26482
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25412
26483
  };
25413
26484
  }
25414
26485
  var TIMELINE_COLUMNS = `
@@ -25416,6 +26487,7 @@ var TIMELINE_COLUMNS = `
25416
26487
  event_type,
25417
26488
  started_at,
25418
26489
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26490
+ content_expired_at,
25419
26491
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25420
26492
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25421
26493
  json_extract(attributes, '$.severity') AS severity,
@@ -25542,7 +26614,8 @@ var SqliteActivityRepository = class {
25542
26614
  SELECT 1 FROM audit_events d
25543
26615
  WHERE d.root_session_id = audit_events.id
25544
26616
  AND (d.content LIKE ? ESCAPE '\\'
25545
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26617
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26618
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25546
26619
  );
25547
26620
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25548
26621
  }
@@ -26080,6 +27153,88 @@ var SqliteAuditEventsRepository = class {
26080
27153
  }
26081
27154
  };
26082
27155
 
27156
+ // ../../packages/persistence/src/repositories/body-retention.ts
27157
+ var DEFAULT_BATCH_SIZE = 500;
27158
+ var DEFAULT_MAX_ROWS = 5e4;
27159
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27160
+ var SqliteBodyRetentionRepository = class {
27161
+ constructor(db) {
27162
+ this.db = db;
27163
+ const select = (laneClause) => `
27164
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27165
+ FROM audit_events
27166
+ WHERE content IS NOT NULL
27167
+ AND started_at < :cutoff
27168
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27169
+ ${laneClause}
27170
+ ORDER BY started_at
27171
+ LIMIT :limit`;
27172
+ this.candidatesStmt = this.db.prepare(select(""));
27173
+ this.candidatesSyncSafeStmt = this.db.prepare(
27174
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27175
+ );
27176
+ this.heldBySyncStmt = this.db.prepare(`
27177
+ SELECT COUNT(*) AS n
27178
+ FROM audit_events
27179
+ WHERE content IS NOT NULL
27180
+ AND started_at < :cutoff
27181
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27182
+ AND synced_at IS NULL`);
27183
+ this.expireStmt = this.db.prepare(
27184
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27185
+ );
27186
+ }
27187
+ db;
27188
+ candidatesStmt;
27189
+ candidatesSyncSafeStmt;
27190
+ heldBySyncStmt;
27191
+ expireStmt;
27192
+ /** How many bytes a pass with these options would free, changing nothing. */
27193
+ preview(opts) {
27194
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27195
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27196
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27197
+ return {
27198
+ rowsExpired: rows.length,
27199
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27200
+ rowsHeldBySync: this.countHeldBySync(opts)
27201
+ };
27202
+ }
27203
+ /** Clear eligible bodies, in bounded batches. */
27204
+ expire(opts) {
27205
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27206
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27207
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27208
+ let rowsExpired = 0;
27209
+ let bytesFreed = 0;
27210
+ let done = true;
27211
+ while (rowsExpired < maxRows) {
27212
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27213
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27214
+ if (batch.length === 0) break;
27215
+ withTransaction(
27216
+ this.db,
27217
+ () => {
27218
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27219
+ },
27220
+ "IMMEDIATE"
27221
+ );
27222
+ rowsExpired += batch.length;
27223
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27224
+ if (batch.length < remaining) break;
27225
+ if (rowsExpired >= maxRows) {
27226
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27227
+ }
27228
+ }
27229
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27230
+ }
27231
+ countHeldBySync(opts) {
27232
+ if (opts.sweepSyncLane) return 0;
27233
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27234
+ return row.n;
27235
+ }
27236
+ };
27237
+
26083
27238
  // ../../packages/persistence/src/repositories/classified-data.ts
26084
27239
  var SqliteClassifiedDataRepository = class {
26085
27240
  constructor(db) {
@@ -26880,23 +28035,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26880
28035
  )`;
26881
28036
 
26882
28037
  // ../../packages/persistence/src/repositories/findings.ts
26883
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26884
- var DEFAULT_LOCATIONS_LIMIT = 100;
26885
- var LOCATION_RULE_IDS_CAP = 20;
26886
- function compareLocationOrder(a, b) {
26887
- return compareFindingGroupOrder(
26888
- {
26889
- severity: a.maxSeverity,
26890
- latestDetectedAt: a.latestDetectedAt,
26891
- id: ""
26892
- },
26893
- {
26894
- severity: b.maxSeverity,
26895
- latestDetectedAt: b.latestDetectedAt,
26896
- id: ""
26897
- }
26898
- );
26899
- }
26900
28038
  var CONCAT_SEP = ",";
26901
28039
  var TUPLE_SEP = "|";
26902
28040
  function splitConcat(value) {
@@ -26925,7 +28063,15 @@ function toFlatFindingRow(r) {
26925
28063
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26926
28064
  eventId: r.event_id,
26927
28065
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26928
- status: deriveInstanceStatus(r)
28066
+ status: deriveInstanceStatus(r),
28067
+ delivery: deriveFindingDelivery({
28068
+ kind: r.kind,
28069
+ syncedAt: r.synced_at,
28070
+ syncClaimedAt: r.sync_claimed_at,
28071
+ syncFailedAt: r.sync_failed_at,
28072
+ syncFailure: r.sync_failure,
28073
+ outboxOwed: r.outbox_owed
28074
+ })
26929
28075
  };
26930
28076
  }
26931
28077
  function encodeGroupCursor(group) {
@@ -26948,13 +28094,51 @@ function decodeGroupCursor(cursor) {
26948
28094
  return null;
26949
28095
  }
26950
28096
  function firstAfter(sorted, cursor) {
26951
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28097
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26952
28098
  return index === -1 ? sorted.length : index;
26953
28099
  }
26954
28100
  function findDeepLinked(sorted, page, id) {
26955
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26956
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28101
+ if (page.some((t) => t.id === id)) return void 0;
28102
+ return sorted.find((t) => t.id === id);
26957
28103
  }
28104
+ function encodeLocationCursor(location) {
28105
+ const payload = {
28106
+ sev: location.maxSeverity,
28107
+ t: location.latestDetectedAt,
28108
+ r: location.repo,
28109
+ f: location.file
28110
+ };
28111
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28112
+ }
28113
+ function decodeLocationCursor(cursor) {
28114
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28115
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28116
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28117
+ }
28118
+ return null;
28119
+ }
28120
+ function firstLocationAfter(sorted, cursor) {
28121
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28122
+ return index === -1 ? sorted.length : index;
28123
+ }
28124
+ function findDeepLinkedLocation(sorted, page, id) {
28125
+ if (page.some((l) => l.id === id)) return void 0;
28126
+ return sorted.find((l) => l.id === id);
28127
+ }
28128
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28129
+ d.severity AS severity, f.masked_match AS masked_match,
28130
+ f.action_taken AS action_taken, f.confidence AS confidence,
28131
+ e.started_at AS occurred_at,
28132
+ e.source_tool AS source_tool,
28133
+ e.repo AS repo,
28134
+ e.file_path AS file,
28135
+ e.tool_name AS tool_name,
28136
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28137
+ e.event_type AS kind, f.finding_key AS finding_key,
28138
+ ${latestResolutionStatusSql("f")} AS latest_status,
28139
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28140
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28141
+ e.outbox_owed AS outbox_owed`;
26958
28142
  var DAY_MS3 = 864e5;
26959
28143
  var SqliteFindingsRepository = class {
26960
28144
  constructor(db) {
@@ -27075,30 +28259,26 @@ var SqliteFindingsRepository = class {
27075
28259
  );
27076
28260
  }
27077
28261
  /**
27078
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27079
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27080
- * attributes bag, rule_id/category/severity from the definition), scoped to
27081
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27082
- * rows this list must never surface), groups by ruleId, computes
27083
- * per-filter-excluded facets, applies the requested filters, and sorts by
27084
- * severity then recency. Filtering
27085
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27086
- * reflect the full filtered set; `items` is the requested
27087
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27088
- * filter, `totals.findings` counts only instances whose derived status was
27089
- * requested, and each item's instance preview is narrowed the same way.
28262
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28263
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28264
+ * list must never surface), with per-filter-excluded facets, the requested
28265
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28266
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28267
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28268
+ * Under a `status` filter, `totals.findings` counts only findings whose
28269
+ * derived status was requested.
28270
+ *
28271
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28272
+ * folding EVERY finding into the numbers a type row and the filters need
28273
+ * (count, severity, category, providers, actions, statuses, latest, search
28274
+ * text). The findings OF a type come from listFindingInstances scoped to
28275
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27090
28276
  *
27091
- * Two reads, neither of which materializes a row per finding:
27092
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27093
- * the group and the filters need (count, providers, actions, statuses,
27094
- * latest, search text);
27095
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27096
- * populate `instances` for the table's expanded rows.
27097
28277
  * The aggregates carry raw DB values and are translated by the same
27098
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27099
- * rule is ever restated in SQL.
28278
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28279
+ * status rule is ever restated in SQL.
27100
28280
  */
27101
- listGroupedFindings(query) {
28281
+ listFindingTypes(query) {
27102
28282
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27103
28283
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27104
28284
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27111,12 +28291,7 @@ var SqliteFindingsRepository = class {
27111
28291
  predicate,
27112
28292
  params: sessionParams
27113
28293
  });
27114
- const rows = this.previewRows(aggregates, {
27115
- sessionId: query.sessionId,
27116
- from: query.from
27117
- });
27118
- const groupable = rows.map(toFlatFindingRow);
27119
- const allGroups = buildFindingGroups(groupable, { aggregates });
28294
+ const allTypes = buildFindingTypes(aggregates);
27120
28295
  const filterOpts = {
27121
28296
  severity: query.severity,
27122
28297
  providers: query.provider,
@@ -27125,30 +28300,25 @@ var SqliteFindingsRepository = class {
27125
28300
  subtype: query.subtype,
27126
28301
  q: query.q
27127
28302
  };
27128
- const facets = computeFindingFacets(allGroups, filterOpts);
27129
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28303
+ const facets = computeFindingFacets(allTypes, filterOpts);
28304
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27130
28305
  const statusFilter = query.status ?? [];
27131
28306
  const totals = {
27132
- findings: sorted.reduce((acc, g) => {
27133
- if (statusFilter.length === 0) return acc + g.instanceCount;
27134
- const agg = aggregates.get(g.id);
27135
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28307
+ findings: sorted.reduce((acc, t) => {
28308
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28309
+ const agg = aggregates.get(t.id);
28310
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27136
28311
  }, 0),
27137
- groups: sorted.length
28312
+ types: sorted.length
27138
28313
  };
27139
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28314
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27140
28315
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27141
28316
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27142
28317
  const page = sorted.slice(start, start + limit);
27143
28318
  const lastOnPage = page.at(-1);
27144
28319
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27145
28320
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27146
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27147
- const narrow = (g) => statusSet ? {
27148
- ...g,
27149
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27150
- } : g;
27151
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28321
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27152
28322
  return Promise.resolve({
27153
28323
  totals,
27154
28324
  facets,
@@ -27159,7 +28329,7 @@ var SqliteFindingsRepository = class {
27159
28329
  }
27160
28330
  /**
27161
28331
  * One row per rule_id, folding EVERY instance of the group into the values
27162
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28332
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27163
28333
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27164
28334
  *
27165
28335
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27213,6 +28383,7 @@ var SqliteFindingsRepository = class {
27213
28383
  providers: query.provider,
27214
28384
  actions: query.action,
27215
28385
  statuses: query.status,
28386
+ deliveries: query.deployment,
27216
28387
  tools: query.tool,
27217
28388
  repo: query.repo,
27218
28389
  file: query.file,
@@ -27253,13 +28424,25 @@ var SqliteFindingsRepository = class {
27253
28424
  });
27254
28425
  }
27255
28426
  /**
27256
- * The same findings folded by location: repository, then file within it.
28427
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27257
28428
  *
27258
28429
  * The grouping keys come from the capturing event's attributes, which is what
27259
- * the local store relates a finding to — there is no finding↔asset row to
27260
- * group by instead. A repo or file the event did not record folds into the
27261
- * empty-string bucket, which the view renders but does not link, since no
27262
- * filter can name it.
28430
+ * the local store relates a finding to; there is no finding↔asset row to group
28431
+ * by instead. A repo or file the event did not record folds into the
28432
+ * empty-string bucket, which is a real location like any other: it is listed,
28433
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28434
+ *
28435
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28436
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28437
+ * list was rebuilt to remove — and two-level pagination inside an
28438
+ * expand/collapse table is what pushed that view to master/detail in the first
28439
+ * place.
28440
+ *
28441
+ * Every filter narrows the FINDINGS and the locations fall out of what
28442
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28443
+ * reports for the same filters scoped to that pair. The view depends on it:
28444
+ * one toolbar sits over both panels precisely because a location owns none of
28445
+ * its fields.
27263
28446
  */
27264
28447
  listFindingLocations(query) {
27265
28448
  const opts = {
@@ -27268,16 +28451,20 @@ var SqliteFindingsRepository = class {
27268
28451
  providers: query.provider,
27269
28452
  actions: query.action,
27270
28453
  statuses: query.status,
28454
+ deliveries: query.deployment,
27271
28455
  tools: query.tool,
27272
28456
  q: query.q
27273
28457
  };
27274
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28458
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28459
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27275
28460
  const byRepo = /* @__PURE__ */ new Map();
28461
+ const accumulator = createInstanceFacetAccumulator(opts);
27276
28462
  let total = 0;
27277
28463
  for (const row of this.scanFindingRows({
27278
28464
  sessionId: query.sessionId,
27279
28465
  from: query.from
27280
28466
  })) {
28467
+ accumulator.add(row);
27281
28468
  if (!matchesInstanceFilters(row, opts)) continue;
27282
28469
  total += 1;
27283
28470
  let files = byRepo.get(row.repo);
@@ -27292,103 +28479,35 @@ var SqliteFindingsRepository = class {
27292
28479
  }
27293
28480
  addToLocation(acc, row);
27294
28481
  }
27295
- let fileCount = 0;
27296
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27297
- fileCount += files.size;
27298
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27299
- file: file2,
27300
- instanceCount: acc.instanceCount,
27301
- maxSeverity: acc.maxSeverity,
27302
- latestDetectedAt: acc.latestDetectedAt,
27303
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27304
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27305
- })).sort(compareLocationOrder);
27306
- const rollup = fileRows.reduce(
27307
- (a, f) => ({
27308
- instanceCount: a.instanceCount + f.instanceCount,
27309
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27310
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27311
- }),
27312
- {
27313
- instanceCount: 0,
27314
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27315
- latestDetectedAt: ""
27316
- }
27317
- );
27318
- const statuses = fileRows.map((f) => f.status);
27319
- const folded = foldGroupStatus(statuses);
27320
- return {
27321
- repo,
27322
- instanceCount: rollup.instanceCount,
27323
- maxSeverity: rollup.maxSeverity,
27324
- latestDetectedAt: rollup.latestDetectedAt,
27325
- ...folded === void 0 ? {} : { status: folded },
27326
- files: fileRows
27327
- };
27328
- });
27329
- repos.sort(compareLocationOrder);
28482
+ const sorted = [];
28483
+ for (const [repo, files] of byRepo) {
28484
+ for (const [file2, acc] of files) {
28485
+ const status = foldGroupStatus(acc.statuses);
28486
+ sorted.push({
28487
+ id: encodeLocationId(repo, file2),
28488
+ repo,
28489
+ file: file2,
28490
+ instanceCount: acc.instanceCount,
28491
+ maxSeverity: acc.maxSeverity,
28492
+ latestDetectedAt: acc.latestDetectedAt,
28493
+ ...status === void 0 ? {} : { status },
28494
+ ruleIds: [...acc.ruleIds]
28495
+ });
28496
+ }
28497
+ }
28498
+ sorted.sort(compareLocationOrder);
28499
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28500
+ const page = sorted.slice(start, start + limit);
28501
+ const lastOnPage = page.at(-1);
28502
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28503
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27330
28504
  return Promise.resolve({
27331
- totals: { findings: total, repos: repos.length, files: fileCount },
27332
- items: repos.slice(0, limit),
27333
- hasMore: repos.length > limit
28505
+ totals: { findings: total, locations: sorted.length },
28506
+ facets: accumulator.facets(),
28507
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28508
+ nextCursor
27334
28509
  });
27335
28510
  }
27336
- /**
27337
- * Each group's newest instances, for the table's expanded rows.
27338
- *
27339
- * ONE index-ordered scan with early termination, and the shape is the point.
27340
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27341
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27342
- * through a temp B-tree to keep a bounded preview of each group, and then
27343
- * sorts the survivors again for the page order. Both sorts grow with the
27344
- * store while the answer does not.
27345
- *
27346
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27347
- * (or the session or window index the scope names — see `findingScanSql`),
27348
- * which is already the order the page wants, and keeps rows per rule until
27349
- * each rule has as many as it can show. The aggregate the caller already holds
27350
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27351
- * per rule, summed, is the number of rows this scan has to find, and it stops
27352
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27353
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27354
- * store with many firing rules widens it. The bound that DOES hold
27355
- * unconditionally is the sorted form's floor: this scan visits at most as
27356
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27357
- * sorted, and stops the moment every rule has its cap, where the sorted form
27358
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27359
- * wanted instances sitting at the tail of the scope — is one pass over
27360
- * everything in scope with a block sort of the id tie-break only, never a
27361
- * sort of the scope, which is still that floor.
27362
- *
27363
- * A row whose rule the aggregate did not see is skipped: the two statements
27364
- * run without a shared snapshot, so a capture landing between them can add a
27365
- * rule here that has no counts there, and the counts are what the group is
27366
- * built from.
27367
- */
27368
- previewRows(aggregates, scope) {
27369
- const wanted = /* @__PURE__ */ new Map();
27370
- let remaining = 0;
27371
- for (const [ruleId, agg] of aggregates) {
27372
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27373
- wanted.set(ruleId, n);
27374
- remaining += n;
27375
- }
27376
- const rows = [];
27377
- if (remaining === 0) return rows;
27378
- const { sql, params } = this.findingScanSql(scope);
27379
- const taken = /* @__PURE__ */ new Map();
27380
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27381
- const want = wanted.get(r.rule_id);
27382
- if (want === void 0) continue;
27383
- const have = taken.get(r.rule_id) ?? 0;
27384
- if (have >= want) continue;
27385
- taken.set(r.rule_id, have + 1);
27386
- rows.push(r);
27387
- remaining -= 1;
27388
- if (remaining === 0) break;
27389
- }
27390
- return rows;
27391
- }
27392
28511
  /**
27393
28512
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27394
28513
  *
@@ -27415,6 +28534,33 @@ var SqliteFindingsRepository = class {
27415
28534
  yield toFlatFindingRow(r);
27416
28535
  }
27417
28536
  }
28537
+ /**
28538
+ * One finding by its own id, or null when no such row exists.
28539
+ *
28540
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28541
+ * the store — and, unlike anything derived from a list page, it resolves a
28542
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28543
+ * deep link needs: the id it carries may name a finding thousands of rows
28544
+ * older than anything a first page holds.
28545
+ *
28546
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28547
+ * RESOLVES an id; whether that row would survive the list's current filters is
28548
+ * a different question, and hiding the target because a filter excludes it is
28549
+ * worse than showing it.
28550
+ *
28551
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28552
+ * type should the list select?" and "what does the drawer show?".
28553
+ */
28554
+ findingInstance(id) {
28555
+ const row = this.db.prepare(
28556
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28557
+ FROM inspection_findings f
28558
+ JOIN audit_events e ON e.id = f.audit_event_id
28559
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28560
+ WHERE f.id = ?`
28561
+ ).get(id);
28562
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28563
+ }
27418
28564
  /**
27419
28565
  * The one statement both instance-level scans run: every finding in scope,
27420
28566
  * joined to its event and definition, newest first.
@@ -27448,17 +28594,7 @@ var SqliteFindingsRepository = class {
27448
28594
  conditions.push("e.started_at >= ?");
27449
28595
  params.push(isoToEpochMillis(scope.from));
27450
28596
  }
27451
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27452
- d.severity AS severity, f.masked_match AS masked_match,
27453
- f.action_taken AS action_taken, f.confidence AS confidence,
27454
- e.started_at AS occurred_at,
27455
- e.source_tool AS source_tool,
27456
- e.repo AS repo,
27457
- e.file_path AS file,
27458
- e.tool_name AS tool_name,
27459
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27460
- e.event_type AS kind, f.finding_key AS finding_key,
27461
- ${latestResolutionStatusSql("f")} AS latest_status
28597
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27462
28598
  FROM audit_events e
27463
28599
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27464
28600
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27472,6 +28608,26 @@ var SqliteFindingsRepository = class {
27472
28608
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27473
28609
  const rows = this.db.prepare(
27474
28610
  `SELECT rule_id,
28611
+ -- BARE columns beside max(latest_at), which is deliberate and
28612
+ -- is SQLite's documented behaviour: with a single min()/max()
28613
+ -- in an aggregate query, every bare column takes its value from
28614
+ -- the row that produced the extremum. So these are the severity
28615
+ -- and category of the definition whose finding is NEWEST, which
28616
+ -- is what the row-based build they replaced read off its first
28617
+ -- (newest-first) row.
28618
+ --
28619
+ -- min() is WRONG here and was the defect: inspection_definitions
28620
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28621
+ -- mints a new row), so a rule whose severity moved between
28622
+ -- versions has several, and min() picks the ALPHABETICALLY
28623
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28624
+ -- That is arbitrary in direction, and it feeds the badge, the
28625
+ -- filter, the facet counts and the primary sort key.
28626
+ --
28627
+ -- Adding a second min()/max() aggregate here would make these
28628
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28629
+ severity,
28630
+ category,
27475
28631
  sum(tuple_count) AS instance_count,
27476
28632
  max(latest_at) AS latest_at,
27477
28633
  group_concat(source_tools) AS source_tools,
@@ -27482,6 +28638,14 @@ var SqliteFindingsRepository = class {
27482
28638
  group_concat(tool_names) AS tool_names
27483
28639
  FROM (
27484
28640
  SELECT d.rule_id AS rule_id,
28641
+ -- Severity and category are columns of the DEFINITION, and
28642
+ -- a rule can have SEVERAL definitions (one per version), so
28643
+ -- these are grouped on below and resolved to the newest
28644
+ -- firing version by the outer query's bare-column select.
28645
+ -- They ride the aggregate because the type build has no rows
28646
+ -- to read them off \u2014 see buildFindingTypes.
28647
+ d.severity AS severity,
28648
+ d.category AS category,
27485
28649
  e.event_type || '${TUPLE_SEP}' ||
27486
28650
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27487
28651
  coalesce(latest.status, '') AS status_tuple,
@@ -27496,7 +28660,7 @@ var SqliteFindingsRepository = class {
27496
28660
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27497
28661
  ON latest.finding_key = f.finding_key
27498
28662
  ${scope.predicate}
27499
- GROUP BY d.rule_id, status_tuple
28663
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27500
28664
  )
27501
28665
  GROUP BY rule_id`
27502
28666
  ).all(scope.params);
@@ -27505,6 +28669,8 @@ var SqliteFindingsRepository = class {
27505
28669
  r.rule_id,
27506
28670
  {
27507
28671
  instanceCount: r.instance_count,
28672
+ severity: r.severity,
28673
+ category: r.category,
27508
28674
  sourceTools: splitConcat(r.source_tools),
27509
28675
  actionsTaken: splitConcat(r.actions_taken),
27510
28676
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27521,7 +28687,7 @@ var SqliteFindingsRepository = class {
27521
28687
  latestDetectedAt: epochMillisToIso(r.latest_at),
27522
28688
  // Free text only — joined and substring-matched, so group_concat's
27523
28689
  // commas need no unpicking (a repo/path containing one still matches).
27524
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28690
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27525
28691
  // tell "no q this request" from "a group with no repo/file at all"
27526
28692
  // and skip priming a haystack nothing will read.
27527
28693
  ...withSearchText ? {
@@ -27549,7 +28715,9 @@ var SqliteFindingsRepository = class {
27549
28715
  )
27550
28716
  );
27551
28717
  for (const row of grouped) {
27552
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28718
+ if (Object.hasOwn(byAction, row.action_taken)) {
28719
+ byAction[row.action_taken] = row.c;
28720
+ }
27553
28721
  }
27554
28722
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27555
28723
  const sevRows = allRows(
@@ -27566,7 +28734,9 @@ var SqliteFindingsRepository = class {
27566
28734
  )
27567
28735
  );
27568
28736
  for (const row of sevRows) {
27569
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28737
+ if (Object.hasOwn(bySeverity, row.severity)) {
28738
+ bySeverity[row.severity] = row.c;
28739
+ }
27570
28740
  }
27571
28741
  const categories = ENFORCEABLE_CATEGORIES;
27572
28742
  const enabledRows = allRows(
@@ -27615,469 +28785,6 @@ function isoDay(ms) {
27615
28785
  return new Date(ms).toISOString().slice(0, 10);
27616
28786
  }
27617
28787
 
27618
- // ../../packages/persistence/src/repositories/history-sync.ts
27619
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27620
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27621
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27622
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27623
- var SKIPPED = -1;
27624
- var ROW_COLUMNS = `id,
27625
- parent_id AS parentId,
27626
- root_session_id AS rootSessionId,
27627
- event_type AS eventType,
27628
- host_id AS hostId,
27629
- harness_id AS harnessId,
27630
- source_project_id AS sourceProjectId,
27631
- started_at AS startedAt,
27632
- ended_at AS endedAt,
27633
- severity,
27634
- priority,
27635
- content,
27636
- content_hash AS contentHash,
27637
- attributes`;
27638
- var SqliteHistorySyncRepository = class {
27639
- constructor(db) {
27640
- this.db = db;
27641
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27642
- this.sessionsStmt = db.prepare(
27643
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27644
- FROM audit_events
27645
- WHERE synced_at IS NULL
27646
- AND event_type IN (${TYPE_LIST})
27647
- AND started_at < :before
27648
- GROUP BY sessionId
27649
- ORDER BY earliest
27650
- LIMIT :limit`
27651
- );
27652
- this.rowsStmt = db.prepare(
27653
- `SELECT ${ROW_COLUMNS}
27654
- FROM audit_events
27655
- WHERE synced_at IS NULL
27656
- AND event_type IN (${TYPE_LIST})
27657
- AND started_at < :before
27658
- AND COALESCE(root_session_id, id) = :sessionId
27659
- ORDER BY (event_type = 'session') DESC, started_at
27660
- LIMIT :limit`
27661
- );
27662
- this.captureRowsStmt = db.prepare(
27663
- `SELECT ${ROW_COLUMNS}
27664
- FROM audit_events
27665
- WHERE synced_at IS NULL
27666
- AND sync_claimed_at IS NULL
27667
- AND outbox_owed = 1
27668
- AND event_type IN (${CAPTURE_TYPE_LIST})
27669
- AND started_at < :before
27670
- ORDER BY started_at
27671
- LIMIT :limit`
27672
- );
27673
- this.markOwedStmt = db.prepare(
27674
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27675
- );
27676
- this.stampStmt = db.prepare(
27677
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27678
- );
27679
- this.claimRowStmt = db.prepare(
27680
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27681
- );
27682
- this.releaseRowStmt = db.prepare(
27683
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27684
- );
27685
- this.releaseStaleClaimsStmt = db.prepare(
27686
- `UPDATE audit_events SET sync_claimed_at = NULL
27687
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27688
- );
27689
- this.partitionStmt = db.prepare(
27690
- `SELECT
27691
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27692
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27693
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27694
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27695
- COUNT(*) AS total
27696
- FROM audit_events
27697
- WHERE event_type IN (${TYPE_LIST})`
27698
- );
27699
- this.countsStmt = db.prepare(
27700
- `SELECT
27701
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27702
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27703
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27704
- FROM audit_events
27705
- WHERE event_type IN (${TYPE_LIST})`
27706
- );
27707
- this.captureSkipCountStmt = db.prepare(
27708
- `SELECT COUNT(*) AS skipped
27709
- FROM audit_events
27710
- WHERE synced_at = ${String(SKIPPED)}
27711
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27712
- );
27713
- this.fingerprintStmt = db.prepare(
27714
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27715
- FROM history_sync WHERE id = 1`
27716
- );
27717
- this.setFingerprintStmt = db.prepare(
27718
- `UPDATE history_sync
27719
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27720
- WHERE id = 1`
27721
- );
27722
- this.disownCapturesStmt = db.prepare(
27723
- `UPDATE audit_events SET outbox_owed = NULL
27724
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27725
- );
27726
- this.rearmStmt = db.prepare(
27727
- `UPDATE audit_events SET synced_at = NULL
27728
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27729
- );
27730
- this.claimStmt = db.prepare(
27731
- `UPDATE history_sync
27732
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27733
- WHERE id = 1
27734
- AND (owner_pid IS NULL
27735
- OR heartbeat_at IS NULL
27736
- OR heartbeat_at < :staleBefore
27737
- OR heartbeat_at > :now)`
27738
- );
27739
- this.heartbeatStmt = db.prepare(
27740
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27741
- );
27742
- this.releaseStmt = db.prepare(
27743
- `UPDATE history_sync
27744
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27745
- WHERE id = 1 AND owner_pid = :pid`
27746
- );
27747
- this.closeWindowStmt = db.prepare(
27748
- `UPDATE audit_events SET synced_at = :at
27749
- WHERE synced_at IS NULL
27750
- AND event_type IN (${TYPE_LIST})
27751
- AND started_at >= :attachedAt`
27752
- );
27753
- this.releaseBoundaryStmt = db.prepare(
27754
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27755
- );
27756
- this.freezeBoundaryStmt = db.prepare(
27757
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27758
- );
27759
- this.leaseStmt = db.prepare(
27760
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27761
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27762
- FROM history_sync WHERE id = 1`
27763
- );
27764
- this.inspectionsStmt = db.prepare(
27765
- `SELECT d.rule_id AS ruleId,
27766
- d.name AS ruleName,
27767
- d.version AS ruleVersion,
27768
- d.category AS category,
27769
- d.severity AS severity,
27770
- f.span_start AS spanStart,
27771
- f.span_end AS spanEnd,
27772
- f.masked_match AS maskedMatch,
27773
- f.action_taken AS actionTaken,
27774
- f.confidence AS confidence
27775
- FROM inspection_findings f
27776
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27777
- WHERE f.audit_event_id = :auditEventId
27778
- ORDER BY f.span_start, f.id`
27779
- );
27780
- }
27781
- db;
27782
- ensureRowStmt;
27783
- sessionsStmt;
27784
- rowsStmt;
27785
- stampStmt;
27786
- countsStmt;
27787
- fingerprintStmt;
27788
- setFingerprintStmt;
27789
- rearmStmt;
27790
- claimStmt;
27791
- heartbeatStmt;
27792
- releaseStmt;
27793
- leaseStmt;
27794
- inspectionsStmt;
27795
- closeWindowStmt;
27796
- releaseBoundaryStmt;
27797
- freezeBoundaryStmt;
27798
- captureRowsStmt;
27799
- markOwedStmt;
27800
- captureSkipCountStmt;
27801
- disownCapturesStmt;
27802
- partitionStmt;
27803
- claimRowStmt;
27804
- releaseRowStmt;
27805
- releaseStaleClaimsStmt;
27806
- /**
27807
- * The masked detections recorded against one tool call.
27808
- *
27809
- * These travel with the event because a tool call's target is not
27810
- * re-inspectable from the event alone — unlike a capture, where the text
27811
- * itself is re-scannable. What crosses is the masked match and the rule that
27812
- * produced it, never the value.
27813
- */
27814
- inspectionsFor(auditEventId) {
27815
- return allRows(this.inspectionsStmt, { auditEventId });
27816
- }
27817
- /**
27818
- * Sessions with structural rows still to send, oldest first.
27819
- *
27820
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27821
- * read. Anything recorded after the machine attached is the live forward
27822
- * path's to deliver; this drain exists for what was recorded before it, and a
27823
- * row both paths send is at best a duplicate request and at worst — for a
27824
- * session root — an overwrite of the inventory ids the live path resolved.
27825
- */
27826
- pendingSessions(limit, before) {
27827
- return allRows(this.sessionsStmt, { limit, before }).map(
27828
- (r) => r.sessionId
27829
- );
27830
- }
27831
- /** One session's undelivered structural rows within the backlog, root first. */
27832
- pendingRows(sessionId, limit, before) {
27833
- return allRows(this.rowsStmt, { sessionId, limit, before });
27834
- }
27835
- /**
27836
- * Captures this machine still owes the deployment, oldest first.
27837
- *
27838
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27839
- * by a time window — see captureRowsStmt for why a window could not express
27840
- * this. `before` is the grace window that leaves a just-recorded capture to
27841
- * the live path.
27842
- */
27843
- pendingCaptureRows(limit, before) {
27844
- return allRows(this.captureRowsStmt, { limit, before });
27845
- }
27846
- /**
27847
- * Record that a capture is OWED to the deployment.
27848
- *
27849
- * Written by the attached forward path when a live send did not confirm
27850
- * delivery, and read by the drain as the whole of its eligibility test. It is
27851
- * a fact rather than an inference: the machine was attached, the send did not
27852
- * land, so the row is owed — which no time window can state, because the same
27853
- * window that holds the rows a past attachment left owed also holds every
27854
- * capture recorded while the machine was DETACHED, and those were never
27855
- * offered to anyone.
27856
- *
27857
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27858
- * out of the drain's read.
27859
- */
27860
- markCaptureOwed(id) {
27861
- this.markOwedStmt.run({ id });
27862
- }
27863
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27864
- markSynced(ids, atMs) {
27865
- this.stampAll(ids, atMs);
27866
- }
27867
- /**
27868
- * Record that a row will never be sent.
27869
- *
27870
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27871
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27872
- * is retried; marking those would turn one outage into permanent data loss.
27873
- */
27874
- markSkipped(ids) {
27875
- this.stampAll(ids, SKIPPED);
27876
- }
27877
- eachInTransaction(ids, run) {
27878
- if (ids.length === 0) return;
27879
- withTransaction(
27880
- this.db,
27881
- () => {
27882
- for (const id of ids) run(id);
27883
- },
27884
- "IMMEDIATE"
27885
- );
27886
- }
27887
- stampAll(ids, value) {
27888
- if (ids.length === 0) return;
27889
- withTransaction(
27890
- this.db,
27891
- () => {
27892
- for (const id of ids) this.stampStmt.run({ at: value, id });
27893
- },
27894
- "IMMEDIATE"
27895
- );
27896
- }
27897
- /**
27898
- * Claim rows as in-flight.
27899
- *
27900
- * Advisory in exactly the sense the lease is: it records that a send is in
27901
- * progress so a surface can say so, and a lost claim costs a row showing as
27902
- * queued while it is actually being sent. It is not exclusion — the far side
27903
- * settles a duplicate on the row id.
27904
- */
27905
- claimRows(ids, atMs) {
27906
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27907
- }
27908
- /** Give back a claim without settling — the send failed, the row is queued again. */
27909
- releaseRows(ids) {
27910
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27911
- }
27912
- /**
27913
- * Clear claims older than `staleBefore`, and report how many were cleared.
27914
- *
27915
- * A process killed between claiming and settling leaves rows claimed with
27916
- * nothing left to settle them. Without this they read as "sending" for ever.
27917
- */
27918
- releaseStaleClaims(staleBefore) {
27919
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27920
- }
27921
- /**
27922
- * Every tracked row in exactly one delivery state.
27923
- *
27924
- * Takes no boundary on purpose. The boundary answers "what should the drain
27925
- * pick up now", which is a different question from "what state is this row
27926
- * in" — and a machine that has never attached has no boundary to pass, so
27927
- * requiring one would force a caller to invent one and report the whole store
27928
- * as queued.
27929
- */
27930
- partition() {
27931
- const row = getRow(this.partitionStmt, {});
27932
- return {
27933
- queued: row?.queued ?? 0,
27934
- inProgress: row?.inProgress ?? 0,
27935
- synced: row?.synced ?? 0,
27936
- failed: row?.failed ?? 0,
27937
- total: row?.total ?? 0
27938
- };
27939
- }
27940
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27941
- counts(before) {
27942
- const row = getRow(
27943
- this.countsStmt,
27944
- { before }
27945
- );
27946
- const captures = getRow(this.captureSkipCountStmt);
27947
- return {
27948
- pending: row?.pending ?? 0,
27949
- sent: row?.sent ?? 0,
27950
- skipped: row?.skipped ?? 0,
27951
- capturesSkipped: captures?.skipped ?? 0
27952
- };
27953
- }
27954
- /**
27955
- * The deployment the current stamps were made against, and where its backlog
27956
- * ends.
27957
- *
27958
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27959
- * machine that has never drained is — and every writer below seeds the row
27960
- * before it needs one, so nothing depends on this creating it. Keeping the
27961
- * write off the gate path matters because the gate runs on every pass while a
27962
- * write has to take the database's write lock.
27963
- */
27964
- deployment() {
27965
- const row = getRow(
27966
- this.fingerprintStmt
27967
- );
27968
- return {
27969
- fingerprint: row?.fingerprint ?? void 0,
27970
- backlogBefore: row?.backlogBefore ?? void 0
27971
- };
27972
- }
27973
- /**
27974
- * Point the ledger at a different deployment, discarding what it recorded
27975
- * about the previous one.
27976
- *
27977
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
27978
- * machine has just left are undelivered as far as the new one is concerned.
27979
- * All three in one transaction, so a crash between them cannot leave stamps
27980
- * attributed to the wrong deployment, or a boundary that belongs to another.
27981
- *
27982
- * The boundary is written HERE and only here, which is what freezes it: a
27983
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
27984
- * unchanged, so this never runs and the backlog does not widen back over rows
27985
- * the live path has since delivered.
27986
- */
27987
- rearmFor(fingerprint, backlogBefore) {
27988
- this.ensureRowStmt.run();
27989
- withTransaction(
27990
- this.db,
27991
- () => {
27992
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
27993
- this.rearmStmt.run();
27994
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
27995
- this.disownCapturesStmt.run();
27996
- }
27997
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27998
- },
27999
- "IMMEDIATE"
28000
- );
28001
- }
28002
- /**
28003
- * End the attached period: hand its rows to the live path, and release the
28004
- * boundary so the next attachment can freeze a new one.
28005
- *
28006
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28007
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28008
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28009
- * during the detached period, because the machine is not attached. Rows
28010
- * recorded in that window sit after the boundary and before the re-attach, so
28011
- * neither path takes them, and the pending count reports none outstanding.
28012
- *
28013
- * Stamping the attached window is not a claim that every one of those rows
28014
- * reached the deployment — the live path drops on failure and says so
28015
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28016
- * status quo: they sit outside the frozen boundary today and are equally never
28017
- * re-sent. Making it explicit is what lets the boundary move.
28018
- *
28019
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28020
- * window unstamped — that half-state would re-send the whole attached period
28021
- * on the next attach, which is the failure the boundary exists to prevent.
28022
- */
28023
- closeAttachedWindow(attachedAtMs, atMs) {
28024
- this.ensureRowStmt.run();
28025
- withTransaction(
28026
- this.db,
28027
- () => {
28028
- const row = getRow(this.fingerprintStmt);
28029
- const from = row?.backlogBefore ?? attachedAtMs;
28030
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28031
- this.releaseBoundaryStmt.run();
28032
- },
28033
- "IMMEDIATE"
28034
- );
28035
- }
28036
- /**
28037
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28038
- *
28039
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28040
- * different deployment and therefore discards what was delivered to the old
28041
- * one: here the recipient is the same, so everything already sent to it stays
28042
- * sent.
28043
- */
28044
- freezeBoundary(backlogBefore) {
28045
- this.ensureRowStmt.run();
28046
- this.freezeBoundaryStmt.run({ backlogBefore });
28047
- }
28048
- /** Take the claim, or report that someone live already holds it. */
28049
- claim(pid, host, nowMs, staleAfterMs) {
28050
- this.ensureRowStmt.run();
28051
- let taken = false;
28052
- withTransaction(
28053
- this.db,
28054
- () => {
28055
- const result = this.claimStmt.run({
28056
- pid,
28057
- host,
28058
- now: nowMs,
28059
- staleBefore: nowMs - staleAfterMs
28060
- });
28061
- taken = result.changes === 1;
28062
- },
28063
- "IMMEDIATE"
28064
- );
28065
- return taken;
28066
- }
28067
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28068
- heartbeat(pid, nowMs) {
28069
- this.heartbeatStmt.run({ now: nowMs, pid });
28070
- }
28071
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28072
- release(pid) {
28073
- this.releaseStmt.run({ pid });
28074
- }
28075
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28076
- lease() {
28077
- return getRow(this.leaseStmt);
28078
- }
28079
- };
28080
-
28081
28788
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28082
28789
  var SqliteInspectionDefinitionsRepository = class {
28083
28790
  constructor(db) {
@@ -28272,7 +28979,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28272
28979
  }
28273
28980
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28274
28981
  }
28275
- function readManagedSettings(paths = managedSettingsPaths()) {
28982
+ var testOnlyManagedPaths = null;
28983
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28276
28984
  for (const path of paths) {
28277
28985
  let text;
28278
28986
  try {
@@ -28307,6 +29015,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28307
29015
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28308
29016
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28309
29017
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29018
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28310
29019
  if (values.vaultConsent !== void 0) {
28311
29020
  merged.vaultConsent = values.vaultConsent ? (
28312
29021
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30752,7 +31461,7 @@ function toUtcDateString(ms) {
30752
31461
  return new Date(ms).toISOString().slice(0, 10);
30753
31462
  }
30754
31463
  function isTimeseriesSeverity(s) {
30755
- return s === "critical" || s === "high" || s === "medium";
31464
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30756
31465
  }
30757
31466
  var SqliteSecurityRepository = class {
30758
31467
  constructor(db, now = () => Date.now()) {
@@ -30814,7 +31523,7 @@ var SqliteSecurityRepository = class {
30814
31523
  ELSE 0
30815
31524
  END) AS open_at_rest
30816
31525
  FROM inspection_findings f
30817
- JOIN audit_events e ON e.id = f.audit_event_id
31526
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30818
31527
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30819
31528
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30820
31529
  ON latest.finding_key = f.finding_key
@@ -30881,12 +31590,16 @@ var SqliteSecurityRepository = class {
30881
31590
  const now = this.now();
30882
31591
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30883
31592
  const rows = this.findingsInRange(windowStart, now);
30884
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30885
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30886
- critical: 0,
30887
- high: 0,
30888
- medium: 0
30889
- }));
31593
+ const points = Array.from(
31594
+ { length: numBuckets },
31595
+ (_, i) => ({
31596
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31597
+ critical: 0,
31598
+ high: 0,
31599
+ medium: 0,
31600
+ low: 0
31601
+ })
31602
+ );
30890
31603
  for (const r of rows) {
30891
31604
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30892
31605
  const bucket = points[idx];
@@ -31036,7 +31749,7 @@ var SqliteSecurityRepository = class {
31036
31749
  this.db.prepare(
31037
31750
  `SELECT e.repo AS repo, count(*) AS c
31038
31751
  FROM inspection_findings f
31039
- JOIN audit_events e ON e.id = f.audit_event_id
31752
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31040
31753
  WHERE e.started_at >= :from AND e.started_at < :to
31041
31754
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31042
31755
  AND e.repo IS NOT NULL
@@ -31104,6 +31817,7 @@ var SqliteSecurityRepository = class {
31104
31817
  `SELECT f.finding_key AS finding_key,
31105
31818
  d.rule_id AS rule_id,
31106
31819
  d.severity AS severity,
31820
+ e.repo AS repo,
31107
31821
  e.file_path AS path,
31108
31822
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31109
31823
  latest.resolved_at AS latest_resolved_at
@@ -31123,6 +31837,7 @@ var SqliteSecurityRepository = class {
31123
31837
  const items = rows.map((r) => ({
31124
31838
  findingKey: r.finding_key,
31125
31839
  ruleId: r.rule_id,
31840
+ repo: r.repo ?? "",
31126
31841
  severity: r.severity,
31127
31842
  path: r.path ?? "",
31128
31843
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31132,15 +31847,68 @@ var SqliteSecurityRepository = class {
31132
31847
  }));
31133
31848
  return Promise.resolve({ items });
31134
31849
  }
31850
+ /**
31851
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31852
+ *
31853
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31854
+ * list: a secret committed three weeks ago and never rotated is still the most
31855
+ * important thing to fix, and any window hides it. It carried a "newest N
31856
+ * findings" cap and then a range; the first meant a different span on every
31857
+ * machine, and the second reported "no recommendations" over live exposure.
31858
+ *
31859
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31860
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31861
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31862
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31863
+ * The two answer different questions and only this one has to match a link.
31864
+ *
31865
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31866
+ * whole-store scope costs a grouped scan rather than a row per finding.
31867
+ */
31868
+ recommendationInputs() {
31869
+ const rows = allRows(
31870
+ this.db.prepare(
31871
+ `SELECT d.rule_id AS rule_id,
31872
+ d.category AS category,
31873
+ d.severity AS severity,
31874
+ COUNT(*) AS count
31875
+ FROM inspection_findings f
31876
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31877
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31878
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31879
+ ON latest.finding_key = f.finding_key
31880
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31881
+ AND e.event_type = 'code_change'
31882
+ AND (
31883
+ f.finding_key IS NULL
31884
+ OR latest.status IS NULL
31885
+ OR latest.status NOT IN ('resolved', 'dismissed')
31886
+ )
31887
+ GROUP BY d.rule_id, d.category, d.severity`
31888
+ )
31889
+ );
31890
+ return Promise.resolve(
31891
+ rows.map((r) => ({
31892
+ ruleId: r.rule_id,
31893
+ category: r.category,
31894
+ severity: r.severity,
31895
+ count: r.count
31896
+ }))
31897
+ );
31898
+ }
31135
31899
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31136
31900
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31137
31901
  // numeric and the JS aggregations bucket/split on ms directly.
31138
31902
  findingsInRange(fromMs, toMs) {
31139
31903
  const rows = allRows(
31140
31904
  this.db.prepare(
31141
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31905
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31906
+ // joined for `severity`, so they are two more columns off a row this read
31907
+ // already fetches. They feed the recommended-actions rollup.
31908
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31909
+ d.rule_id AS rule_id, d.category AS category
31142
31910
  FROM inspection_findings f
31143
- JOIN audit_events e ON e.id = f.audit_event_id
31911
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31144
31912
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31145
31913
  WHERE e.started_at >= :from AND e.started_at < :to
31146
31914
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31151,7 +31919,9 @@ var SqliteSecurityRepository = class {
31151
31919
  return rows.map((r) => ({
31152
31920
  occurredAt: r.occurred_at,
31153
31921
  severity: r.severity,
31154
- actionTaken: r.action_taken
31922
+ actionTaken: r.action_taken,
31923
+ ruleId: r.rule_id,
31924
+ category: r.category
31155
31925
  }));
31156
31926
  }
31157
31927
  };
@@ -31979,6 +32749,7 @@ function openWithPragmas(file2) {
31979
32749
  db.exec("PRAGMA journal_mode = WAL");
31980
32750
  db.exec("PRAGMA busy_timeout = 2000");
31981
32751
  db.exec("PRAGMA foreign_keys = ON");
32752
+ registerSqlFunctions(db);
31982
32753
  } catch (err) {
31983
32754
  closeQuietly(db);
31984
32755
  throw err;
@@ -32008,7 +32779,7 @@ function backupLegacyStore(db, file2) {
32008
32779
  discardStore(file2, backup);
32009
32780
  return backup;
32010
32781
  }
32011
- function openAndInitialize(file2, base) {
32782
+ function openAndInitialize(file2, base, skipTags) {
32012
32783
  let db = openWithPragmas(file2);
32013
32784
  try {
32014
32785
  if (isForeignSqliteLineage(db)) {
@@ -32018,7 +32789,7 @@ function openAndInitialize(file2, base) {
32018
32789
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32019
32790
  );
32020
32791
  }
32021
- applyMigrations(db, file2);
32792
+ applyMigrations(db, file2, { skipTags });
32022
32793
  tightenPerms(file2);
32023
32794
  const policies = new SqlitePoliciesRepository(db);
32024
32795
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32033,6 +32804,7 @@ function openAndInitialize(file2, base) {
32033
32804
  exceptions: new SqliteExceptionsRepository(db),
32034
32805
  resolutions: new SqliteResolutionsRepository(db),
32035
32806
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32807
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32036
32808
  security: new SqliteSecurityRepository(db),
32037
32809
  detections: new SqliteDetectionsRepository(db),
32038
32810
  shares: new SqliteSharesRepository(db),
@@ -32055,7 +32827,8 @@ function openAndInitialize(file2, base) {
32055
32827
  throw err;
32056
32828
  }
32057
32829
  }
32058
- function openLocalDatabase(dir) {
32830
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32831
+ function openLocalDatabase(dir, options = {}) {
32059
32832
  ensureDataDirSync(dir);
32060
32833
  const file2 = join7(dir, DB_FILENAME);
32061
32834
  reapStalePartials(file2);
@@ -32067,6 +32840,7 @@ function openLocalDatabase(dir) {
32067
32840
  installedPacks,
32068
32841
  scanLedger,
32069
32842
  historySync,
32843
+ bodyRetention,
32070
32844
  secretVault,
32071
32845
  exceptions,
32072
32846
  resolutions,
@@ -32090,7 +32864,8 @@ function openLocalDatabase(dir) {
32090
32864
  // `dir` is always `<base>/data` — every caller resolves it through
32091
32865
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32092
32866
  // settings/ and data/, and the pack-policy floor needs both halves.
32093
- dirname2(dir)
32867
+ dirname2(dir),
32868
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32094
32869
  );
32095
32870
  function captureRowId(event) {
32096
32871
  return captureId(
@@ -32283,6 +33058,7 @@ function openLocalDatabase(dir) {
32283
33058
  installedPacks,
32284
33059
  scanLedger,
32285
33060
  historySync,
33061
+ bodyRetention,
32286
33062
  secretVault,
32287
33063
  exceptions,
32288
33064
  resolutions,
@@ -32321,8 +33097,72 @@ function openLocalDatabase(dir) {
32321
33097
  };
32322
33098
  }
32323
33099
 
32324
- // ../../packages/persistence/src/finding-key.ts
33100
+ // ../../packages/persistence/src/egress-wire.ts
32325
33101
  import { createHash as createHash3 } from "crypto";
33102
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33103
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33104
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33105
+ var FILE_URL = /^file:\/\//i;
33106
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33107
+ var SLASH = "/".charCodeAt(0);
33108
+ var GIT_SUFFIX = ".git";
33109
+ function trimSlashes(path) {
33110
+ let start = 0;
33111
+ let end = path.length;
33112
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33113
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33114
+ return path.slice(start, end);
33115
+ }
33116
+ function canonicalGitUrl(url2) {
33117
+ const trimmed = url2.trim();
33118
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33119
+ const scheme = SCHEME_FORM.exec(trimmed);
33120
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33121
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33122
+ if (host === void 0) return trimmed;
33123
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33124
+ const bare = trimSlashes(path);
33125
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33126
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33127
+ }
33128
+ function hashProjectKey(projectKey) {
33129
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33130
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33131
+ }
33132
+ function toIngestHit(hit) {
33133
+ return {
33134
+ host: hit.host,
33135
+ kind: hit.kind,
33136
+ name: hit.name,
33137
+ category: hit.category,
33138
+ trust: hit.trust,
33139
+ network: hit.network,
33140
+ method: hit.method,
33141
+ transport: hit.transport,
33142
+ url: hit.url,
33143
+ template: hit.template,
33144
+ dataClass: hit.dataClass,
33145
+ site: {
33146
+ file: hit.site.file,
33147
+ line: hit.site.line,
33148
+ dynamic: hit.site.dynamic,
33149
+ vendored: hit.site.vendored
33150
+ }
33151
+ };
33152
+ }
33153
+ function toEgressIngestRequest(input2) {
33154
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33155
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33156
+ return {
33157
+ projectKey: hashProjectKey(input2.projectKey),
33158
+ project: input2.project,
33159
+ reconcile,
33160
+ hits: hits.map(toIngestHit)
33161
+ };
33162
+ }
33163
+
33164
+ // ../../packages/persistence/src/finding-key.ts
33165
+ import { createHash as createHash4 } from "crypto";
32326
33166
 
32327
33167
  // ../../packages/persistence/src/fingerprint.ts
32328
33168
  import { createHmac, randomBytes } from "crypto";
@@ -32363,14 +33203,50 @@ function readFingerprintKey(dataDir2) {
32363
33203
  return parseKeyFile(raw);
32364
33204
  }
32365
33205
 
32366
- // ../../packages/persistence/src/history-preview.ts
32367
- import { existsSync as existsSync4 } from "fs";
33206
+ // ../../packages/persistence/src/forward-health.ts
33207
+ import { readFileSync as readFileSync7 } from "fs";
32368
33208
  import { join as join9 } from "path";
33209
+ var FAILURES = /* @__PURE__ */ new Set([
33210
+ "unauthorized",
33211
+ "forbidden",
33212
+ "unreachable"
33213
+ ]);
33214
+ var BREAKER_COOLDOWN_MS = 3e4;
33215
+ function parseForwardHealth(raw, nowMs) {
33216
+ try {
33217
+ const parsed2 = JSON.parse(raw);
33218
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33219
+ const record2 = parsed2;
33220
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33221
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33222
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33223
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33224
+ } catch {
33225
+ return null;
33226
+ }
33227
+ }
33228
+ function isForwardPaused(health, nowMs) {
33229
+ const openedAtMs = health?.openedAtMs ?? null;
33230
+ if (openedAtMs === null) return false;
33231
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33232
+ }
33233
+
33234
+ // ../../packages/persistence/src/history-backfill.ts
33235
+ import { existsSync as existsSync4 } from "fs";
33236
+ import { join as join10 } from "path";
33237
+
33238
+ // ../../packages/persistence/src/history-preview.ts
33239
+ import { existsSync as existsSync5 } from "fs";
33240
+ import { join as join11 } from "path";
32369
33241
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32370
33242
 
33243
+ // ../../packages/persistence/src/history-sync-state.ts
33244
+ import { readFileSync as readFileSync8 } from "fs";
33245
+ import { join as join12 } from "path";
33246
+
32371
33247
  // ../../packages/persistence/src/store-symlinks.ts
32372
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32373
- import { dirname as dirname3, join as join10, resolve } from "path";
33248
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33249
+ import { dirname as dirname3, join as join13, resolve } from "path";
32374
33250
  var STORE_DB = "the store database (including the prompt corpus)";
32375
33251
  var STORE_SETTINGS = "your settings file";
32376
33252
  function storeContents(home) {
@@ -32379,7 +33255,7 @@ function storeContents(home) {
32379
33255
  [settingsDir(home), STORE_SETTINGS],
32380
33256
  [dataDir(home), STORE_DB],
32381
33257
  [keysDir(home), "the vault key"],
32382
- [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
33258
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32383
33259
  [dbPath(home), STORE_DB]
32384
33260
  ]);
32385
33261
  }
@@ -32394,7 +33270,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
32394
33270
  holds,
32395
33271
  // existsSync follows the link, so a target that is gone reads as
32396
33272
  // absent here while lstat above still sees the link itself.
32397
- missing: !existsSync5(path),
33273
+ missing: !existsSync6(path),
32398
33274
  mode: targetMode(path, platform2)
32399
33275
  }
32400
33276
  ];
@@ -32431,20 +33307,20 @@ import {
32431
33307
  // ../../packages/persistence/src/vault/key-provider.ts
32432
33308
  import { execFileSync } from "child_process";
32433
33309
  import { randomBytes as randomBytes2 } from "crypto";
32434
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32435
- import { join as join11 } from "path";
33310
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33311
+ import { join as join14 } from "path";
32436
33312
 
32437
33313
  // ../../packages/persistence/src/vault/vault.ts
32438
33314
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32439
33315
 
32440
33316
  // ../../packages/persistence/src/warn-era-cap.ts
32441
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32442
- import { join as join12 } from "path";
33317
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33318
+ import { join as join15 } from "path";
32443
33319
  var MARKER = "warn-era-capped";
32444
33320
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32445
33321
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32446
- const marker = join12(dataDir2, MARKER);
32447
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33322
+ const marker = join15(dataDir2, MARKER);
33323
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32448
33324
  const capped = db.policies.capCategoryActions();
32449
33325
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32450
33326
  `, { mode: DATA_FILE_MODE });
@@ -32503,8 +33379,8 @@ function resolveProvider() {
32503
33379
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32504
33380
  try {
32505
33381
  ensureLayoutDirSync(base);
32506
- const settingsFile = join13(settingsDir(base), "settings.json");
32507
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33382
+ const settingsFile = join16(settingsDir(base), "settings.json");
33383
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
32508
33384
  } catch {
32509
33385
  }
32510
33386
  migrateLegacyLayout(base);
@@ -32527,9 +33403,9 @@ function resolveProviderSafe(resolveProviderFn) {
32527
33403
  }
32528
33404
 
32529
33405
  // ../../packages/plugin-sdk/src/config-inventory.ts
32530
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33406
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32531
33407
  import { homedir as homedir2 } from "os";
32532
- import { basename as basename3, join as join15 } from "path";
33408
+ import { basename as basename3, join as join18 } from "path";
32533
33409
 
32534
33410
  // ../../packages/detections/src/egress/registry.ts
32535
33411
  var EXTRACTOR_VERSION = "1";
@@ -35312,24 +36188,20 @@ function bundledDetections() {
35312
36188
  }
35313
36189
 
35314
36190
  // ../../packages/plugin-sdk/src/repo.ts
35315
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35316
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
36191
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
36192
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
35317
36193
 
35318
36194
  // ../../packages/plugin-sdk/src/events.ts
35319
- import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
36195
+ import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
35320
36196
 
35321
36197
  // ../../packages/plugin-sdk/src/isolated-scan.ts
35322
- import { existsSync as existsSync9 } from "fs";
36198
+ import { existsSync as existsSync10 } from "fs";
35323
36199
  import { fileURLToPath } from "url";
35324
36200
  import { Worker } from "worker_threads";
35325
36201
 
35326
- // ../../packages/plugin-sdk/src/ignore-layers.ts
35327
- var import_ignore = __toESM(require_ignore(), 1);
35328
- import { readFileSync as readFileSync10 } from "fs";
35329
- import { join as join16 } from "path";
35330
-
35331
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
35332
- import { arch, hostname as hostname4, platform, release } from "os";
36202
+ // ../../packages/plugin-sdk/src/host-floor.ts
36203
+ import { readFileSync as readFileSync13 } from "fs";
36204
+ import { join as join20 } from "path";
35333
36205
 
35334
36206
  // ../../packages/plugin-sdk/src/model-governance.ts
35335
36207
  import {
@@ -35337,11 +36209,11 @@ import {
35337
36209
  fstatSync,
35338
36210
  mkdirSync as mkdirSync2,
35339
36211
  openSync as openSync2,
35340
- readFileSync as readFileSync11,
36212
+ readFileSync as readFileSync12,
35341
36213
  readSync,
35342
36214
  writeFileSync as writeFileSync5
35343
36215
  } from "fs";
35344
- import { join as join17 } from "path";
36216
+ import { join as join19 } from "path";
35345
36217
  var SESSION_MODEL_MARKER = "session-model";
35346
36218
  var DATE_SUFFIX = /-\d{8}$/;
35347
36219
  function normalizeModelId(model) {
@@ -35359,7 +36231,7 @@ function recordSessionModel(dataDir2, sessionId, model) {
35359
36231
  if (model === void 0 || model === "") return;
35360
36232
  try {
35361
36233
  mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
35362
- writeFileSync5(join17(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
36234
+ writeFileSync5(join19(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
35363
36235
  encoding: "utf8",
35364
36236
  mode: DATA_FILE_MODE
35365
36237
  });
@@ -35393,17 +36265,43 @@ function buildModelRefusalEvent(input2) {
35393
36265
  };
35394
36266
  }
35395
36267
 
36268
+ // ../../packages/plugin-sdk/src/host-floor.ts
36269
+ var HOST_FEATURE = {
36270
+ ModelSwitch: "model-switch",
36271
+ VaultPointerDisplay: "vault-pointer-display"
36272
+ };
36273
+ var HOST_FLOORS = {
36274
+ [HOST_FEATURE.ModelSwitch]: {
36275
+ label: "model-switch protection",
36276
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
36277
+ since: "2.1.251"
36278
+ },
36279
+ [HOST_FEATURE.VaultPointerDisplay]: {
36280
+ label: "vault pointer display",
36281
+ hookEvents: ["MessageDisplay"],
36282
+ since: "2.1.152"
36283
+ }
36284
+ };
36285
+
36286
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
36287
+ var import_ignore = __toESM(require_ignore(), 1);
36288
+ import { readFileSync as readFileSync14 } from "fs";
36289
+ import { join as join21 } from "path";
36290
+
36291
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
36292
+ import { arch, hostname as hostname4, platform, release } from "os";
36293
+
35396
36294
  // ../../packages/plugin-sdk/src/nudge.ts
35397
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
35398
- import { join as join18 } from "path";
36295
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
36296
+ import { join as join22 } from "path";
35399
36297
 
35400
36298
  // ../../packages/plugin-sdk/src/paths.ts
35401
36299
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
35402
36300
  import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
35403
36301
 
35404
36302
  // ../../packages/plugin-sdk/src/project-files.ts
35405
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
35406
- import { basename as basename5, join as join19 } from "path";
36303
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36304
+ import { basename as basename5, join as join23 } from "path";
35407
36305
 
35408
36306
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35409
36307
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35439,16 +36337,16 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
35439
36337
 
35440
36338
  // ../../packages/plugin-sdk/src/throttle.ts
35441
36339
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35442
- import { join as join20 } from "path";
36340
+ import { join as join24 } from "path";
35443
36341
 
35444
36342
  // src/hooks/model-switch-run.ts
35445
36343
  import { randomUUID as randomUUID16 } from "crypto";
35446
36344
 
35447
36345
  // src/hooks/model-guard.ts
35448
36346
  import { randomUUID as randomUUID15 } from "crypto";
35449
- import { readFileSync as readFileSync13, statSync as statSync9 } from "fs";
36347
+ import { readFileSync as readFileSync16, statSync as statSync9 } from "fs";
35450
36348
  import { homedir as homedir3 } from "os";
35451
- import { dirname as dirname6, join as join21 } from "path";
36349
+ import { dirname as dirname6, join as join25 } from "path";
35452
36350
  function decidePreModelSwitch(toModel, prohibitedModels) {
35453
36351
  if (toModel === void 0 || toModel === "") return null;
35454
36352
  if (!isModelProhibited(toModel, prohibitedModels)) return null;
@@ -35548,45 +36446,8 @@ function emit(output2) {
35548
36446
  }
35549
36447
 
35550
36448
  // src/hooks/store-health.ts
35551
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync19, writeFileSync as writeFileSync8 } from "fs";
35552
- import { dirname as dirname7, join as join28 } from "path";
35553
-
35554
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
35555
- import { createHash as createHash5 } from "crypto";
35556
- function hashProjectKey(projectKey) {
35557
- return createHash5("sha256").update(projectKey, "utf8").digest("hex");
35558
- }
35559
- function toIngestHit(hit) {
35560
- return {
35561
- host: hit.host,
35562
- kind: hit.kind,
35563
- name: hit.name,
35564
- category: hit.category,
35565
- trust: hit.trust,
35566
- network: hit.network,
35567
- method: hit.method,
35568
- transport: hit.transport,
35569
- url: hit.url,
35570
- template: hit.template,
35571
- dataClass: hit.dataClass,
35572
- site: {
35573
- file: hit.site.file,
35574
- line: hit.site.line,
35575
- dynamic: hit.site.dynamic,
35576
- vendored: hit.site.vendored
35577
- }
35578
- };
35579
- }
35580
- function toEgressIngestRequest(input2) {
35581
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
35582
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
35583
- return {
35584
- projectKey: hashProjectKey(input2.projectKey),
35585
- project: input2.project,
35586
- reconcile,
35587
- hits: hits.map(toIngestHit)
35588
- };
35589
- }
36449
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync20, writeFileSync as writeFileSync8 } from "fs";
36450
+ import { dirname as dirname7, join as join31 } from "path";
35590
36451
 
35591
36452
  // ../../packages/remote/src/http.ts
35592
36453
  import { request as httpRequest } from "http";
@@ -35771,10 +36632,10 @@ function parsed(schema, body, route) {
35771
36632
  }
35772
36633
  function withoutTrailingSlashes(endpoint) {
35773
36634
  let end = endpoint.length;
35774
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
36635
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
35775
36636
  return endpoint.slice(0, end);
35776
36637
  }
35777
- var SLASH = "/".charCodeAt(0);
36638
+ var SLASH2 = "/".charCodeAt(0);
35778
36639
  function createRemoteClient(options) {
35779
36640
  const base = withoutTrailingSlashes(options.endpoint);
35780
36641
  const url2 = (route) => `${base}${route}`;
@@ -35867,6 +36728,7 @@ function createRemoteClient(options) {
35867
36728
  url: url2(ROUTES.shares),
35868
36729
  body: JSON.stringify(validated.data)
35869
36730
  });
36731
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
35870
36732
  okBody(response);
35871
36733
  },
35872
36734
  async pollCommand() {
@@ -35889,19 +36751,51 @@ function createRemoteClient(options) {
35889
36751
  };
35890
36752
  }
35891
36753
 
35892
- // ../../packages/plugin-runtime/src/attached/failure.ts
36754
+ // ../../packages/remote/src/failure-kind.ts
35893
36755
  function statusOf(err) {
35894
36756
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
35895
36757
  const { status } = err;
35896
36758
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
35897
36759
  return status >= 100 && status <= 599 ? status : null;
35898
36760
  }
35899
- function classifyFailure(err) {
35900
- switch (statusOf(err)) {
36761
+ function nameOf(err) {
36762
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
36763
+ return typeof err.name === "string" ? err.name : null;
36764
+ }
36765
+ function classifyRemoteFailure(err) {
36766
+ switch (nameOf(err)) {
36767
+ case "RemoteRouteAbsent":
36768
+ return "route-absent";
36769
+ case "RemoteRequestInvalid":
36770
+ return "invalid-request";
36771
+ case "RemoteResponseInvalid":
36772
+ return "rejected";
36773
+ default:
36774
+ break;
36775
+ }
36776
+ const status = statusOf(err);
36777
+ if (status === null) return "unreachable";
36778
+ switch (status) {
35901
36779
  case 401:
35902
36780
  return "unauthorized";
35903
36781
  case 403:
35904
36782
  return "forbidden";
36783
+ case 429:
36784
+ return "unreachable";
36785
+ case 404:
36786
+ return "unreachable";
36787
+ default:
36788
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
36789
+ }
36790
+ }
36791
+
36792
+ // ../../packages/plugin-runtime/src/attached/failure.ts
36793
+ function classifyFailure(err) {
36794
+ switch (classifyRemoteFailure(err)) {
36795
+ case "unauthorized":
36796
+ return "unauthorized";
36797
+ case "forbidden":
36798
+ return "forbidden";
35905
36799
  default:
35906
36800
  return "unreachable";
35907
36801
  }
@@ -35923,11 +36817,11 @@ function withTimeout(promise2, ms) {
35923
36817
  }
35924
36818
 
35925
36819
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
35926
- import { readFileSync as readFileSync14 } from "fs";
35927
- import { join as join22 } from "path";
36820
+ import { readFileSync as readFileSync17 } from "fs";
36821
+ import { join as join26 } from "path";
35928
36822
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
35929
36823
  function forwardDropsPath(dataDir2) {
35930
- return join22(dataDir2, FORWARD_DROPS_FILENAME);
36824
+ return join26(dataDir2, FORWARD_DROPS_FILENAME);
35931
36825
  }
35932
36826
  function recordForwardDrops(dataDir2, count, nowMs) {
35933
36827
  if (count <= 0) return;
@@ -35945,7 +36839,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
35945
36839
  }
35946
36840
  function readForwardDrops(dataDir2) {
35947
36841
  try {
35948
- const parsed2 = JSON.parse(readFileSync14(forwardDropsPath(dataDir2), "utf8"));
36842
+ const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
35949
36843
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
35950
36844
  const record2 = parsed2;
35951
36845
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -35963,9 +36857,8 @@ function readForwardDrops(dataDir2) {
35963
36857
 
35964
36858
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35965
36859
  import { randomUUID as randomUUID17 } from "crypto";
35966
- import { readFileSync as readFileSync15 } from "fs";
35967
36860
  import { readFile, rename, writeFile } from "fs/promises";
35968
- import { join as join23 } from "path";
36861
+ import { join as join27 } from "path";
35969
36862
  function isInvalidRequest(err) {
35970
36863
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
35971
36864
  }
@@ -35979,31 +36872,12 @@ function isServerRejection(err) {
35979
36872
  var FORWARD_BUDGET_MS = 1500;
35980
36873
  var DECISION_PATH_BUDGET_MS = 800;
35981
36874
  var BREAKER_FAILURE_THRESHOLD = 3;
35982
- var BREAKER_COOLDOWN_MS = 3e4;
35983
36875
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
35984
- var FAILURES = /* @__PURE__ */ new Set([
35985
- "unauthorized",
35986
- "forbidden",
35987
- "unreachable"
35988
- ]);
35989
36876
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
35990
36877
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
35991
- function parseBreakerState(raw, nowMs) {
35992
- try {
35993
- const parsed2 = JSON.parse(raw);
35994
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
35995
- const record2 = parsed2;
35996
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
35997
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
35998
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
35999
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
36000
- } catch {
36001
- return null;
36002
- }
36003
- }
36004
36878
  function createForwardPolicy(deps) {
36005
36879
  const now = deps.now ?? (() => Date.now());
36006
- const file2 = join23(deps.dir, STATE_FILENAME);
36880
+ const file2 = join27(deps.dir, STATE_FILENAME);
36007
36881
  let state = null;
36008
36882
  let loading = null;
36009
36883
  async function readState() {
@@ -36013,7 +36887,7 @@ function createForwardPolicy(deps) {
36013
36887
  } catch {
36014
36888
  return { ...CLOSED };
36015
36889
  }
36016
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
36890
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
36017
36891
  }
36018
36892
  async function load() {
36019
36893
  if (state !== null) return state;
@@ -36059,7 +36933,7 @@ function createForwardPolicy(deps) {
36059
36933
  };
36060
36934
  const at = now();
36061
36935
  if (current.openedAtMs !== null) {
36062
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
36936
+ if (isForwardPaused(current, at)) {
36063
36937
  return { ok: false, reason: "breaker-open" };
36064
36938
  }
36065
36939
  await persist({
@@ -36596,7 +37470,18 @@ var AttachedDataGateway = class {
36596
37470
  // and the spread above would otherwise drop the field silently — which is
36597
37471
  // exactly what it did, leaving the whole control inert on every device
36598
37472
  // while every test around it stayed green.
36599
- prohibitedModels: cached2.prohibitedModels
37473
+ prohibitedModels: cached2.prohibitedModels,
37474
+ // NAMED for the same reason as the line above, and it is the same defect
37475
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
37476
+ // only the cache carries is dropped in silence. That is what left
37477
+ // `prohibitedModels` inert on every attached device with every test
37478
+ // around it green.
37479
+ //
37480
+ // Taken from the cache rather than merged here, because merging it needs
37481
+ // the device's own SETTING — which is not a bundle field and is not in
37482
+ // scope at this seam. The runtime does that merge, raise-only, where both
37483
+ // values are in hand (createPluginRuntime's ensureInitialized).
37484
+ redactFallback: cached2.redactFallback
36600
37485
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
36601
37486
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
36602
37487
  // it emits, so an 'authored' policy arriving from the control plane
@@ -36724,10 +37609,6 @@ function toolAuditEvent(input2) {
36724
37609
  };
36725
37610
  }
36726
37611
 
36727
- // ../../packages/plugin-runtime/src/attached/history-state.ts
36728
- import { readFileSync as readFileSync16 } from "fs";
36729
- import { join as join24 } from "path";
36730
-
36731
37612
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36732
37613
  import { createHash as createHash6 } from "crypto";
36733
37614
  import { hostname as hostname5 } from "os";
@@ -36736,6 +37617,10 @@ import { hostname as hostname5 } from "os";
36736
37617
  var CORRELATION_ID = EventMetadata.shape.correlationId;
36737
37618
  var TRACE_ID = EventMetadata.shape.traceId;
36738
37619
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37620
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
37621
+
37622
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
37623
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
36739
37624
 
36740
37625
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36741
37626
  import { spawn } from "child_process";
@@ -36743,7 +37628,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
36743
37628
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
36744
37629
 
36745
37630
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
36746
- import { readFileSync as readFileSync17 } from "fs";
37631
+ import { readFileSync as readFileSync18 } from "fs";
36747
37632
  function createPluginBlock(build, policyStore) {
36748
37633
  return async () => {
36749
37634
  const cached2 = await policyStore.read();
@@ -36762,7 +37647,7 @@ function createPluginBlock(build, policyStore) {
36762
37647
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36763
37648
  import { randomUUID as randomUUID18 } from "crypto";
36764
37649
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36765
- import { join as join25 } from "path";
37650
+ import { join as join28 } from "path";
36766
37651
 
36767
37652
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36768
37653
  import { rename as rename2 } from "fs/promises";
@@ -36786,7 +37671,7 @@ async function publishByRename(tmp, file2, move = rename2) {
36786
37671
 
36787
37672
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36788
37673
  function createPolicyStore(dir = dataDir()) {
36789
- const file2 = join25(dir, "policy-cache.json");
37674
+ const file2 = join28(dir, "policy-cache.json");
36790
37675
  async function read() {
36791
37676
  try {
36792
37677
  const raw = await readFile2(file2, "utf8");
@@ -37017,11 +37902,11 @@ function readStorePosture(dbPath2) {
37017
37902
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37018
37903
  import { randomUUID as randomUUID19 } from "crypto";
37019
37904
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37020
- import { join as join26 } from "path";
37905
+ import { join as join29 } from "path";
37021
37906
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37022
37907
  function createPostureStore(dir = settingsDir(), legacyDir) {
37023
- const file2 = join26(dir, "posture-state.json");
37024
- const legacyFile = legacyDir === void 0 ? null : join26(legacyDir, "posture-state.json");
37908
+ const file2 = join29(dir, "posture-state.json");
37909
+ const legacyFile = legacyDir === void 0 ? null : join29(legacyDir, "posture-state.json");
37025
37910
  async function persist(state) {
37026
37911
  await ensureDataDir(dir);
37027
37912
  const tmp = `${file2}.${randomUUID19()}.tmp`;
@@ -37089,8 +37974,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37089
37974
  }
37090
37975
 
37091
37976
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37092
- import { readFileSync as readFileSync18 } from "fs";
37093
- import { join as join27 } from "path";
37977
+ import { readFileSync as readFileSync19 } from "fs";
37978
+ import { join as join30 } from "path";
37094
37979
 
37095
37980
  // ../../packages/plugin-runtime/src/attached/status.ts
37096
37981
  var REFUSAL_LINES = {
@@ -37111,6 +37996,14 @@ import { spawn as spawn2 } from "child_process";
37111
37996
  import { fileURLToPath as fileURLToPath3 } from "url";
37112
37997
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
37113
37998
 
37999
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
38000
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
38001
+
38002
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
38003
+ import { spawn as spawn3 } from "child_process";
38004
+ import { fileURLToPath as fileURLToPath4 } from "url";
38005
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
38006
+
37114
38007
  // ../../packages/plugin-runtime/src/attached/factory.ts
37115
38008
  import { hostname as hostname6 } from "os";
37116
38009
 
@@ -37575,7 +38468,7 @@ function markerDirs(dataDir2) {
37575
38468
  function alreadyClaimed(dirs, marker, sessionId) {
37576
38469
  return dirs.some((dir) => {
37577
38470
  try {
37578
- return readFileSync19(join28(dir, marker), "utf8") === sessionId;
38471
+ return readFileSync20(join31(dir, marker), "utf8") === sessionId;
37579
38472
  } catch {
37580
38473
  return false;
37581
38474
  }
@@ -37585,7 +38478,7 @@ function recordClaim(dirs, marker, sessionId) {
37585
38478
  for (const dir of dirs) {
37586
38479
  try {
37587
38480
  mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
37588
- writeFileSync8(join28(dir, marker), sessionId, { mode: DATA_FILE_MODE });
38481
+ writeFileSync8(join31(dir, marker), sessionId, { mode: DATA_FILE_MODE });
37589
38482
  return;
37590
38483
  } catch {
37591
38484
  }