@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
@@ -491,9 +491,6 @@ var require_ignore = __commonJS({
491
491
  }
492
492
  });
493
493
 
494
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
495
- import { createHash as createHash4 } from "crypto";
496
-
497
494
  // ../../packages/persistence/src/attached-derived.ts
498
495
  import { rmSync } from "fs";
499
496
  import { join } from "path";
@@ -505,6 +502,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
505
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
506
503
  import { join as join2 } from "path";
507
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
508
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
509
514
  var SQLITE_MIGRATIONS = [
510
515
  {
@@ -622,6 +627,30 @@ var SQLITE_MIGRATIONS = [
622
627
  {
623
628
  tag: "0028_activity_session_probe_indexes",
624
629
  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"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ 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');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ 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;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ 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');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ 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');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ 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');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
625
654
  }
626
655
  ];
627
656
 
@@ -20423,6 +20452,20 @@ function epochMillisToIso(ms) {
20423
20452
  return new Date(ms).toISOString();
20424
20453
  }
20425
20454
 
20455
+ // ../../packages/schema/src/security/recommendations.ts
20456
+ function healthScore(summary) {
20457
+ const handled = summary.byAction.block + summary.byAction.redact + summary.byAction.warn;
20458
+ const handledRatio = summary.findings === 0 ? 1 : handled / summary.findings;
20459
+ return Math.round(100 * (0.6 * summary.coverage + 0.4 * handledRatio));
20460
+ }
20461
+ function findingStatus(summary) {
20462
+ return {
20463
+ score: healthScore(summary),
20464
+ unreviewed: { ...summary.bySeverity },
20465
+ openFindings: summary.findings
20466
+ };
20467
+ }
20468
+
20426
20469
  // ../../packages/schema/src/token/cost-model.ts
20427
20470
  var PROVIDER_PLATFORM = /* @__PURE__ */ new Map([
20428
20471
  ["anthropic", "anthropic"],
@@ -20669,6 +20712,15 @@ var FindingCategory = external_exports.enum([
20669
20712
  ]).meta({ id: "FindingCategory" });
20670
20713
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20671
20714
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20715
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20716
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20717
+ var FindingDelivery = external_exports.object({
20718
+ state: FindingDeliveryState,
20719
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20720
+ at: external_exports.iso.datetime().optional(),
20721
+ // Only on `not_sent`, and only when a known reason was recorded.
20722
+ reason: SyncFailureReason.optional()
20723
+ }).meta({ id: "FindingDelivery" });
20672
20724
  var ResolutionMethod = external_exports.enum([
20673
20725
  "enforced-in-flight",
20674
20726
  "fixed-at-source",
@@ -20725,7 +20777,10 @@ var FindingInstance = external_exports.object({
20725
20777
  // The session that event belongs to, when it has one — the seam a
20726
20778
  // per-instance "view session" link needs. Absent for events captured
20727
20779
  // outside a session.
20728
- sessionId: external_exports.string().optional()
20780
+ sessionId: external_exports.string().optional(),
20781
+ // The delivery state of the event above (see FindingDelivery). Optional so
20782
+ // readers that do not project it stay valid.
20783
+ delivery: FindingDelivery.optional()
20729
20784
  }).meta({ id: "FindingInstance" });
20730
20785
  var FindingGroup = external_exports.object({
20731
20786
  id: external_exports.string(),
@@ -20742,13 +20797,11 @@ var FindingGroup = external_exports.object({
20742
20797
  latestDetectedAt: external_exports.iso.datetime(),
20743
20798
  instances: external_exports.array(FindingInstance),
20744
20799
  // Derived from instances' statuses with open-dominates precedence (see
20745
- // buildFindingGroups). Undefined only when no instance carries a status.
20800
+ // foldGroupStatus). Undefined only when no instance carries a status.
20746
20801
  status: FindingStatus.optional(),
20747
- // The distinct people across the WHOLE group, not just the `instances`
20748
- // preview — from the store's whole-group aggregate when it supplies one,
20749
- // else folded from the rows (see buildFindingGroups). Undefined when no
20750
- // instance carries a user, or when the store supplied whole-group folds
20751
- // without one.
20802
+ // The distinct people across the WHOLE group, not just the instances
20803
+ // carried here. Undefined when no instance carries a user, or when the
20804
+ // store supplied whole-group folds without one.
20752
20805
  users: external_exports.array(FindingUser).optional()
20753
20806
  }).meta({ id: "FindingGroup" });
20754
20807
  var FindingStats = external_exports.object({
@@ -20777,21 +20830,34 @@ var FindingFacets = external_exports.object({
20777
20830
  // counted under no value.
20778
20831
  status: external_exports.array(FindingFacetItem),
20779
20832
  // Host tool (attributes.tool_name). Present only on the instance-level
20780
- // reads, which can filter by it; the grouped read omits the dimension
20833
+ // reads, which can filter by it; the type-level read omits the dimension
20781
20834
  // because a group spans tools.
20782
- tool: external_exports.array(FindingFacetItem).optional()
20835
+ tool: external_exports.array(FindingFacetItem).optional(),
20836
+ // Delivery states (FindingDeliveryState). Present only on the
20837
+ // instance-level reads, like `tool`.
20838
+ deployment: external_exports.array(FindingFacetItem).optional()
20783
20839
  }).meta({ id: "FindingFacets" });
20784
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20785
- var ListGroupedFindingsQuery = external_exports.object({
20840
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20841
+ id: "FindingTypeSummary"
20842
+ });
20843
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20844
+ var MAX_FINDING_TYPES_LIMIT = 100;
20845
+ var ListFindingTypesQuery = external_exports.object({
20786
20846
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20787
- // FindingAction.
20847
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20848
+ // firing version carries, and this list pages types.
20849
+ //
20850
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20851
+ // definition versions at different severities, so a type kept by this filter
20852
+ // can hold findings that individually do not match — see totals.findings on
20853
+ // ListFindingTypesResponse, which counts them all.
20788
20854
  severity: external_exports.array(Severity).optional(),
20789
20855
  subtype: external_exports.array(external_exports.string()).optional(),
20790
20856
  provider: external_exports.array(FindingProvider).optional(),
20791
20857
  action: external_exports.array(FindingAction).optional(),
20792
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20793
- // individual instances' — so a filtered group's Status column always reads
20794
- // one of the requested values.
20858
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20859
+ // individual findings' — so a filtered row's status always reads one of the
20860
+ // requested values.
20795
20861
  status: external_exports.array(FindingStatus).optional(),
20796
20862
  q: external_exports.string().optional(),
20797
20863
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20801,23 +20867,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20801
20867
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20802
20868
  // means all time — this list has no default window.
20803
20869
  from: external_exports.iso.datetime().optional(),
20804
- // A group or instance id that must appear in the page even when the cursor
20805
- // has already advanced past its sort position. This is what keeps the
20806
- // Findings page's one-shot ?finding= deep link resolving once the list
20807
- // paginates: the target group is appended out of sort order rather than
20808
- // scanning forward for it. Never affects totals, facets or the cursor.
20870
+ // A RULE id that must appear in the page even when the cursor has already
20871
+ // advanced past its sort position. This is what keeps the selected type
20872
+ // visible in the list once it paginates: the target is appended out of sort
20873
+ // order rather than scanned forward for. Never affects totals, facets or the
20874
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20875
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20876
+ // and so is not bounded by what any page happens to hold.
20809
20877
  includeId: external_exports.string().optional(),
20810
- groupBy: external_exports.literal("type").optional(),
20811
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20878
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20812
20879
  cursor: external_exports.string().optional()
20813
20880
  });
20814
- var ListGroupedFindingsResponse = external_exports.object({
20881
+ var ListFindingTypesResponse = external_exports.object({
20815
20882
  totals: external_exports.object({
20883
+ // Findings belonging to the matching TYPES — not findings that each match
20884
+ // the filters. The filters here select types, so a type that survives
20885
+ // contributes its whole instanceCount.
20886
+ //
20887
+ // `status` is the one exception, narrowed per finding via
20888
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20889
+ // this can exceed what the instance read reports for the same filters: a
20890
+ // rule whose severity moved between versions is kept on its newest and
20891
+ // still counts its older findings. Narrowing the other three needs
20892
+ // per-dimension counts the aggregate does not carry today.
20816
20893
  findings: external_exports.number().int().nonnegative(),
20817
- groups: external_exports.number().int().nonnegative()
20894
+ // Counts TYPES, which is the unit this read pages. The instance read's
20895
+ // own totals count findings; the two deliberately answer different
20896
+ // questions and are never summed.
20897
+ types: external_exports.number().int().nonnegative()
20818
20898
  }),
20819
20899
  facets: FindingFacets,
20820
- items: external_exports.array(FindingGroup),
20900
+ items: external_exports.array(FindingTypeSummary),
20821
20901
  nextCursor: external_exports.string().nullable(),
20822
20902
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20823
20903
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20825,7 +20905,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20825
20905
  // every firing, so the two numbers legitimately differ — this map lets a
20826
20906
  // session-scoped view show both.
20827
20907
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20828
- }).meta({ id: "ListGroupedFindingsResponse" });
20908
+ }).meta({ id: "ListFindingTypesResponse" });
20829
20909
  var ApplyFindingActionRequest = external_exports.object({
20830
20910
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20831
20911
  // it, so it is excluded from the request contract. The mapping helper
@@ -20855,16 +20935,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20855
20935
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20856
20936
  var ListFindingInstancesQuery = external_exports.object({
20857
20937
  severity: external_exports.array(Severity).optional(),
20858
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20938
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20939
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20859
20940
  subtype: external_exports.array(external_exports.string()).optional(),
20860
20941
  provider: external_exports.array(FindingProvider).optional(),
20861
20942
  action: external_exports.array(FindingAction).optional(),
20862
20943
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20863
- // the grouped query's group-level fold.
20944
+ // the types query's type-level fold.
20864
20945
  status: external_exports.array(FindingStatus).optional(),
20865
20946
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20866
20947
  // where the free-text `q` can only match the rendered "via Bash" label.
20867
20948
  tool: external_exports.array(external_exports.string()).optional(),
20949
+ // The delivery state of each finding's event (see FindingDelivery).
20950
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20868
20951
  // Exact repository / file-path matches, for the drill-down out of the
20869
20952
  // locations view. A row whose event carries no repo/file matches neither.
20870
20953
  repo: external_exports.string().optional(),
@@ -20877,37 +20960,51 @@ var ListFindingInstancesQuery = external_exports.object({
20877
20960
  });
20878
20961
  var ListFindingInstancesResponse = external_exports.object({
20879
20962
  // Instances matching the filters across the whole scope, not just this
20880
- // page — cursor-independent, like the grouped list's totals.
20963
+ // page — cursor-independent, like the types list's totals.
20881
20964
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20882
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20965
+ // Counts in INSTANCES here, where the types response counts types. Each
20883
20966
  // dimension still excludes its own filter.
20884
20967
  facets: FindingFacets,
20885
20968
  items: external_exports.array(FindingInstanceDetail),
20886
20969
  nextCursor: external_exports.string().nullable()
20887
20970
  }).meta({ id: "ListFindingInstancesResponse" });
20888
- var FindingLocationFile = external_exports.object({
20889
- // Empty when the instances carried no file path (a prompt or a tool call
20890
- // with no file attribution).
20891
- file: external_exports.string(),
20892
- instanceCount: external_exports.number().int().nonnegative(),
20893
- maxSeverity: Severity,
20894
- latestDetectedAt: external_exports.iso.datetime(),
20895
- // Folded from the instances' derived statuses with the same
20896
- // open-dominates precedence a group uses.
20897
- status: FindingStatus.optional(),
20898
- // Distinct rules seen at this location, capped — the row shows them as
20899
- // chips, and the count is what conveys scale.
20900
- ruleIds: external_exports.array(external_exports.string())
20901
- }).meta({ id: "FindingLocationFile" });
20902
- var FindingLocationRepo = external_exports.object({
20971
+ var ListFindingInstancesPage = external_exports.object({
20972
+ items: external_exports.array(FindingInstanceDetail),
20973
+ nextCursor: external_exports.string().nullable()
20974
+ }).meta({ id: "ListFindingInstancesPage" });
20975
+ var FindingLocationSummary = external_exports.object({
20976
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20977
+ // because a location's identity is two values and a URL param carries one:
20978
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20979
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20980
+ // client's page dedupe — never decoded, and never a sort key.
20981
+ id: external_exports.string(),
20903
20982
  /** Empty when the instances carried no repo attribute. */
20904
20983
  repo: external_exports.string(),
20984
+ // Empty when the instances carried no file path (a prompt, or a tool call
20985
+ // with no file attribution). Both halves empty is a real location — usually
20986
+ // the largest one in a store — and is selectable like any other.
20987
+ file: external_exports.string(),
20905
20988
  instanceCount: external_exports.number().int().nonnegative(),
20989
+ // The WORST severity present, not the first row's. It is this list's primary
20990
+ // sort key, so it is also what explains why a row is where it is, and it is
20991
+ // how a reader decides what to open without opening everything.
20906
20992
  maxSeverity: Severity,
20907
20993
  latestDetectedAt: external_exports.iso.datetime(),
20994
+ // Folded from the instances' derived statuses with the same open-dominates
20995
+ // precedence a group uses, so it answers "is anything left to do here" and
20996
+ // not much more: a location holding 1 open among 40 resolved reads like one
20997
+ // holding 40 open. That loss is accepted — the panel beside this list
20998
+ // carries each finding's own status, and instanceCount sits next to the
20999
+ // badge.
20908
21000
  status: FindingStatus.optional(),
20909
- files: external_exports.array(FindingLocationFile)
20910
- }).meta({ id: "FindingLocationRepo" });
21001
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
21002
+ // tally rather than a sample and a row can say how many there are. Bounded
21003
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
21004
+ ruleIds: external_exports.array(external_exports.string())
21005
+ }).meta({ id: "FindingLocationSummary" });
21006
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
21007
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20911
21008
  var ListFindingLocationsQuery = external_exports.object({
20912
21009
  severity: external_exports.array(Severity).optional(),
20913
21010
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20917,21 +21014,47 @@ var ListFindingLocationsQuery = external_exports.object({
20917
21014
  // instances that match, and folds its status from those.
20918
21015
  status: external_exports.array(FindingStatus).optional(),
20919
21016
  tool: external_exports.array(external_exports.string()).optional(),
21017
+ // The delivery state of each finding's event (see FindingDelivery).
21018
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20920
21019
  q: external_exports.string().optional(),
20921
21020
  sessionId: external_exports.string().optional(),
20922
21021
  from: external_exports.iso.datetime().optional(),
20923
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21022
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21023
+ // even when the cursor has already advanced past its sort position — the
21024
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21025
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21026
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21027
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21028
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21029
+ includeId: external_exports.string().optional(),
21030
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21031
+ cursor: external_exports.string().optional()
20924
21032
  });
20925
21033
  var ListFindingLocationsResponse = external_exports.object({
20926
21034
  totals: external_exports.object({
21035
+ // Findings matching the filters across the whole scope. Unlike the types
21036
+ // read's same-named field this needs no caveat: the filters here narrow
21037
+ // per finding, so this is the sum of every row's instanceCount.
20927
21038
  findings: external_exports.number().int().nonnegative(),
20928
- repos: external_exports.number().int().nonnegative(),
20929
- files: external_exports.number().int().nonnegative()
21039
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21040
+ // states. The facets beside it count FINDINGS (see below); a surface
21041
+ // showing both says which is which.
21042
+ locations: external_exports.number().int().nonnegative()
20930
21043
  }),
20931
- /** Sorted by max severity, then most recent. */
20932
- items: external_exports.array(FindingLocationRepo),
20933
- /** Whether `limit` truncated the repo list. */
20934
- hasMore: external_exports.boolean()
21044
+ // Counts in FINDINGS, where the types response counts types, each dimension
21045
+ // still excluding its own filter. Deliberately not locations: counting those
21046
+ // needs a set of location keys per dimension per value — memory tracking the
21047
+ // store times the vocabulary, in a read whose scan promises flat memory —
21048
+ // and the cheap per-location version is not an approximation but WRONG. A
21049
+ // location holding {claudecode, block} and {codex, warn} would survive
21050
+ // provider=claudecode AND action=warn, under which no single finding
21051
+ // matches, so the facet would contradict the instanceCount this whole view
21052
+ // rests on. Findings also keep the toolbar in the same unit as the page
21053
+ // tally and the panel it sits above.
21054
+ facets: FindingFacets,
21055
+ /** Sorted by max severity, then most recent, then (repo, file). */
21056
+ items: external_exports.array(FindingLocationSummary),
21057
+ nextCursor: external_exports.string().nullable()
20935
21058
  }).meta({ id: "ListFindingLocationsResponse" });
20936
21059
 
20937
21060
  // ../../packages/schema/src/zod/meta.ts
@@ -21095,6 +21218,10 @@ var CaptureAttributes = external_exports.object({
21095
21218
  // to 'allow' — the enforcement audit trail's link back to the grant that
21096
21219
  // authorized the bypass.
21097
21220
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21221
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21222
+ // join back to the `llm_call` leaf for the same assistant turn.
21223
+ message_id: external_exports.string().optional(),
21224
+ conversation_id: external_exports.string().optional(),
21098
21225
  // Whole milliseconds this capture's inspection blocked its caller — the
21099
21226
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21100
21227
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21103,7 +21230,19 @@ var CaptureAttributes = external_exports.object({
21103
21230
  // inline json_extract and is not itself an optimization.
21104
21231
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21105
21232
  // before the measurement shipped — never present as a placeholder 0.
21106
- inspection_ms: external_exports.number().int().nonnegative().optional()
21233
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21234
+ // What a `redact` this capture could not carry out became instead (see
21235
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21236
+ // degrade actually happened, so absence is the ordinary case rather than a
21237
+ // reader having to distinguish it from a zero.
21238
+ //
21239
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21240
+ // so on a multi-finding row this does not say which finding degraded, and
21241
+ // its presence does not mean the fallback decided the capture's action. A
21242
+ // capture denied by another finding's own Block policy carries `block`
21243
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21244
+ // repeated rather than referenced because a store reader opens this file.
21245
+ redact_degraded_to: ActionTaken.optional()
21107
21246
  }).catchall(external_exports.unknown());
21108
21247
  var ToolCallInspection = external_exports.object({
21109
21248
  ruleId: external_exports.string().min(1),
@@ -21302,7 +21441,17 @@ var AuditEvent = external_exports.object({
21302
21441
  /** `share` to a first-party/internal destination. */
21303
21442
  internal: external_exports.boolean(),
21304
21443
  /** Event needs review (e.g. unverified egress). */
21305
- flagged: external_exports.boolean()
21444
+ flagged: external_exports.boolean(),
21445
+ /**
21446
+ * The body this event's `title` is drawn from was cleared by local body
21447
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21448
+ *
21449
+ * A separate flag rather than a sentinel written into `title`: the title is
21450
+ * rendered text, and a store-layer module that invented display copy for it
21451
+ * would be choosing words the view is supposed to choose. Additive and
21452
+ * defaulted, so an older producer still validates.
21453
+ */
21454
+ bodyExpired: external_exports.boolean().default(false)
21306
21455
  }).meta({ id: "ActivityAuditEvent" });
21307
21456
  var ActivitySessionSummary = external_exports.object({
21308
21457
  id: external_exports.string(),
@@ -22100,6 +22249,14 @@ var ControlPlaneErrorBody = external_exports.object({
22100
22249
  message: external_exports.string().optional()
22101
22250
  }).optional()
22102
22251
  });
22252
+ var RemoteFailureKind = external_exports.enum([
22253
+ "unauthorized",
22254
+ "forbidden",
22255
+ "route-absent",
22256
+ "invalid-request",
22257
+ "rejected",
22258
+ "unreachable"
22259
+ ]);
22103
22260
  var AttachDeviceRequest = external_exports.object({
22104
22261
  // This machine's own continuity id, so re-attaching ROTATES the credential
22105
22262
  // on one machine record instead of producing a second one. Client-minted
@@ -22635,6 +22792,12 @@ var EventMetadata = external_exports.object({
22635
22792
  // to 'allow' — the enforcement audit trail's link back to the grant that
22636
22793
  // authorized the bypass. Absent on captures where no exception applied.
22637
22794
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22795
+ // The assistant message this capture belongs to, and the conversation it sits
22796
+ // in — set by the browser extension's network capture so a stored `response`
22797
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22798
+ // on every other capture path, which has no such id.
22799
+ messageId: external_exports.string().optional(),
22800
+ conversationId: external_exports.string().optional(),
22638
22801
  // How long THIS capture's inspection blocked its caller, in whole
22639
22802
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22640
22803
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22647,7 +22810,37 @@ var EventMetadata = external_exports.object({
22647
22810
  // Absent is also what every pre-measurement client writes, and what a
22648
22811
  // clock failure degrades to — a reader must treat absence as "not measured"
22649
22812
  // and never as a zero, which would read as "inspection is free".
22650
- inspectionMs: external_exports.number().int().nonnegative().optional()
22813
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22814
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22815
+ // workspace's `redactFallback`, applied because the field could not be
22816
+ // masked in place (a shell command, a URL, or any argument on a host whose
22817
+ // hook contract offers no rewrite channel).
22818
+ //
22819
+ // It exists because the action alone cannot say why. A finding recorded as
22820
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22821
+ // assigned Redact on a field that could not take one — and those are
22822
+ // different facts about the same row: the first is a policy the user chose,
22823
+ // the second is a masking the host could not perform. Absent means no
22824
+ // degrade happened, which is every ordinary capture.
22825
+ //
22826
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22827
+ // is the CAPTURE while `actionTaken` is per FINDING:
22828
+ //
22829
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22830
+ // `redact` alongside a finding ASSIGNED the same action stores both
22831
+ // identically and one reason for the pair; attributing it to both
22832
+ // describes the assigned one wrongly, and to neither loses the degrade.
22833
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22834
+ // became, not the reason the capture ended as it did — a capture denied
22835
+ // by some other finding's own Block policy still carries `block` here,
22836
+ // and clearing the workspace's fallback would not have let it through.
22837
+ // Gate on the value against what a fallback can produce; never read the
22838
+ // field's presence as "this was the fallback's doing".
22839
+ //
22840
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22841
+ // Closing either means moving the reason onto the finding row, which
22842
+ // already carries its own action.
22843
+ redactDegradedTo: ActionTaken.optional()
22651
22844
  }).meta({ id: "EventMetadata" });
22652
22845
  var Event = external_exports.object({
22653
22846
  id: external_exports.guid(),
@@ -22757,7 +22950,32 @@ var RotateKeyInput = external_exports.object({
22757
22950
  confirmation: external_exports.string()
22758
22951
  });
22759
22952
 
22953
+ // ../../packages/schema/src/zod/finding-delivery.ts
22954
+ var KNOWN_REASONS = SyncFailureReason.options;
22955
+ function knownReason(value) {
22956
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22957
+ }
22958
+ function deriveFindingDelivery(row) {
22959
+ if (row.kind === "code_change") return { state: "local_scan" };
22960
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22961
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22962
+ }
22963
+ if (row.syncedAt !== null) {
22964
+ const reason = knownReason(row.syncFailure);
22965
+ return {
22966
+ state: "not_sent",
22967
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22968
+ ...reason === void 0 ? {} : { reason }
22969
+ };
22970
+ }
22971
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22972
+ return { state: "never_offered" };
22973
+ }
22974
+
22760
22975
  // ../../packages/schema/src/zod/findings-group-build.ts
22976
+ function lookupOwn(map2, key) {
22977
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22978
+ }
22761
22979
  function toApiAction(dbVal) {
22762
22980
  const map2 = {
22763
22981
  log: "monitored",
@@ -22766,7 +22984,7 @@ function toApiAction(dbVal) {
22766
22984
  warn: "warned",
22767
22985
  allow: "allowed"
22768
22986
  };
22769
- return map2[dbVal] ?? "allowed";
22987
+ return lookupOwn(map2, dbVal) ?? "allowed";
22770
22988
  }
22771
22989
  function toApiCategory(dbVal) {
22772
22990
  if (dbVal === "code_context") return "source_code";
@@ -22774,13 +22992,18 @@ function toApiCategory(dbVal) {
22774
22992
  return parsed2.success ? parsed2.data : "custom";
22775
22993
  }
22776
22994
  function toApiProvider(sourceTool) {
22777
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22995
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22778
22996
  }
22779
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22997
+ var FINDING_STATUS_PRECEDENCE = [
22998
+ "open",
22999
+ "handled",
23000
+ "dismissed",
23001
+ "resolved"
23002
+ ];
22780
23003
  function foldGroupStatus(instanceStatuses) {
22781
23004
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22782
23005
  if (statuses.size === 0) return void 0;
22783
- for (const candidate of STATUS_PRECEDENCE) {
23006
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22784
23007
  if (statuses.has(candidate)) return candidate;
22785
23008
  }
22786
23009
  return void 0;
@@ -22793,139 +23016,62 @@ function deriveFindingStatus(row) {
22793
23016
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22794
23017
  return "open";
22795
23018
  }
22796
- function distinctUsers(instances) {
22797
- const seen = /* @__PURE__ */ new Set();
22798
- const users = [];
22799
- for (const i of instances) {
22800
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22801
- seen.add(i.user.id);
22802
- users.push(i.user);
22803
- }
22804
- return users;
22805
- }
22806
23019
  function sortUsers(users) {
22807
23020
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22808
23021
  }
22809
- function buildFindingGroups(rows, opts = {}) {
22810
- const overrides = opts.overrides;
23022
+ function buildFindingTypes(aggregates, opts = {}) {
22811
23023
  const packNames = opts.packNames;
22812
- const aggregates = opts.aggregates;
22813
- const byRuleId = /* @__PURE__ */ new Map();
22814
- for (const row of rows) {
22815
- const existing = byRuleId.get(row.ruleId);
22816
- if (existing) existing.push(row);
22817
- else byRuleId.set(row.ruleId, [row]);
22818
- }
22819
- const groups = [];
22820
- for (const [ruleId, ruleRows] of byRuleId) {
22821
- const instances = ruleRows.map((r) => {
22822
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22823
- return {
22824
- id: r.id,
22825
- provider: toApiProvider(r.sourceTool),
22826
- repo: r.repo,
22827
- file: r.file,
22828
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22829
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22830
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22831
- ...r.user === void 0 ? {} : { user: r.user },
22832
- action: toApiAction(effectiveDbAction),
22833
- detectedAt: r.occurredAt,
22834
- confidence: r.confidence,
22835
- status: r.status
22836
- };
22837
- });
22838
- const agg = aggregates?.get(ruleId);
22839
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22840
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22841
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22842
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22843
- );
22844
- const seenProviders = /* @__PURE__ */ new Set();
22845
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22846
- if (seenProviders.has(p)) return false;
22847
- seenProviders.add(p);
22848
- return true;
22849
- });
22850
- const actionSet = new Set(
22851
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22852
- );
23024
+ const types = [];
23025
+ for (const [ruleId, agg] of aggregates) {
23026
+ const users = sortUsers(agg.users ?? []);
23027
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23028
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22853
23029
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22854
- const severity = ruleRows[0]?.severity ?? "low";
22855
- const detection = {
22856
- id: ruleId,
22857
- name: packNames?.get(ruleId) ?? null
22858
- };
22859
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22860
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22861
- const match = {
22862
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22863
- contextPrefix: ""
22864
- // empty (pending privacy review)
22865
- };
22866
- const status = foldGroupStatus(
22867
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22868
- );
22869
- const group = {
23030
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23031
+ const type = {
22870
23032
  id: ruleId,
22871
23033
  category: apiCategory,
22872
23034
  subtype: ruleId,
22873
23035
  // human label comes with pack metadata later
22874
- severity,
22875
- match,
22876
- detection,
22877
- policy,
22878
- instanceCount: agg?.instanceCount ?? instances.length,
23036
+ severity: agg.severity ?? "low",
23037
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23038
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23039
+ instanceCount: agg.instanceCount,
22879
23040
  providers,
22880
23041
  aggregateAction,
22881
- latestDetectedAt,
22882
- instances,
22883
- status,
23042
+ latestDetectedAt: agg.latestDetectedAt,
23043
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22884
23044
  ...users.length > 0 ? { users } : {}
22885
23045
  };
22886
- if (agg) {
22887
- actionsCache.set(group, [...actionSet]);
22888
- if (agg.searchText !== void 0) {
22889
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22890
- }
23046
+ actionsCache.set(type, [...actionSet]);
23047
+ if (agg.searchText !== void 0) {
23048
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22891
23049
  }
22892
- groups.push(group);
23050
+ types.push(type);
22893
23051
  }
22894
- return groups;
23052
+ return types;
22895
23053
  }
22896
23054
  var haystackCache = /* @__PURE__ */ new WeakMap();
22897
- function buildHaystack(g, extra) {
23055
+ function buildHaystack(t, extra) {
22898
23056
  return [
22899
- g.subtype,
22900
- g.category,
22901
- g.match.maskedValue,
22902
- g.policy.name,
22903
- g.id,
22904
- ...g.instances.map((i) => i.repo),
22905
- ...g.instances.map((i) => i.file),
22906
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22907
- ...g.instances.map((i) => i.id),
22908
- // The people: the whole group's list when the store folded one, plus the
22909
- // preview's own — the two overlap, and a haystack does not mind.
22910
- ...(g.users ?? []).map((u) => u.name),
22911
- ...g.instances.map((i) => i.user?.name ?? ""),
23057
+ t.subtype,
23058
+ t.category,
23059
+ t.policy.name,
23060
+ t.id,
23061
+ ...(t.users ?? []).map((u) => u.name),
22912
23062
  ...extra === void 0 ? [] : [extra]
22913
23063
  ].join(" ").toLowerCase();
22914
23064
  }
22915
- function groupHaystack(g) {
22916
- const cached2 = haystackCache.get(g);
23065
+ function typeHaystack(t) {
23066
+ const cached2 = haystackCache.get(t);
22917
23067
  if (cached2 !== void 0) return cached2;
22918
- const haystack = buildHaystack(g);
22919
- haystackCache.set(g, haystack);
23068
+ const haystack = buildHaystack(t);
23069
+ haystackCache.set(t, haystack);
22920
23070
  return haystack;
22921
23071
  }
22922
23072
  var actionsCache = /* @__PURE__ */ new WeakMap();
22923
- function groupActions(g) {
22924
- const cached2 = actionsCache.get(g);
22925
- if (cached2 !== void 0) return cached2;
22926
- const actions = [...new Set(g.instances.map((i) => i.action))];
22927
- actionsCache.set(g, actions);
22928
- return actions;
23073
+ function typeActions(t) {
23074
+ return actionsCache.get(t) ?? [];
22929
23075
  }
22930
23076
  function countInstancesByStatus(statusInputs, statuses) {
22931
23077
  const statusSet = new Set(statuses);
@@ -22936,8 +23082,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22936
23082
  }
22937
23083
  return sum;
22938
23084
  }
22939
- function applyFindingFilters(groups, opts) {
22940
- let filtered = groups;
23085
+ function applyFindingFilters(types, opts) {
23086
+ let filtered = types;
22941
23087
  if (opts.severity && opts.severity.length > 0) {
22942
23088
  const sevSet = new Set(opts.severity);
22943
23089
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22948,7 +23094,7 @@ function applyFindingFilters(groups, opts) {
22948
23094
  }
22949
23095
  if (opts.actions && opts.actions.length > 0) {
22950
23096
  const actionSet = new Set(opts.actions);
22951
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23097
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22952
23098
  }
22953
23099
  if (opts.subtype && opts.subtype.length > 0) {
22954
23100
  const subtypeSet = new Set(opts.subtype);
@@ -22960,26 +23106,31 @@ function applyFindingFilters(groups, opts) {
22960
23106
  }
22961
23107
  if (opts.q) {
22962
23108
  const q = opts.q.toLowerCase();
22963
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23109
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22964
23110
  }
22965
23111
  return filtered;
22966
23112
  }
22967
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22968
- var SEVERITY_RANK = SEVERITY_ORDER;
23113
+ function rankByOrder(members2) {
23114
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23115
+ }
23116
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23117
+ function severityRank(severity) {
23118
+ return lookupOwn(SEVERITY_RANK, severity);
23119
+ }
22969
23120
  function compareFindingGroupOrder(a, b) {
22970
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22971
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23121
+ const rankA = severityRank(a.severity) ?? -1;
23122
+ const rankB = severityRank(b.severity) ?? -1;
22972
23123
  const severityDiff = rankA - rankB;
22973
23124
  if (severityDiff !== 0) return severityDiff;
22974
23125
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22975
23126
  if (recencyDiff !== 0) return recencyDiff;
22976
23127
  return a.id.localeCompare(b.id);
22977
23128
  }
22978
- function sortFindingGroups(groups) {
22979
- return [...groups].sort(compareFindingGroupOrder);
23129
+ function sortFindingTypes(types) {
23130
+ return [...types].sort(compareFindingGroupOrder);
22980
23131
  }
22981
- function computeFindingFacets(allGroups, opts) {
22982
- const forSeverity = applyFindingFilters(allGroups, {
23132
+ function computeFindingFacets(allTypes, opts) {
23133
+ const forSeverity = applyFindingFilters(allTypes, {
22983
23134
  providers: opts.providers,
22984
23135
  actions: opts.actions,
22985
23136
  statuses: opts.statuses,
@@ -22990,7 +23141,7 @@ function computeFindingFacets(allGroups, opts) {
22990
23141
  for (const g of forSeverity) {
22991
23142
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22992
23143
  }
22993
- const forProvider = applyFindingFilters(allGroups, {
23144
+ const forProvider = applyFindingFilters(allTypes, {
22994
23145
  actions: opts.actions,
22995
23146
  statuses: opts.statuses,
22996
23147
  q: opts.q,
@@ -23001,7 +23152,7 @@ function computeFindingFacets(allGroups, opts) {
23001
23152
  for (const g of forProvider) {
23002
23153
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23003
23154
  }
23004
- const forAction = applyFindingFilters(allGroups, {
23155
+ const forAction = applyFindingFilters(allTypes, {
23005
23156
  providers: opts.providers,
23006
23157
  statuses: opts.statuses,
23007
23158
  q: opts.q,
@@ -23010,9 +23161,9 @@ function computeFindingFacets(allGroups, opts) {
23010
23161
  });
23011
23162
  const actionMap = /* @__PURE__ */ new Map();
23012
23163
  for (const g of forAction) {
23013
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23164
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23014
23165
  }
23015
- const forSubtype = applyFindingFilters(allGroups, {
23166
+ const forSubtype = applyFindingFilters(allTypes, {
23016
23167
  providers: opts.providers,
23017
23168
  actions: opts.actions,
23018
23169
  statuses: opts.statuses,
@@ -23021,7 +23172,7 @@ function computeFindingFacets(allGroups, opts) {
23021
23172
  });
23022
23173
  const subtypeMap = /* @__PURE__ */ new Map();
23023
23174
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23024
- const forStatus = applyFindingFilters(allGroups, {
23175
+ const forStatus = applyFindingFilters(allTypes, {
23025
23176
  providers: opts.providers,
23026
23177
  actions: opts.actions,
23027
23178
  q: opts.q,
@@ -23043,6 +23194,20 @@ function computeFindingFacets(allGroups, opts) {
23043
23194
  }
23044
23195
 
23045
23196
  // ../../packages/schema/src/zod/findings-flat-build.ts
23197
+ function compareCodePoints(a, b) {
23198
+ const aIter = a[Symbol.iterator]();
23199
+ const bIter = b[Symbol.iterator]();
23200
+ for (; ; ) {
23201
+ const aNext = aIter.next();
23202
+ const bNext = bIter.next();
23203
+ if (aNext.done && bNext.done) return 0;
23204
+ if (aNext.done) return -1;
23205
+ if (bNext.done) return 1;
23206
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23207
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23208
+ if (aPoint !== bPoint) return aPoint - bPoint;
23209
+ }
23210
+ }
23046
23211
  function rowHaystack(row) {
23047
23212
  return [
23048
23213
  row.ruleId,
@@ -23067,12 +23232,24 @@ function matchesDimension(row, opts, dimension) {
23067
23232
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23068
23233
  case "statuses":
23069
23234
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23235
+ case "deliveries":
23236
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23070
23237
  case "tools":
23071
23238
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23239
+ // An EMPTY value is a real filter here, not an absent one. The location
23240
+ // list buckets a finding whose event recorded no repo — or no file — under
23241
+ // the empty string, and selecting that bucket has to narrow the panel to
23242
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23243
+ // row omits the key, which every call site already does.
23244
+ //
23245
+ // Reading '' as unset is what this replaced, and it failed in the one place
23246
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23247
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23248
+ // — a row reading 3 findings beside a panel listing every finding there is.
23072
23249
  case "repo":
23073
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23250
+ return opts.repo === void 0 || row.repo === opts.repo;
23074
23251
  case "file":
23075
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23252
+ return opts.file === void 0 || row.file === opts.file;
23076
23253
  case "q":
23077
23254
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23078
23255
  }
@@ -23083,6 +23260,7 @@ var DIMENSIONS = [
23083
23260
  "providers",
23084
23261
  "actions",
23085
23262
  "statuses",
23263
+ "deliveries",
23086
23264
  "tools",
23087
23265
  "repo",
23088
23266
  "file",
@@ -23096,10 +23274,19 @@ function matchesInstanceFilters(row, opts, except) {
23096
23274
  return true;
23097
23275
  }
23098
23276
  function toItems(counts) {
23099
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23277
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23278
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23279
+ // NFD spelling of the same text) as equal, so a count tie between
23280
+ // them would otherwise be ordered by whichever the Map iteration
23281
+ // produced. compareCodePoints breaks that tie deterministically, which
23282
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23283
+ // which it need not: foldFacetTuples runs this same sort over grouped
23284
+ // tuples, so both paths order facets identically by construction.
23285
+ compareCodePoints(a.value, b.value)
23286
+ );
23100
23287
  }
23101
- function bump(counts, value) {
23102
- counts.set(value, (counts.get(value) ?? 0) + 1);
23288
+ function bump(counts, value, by = 1) {
23289
+ counts.set(value, (counts.get(value) ?? 0) + by);
23103
23290
  }
23104
23291
  function createInstanceFacetAccumulator(opts) {
23105
23292
  const severity = /* @__PURE__ */ new Map();
@@ -23108,6 +23295,7 @@ function createInstanceFacetAccumulator(opts) {
23108
23295
  const action = /* @__PURE__ */ new Map();
23109
23296
  const status = /* @__PURE__ */ new Map();
23110
23297
  const tool = /* @__PURE__ */ new Map();
23298
+ const deployment = /* @__PURE__ */ new Map();
23111
23299
  return {
23112
23300
  add(row) {
23113
23301
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23122,6 +23310,9 @@ function createInstanceFacetAccumulator(opts) {
23122
23310
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23123
23311
  bump(tool, row.toolName);
23124
23312
  }
23313
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23314
+ bump(deployment, row.delivery.state);
23315
+ }
23125
23316
  },
23126
23317
  facets: () => ({
23127
23318
  severity: toItems(severity),
@@ -23129,7 +23320,8 @@ function createInstanceFacetAccumulator(opts) {
23129
23320
  provider: toItems(provider),
23130
23321
  action: toItems(action),
23131
23322
  status: toItems(status),
23132
- tool: toItems(tool)
23323
+ tool: toItems(tool),
23324
+ deployment: toItems(deployment)
23133
23325
  })
23134
23326
  };
23135
23327
  }
@@ -23143,6 +23335,7 @@ function toInstanceDetail(row) {
23143
23335
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23144
23336
  eventId: row.eventId,
23145
23337
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23338
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23146
23339
  ...row.user === void 0 ? {} : { user: row.user },
23147
23340
  action: toApiAction(row.actionTaken),
23148
23341
  detectedAt: row.occurredAt,
@@ -23157,12 +23350,6 @@ function toInstanceDetail(row) {
23157
23350
  policy: { id: `category:${category}`, name: category }
23158
23351
  };
23159
23352
  }
23160
- var SEVERITY_ORDER2 = {
23161
- critical: 0,
23162
- high: 1,
23163
- medium: 2,
23164
- low: 3
23165
- };
23166
23353
  function newLocationAccumulator() {
23167
23354
  return {
23168
23355
  instanceCount: 0,
@@ -23177,7 +23364,7 @@ function newLocationAccumulator() {
23177
23364
  }
23178
23365
  function addToLocation(acc, row) {
23179
23366
  acc.instanceCount += 1;
23180
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23367
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23181
23368
  if (rank < acc.maxSeverityRank) {
23182
23369
  acc.maxSeverityRank = rank;
23183
23370
  acc.maxSeverity = row.severity;
@@ -23186,6 +23373,23 @@ function addToLocation(acc, row) {
23186
23373
  acc.statuses.push(row.status);
23187
23374
  acc.ruleIds.add(row.ruleId);
23188
23375
  }
23376
+ function compareLocationOrder(a, b) {
23377
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23378
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23379
+ if (rankA !== rankB) return rankA - rankB;
23380
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23381
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23382
+ }
23383
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23384
+ if (repoDiff !== 0) return repoDiff;
23385
+ return compareCodePoints(a.file, b.file);
23386
+ }
23387
+ function encodeLocationId(repo, file2) {
23388
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23389
+ }
23390
+ function encodePart(value) {
23391
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23392
+ }
23189
23393
 
23190
23394
  // ../../packages/schema/src/zod/installed-pack.ts
23191
23395
  var InstalledPack = external_exports.object({
@@ -23253,6 +23457,11 @@ var Policy = external_exports.object({
23253
23457
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23254
23458
  provenance: PolicyProvenance.optional()
23255
23459
  }).meta({ id: "Policy" });
23460
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23461
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23462
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23463
+ id: "RedactFallback"
23464
+ });
23256
23465
  var PolicyBundle = external_exports.object({
23257
23466
  version: external_exports.string(),
23258
23467
  policies: external_exports.array(Policy),
@@ -23300,6 +23509,16 @@ var PolicyBundle = external_exports.object({
23300
23509
  // control plane), so no name resolution stands between the decision and the
23301
23510
  // comparison.
23302
23511
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23512
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23513
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23514
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23515
+ // a control plane can tighten a machine and never loosen one — the same
23516
+ // direction `mergeRaiseOnly` enforces for policies.
23517
+ //
23518
+ // Optional so an older backend, and an older on-disk cache, still parses;
23519
+ // absent leaves the device's own setting in force, which is the behaviour
23520
+ // that predates the field and the safe direction to default.
23521
+ redactFallback: RedactFallback.optional(),
23303
23522
  customKeywords: external_exports.array(external_exports.string()),
23304
23523
  fetchedAt: external_exports.iso.datetime()
23305
23524
  }).meta({ id: "PolicyBundle" });
@@ -23329,11 +23548,6 @@ function severityFloorPolicy(category) {
23329
23548
  const peak = CATEGORY_PEAK_SEVERITY[category];
23330
23549
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23331
23550
  }
23332
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23333
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23334
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23335
- id: "RedactFallback"
23336
- });
23337
23551
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23338
23552
  var BUILTIN_POLICY_SPECS = {
23339
23553
  monitor: {
@@ -23626,7 +23840,7 @@ var VaultConsent = external_exports.object({
23626
23840
  });
23627
23841
 
23628
23842
  // ../../packages/schema/src/zod/local.ts
23629
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23843
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23630
23844
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23631
23845
  var RunMode = external_exports.enum(["standalone", "attached"]);
23632
23846
  var ControlPlaneConnection = external_exports.object({
@@ -23646,6 +23860,15 @@ var HistorySyncConsent = external_exports.object({
23646
23860
  payloadVersion: external_exports.number().int().positive(),
23647
23861
  endpoint: external_exports.string()
23648
23862
  });
23863
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23864
+ var BodyRetention = external_exports.object({
23865
+ enabled: external_exports.boolean().default(false),
23866
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23867
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23868
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23869
+ // candidate set that is already bounded by "delivered, or never owed".
23870
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23871
+ }).meta({ id: "BodyRetention" });
23649
23872
  var WorkspaceSettings = external_exports.object({
23650
23873
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23651
23874
  runMode: RunMode.default("standalone"),
@@ -23689,12 +23912,18 @@ var WorkspaceSettings = external_exports.object({
23689
23912
  // covers the current payload and must be re-granted.
23690
23913
  modelJudgeConsent: ModelJudgeConsent.optional(),
23691
23914
  // Records that the user consented to the DEFERRED send — the outbox — along
23692
- // with the payload shape and the endpoint they agreed to. Since payload v2
23693
- // that covers both the pre-attach backlog and undelivered captures (which
23694
- // carry prompt/reply text in `content`); the key name predates the widening.
23695
- // Absent until granted, and a grant for a different endpoint or an older
23696
- // payload no longer counts.
23697
- historySyncConsent: HistorySyncConsent.optional()
23915
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23916
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23917
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23918
+ // both widenings. Absent until granted, and a grant for a different endpoint
23919
+ // or an older payload no longer counts.
23920
+ historySyncConsent: HistorySyncConsent.optional(),
23921
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23922
+ // body never removes the row or its findings.
23923
+ bodyRetention: BodyRetention.default({
23924
+ enabled: false,
23925
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23926
+ })
23698
23927
  });
23699
23928
  function defaultWorkspaceSettings() {
23700
23929
  return WorkspaceSettings.parse({});
@@ -23789,12 +24018,15 @@ function toCaptureAttributes(event) {
23789
24018
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23790
24019
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23791
24020
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24021
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23792
24022
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23793
24023
  // has ever populated either), but every legacy metadata key still rides
23794
24024
  // the bag rather than being silently dropped — CaptureAttributes'
23795
24025
  // `.catchall(z.unknown())` carries the long tail.
23796
24026
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23797
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24027
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24028
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24029
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23798
24030
  };
23799
24031
  }
23800
24032
  function captureDefinitionVersion(finding) {
@@ -23822,10 +24054,22 @@ var ManagedSettingKey = external_exports.enum([
23822
24054
  "vaultInlineReveal",
23823
24055
  "modelJudgeConsent",
23824
24056
  "dataSharesInPlace",
23825
- "redactFallback"
24057
+ "redactFallback",
24058
+ // Pins the toggle and the day count together — see BodyRetention on why the
24059
+ // two are one unit. An administrator mandating a window wants the count
24060
+ // enforced with it, not one a user can widen while the toggle stays on.
24061
+ "bodyRetention"
23826
24062
  ]).meta({ id: "ManagedSettingKey" });
24063
+ function isManagedSettingKey(value) {
24064
+ return ManagedSettingKey.safeParse(value).success;
24065
+ }
23827
24066
  var ManagedSettingsValues = external_exports.object({
23828
24067
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24068
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24069
+ // plain, non-strict objects: a key under either that this build does not know
24070
+ // is stripped and nothing reports it. The unknown-value split in
24071
+ // ManagedSettings below classifies top-level names only, so it stops at
24072
+ // these boundaries.
23829
24073
  controlPlane: external_exports.object({
23830
24074
  endpoint: external_exports.string().min(1),
23831
24075
  label: external_exports.string().min(1).optional()
@@ -23836,7 +24080,8 @@ var ManagedSettingsValues = external_exports.object({
23836
24080
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23837
24081
  modelJudgeConsent: external_exports.boolean().optional(),
23838
24082
  dataSharesInPlace: external_exports.boolean().optional(),
23839
- redactFallback: RedactFallback.optional()
24083
+ redactFallback: RedactFallback.optional(),
24084
+ bodyRetention: BodyRetention.optional()
23840
24085
  }).meta({ id: "ManagedSettingsValues" });
23841
24086
  var ManagedSettings = external_exports.object({
23842
24087
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23844,11 +24089,59 @@ var ManagedSettings = external_exports.object({
23844
24089
  // decision from a bug. Absent renders as a generic "your organization".
23845
24090
  organization: external_exports.string().min(1).optional(),
23846
24091
  // What the administrator pinned.
23847
- values: ManagedSettingsValues.default({}),
24092
+ //
24093
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24094
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24095
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24096
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24097
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24098
+ // exactly the file an administrator is most likely to write while a fleet
24099
+ // is mid-upgrade.
24100
+ //
24101
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24102
+ // file, which is the outcome the lock half already rejected — an older
24103
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24104
+ // value still fails, because the nested schema is re-run over the known
24105
+ // subset and its issues are re-raised on this parse.
24106
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23848
24107
  // Which of those the user may not change. A key here with no matching value
23849
24108
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23850
24109
  // the user may still override. The two are separable on purpose.
23851
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24110
+ //
24111
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24112
+ // build does not know is dropped from the locked set and reported, never a
24113
+ // reason to refuse the file. The same shape reaches an older build whenever
24114
+ // an administrator locks a key a newer build added, and refusing it there
24115
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24116
+ // the fleets most likely to carry a version skew. A name outside the enum
24117
+ // is still never HONOURED: the lockable set stays explicit above.
24118
+ lockedFields: external_exports.array(external_exports.string()).default([])
24119
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24120
+ const known = [];
24121
+ const unknown2 = [];
24122
+ for (const name of lockedFields) {
24123
+ if (isManagedSettingKey(name)) known.push(name);
24124
+ else unknown2.push(name);
24125
+ }
24126
+ const knownValues = /* @__PURE__ */ Object.create(null);
24127
+ const unknownValues = [];
24128
+ for (const [name, value] of Object.entries(values)) {
24129
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24130
+ else unknownValues.push(name);
24131
+ }
24132
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24133
+ if (!pinned.success) {
24134
+ for (const issue2 of pinned.error.issues)
24135
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24136
+ return external_exports.NEVER;
24137
+ }
24138
+ return {
24139
+ ...rest,
24140
+ values: pinned.data,
24141
+ lockedFields: known,
24142
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24143
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24144
+ };
23852
24145
  }).meta({ id: "ManagedSettings" });
23853
24146
 
23854
24147
  // ../../packages/schema/src/zod/project-files.ts
@@ -23972,7 +24265,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23972
24265
  timestamp: external_exports.iso.date(),
23973
24266
  critical: external_exports.number().int().nonnegative(),
23974
24267
  high: external_exports.number().int().nonnegative(),
23975
- medium: external_exports.number().int().nonnegative()
24268
+ medium: external_exports.number().int().nonnegative(),
24269
+ // Optional and additive, so a producer written against the earlier
24270
+ // three-series contract keeps validating. A consumer plotting it resolves the
24271
+ // absent case itself — the chart point requires a number.
24272
+ low: external_exports.number().int().nonnegative().optional()
23976
24273
  }).meta({ id: "FindingsTimeseriesPoint" });
23977
24274
  var FindingsTimeseriesResponse = external_exports.object({
23978
24275
  range: TimeRange,
@@ -23998,6 +24295,10 @@ var ResolvedFeedItem = external_exports.object({
23998
24295
  findingKey: external_exports.string(),
23999
24296
  ruleId: external_exports.string(),
24000
24297
  severity: Severity,
24298
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24299
+ // identifies the file: a bare path matches the same name in every repo.
24300
+ // Optional and additive; empty when the event carried no repo.
24301
+ repo: external_exports.string().optional(),
24001
24302
  path: external_exports.string(),
24002
24303
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24003
24304
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24103,7 +24404,23 @@ var SaveSettingsInput = external_exports.object({
24103
24404
  modelJudgeConsent: ModelJudgeConsentChoice,
24104
24405
  historySyncConsent: HistorySyncConsentChoice,
24105
24406
  vaultConsent: external_exports.string(),
24106
- vaultInlineReveal: external_exports.string()
24407
+ vaultInlineReveal: external_exports.string(),
24408
+ // Widened to `string` like its neighbours rather than typed as
24409
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24410
+ // the call site, so the domain check receives the type it was written for.
24411
+ //
24412
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24413
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24414
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24415
+ // trade against. The real cost runs the other way and is the part worth
24416
+ // knowing: a value this schema admits and the domain enum then rejects lands
24417
+ // on the action's shared refusal, which names NO field, where a shape
24418
+ // rejection reaches `malformedInput` and names the schema key.
24419
+ redactFallback: external_exports.string(),
24420
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24421
+ // `BodyRetention`'s and the action checks it there, so there is one place
24422
+ // that decides what a legal horizon is rather than two that can drift.
24423
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24107
24424
  });
24108
24425
  var AttachInput = external_exports.object({
24109
24426
  endpoint: external_exports.string(),
@@ -24275,6 +24592,52 @@ function reviewSeverityRank(reasons) {
24275
24592
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24276
24593
  }
24277
24594
 
24595
+ // ../../packages/schema/src/zod/web-capture.ts
24596
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24597
+ var WebUsage = external_exports.object({
24598
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24599
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24600
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24601
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24602
+ });
24603
+ var WebToolCall = external_exports.object({
24604
+ toolUseId: external_exports.string().min(1),
24605
+ toolName: external_exports.string().min(1),
24606
+ target: external_exports.string().optional(),
24607
+ isError: external_exports.boolean().optional(),
24608
+ inputSize: external_exports.number().int().nonnegative().optional(),
24609
+ outputSize: external_exports.number().int().nonnegative().optional()
24610
+ });
24611
+ var WebExchange = external_exports.object({
24612
+ messageId: external_exports.string().min(1),
24613
+ startedAt: external_exports.iso.datetime(),
24614
+ model: external_exports.string().optional(),
24615
+ usage: WebUsage.optional(),
24616
+ usageSource: WebUsageSource,
24617
+ stopReason: external_exports.string().optional(),
24618
+ conversationId: external_exports.string().optional(),
24619
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24620
+ toolCalls: external_exports.array(WebToolCall).default([]),
24621
+ // Absent when the adapter recovered no text. Capped by the caller at
24622
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24623
+ // short capture is never mistaken for a short reply.
24624
+ responseText: external_exports.string().optional(),
24625
+ truncated: external_exports.boolean().default(false)
24626
+ });
24627
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24628
+ var WebCaptureStatus = external_exports.object({
24629
+ patched: external_exports.boolean(),
24630
+ live: external_exports.boolean(),
24631
+ blind: external_exports.boolean(),
24632
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24633
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24634
+ parseFailures: external_exports.number().int().nonnegative(),
24635
+ unparsedBodies: external_exports.number().int().nonnegative(),
24636
+ // The adapter-declared JSON key paths that were absent from a real payload —
24637
+ // the earliest signal that a site's contract moved.
24638
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24639
+ });
24640
+
24278
24641
  // ../../packages/persistence/src/paths.ts
24279
24642
  import {
24280
24643
  chmodSync,
@@ -24605,6 +24968,22 @@ function discardStore(file2, backup) {
24605
24968
  }
24606
24969
  }
24607
24970
 
24971
+ // ../../packages/persistence/src/internal/sql-functions.ts
24972
+ var utf8 = new TextDecoder();
24973
+ function akaLower(value) {
24974
+ if (value === null) return null;
24975
+ if (typeof value === "string") return value.toLowerCase();
24976
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
24977
+ return utf8.decode(value).toLowerCase();
24978
+ }
24979
+ function registerSqlFunctions(db) {
24980
+ db.function(
24981
+ "aka_lower",
24982
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
24983
+ akaLower
24984
+ );
24985
+ }
24986
+
24608
24987
  // ../../packages/persistence/src/internal/sql-text.ts
24609
24988
  function escapeLikePattern(s) {
24610
24989
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24689,6 +25068,11 @@ function schemaObjectExists(db, kind, name) {
24689
25068
  function indexExists(db, name) {
24690
25069
  return schemaObjectExists(db, "index", name);
24691
25070
  }
25071
+ function indexColumns(db, name) {
25072
+ if (!indexExists(db, name)) return [];
25073
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25074
+ return columns.map((c) => c.name).filter((c) => c !== null);
25075
+ }
24692
25076
  function columnNames(db, table2, opts) {
24693
25077
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24694
25078
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24750,131 +25134,773 @@ function mapRowsTolerant(rows, map2) {
24750
25134
  return out;
24751
25135
  }
24752
25136
 
24753
- // ../../packages/persistence/src/migrations.ts
24754
- function describeObject(object2) {
24755
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24756
- }
24757
- function splitStatements(sql) {
24758
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24759
- }
24760
- function createdIndexName(statement) {
24761
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24762
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25137
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25138
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25139
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25140
+
25141
+ // ../../packages/persistence/src/sync-failure.ts
25142
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25143
+ function syncFailureRejectCondition(column = "sync_failure") {
25144
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25145
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24763
25146
  }
24764
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24765
- function applyMigrations(db, file2) {
24766
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24767
- db.exec(
24768
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24769
- );
24770
- const applied = new Set(
24771
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24772
- );
24773
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24774
- const record2 = db.prepare(
24775
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24776
- );
24777
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24778
- if (applied.has(migration.tag)) continue;
24779
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24780
- const evidence = evidenceObjects(migration.sql);
24781
- const present = evidence.filter((o) => evidenceExists(db, o));
24782
- if (present.length > 0 && present.length < evidence.length) {
24783
- const missing = evidence.filter((o) => !present.includes(o));
24784
- 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.`;
24785
- akaWarn(message);
24786
- throw new Error(`[aka] ${message}`);
24787
- }
24788
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24789
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24790
- const statements = splitStatements(migration.sql);
24791
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24792
- try {
24793
- withTransaction(
24794
- db,
24795
- () => {
24796
- for (const statement of statements) {
24797
- const indexName = createdIndexName(statement);
24798
- if (indexName === void 0) {
24799
- if (alreadyApplied) continue;
24800
- } else if (indexExists(db, indexName)) {
24801
- continue;
24802
- }
24803
- db.exec(statement);
24804
- }
24805
- if (wantsFkOff && !alreadyApplied) {
24806
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24807
- if (violations.length > 0) {
24808
- throw new Error(
24809
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24810
- );
24811
- }
24812
- }
24813
- record2.run(migration.tag, Date.now());
24814
- },
24815
- "IMMEDIATE"
24816
- );
24817
- } finally {
24818
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24819
- }
25147
+
25148
+ // ../../packages/persistence/src/repositories/history-sync.ts
25149
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25150
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25151
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25152
+ var COUNTED_EVENT_TYPES = [
25153
+ ...STRUCTURAL_EVENT_TYPES,
25154
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25155
+ ];
25156
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25157
+ var PARTITION_BUCKETS = `
25158
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25159
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25160
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25161
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25162
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25163
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25164
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25165
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25166
+ -- added later lands in no bucket and fails the sum assertion, instead
25167
+ -- of silently joining this one.
25168
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25169
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25170
+ THEN 1 ELSE 0 END) AS failed,
25171
+ COUNT(*) AS total`;
25172
+ var COUNTED_SCOPE = `
25173
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25174
+ AND (
25175
+ event_type IN (${TYPE_LIST})
25176
+ OR synced_at IS NOT NULL
25177
+ OR outbox_owed = 1
25178
+ )`;
25179
+ var SKIPPED = -1;
25180
+ var ROW_COLUMNS = `id,
25181
+ parent_id AS parentId,
25182
+ root_session_id AS rootSessionId,
25183
+ event_type AS eventType,
25184
+ host_id AS hostId,
25185
+ harness_id AS harnessId,
25186
+ source_project_id AS sourceProjectId,
25187
+ started_at AS startedAt,
25188
+ ended_at AS endedAt,
25189
+ severity,
25190
+ priority,
25191
+ content,
25192
+ content_hash AS contentHash,
25193
+ attributes`;
25194
+ var SqliteHistorySyncRepository = class {
25195
+ constructor(db) {
25196
+ this.db = db;
25197
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25198
+ this.sessionsStmt = db.prepare(
25199
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25200
+ FROM audit_events
25201
+ WHERE synced_at IS NULL
25202
+ AND event_type IN (${TYPE_LIST})
25203
+ AND started_at < :before
25204
+ GROUP BY sessionId
25205
+ ORDER BY earliest
25206
+ LIMIT :limit`
25207
+ );
25208
+ this.rowsStmt = db.prepare(
25209
+ `SELECT ${ROW_COLUMNS}
25210
+ FROM audit_events
25211
+ WHERE synced_at IS NULL
25212
+ AND event_type IN (${TYPE_LIST})
25213
+ AND started_at < :before
25214
+ AND COALESCE(root_session_id, id) = :sessionId
25215
+ ORDER BY (event_type = 'session') DESC, started_at
25216
+ LIMIT :limit`
25217
+ );
25218
+ this.captureRowsStmt = db.prepare(
25219
+ `SELECT ${ROW_COLUMNS}
25220
+ FROM audit_events
25221
+ WHERE synced_at IS NULL
25222
+ AND sync_claimed_at IS NULL
25223
+ AND outbox_owed = 1
25224
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25225
+ AND started_at < :before
25226
+ ORDER BY started_at
25227
+ LIMIT :limit`
25228
+ );
25229
+ this.markOwedStmt = db.prepare(
25230
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25231
+ );
25232
+ this.markCaptureBacklogOwedStmt = db.prepare(
25233
+ `UPDATE audit_events SET outbox_owed = 1
25234
+ WHERE synced_at IS NULL
25235
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25236
+ AND started_at < :before`
25237
+ );
25238
+ this.stampStmt = db.prepare(
25239
+ `UPDATE audit_events
25240
+ SET synced_at = :at,
25241
+ sync_claimed_at = NULL,
25242
+ sync_failed_at = :failedAt,
25243
+ sync_failure = :failure
25244
+ WHERE id = :id`
25245
+ );
25246
+ this.claimRowStmt = db.prepare(
25247
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25248
+ );
25249
+ this.releaseRowStmt = db.prepare(
25250
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25251
+ );
25252
+ this.releaseStaleClaimsStmt = db.prepare(
25253
+ `UPDATE audit_events SET sync_claimed_at = NULL
25254
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25255
+ );
25256
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25257
+ FROM audit_events${COUNTED_SCOPE}`);
25258
+ this.partitionByKindStmt = db.prepare(
25259
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25260
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25261
+ GROUP BY event_type`
25262
+ );
25263
+ this.countsStmt = db.prepare(
25264
+ `SELECT
25265
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25266
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25267
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25268
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25269
+ THEN 1 ELSE 0 END) AS skipped,
25270
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25271
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25272
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25273
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25274
+ FROM audit_events
25275
+ WHERE event_type IN (${TYPE_LIST})`
25276
+ );
25277
+ this.captureSkipCountStmt = db.prepare(
25278
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25279
+ // way the structural totals are. The split exists because a refusal is
25280
+ // terminal only against the deployment that gave it, and the structural
25281
+ // re-arm frees it on a change of deployment. The capture lane has no such
25282
+ // escape: re-arming a capture would offer one deployment's undelivered
25283
+ // prompts, with their text, to a deployment that never saw them, which is
25284
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25285
+ // reasons mean the same thing — this row will not be sent — and splitting
25286
+ // them would put refused captures in a bucket nothing reads and nothing
25287
+ // frees.
25288
+ `SELECT COUNT(*) AS skipped
25289
+ FROM audit_events
25290
+ WHERE synced_at = ${String(SKIPPED)}
25291
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25292
+ );
25293
+ this.fingerprintStmt = db.prepare(
25294
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25295
+ FROM history_sync WHERE id = 1`
25296
+ );
25297
+ this.setFingerprintStmt = db.prepare(
25298
+ `UPDATE history_sync
25299
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25300
+ WHERE id = 1`
25301
+ );
25302
+ this.disownCapturesStmt = db.prepare(
25303
+ `UPDATE audit_events SET outbox_owed = NULL
25304
+ WHERE outbox_owed IS NOT NULL
25305
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25306
+ AND started_at < :attachedAt`
25307
+ );
25308
+ this.rearmStmt = db.prepare(
25309
+ `UPDATE audit_events
25310
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25311
+ WHERE (synced_at > 0
25312
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25313
+ AND event_type IN (${TYPE_LIST})`
25314
+ );
25315
+ this.claimStmt = db.prepare(
25316
+ `UPDATE history_sync
25317
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25318
+ WHERE id = 1
25319
+ AND (owner_pid IS NULL
25320
+ OR heartbeat_at IS NULL
25321
+ OR heartbeat_at < :staleBefore
25322
+ OR heartbeat_at > :now)`
25323
+ );
25324
+ this.heartbeatStmt = db.prepare(
25325
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25326
+ );
25327
+ this.releaseStmt = db.prepare(
25328
+ `UPDATE history_sync
25329
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25330
+ WHERE id = 1 AND owner_pid = :pid`
25331
+ );
25332
+ this.closeWindowStmt = db.prepare(
25333
+ `UPDATE audit_events
25334
+ SET synced_at = ${String(SKIPPED)},
25335
+ sync_failed_at = :at,
25336
+ sync_failure = 'detached_undelivered'
25337
+ WHERE synced_at IS NULL
25338
+ AND event_type IN (${TYPE_LIST})
25339
+ AND started_at >= :attachedAt`
25340
+ );
25341
+ this.releaseBoundaryStmt = db.prepare(
25342
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25343
+ );
25344
+ this.freezeBoundaryStmt = db.prepare(
25345
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25346
+ );
25347
+ this.leaseStmt = db.prepare(
25348
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25349
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25350
+ FROM history_sync WHERE id = 1`
25351
+ );
25352
+ this.inspectionsStmt = db.prepare(
25353
+ `SELECT d.rule_id AS ruleId,
25354
+ d.name AS ruleName,
25355
+ d.version AS ruleVersion,
25356
+ d.category AS category,
25357
+ d.severity AS severity,
25358
+ f.span_start AS spanStart,
25359
+ f.span_end AS spanEnd,
25360
+ f.masked_match AS maskedMatch,
25361
+ f.action_taken AS actionTaken,
25362
+ f.confidence AS confidence
25363
+ FROM inspection_findings f
25364
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25365
+ WHERE f.audit_event_id = :auditEventId
25366
+ ORDER BY f.span_start, f.id`
25367
+ );
24820
25368
  }
24821
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24822
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25369
+ db;
25370
+ ensureRowStmt;
25371
+ sessionsStmt;
25372
+ rowsStmt;
25373
+ stampStmt;
25374
+ countsStmt;
25375
+ fingerprintStmt;
25376
+ setFingerprintStmt;
25377
+ rearmStmt;
25378
+ claimStmt;
25379
+ heartbeatStmt;
25380
+ releaseStmt;
25381
+ leaseStmt;
25382
+ inspectionsStmt;
25383
+ closeWindowStmt;
25384
+ releaseBoundaryStmt;
25385
+ freezeBoundaryStmt;
25386
+ captureRowsStmt;
25387
+ markOwedStmt;
25388
+ markCaptureBacklogOwedStmt;
25389
+ captureSkipCountStmt;
25390
+ disownCapturesStmt;
25391
+ partitionStmt;
25392
+ partitionByKindStmt;
25393
+ claimRowStmt;
25394
+ releaseRowStmt;
25395
+ releaseStaleClaimsStmt;
25396
+ /**
25397
+ * The masked detections recorded against one tool call.
25398
+ *
25399
+ * These travel with the event because a tool call's target is not
25400
+ * re-inspectable from the event alone — unlike a capture, where the text
25401
+ * itself is re-scannable. What crosses is the masked match and the rule that
25402
+ * produced it, never the value.
25403
+ */
25404
+ inspectionsFor(auditEventId) {
25405
+ return allRows(this.inspectionsStmt, { auditEventId });
24823
25406
  }
24824
- ensureSyncedAtColumn(db, "audit_events");
24825
- ensureScanLedgerTable(db);
24826
- ensureHistorySyncTable(db);
24827
- ensureBlockedDetectionsTable(db);
24828
- ensureRuleProbeCacheTable(db);
24829
- ensureWriteGateTrigger(db);
24830
- ensureTokenUsageColumns(db);
24831
- reconcileSourceProjectIds(db);
24832
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24833
- const drained = runLegacyHistoryBackfill(db);
24834
- if (drained) applyLegacyDropMigration(db, file2);
25407
+ /**
25408
+ * Sessions with structural rows still to send, oldest first.
25409
+ *
25410
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25411
+ * read. Anything recorded after the machine attached is the live forward
25412
+ * path's to deliver; this drain exists for what was recorded before it, and a
25413
+ * row both paths send is at best a duplicate request and at worst — for a
25414
+ * session root — an overwrite of the inventory ids the live path resolved.
25415
+ */
25416
+ pendingSessions(limit, before) {
25417
+ return allRows(this.sessionsStmt, { limit, before }).map(
25418
+ (r) => r.sessionId
25419
+ );
24835
25420
  }
24836
- }
24837
- function readLegacyTables(db) {
24838
- let holdsRows = false;
24839
- const marks = [];
24840
- for (const table2 of ["events", "findings"]) {
24841
- try {
24842
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
24843
- if (row === void 0) {
24844
- holdsRows = true;
24845
- marks.push(`${table2}:unreadable`);
24846
- continue;
24847
- }
24848
- if (row.n > 0) holdsRows = true;
24849
- marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
24850
- } catch {
24851
- holdsRows = true;
24852
- marks.push(`${table2}:unreadable`);
24853
- }
25421
+ /** One session's undelivered structural rows within the backlog, root first. */
25422
+ pendingRows(sessionId, limit, before) {
25423
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24854
25424
  }
24855
- return { holdsRows, mark: marks.join("|") };
24856
- }
24857
- function applyLegacyDropMigration(db, file2) {
24858
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24859
- if (!migration) return;
24860
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24861
- if (file2 !== void 0 && before?.holdsRows === true) {
24862
- try {
24863
- backupBeforeLegacyDrop(db, file2);
24864
- } catch (error61) {
24865
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24866
- return;
24867
- }
25425
+ /**
25426
+ * Captures this machine still owes the deployment, oldest first.
25427
+ *
25428
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25429
+ * by a time window — see captureRowsStmt for why a window could not express
25430
+ * this. `before` is the grace window that leaves a just-recorded capture to
25431
+ * the live path.
25432
+ */
25433
+ pendingCaptureRows(limit, before) {
25434
+ return allRows(this.captureRowsStmt, { limit, before });
24868
25435
  }
24869
- try {
25436
+ /**
25437
+ * Record that a capture is OWED to the deployment.
25438
+ *
25439
+ * Written by the attached forward path when a live send did not confirm
25440
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25441
+ * a fact rather than an inference: the machine was attached, the send did not
25442
+ * land, so the row is owed — which no time window can state, because the same
25443
+ * window that holds the rows a past attachment left owed also holds every
25444
+ * capture recorded while the machine was DETACHED, and those were never
25445
+ * offered to anyone.
25446
+ *
25447
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25448
+ * out of the drain's read.
25449
+ */
25450
+ markCaptureOwed(id) {
25451
+ this.markOwedStmt.run({ id });
25452
+ }
25453
+ /**
25454
+ * Mark every capture already on disk as owed, as of `before`.
25455
+ *
25456
+ * The consent-time backfill, called once from `aka attach` when a human
25457
+ * grants existing-history consent — never from an ongoing drain pass, and
25458
+ * never inferred from a boundary that could later move. `before` is the
25459
+ * caller's own "now" at the moment consent was granted, so what this marks
25460
+ * is exactly the backlog the consent prompt already counted, not whatever a
25461
+ * later re-attach or key rotation might widen it to.
25462
+ *
25463
+ * Returns how many rows matched, for the caller to log or test against. Not a
25464
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25465
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25466
+ */
25467
+ markCaptureBacklogOwed(before) {
25468
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25469
+ }
25470
+ /**
25471
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25472
+ *
25473
+ * CLEARS any failure reason in the same statement. A row that failed against
25474
+ * one deployment and then landed is delivered, and leaving the reason behind
25475
+ * would leave the store holding two contradictory answers about one row —
25476
+ * with the surface free to render either.
25477
+ */
25478
+ markSynced(ids, atMs) {
25479
+ this.stampAll(ids, atMs, null);
25480
+ }
25481
+ /**
25482
+ * Record that THIS MACHINE cannot express the row on the wire.
25483
+ *
25484
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25485
+ * payload, or a body the client itself refused to send. It fails identically
25486
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25487
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25488
+ * is retried; marking those would turn one outage into permanent data loss.
25489
+ */
25490
+ markSkipped(ids, atMs) {
25491
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25492
+ }
25493
+ /**
25494
+ * Record that THIS DEPLOYMENT refused the row.
25495
+ *
25496
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25497
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25498
+ * row is outstanding rather than why. What separates them is the reason, and
25499
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25500
+ * on one body, so it is terminal only for as long as this machine points at
25501
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25502
+ *
25503
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25504
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25505
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25506
+ */
25507
+ markRefused(ids, atMs) {
25508
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25509
+ }
25510
+ eachInTransaction(ids, run) {
25511
+ if (ids.length === 0) return;
24870
25512
  withTransaction(
24871
- db,
25513
+ this.db,
24872
25514
  () => {
24873
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24874
- if (alreadyDropped) return;
24875
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24876
- akaWarn(
24877
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25515
+ for (const id of ids) run(id);
25516
+ },
25517
+ "IMMEDIATE"
25518
+ );
25519
+ }
25520
+ stampAll(ids, value, failure, failedAtMs) {
25521
+ if (ids.length === 0) return;
25522
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25523
+ withTransaction(
25524
+ this.db,
25525
+ () => {
25526
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25527
+ },
25528
+ "IMMEDIATE"
25529
+ );
25530
+ }
25531
+ /**
25532
+ * Claim rows as in-flight.
25533
+ *
25534
+ * Advisory in exactly the sense the lease is: it records that a send is in
25535
+ * progress so a surface can say so, and a lost claim costs a row showing as
25536
+ * queued while it is actually being sent. It is not exclusion — the far side
25537
+ * settles a duplicate on the row id.
25538
+ */
25539
+ claimRows(ids, atMs) {
25540
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25541
+ }
25542
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25543
+ releaseRows(ids) {
25544
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25545
+ }
25546
+ /**
25547
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25548
+ *
25549
+ * A process killed between claiming and settling leaves rows claimed with
25550
+ * nothing left to settle them. Without this they read as "sending" for ever.
25551
+ */
25552
+ releaseStaleClaims(staleBefore) {
25553
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25554
+ }
25555
+ /**
25556
+ * Every tracked row in exactly one delivery state.
25557
+ *
25558
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25559
+ * pick up now", which is a different question from "what state is this row
25560
+ * in" — and a machine that has never attached has no boundary to pass, so
25561
+ * requiring one would force a caller to invent one and report the whole store
25562
+ * as queued.
25563
+ */
25564
+ /**
25565
+ * The same partition, one row per kind that a lane carries.
25566
+ *
25567
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25568
+ * scope decides which rows exist at all, so a kind that has never been
25569
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25570
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25571
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25572
+ * different things.
25573
+ */
25574
+ partitionByKind() {
25575
+ return allRows(
25576
+ this.partitionByKindStmt,
25577
+ {}
25578
+ ).map((row) => ({
25579
+ kind: row.kind,
25580
+ queued: row.queued ?? 0,
25581
+ inProgress: row.inProgress ?? 0,
25582
+ synced: row.synced ?? 0,
25583
+ failed: row.failed ?? 0,
25584
+ refused: row.refused ?? 0,
25585
+ detached: row.detached ?? 0,
25586
+ total: row.total ?? 0
25587
+ }));
25588
+ }
25589
+ partition() {
25590
+ const row = getRow(this.partitionStmt, {});
25591
+ return {
25592
+ queued: row?.queued ?? 0,
25593
+ inProgress: row?.inProgress ?? 0,
25594
+ synced: row?.synced ?? 0,
25595
+ failed: row?.failed ?? 0,
25596
+ refused: row?.refused ?? 0,
25597
+ detached: row?.detached ?? 0,
25598
+ total: row?.total ?? 0
25599
+ };
25600
+ }
25601
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25602
+ counts(before) {
25603
+ const row = getRow(this.countsStmt, { before });
25604
+ const captures = getRow(this.captureSkipCountStmt);
25605
+ return {
25606
+ pending: row?.pending ?? 0,
25607
+ sent: row?.sent ?? 0,
25608
+ skipped: row?.skipped ?? 0,
25609
+ refused: row?.refused ?? 0,
25610
+ detached: row?.detached ?? 0,
25611
+ capturesSkipped: captures?.skipped ?? 0
25612
+ };
25613
+ }
25614
+ /**
25615
+ * The deployment the current stamps were made against, and where its backlog
25616
+ * ends.
25617
+ *
25618
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25619
+ * machine that has never drained is — and every writer below seeds the row
25620
+ * before it needs one, so nothing depends on this creating it. Keeping the
25621
+ * write off the gate path matters because the gate runs on every pass while a
25622
+ * write has to take the database's write lock.
25623
+ */
25624
+ deployment() {
25625
+ const row = getRow(
25626
+ this.fingerprintStmt
25627
+ );
25628
+ return {
25629
+ fingerprint: row?.fingerprint ?? void 0,
25630
+ backlogBefore: row?.backlogBefore ?? void 0
25631
+ };
25632
+ }
25633
+ /**
25634
+ * Point the ledger at a different deployment, discarding what it recorded
25635
+ * about the previous one.
25636
+ *
25637
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25638
+ * machine has just left are undelivered as far as the new one is concerned.
25639
+ * All four in one transaction, so a crash between them cannot leave stamps
25640
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25641
+ * a disown with no re-mark to follow it.
25642
+ *
25643
+ * The boundary is written HERE and only here, which is what freezes it: a
25644
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25645
+ * unchanged, so this never runs and the backlog does not widen back over rows
25646
+ * the live path has since delivered.
25647
+ *
25648
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25649
+ * granted existing-history consent for the deployment this call is arming —
25650
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25651
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25652
+ * apart. Passed only when that grant is valid, since this method has no way
25653
+ * to check consent itself and must not mark a row owed for a machine that
25654
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25655
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25656
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25657
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25658
+ * on the cleared side of that bound — and the re-mark in the same
25659
+ * transaction is what puts those rows back. A crash between the two cannot
25660
+ * strand the ledger disowned with nothing re-marked — the transaction either
25661
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25662
+ * committed re-enters this method on the very next pass. Omit it (the
25663
+ * structural-only tests do) to exercise the disown in isolation.
25664
+ *
25665
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25666
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25667
+ * live path can mark a capture owed from the moment `aka attach` writes the
25668
+ * descriptor, before the drain's first pass ever reaches this method, and
25669
+ * such a row sits at or after the bound rather than below it. What keeps the
25670
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25671
+ * bound — disown runs first, re-mark second, both inside the one
25672
+ * transaction above.
25673
+ */
25674
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25675
+ this.ensureRowStmt.run();
25676
+ withTransaction(
25677
+ this.db,
25678
+ () => {
25679
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25680
+ this.rearmStmt.run();
25681
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25682
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25683
+ }
25684
+ if (backfillCapturesBefore !== void 0) {
25685
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25686
+ }
25687
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25688
+ },
25689
+ "IMMEDIATE"
25690
+ );
25691
+ }
25692
+ /**
25693
+ * End the attached period: hand its rows to the live path, and release the
25694
+ * boundary so the next attachment can freeze a new one.
25695
+ *
25696
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25697
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25698
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25699
+ * during the detached period, because the machine is not attached. Rows
25700
+ * recorded in that window sit after the boundary and before the re-attach, so
25701
+ * neither path takes them, and the pending count reports none outstanding.
25702
+ *
25703
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25704
+ * closing attachment's to deliver and are no longer outstanding — that is what
25705
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25706
+ * distinction is not academic: this used to write a delivery TIME, which every
25707
+ * read treats as delivery, so one detach turned a window of undelivered rows
25708
+ * into a window of delivered ones and no surface could tell. It writes the
25709
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25710
+ * "received" stop being the same fact.
25711
+ *
25712
+ * A change of deployment still frees them (see the re-arm), because the next
25713
+ * deployment has seen none of this machine's history — so the rows reach it
25714
+ * exactly as they did when this wrote a delivery time.
25715
+ *
25716
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25717
+ * window unstamped — that half-state would re-send the whole attached period
25718
+ * on the next attach, which is the failure the boundary exists to prevent.
25719
+ */
25720
+ closeAttachedWindow(attachedAtMs, atMs) {
25721
+ this.ensureRowStmt.run();
25722
+ withTransaction(
25723
+ this.db,
25724
+ () => {
25725
+ const row = getRow(this.fingerprintStmt);
25726
+ const from = row?.backlogBefore ?? attachedAtMs;
25727
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25728
+ this.releaseBoundaryStmt.run();
25729
+ },
25730
+ "IMMEDIATE"
25731
+ );
25732
+ }
25733
+ /**
25734
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25735
+ *
25736
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25737
+ * different deployment and therefore discards what was delivered to the old
25738
+ * one: here the recipient is the same, so everything already sent to it stays
25739
+ * sent.
25740
+ */
25741
+ freezeBoundary(backlogBefore) {
25742
+ this.ensureRowStmt.run();
25743
+ this.freezeBoundaryStmt.run({ backlogBefore });
25744
+ }
25745
+ /** Take the claim, or report that someone live already holds it. */
25746
+ claim(pid, host, nowMs, staleAfterMs) {
25747
+ this.ensureRowStmt.run();
25748
+ let taken = false;
25749
+ withTransaction(
25750
+ this.db,
25751
+ () => {
25752
+ const result = this.claimStmt.run({
25753
+ pid,
25754
+ host,
25755
+ now: nowMs,
25756
+ staleBefore: nowMs - staleAfterMs
25757
+ });
25758
+ taken = result.changes === 1;
25759
+ },
25760
+ "IMMEDIATE"
25761
+ );
25762
+ return taken;
25763
+ }
25764
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25765
+ heartbeat(pid, nowMs) {
25766
+ this.heartbeatStmt.run({ now: nowMs, pid });
25767
+ }
25768
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25769
+ release(pid) {
25770
+ this.releaseStmt.run({ pid });
25771
+ }
25772
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25773
+ lease() {
25774
+ return getRow(this.leaseStmt);
25775
+ }
25776
+ };
25777
+
25778
+ // ../../packages/persistence/src/migrations.ts
25779
+ function describeObject(object2) {
25780
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25781
+ }
25782
+ function splitStatements(sql) {
25783
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25784
+ }
25785
+ function createdIndexName(statement) {
25786
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25787
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25788
+ }
25789
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25790
+ function applyMigrations(db, file2, options = {}) {
25791
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25792
+ db.exec(
25793
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25794
+ );
25795
+ const applied = new Set(
25796
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25797
+ );
25798
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25799
+ const record2 = db.prepare(
25800
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25801
+ );
25802
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25803
+ if (applied.has(migration.tag)) continue;
25804
+ if (options.skipTags?.has(migration.tag) === true) continue;
25805
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25806
+ const evidence = evidenceObjects(migration.sql);
25807
+ const present = evidence.filter((o) => evidenceExists(db, o));
25808
+ if (present.length > 0 && present.length < evidence.length) {
25809
+ const missing = evidence.filter((o) => !present.includes(o));
25810
+ 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.`;
25811
+ akaWarn(message);
25812
+ throw new Error(`[aka] ${message}`);
25813
+ }
25814
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25815
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25816
+ const statements = splitStatements(migration.sql);
25817
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25818
+ try {
25819
+ withTransaction(
25820
+ db,
25821
+ () => {
25822
+ for (const statement of statements) {
25823
+ const indexName = createdIndexName(statement);
25824
+ if (indexName === void 0) {
25825
+ if (alreadyApplied) continue;
25826
+ } else if (indexExists(db, indexName)) {
25827
+ continue;
25828
+ }
25829
+ db.exec(statement);
25830
+ }
25831
+ if (wantsFkOff && !alreadyApplied) {
25832
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25833
+ if (violations.length > 0) {
25834
+ throw new Error(
25835
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25836
+ );
25837
+ }
25838
+ }
25839
+ record2.run(migration.tag, Date.now());
25840
+ },
25841
+ "IMMEDIATE"
25842
+ );
25843
+ } finally {
25844
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25845
+ }
25846
+ }
25847
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25848
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25849
+ }
25850
+ ensureSyncedAtColumn(db, "audit_events");
25851
+ ensureScanLedgerTable(db);
25852
+ ensureHistorySyncTable(db);
25853
+ ensureBlockedDetectionsTable(db);
25854
+ ensureRuleProbeCacheTable(db);
25855
+ ensureWriteGateTrigger(db);
25856
+ ensureTokenUsageColumns(db);
25857
+ reconcileSourceProjectIds(db);
25858
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25859
+ const drained = runLegacyHistoryBackfill(db);
25860
+ if (drained) applyLegacyDropMigration(db, file2);
25861
+ }
25862
+ }
25863
+ function readLegacyTables(db) {
25864
+ let holdsRows = false;
25865
+ const marks = [];
25866
+ for (const table2 of ["events", "findings"]) {
25867
+ try {
25868
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
25869
+ if (row === void 0) {
25870
+ holdsRows = true;
25871
+ marks.push(`${table2}:unreadable`);
25872
+ continue;
25873
+ }
25874
+ if (row.n > 0) holdsRows = true;
25875
+ marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
25876
+ } catch {
25877
+ holdsRows = true;
25878
+ marks.push(`${table2}:unreadable`);
25879
+ }
25880
+ }
25881
+ return { holdsRows, mark: marks.join("|") };
25882
+ }
25883
+ function applyLegacyDropMigration(db, file2) {
25884
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25885
+ if (!migration) return;
25886
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25887
+ if (file2 !== void 0 && before?.holdsRows === true) {
25888
+ try {
25889
+ backupBeforeLegacyDrop(db, file2);
25890
+ } catch (error61) {
25891
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25892
+ return;
25893
+ }
25894
+ }
25895
+ try {
25896
+ withTransaction(
25897
+ db,
25898
+ () => {
25899
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25900
+ if (alreadyDropped) return;
25901
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25902
+ akaWarn(
25903
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24878
25904
  );
24879
25905
  return;
24880
25906
  }
@@ -25182,10 +26208,62 @@ function ensureSyncedAtColumn(db, table2) {
25182
26208
  if (!columns.includes("outbox_owed")) {
25183
26209
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25184
26210
  }
26211
+ if (!columns.includes("sync_failed_at")) {
26212
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26213
+ }
26214
+ if (!columns.includes("sync_failure")) {
26215
+ withTransaction(
26216
+ db,
26217
+ () => {
26218
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26219
+ db.exec(
26220
+ `UPDATE ${table2} SET synced_at = NULL
26221
+ WHERE synced_at = -1
26222
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26223
+ );
26224
+ },
26225
+ "IMMEDIATE"
26226
+ );
26227
+ }
25185
26228
  db.exec(
25186
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25187
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26229
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26230
+ BEFORE UPDATE OF sync_failure ON ${table2}
26231
+ WHEN ${syncFailureRejectCondition()}
26232
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25188
26233
  );
26234
+ const syncIndexColumns = [
26235
+ "event_type",
26236
+ "synced_at",
26237
+ "sync_claimed_at",
26238
+ "started_at",
26239
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26240
+ // has to be in the index for the read to stay covered — but putting it
26241
+ // ahead of `started_at` would reorder the prefix the structural drain's
26242
+ // reads match on.
26243
+ "sync_failure"
26244
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26245
+ //
26246
+ // The delivery-state read tests it — a capture's state depends on whether a
26247
+ // live forward marked it owed — so carrying it here makes that read covering
26248
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26249
+ // But a sixth column changes what the planner charges for this index, and
26250
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26251
+ // then stops choosing the per-session index for the token rollup and walks
26252
+ // every `llm_call` in the store through the event-type index instead. That
26253
+ // read grows with the store; this one does not.
26254
+ //
26255
+ // 40 ms on the largest store measured, once per render, is a cost worth
26256
+ // paying to leave every other read's plan where it was.
26257
+ ];
26258
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26259
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26260
+ if (!syncIndexMatches) {
26261
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26262
+ db.exec(
26263
+ `CREATE INDEX idx_audit_events_sync
26264
+ ON audit_events (${syncIndexColumns.join(", ")})`
26265
+ );
26266
+ }
25189
26267
  db.exec(
25190
26268
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25191
26269
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25407,7 +26485,11 @@ function buildAuditEvent(row) {
25407
26485
  link: linkParsed?.success ? linkParsed.data : null,
25408
26486
  targetId: row.target_id,
25409
26487
  internal: intToBool(row.internal),
25410
- flagged: intToBool(row.flagged)
26488
+ flagged: intToBool(row.flagged),
26489
+ // Only meaningful when the title came out empty — a row whose body was
26490
+ // expired but whose title fell back to `tool_name` still has something to
26491
+ // render, and flagging it would make the view apologise for nothing.
26492
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25411
26493
  };
25412
26494
  }
25413
26495
  var TIMELINE_COLUMNS = `
@@ -25415,6 +26497,7 @@ var TIMELINE_COLUMNS = `
25415
26497
  event_type,
25416
26498
  started_at,
25417
26499
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26500
+ content_expired_at,
25418
26501
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25419
26502
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25420
26503
  json_extract(attributes, '$.severity') AS severity,
@@ -25541,7 +26624,8 @@ var SqliteActivityRepository = class {
25541
26624
  SELECT 1 FROM audit_events d
25542
26625
  WHERE d.root_session_id = audit_events.id
25543
26626
  AND (d.content LIKE ? ESCAPE '\\'
25544
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26627
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26628
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25545
26629
  );
25546
26630
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25547
26631
  }
@@ -26079,6 +27163,88 @@ var SqliteAuditEventsRepository = class {
26079
27163
  }
26080
27164
  };
26081
27165
 
27166
+ // ../../packages/persistence/src/repositories/body-retention.ts
27167
+ var DEFAULT_BATCH_SIZE = 500;
27168
+ var DEFAULT_MAX_ROWS = 5e4;
27169
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27170
+ var SqliteBodyRetentionRepository = class {
27171
+ constructor(db) {
27172
+ this.db = db;
27173
+ const select = (laneClause) => `
27174
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27175
+ FROM audit_events
27176
+ WHERE content IS NOT NULL
27177
+ AND started_at < :cutoff
27178
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27179
+ ${laneClause}
27180
+ ORDER BY started_at
27181
+ LIMIT :limit`;
27182
+ this.candidatesStmt = this.db.prepare(select(""));
27183
+ this.candidatesSyncSafeStmt = this.db.prepare(
27184
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27185
+ );
27186
+ this.heldBySyncStmt = this.db.prepare(`
27187
+ SELECT COUNT(*) AS n
27188
+ FROM audit_events
27189
+ WHERE content IS NOT NULL
27190
+ AND started_at < :cutoff
27191
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27192
+ AND synced_at IS NULL`);
27193
+ this.expireStmt = this.db.prepare(
27194
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27195
+ );
27196
+ }
27197
+ db;
27198
+ candidatesStmt;
27199
+ candidatesSyncSafeStmt;
27200
+ heldBySyncStmt;
27201
+ expireStmt;
27202
+ /** How many bytes a pass with these options would free, changing nothing. */
27203
+ preview(opts) {
27204
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27205
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27206
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27207
+ return {
27208
+ rowsExpired: rows.length,
27209
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27210
+ rowsHeldBySync: this.countHeldBySync(opts)
27211
+ };
27212
+ }
27213
+ /** Clear eligible bodies, in bounded batches. */
27214
+ expire(opts) {
27215
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27216
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27217
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27218
+ let rowsExpired = 0;
27219
+ let bytesFreed = 0;
27220
+ let done = true;
27221
+ while (rowsExpired < maxRows) {
27222
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27223
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27224
+ if (batch.length === 0) break;
27225
+ withTransaction(
27226
+ this.db,
27227
+ () => {
27228
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27229
+ },
27230
+ "IMMEDIATE"
27231
+ );
27232
+ rowsExpired += batch.length;
27233
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27234
+ if (batch.length < remaining) break;
27235
+ if (rowsExpired >= maxRows) {
27236
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27237
+ }
27238
+ }
27239
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27240
+ }
27241
+ countHeldBySync(opts) {
27242
+ if (opts.sweepSyncLane) return 0;
27243
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27244
+ return row.n;
27245
+ }
27246
+ };
27247
+
26082
27248
  // ../../packages/persistence/src/repositories/classified-data.ts
26083
27249
  var SqliteClassifiedDataRepository = class {
26084
27250
  constructor(db) {
@@ -26879,23 +28045,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26879
28045
  )`;
26880
28046
 
26881
28047
  // ../../packages/persistence/src/repositories/findings.ts
26882
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26883
- var DEFAULT_LOCATIONS_LIMIT = 100;
26884
- var LOCATION_RULE_IDS_CAP = 20;
26885
- function compareLocationOrder(a, b) {
26886
- return compareFindingGroupOrder(
26887
- {
26888
- severity: a.maxSeverity,
26889
- latestDetectedAt: a.latestDetectedAt,
26890
- id: ""
26891
- },
26892
- {
26893
- severity: b.maxSeverity,
26894
- latestDetectedAt: b.latestDetectedAt,
26895
- id: ""
26896
- }
26897
- );
26898
- }
26899
28048
  var CONCAT_SEP = ",";
26900
28049
  var TUPLE_SEP = "|";
26901
28050
  function splitConcat(value) {
@@ -26924,7 +28073,15 @@ function toFlatFindingRow(r) {
26924
28073
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26925
28074
  eventId: r.event_id,
26926
28075
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26927
- status: deriveInstanceStatus(r)
28076
+ status: deriveInstanceStatus(r),
28077
+ delivery: deriveFindingDelivery({
28078
+ kind: r.kind,
28079
+ syncedAt: r.synced_at,
28080
+ syncClaimedAt: r.sync_claimed_at,
28081
+ syncFailedAt: r.sync_failed_at,
28082
+ syncFailure: r.sync_failure,
28083
+ outboxOwed: r.outbox_owed
28084
+ })
26928
28085
  };
26929
28086
  }
26930
28087
  function encodeGroupCursor(group) {
@@ -26947,13 +28104,51 @@ function decodeGroupCursor(cursor) {
26947
28104
  return null;
26948
28105
  }
26949
28106
  function firstAfter(sorted, cursor) {
26950
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28107
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26951
28108
  return index === -1 ? sorted.length : index;
26952
28109
  }
26953
28110
  function findDeepLinked(sorted, page, id) {
26954
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26955
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28111
+ if (page.some((t) => t.id === id)) return void 0;
28112
+ return sorted.find((t) => t.id === id);
28113
+ }
28114
+ function encodeLocationCursor(location) {
28115
+ const payload = {
28116
+ sev: location.maxSeverity,
28117
+ t: location.latestDetectedAt,
28118
+ r: location.repo,
28119
+ f: location.file
28120
+ };
28121
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28122
+ }
28123
+ function decodeLocationCursor(cursor) {
28124
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28125
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28126
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28127
+ }
28128
+ return null;
28129
+ }
28130
+ function firstLocationAfter(sorted, cursor) {
28131
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28132
+ return index === -1 ? sorted.length : index;
28133
+ }
28134
+ function findDeepLinkedLocation(sorted, page, id) {
28135
+ if (page.some((l) => l.id === id)) return void 0;
28136
+ return sorted.find((l) => l.id === id);
26956
28137
  }
28138
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28139
+ d.severity AS severity, f.masked_match AS masked_match,
28140
+ f.action_taken AS action_taken, f.confidence AS confidence,
28141
+ e.started_at AS occurred_at,
28142
+ e.source_tool AS source_tool,
28143
+ e.repo AS repo,
28144
+ e.file_path AS file,
28145
+ e.tool_name AS tool_name,
28146
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28147
+ e.event_type AS kind, f.finding_key AS finding_key,
28148
+ ${latestResolutionStatusSql("f")} AS latest_status,
28149
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28150
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28151
+ e.outbox_owed AS outbox_owed`;
26957
28152
  var DAY_MS3 = 864e5;
26958
28153
  var SqliteFindingsRepository = class {
26959
28154
  constructor(db) {
@@ -27074,30 +28269,26 @@ var SqliteFindingsRepository = class {
27074
28269
  );
27075
28270
  }
27076
28271
  /**
27077
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27078
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27079
- * attributes bag, rule_id/category/severity from the definition), scoped to
27080
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27081
- * rows this list must never surface), groups by ruleId, computes
27082
- * per-filter-excluded facets, applies the requested filters, and sorts by
27083
- * severity then recency. Filtering
27084
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27085
- * reflect the full filtered set; `items` is the requested
27086
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27087
- * filter, `totals.findings` counts only instances whose derived status was
27088
- * requested, and each item's instance preview is narrowed the same way.
28272
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28273
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28274
+ * list must never surface), with per-filter-excluded facets, the requested
28275
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28276
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28277
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28278
+ * Under a `status` filter, `totals.findings` counts only findings whose
28279
+ * derived status was requested.
28280
+ *
28281
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28282
+ * folding EVERY finding into the numbers a type row and the filters need
28283
+ * (count, severity, category, providers, actions, statuses, latest, search
28284
+ * text). The findings OF a type come from listFindingInstances scoped to
28285
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27089
28286
  *
27090
- * Two reads, neither of which materializes a row per finding:
27091
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27092
- * the group and the filters need (count, providers, actions, statuses,
27093
- * latest, search text);
27094
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27095
- * populate `instances` for the table's expanded rows.
27096
28287
  * The aggregates carry raw DB values and are translated by the same
27097
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27098
- * rule is ever restated in SQL.
28288
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28289
+ * status rule is ever restated in SQL.
27099
28290
  */
27100
- listGroupedFindings(query) {
28291
+ listFindingTypes(query) {
27101
28292
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27102
28293
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27103
28294
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27110,12 +28301,7 @@ var SqliteFindingsRepository = class {
27110
28301
  predicate,
27111
28302
  params: sessionParams
27112
28303
  });
27113
- const rows = this.previewRows(aggregates, {
27114
- sessionId: query.sessionId,
27115
- from: query.from
27116
- });
27117
- const groupable = rows.map(toFlatFindingRow);
27118
- const allGroups = buildFindingGroups(groupable, { aggregates });
28304
+ const allTypes = buildFindingTypes(aggregates);
27119
28305
  const filterOpts = {
27120
28306
  severity: query.severity,
27121
28307
  providers: query.provider,
@@ -27124,30 +28310,25 @@ var SqliteFindingsRepository = class {
27124
28310
  subtype: query.subtype,
27125
28311
  q: query.q
27126
28312
  };
27127
- const facets = computeFindingFacets(allGroups, filterOpts);
27128
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28313
+ const facets = computeFindingFacets(allTypes, filterOpts);
28314
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27129
28315
  const statusFilter = query.status ?? [];
27130
28316
  const totals = {
27131
- findings: sorted.reduce((acc, g) => {
27132
- if (statusFilter.length === 0) return acc + g.instanceCount;
27133
- const agg = aggregates.get(g.id);
27134
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28317
+ findings: sorted.reduce((acc, t) => {
28318
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28319
+ const agg = aggregates.get(t.id);
28320
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27135
28321
  }, 0),
27136
- groups: sorted.length
28322
+ types: sorted.length
27137
28323
  };
27138
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28324
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27139
28325
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27140
28326
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27141
28327
  const page = sorted.slice(start, start + limit);
27142
28328
  const lastOnPage = page.at(-1);
27143
28329
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27144
28330
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27145
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27146
- const narrow = (g) => statusSet ? {
27147
- ...g,
27148
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27149
- } : g;
27150
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28331
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27151
28332
  return Promise.resolve({
27152
28333
  totals,
27153
28334
  facets,
@@ -27158,7 +28339,7 @@ var SqliteFindingsRepository = class {
27158
28339
  }
27159
28340
  /**
27160
28341
  * One row per rule_id, folding EVERY instance of the group into the values
27161
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28342
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27162
28343
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27163
28344
  *
27164
28345
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27212,6 +28393,7 @@ var SqliteFindingsRepository = class {
27212
28393
  providers: query.provider,
27213
28394
  actions: query.action,
27214
28395
  statuses: query.status,
28396
+ deliveries: query.deployment,
27215
28397
  tools: query.tool,
27216
28398
  repo: query.repo,
27217
28399
  file: query.file,
@@ -27252,13 +28434,25 @@ var SqliteFindingsRepository = class {
27252
28434
  });
27253
28435
  }
27254
28436
  /**
27255
- * The same findings folded by location: repository, then file within it.
28437
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27256
28438
  *
27257
28439
  * The grouping keys come from the capturing event's attributes, which is what
27258
- * the local store relates a finding to — there is no finding↔asset row to
27259
- * group by instead. A repo or file the event did not record folds into the
27260
- * empty-string bucket, which the view renders but does not link, since no
27261
- * filter can name it.
28440
+ * the local store relates a finding to; there is no finding↔asset row to group
28441
+ * by instead. A repo or file the event did not record folds into the
28442
+ * empty-string bucket, which is a real location like any other: it is listed,
28443
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28444
+ *
28445
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28446
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28447
+ * list was rebuilt to remove — and two-level pagination inside an
28448
+ * expand/collapse table is what pushed that view to master/detail in the first
28449
+ * place.
28450
+ *
28451
+ * Every filter narrows the FINDINGS and the locations fall out of what
28452
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28453
+ * reports for the same filters scoped to that pair. The view depends on it:
28454
+ * one toolbar sits over both panels precisely because a location owns none of
28455
+ * its fields.
27262
28456
  */
27263
28457
  listFindingLocations(query) {
27264
28458
  const opts = {
@@ -27267,16 +28461,20 @@ var SqliteFindingsRepository = class {
27267
28461
  providers: query.provider,
27268
28462
  actions: query.action,
27269
28463
  statuses: query.status,
28464
+ deliveries: query.deployment,
27270
28465
  tools: query.tool,
27271
28466
  q: query.q
27272
28467
  };
27273
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28468
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28469
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27274
28470
  const byRepo = /* @__PURE__ */ new Map();
28471
+ const accumulator = createInstanceFacetAccumulator(opts);
27275
28472
  let total = 0;
27276
28473
  for (const row of this.scanFindingRows({
27277
28474
  sessionId: query.sessionId,
27278
28475
  from: query.from
27279
28476
  })) {
28477
+ accumulator.add(row);
27280
28478
  if (!matchesInstanceFilters(row, opts)) continue;
27281
28479
  total += 1;
27282
28480
  let files = byRepo.get(row.repo);
@@ -27291,103 +28489,35 @@ var SqliteFindingsRepository = class {
27291
28489
  }
27292
28490
  addToLocation(acc, row);
27293
28491
  }
27294
- let fileCount = 0;
27295
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27296
- fileCount += files.size;
27297
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27298
- file: file2,
27299
- instanceCount: acc.instanceCount,
27300
- maxSeverity: acc.maxSeverity,
27301
- latestDetectedAt: acc.latestDetectedAt,
27302
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27303
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27304
- })).sort(compareLocationOrder);
27305
- const rollup = fileRows.reduce(
27306
- (a, f) => ({
27307
- instanceCount: a.instanceCount + f.instanceCount,
27308
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27309
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27310
- }),
27311
- {
27312
- instanceCount: 0,
27313
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27314
- latestDetectedAt: ""
27315
- }
27316
- );
27317
- const statuses = fileRows.map((f) => f.status);
27318
- const folded = foldGroupStatus(statuses);
27319
- return {
27320
- repo,
27321
- instanceCount: rollup.instanceCount,
27322
- maxSeverity: rollup.maxSeverity,
27323
- latestDetectedAt: rollup.latestDetectedAt,
27324
- ...folded === void 0 ? {} : { status: folded },
27325
- files: fileRows
27326
- };
27327
- });
27328
- repos.sort(compareLocationOrder);
28492
+ const sorted = [];
28493
+ for (const [repo, files] of byRepo) {
28494
+ for (const [file2, acc] of files) {
28495
+ const status = foldGroupStatus(acc.statuses);
28496
+ sorted.push({
28497
+ id: encodeLocationId(repo, file2),
28498
+ repo,
28499
+ file: file2,
28500
+ instanceCount: acc.instanceCount,
28501
+ maxSeverity: acc.maxSeverity,
28502
+ latestDetectedAt: acc.latestDetectedAt,
28503
+ ...status === void 0 ? {} : { status },
28504
+ ruleIds: [...acc.ruleIds]
28505
+ });
28506
+ }
28507
+ }
28508
+ sorted.sort(compareLocationOrder);
28509
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28510
+ const page = sorted.slice(start, start + limit);
28511
+ const lastOnPage = page.at(-1);
28512
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28513
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27329
28514
  return Promise.resolve({
27330
- totals: { findings: total, repos: repos.length, files: fileCount },
27331
- items: repos.slice(0, limit),
27332
- hasMore: repos.length > limit
28515
+ totals: { findings: total, locations: sorted.length },
28516
+ facets: accumulator.facets(),
28517
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28518
+ nextCursor
27333
28519
  });
27334
28520
  }
27335
- /**
27336
- * Each group's newest instances, for the table's expanded rows.
27337
- *
27338
- * ONE index-ordered scan with early termination, and the shape is the point.
27339
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27340
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27341
- * through a temp B-tree to keep a bounded preview of each group, and then
27342
- * sorts the survivors again for the page order. Both sorts grow with the
27343
- * store while the answer does not.
27344
- *
27345
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27346
- * (or the session or window index the scope names — see `findingScanSql`),
27347
- * which is already the order the page wants, and keeps rows per rule until
27348
- * each rule has as many as it can show. The aggregate the caller already holds
27349
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27350
- * per rule, summed, is the number of rows this scan has to find, and it stops
27351
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27352
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27353
- * store with many firing rules widens it. The bound that DOES hold
27354
- * unconditionally is the sorted form's floor: this scan visits at most as
27355
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27356
- * sorted, and stops the moment every rule has its cap, where the sorted form
27357
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27358
- * wanted instances sitting at the tail of the scope — is one pass over
27359
- * everything in scope with a block sort of the id tie-break only, never a
27360
- * sort of the scope, which is still that floor.
27361
- *
27362
- * A row whose rule the aggregate did not see is skipped: the two statements
27363
- * run without a shared snapshot, so a capture landing between them can add a
27364
- * rule here that has no counts there, and the counts are what the group is
27365
- * built from.
27366
- */
27367
- previewRows(aggregates, scope) {
27368
- const wanted = /* @__PURE__ */ new Map();
27369
- let remaining = 0;
27370
- for (const [ruleId, agg] of aggregates) {
27371
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27372
- wanted.set(ruleId, n);
27373
- remaining += n;
27374
- }
27375
- const rows = [];
27376
- if (remaining === 0) return rows;
27377
- const { sql, params } = this.findingScanSql(scope);
27378
- const taken = /* @__PURE__ */ new Map();
27379
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27380
- const want = wanted.get(r.rule_id);
27381
- if (want === void 0) continue;
27382
- const have = taken.get(r.rule_id) ?? 0;
27383
- if (have >= want) continue;
27384
- taken.set(r.rule_id, have + 1);
27385
- rows.push(r);
27386
- remaining -= 1;
27387
- if (remaining === 0) break;
27388
- }
27389
- return rows;
27390
- }
27391
28521
  /**
27392
28522
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27393
28523
  *
@@ -27414,6 +28544,33 @@ var SqliteFindingsRepository = class {
27414
28544
  yield toFlatFindingRow(r);
27415
28545
  }
27416
28546
  }
28547
+ /**
28548
+ * One finding by its own id, or null when no such row exists.
28549
+ *
28550
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28551
+ * the store — and, unlike anything derived from a list page, it resolves a
28552
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28553
+ * deep link needs: the id it carries may name a finding thousands of rows
28554
+ * older than anything a first page holds.
28555
+ *
28556
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28557
+ * RESOLVES an id; whether that row would survive the list's current filters is
28558
+ * a different question, and hiding the target because a filter excludes it is
28559
+ * worse than showing it.
28560
+ *
28561
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28562
+ * type should the list select?" and "what does the drawer show?".
28563
+ */
28564
+ findingInstance(id) {
28565
+ const row = this.db.prepare(
28566
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28567
+ FROM inspection_findings f
28568
+ JOIN audit_events e ON e.id = f.audit_event_id
28569
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28570
+ WHERE f.id = ?`
28571
+ ).get(id);
28572
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28573
+ }
27417
28574
  /**
27418
28575
  * The one statement both instance-level scans run: every finding in scope,
27419
28576
  * joined to its event and definition, newest first.
@@ -27447,17 +28604,7 @@ var SqliteFindingsRepository = class {
27447
28604
  conditions.push("e.started_at >= ?");
27448
28605
  params.push(isoToEpochMillis(scope.from));
27449
28606
  }
27450
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27451
- d.severity AS severity, f.masked_match AS masked_match,
27452
- f.action_taken AS action_taken, f.confidence AS confidence,
27453
- e.started_at AS occurred_at,
27454
- e.source_tool AS source_tool,
27455
- e.repo AS repo,
27456
- e.file_path AS file,
27457
- e.tool_name AS tool_name,
27458
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27459
- e.event_type AS kind, f.finding_key AS finding_key,
27460
- ${latestResolutionStatusSql("f")} AS latest_status
28607
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27461
28608
  FROM audit_events e
27462
28609
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27463
28610
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27471,6 +28618,26 @@ var SqliteFindingsRepository = class {
27471
28618
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27472
28619
  const rows = this.db.prepare(
27473
28620
  `SELECT rule_id,
28621
+ -- BARE columns beside max(latest_at), which is deliberate and
28622
+ -- is SQLite's documented behaviour: with a single min()/max()
28623
+ -- in an aggregate query, every bare column takes its value from
28624
+ -- the row that produced the extremum. So these are the severity
28625
+ -- and category of the definition whose finding is NEWEST, which
28626
+ -- is what the row-based build they replaced read off its first
28627
+ -- (newest-first) row.
28628
+ --
28629
+ -- min() is WRONG here and was the defect: inspection_definitions
28630
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28631
+ -- mints a new row), so a rule whose severity moved between
28632
+ -- versions has several, and min() picks the ALPHABETICALLY
28633
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28634
+ -- That is arbitrary in direction, and it feeds the badge, the
28635
+ -- filter, the facet counts and the primary sort key.
28636
+ --
28637
+ -- Adding a second min()/max() aggregate here would make these
28638
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28639
+ severity,
28640
+ category,
27474
28641
  sum(tuple_count) AS instance_count,
27475
28642
  max(latest_at) AS latest_at,
27476
28643
  group_concat(source_tools) AS source_tools,
@@ -27481,6 +28648,14 @@ var SqliteFindingsRepository = class {
27481
28648
  group_concat(tool_names) AS tool_names
27482
28649
  FROM (
27483
28650
  SELECT d.rule_id AS rule_id,
28651
+ -- Severity and category are columns of the DEFINITION, and
28652
+ -- a rule can have SEVERAL definitions (one per version), so
28653
+ -- these are grouped on below and resolved to the newest
28654
+ -- firing version by the outer query's bare-column select.
28655
+ -- They ride the aggregate because the type build has no rows
28656
+ -- to read them off \u2014 see buildFindingTypes.
28657
+ d.severity AS severity,
28658
+ d.category AS category,
27484
28659
  e.event_type || '${TUPLE_SEP}' ||
27485
28660
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27486
28661
  coalesce(latest.status, '') AS status_tuple,
@@ -27495,7 +28670,7 @@ var SqliteFindingsRepository = class {
27495
28670
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27496
28671
  ON latest.finding_key = f.finding_key
27497
28672
  ${scope.predicate}
27498
- GROUP BY d.rule_id, status_tuple
28673
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27499
28674
  )
27500
28675
  GROUP BY rule_id`
27501
28676
  ).all(scope.params);
@@ -27504,6 +28679,8 @@ var SqliteFindingsRepository = class {
27504
28679
  r.rule_id,
27505
28680
  {
27506
28681
  instanceCount: r.instance_count,
28682
+ severity: r.severity,
28683
+ category: r.category,
27507
28684
  sourceTools: splitConcat(r.source_tools),
27508
28685
  actionsTaken: splitConcat(r.actions_taken),
27509
28686
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27520,7 +28697,7 @@ var SqliteFindingsRepository = class {
27520
28697
  latestDetectedAt: epochMillisToIso(r.latest_at),
27521
28698
  // Free text only — joined and substring-matched, so group_concat's
27522
28699
  // commas need no unpicking (a repo/path containing one still matches).
27523
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28700
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27524
28701
  // tell "no q this request" from "a group with no repo/file at all"
27525
28702
  // and skip priming a haystack nothing will read.
27526
28703
  ...withSearchText ? {
@@ -27548,7 +28725,9 @@ var SqliteFindingsRepository = class {
27548
28725
  )
27549
28726
  );
27550
28727
  for (const row of grouped) {
27551
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28728
+ if (Object.hasOwn(byAction, row.action_taken)) {
28729
+ byAction[row.action_taken] = row.c;
28730
+ }
27552
28731
  }
27553
28732
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27554
28733
  const sevRows = allRows(
@@ -27565,7 +28744,9 @@ var SqliteFindingsRepository = class {
27565
28744
  )
27566
28745
  );
27567
28746
  for (const row of sevRows) {
27568
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28747
+ if (Object.hasOwn(bySeverity, row.severity)) {
28748
+ bySeverity[row.severity] = row.c;
28749
+ }
27569
28750
  }
27570
28751
  const categories = ENFORCEABLE_CATEGORIES;
27571
28752
  const enabledRows = allRows(
@@ -27614,469 +28795,6 @@ function isoDay(ms) {
27614
28795
  return new Date(ms).toISOString().slice(0, 10);
27615
28796
  }
27616
28797
 
27617
- // ../../packages/persistence/src/repositories/history-sync.ts
27618
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27619
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27620
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27621
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27622
- var SKIPPED = -1;
27623
- var ROW_COLUMNS = `id,
27624
- parent_id AS parentId,
27625
- root_session_id AS rootSessionId,
27626
- event_type AS eventType,
27627
- host_id AS hostId,
27628
- harness_id AS harnessId,
27629
- source_project_id AS sourceProjectId,
27630
- started_at AS startedAt,
27631
- ended_at AS endedAt,
27632
- severity,
27633
- priority,
27634
- content,
27635
- content_hash AS contentHash,
27636
- attributes`;
27637
- var SqliteHistorySyncRepository = class {
27638
- constructor(db) {
27639
- this.db = db;
27640
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27641
- this.sessionsStmt = db.prepare(
27642
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27643
- FROM audit_events
27644
- WHERE synced_at IS NULL
27645
- AND event_type IN (${TYPE_LIST})
27646
- AND started_at < :before
27647
- GROUP BY sessionId
27648
- ORDER BY earliest
27649
- LIMIT :limit`
27650
- );
27651
- this.rowsStmt = db.prepare(
27652
- `SELECT ${ROW_COLUMNS}
27653
- FROM audit_events
27654
- WHERE synced_at IS NULL
27655
- AND event_type IN (${TYPE_LIST})
27656
- AND started_at < :before
27657
- AND COALESCE(root_session_id, id) = :sessionId
27658
- ORDER BY (event_type = 'session') DESC, started_at
27659
- LIMIT :limit`
27660
- );
27661
- this.captureRowsStmt = db.prepare(
27662
- `SELECT ${ROW_COLUMNS}
27663
- FROM audit_events
27664
- WHERE synced_at IS NULL
27665
- AND sync_claimed_at IS NULL
27666
- AND outbox_owed = 1
27667
- AND event_type IN (${CAPTURE_TYPE_LIST})
27668
- AND started_at < :before
27669
- ORDER BY started_at
27670
- LIMIT :limit`
27671
- );
27672
- this.markOwedStmt = db.prepare(
27673
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27674
- );
27675
- this.stampStmt = db.prepare(
27676
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27677
- );
27678
- this.claimRowStmt = db.prepare(
27679
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27680
- );
27681
- this.releaseRowStmt = db.prepare(
27682
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27683
- );
27684
- this.releaseStaleClaimsStmt = db.prepare(
27685
- `UPDATE audit_events SET sync_claimed_at = NULL
27686
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27687
- );
27688
- this.partitionStmt = db.prepare(
27689
- `SELECT
27690
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27691
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27692
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27693
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27694
- COUNT(*) AS total
27695
- FROM audit_events
27696
- WHERE event_type IN (${TYPE_LIST})`
27697
- );
27698
- this.countsStmt = db.prepare(
27699
- `SELECT
27700
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27701
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27702
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27703
- FROM audit_events
27704
- WHERE event_type IN (${TYPE_LIST})`
27705
- );
27706
- this.captureSkipCountStmt = db.prepare(
27707
- `SELECT COUNT(*) AS skipped
27708
- FROM audit_events
27709
- WHERE synced_at = ${String(SKIPPED)}
27710
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27711
- );
27712
- this.fingerprintStmt = db.prepare(
27713
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27714
- FROM history_sync WHERE id = 1`
27715
- );
27716
- this.setFingerprintStmt = db.prepare(
27717
- `UPDATE history_sync
27718
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27719
- WHERE id = 1`
27720
- );
27721
- this.disownCapturesStmt = db.prepare(
27722
- `UPDATE audit_events SET outbox_owed = NULL
27723
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27724
- );
27725
- this.rearmStmt = db.prepare(
27726
- `UPDATE audit_events SET synced_at = NULL
27727
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27728
- );
27729
- this.claimStmt = db.prepare(
27730
- `UPDATE history_sync
27731
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27732
- WHERE id = 1
27733
- AND (owner_pid IS NULL
27734
- OR heartbeat_at IS NULL
27735
- OR heartbeat_at < :staleBefore
27736
- OR heartbeat_at > :now)`
27737
- );
27738
- this.heartbeatStmt = db.prepare(
27739
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27740
- );
27741
- this.releaseStmt = db.prepare(
27742
- `UPDATE history_sync
27743
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27744
- WHERE id = 1 AND owner_pid = :pid`
27745
- );
27746
- this.closeWindowStmt = db.prepare(
27747
- `UPDATE audit_events SET synced_at = :at
27748
- WHERE synced_at IS NULL
27749
- AND event_type IN (${TYPE_LIST})
27750
- AND started_at >= :attachedAt`
27751
- );
27752
- this.releaseBoundaryStmt = db.prepare(
27753
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27754
- );
27755
- this.freezeBoundaryStmt = db.prepare(
27756
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27757
- );
27758
- this.leaseStmt = db.prepare(
27759
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27760
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27761
- FROM history_sync WHERE id = 1`
27762
- );
27763
- this.inspectionsStmt = db.prepare(
27764
- `SELECT d.rule_id AS ruleId,
27765
- d.name AS ruleName,
27766
- d.version AS ruleVersion,
27767
- d.category AS category,
27768
- d.severity AS severity,
27769
- f.span_start AS spanStart,
27770
- f.span_end AS spanEnd,
27771
- f.masked_match AS maskedMatch,
27772
- f.action_taken AS actionTaken,
27773
- f.confidence AS confidence
27774
- FROM inspection_findings f
27775
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27776
- WHERE f.audit_event_id = :auditEventId
27777
- ORDER BY f.span_start, f.id`
27778
- );
27779
- }
27780
- db;
27781
- ensureRowStmt;
27782
- sessionsStmt;
27783
- rowsStmt;
27784
- stampStmt;
27785
- countsStmt;
27786
- fingerprintStmt;
27787
- setFingerprintStmt;
27788
- rearmStmt;
27789
- claimStmt;
27790
- heartbeatStmt;
27791
- releaseStmt;
27792
- leaseStmt;
27793
- inspectionsStmt;
27794
- closeWindowStmt;
27795
- releaseBoundaryStmt;
27796
- freezeBoundaryStmt;
27797
- captureRowsStmt;
27798
- markOwedStmt;
27799
- captureSkipCountStmt;
27800
- disownCapturesStmt;
27801
- partitionStmt;
27802
- claimRowStmt;
27803
- releaseRowStmt;
27804
- releaseStaleClaimsStmt;
27805
- /**
27806
- * The masked detections recorded against one tool call.
27807
- *
27808
- * These travel with the event because a tool call's target is not
27809
- * re-inspectable from the event alone — unlike a capture, where the text
27810
- * itself is re-scannable. What crosses is the masked match and the rule that
27811
- * produced it, never the value.
27812
- */
27813
- inspectionsFor(auditEventId) {
27814
- return allRows(this.inspectionsStmt, { auditEventId });
27815
- }
27816
- /**
27817
- * Sessions with structural rows still to send, oldest first.
27818
- *
27819
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27820
- * read. Anything recorded after the machine attached is the live forward
27821
- * path's to deliver; this drain exists for what was recorded before it, and a
27822
- * row both paths send is at best a duplicate request and at worst — for a
27823
- * session root — an overwrite of the inventory ids the live path resolved.
27824
- */
27825
- pendingSessions(limit, before) {
27826
- return allRows(this.sessionsStmt, { limit, before }).map(
27827
- (r) => r.sessionId
27828
- );
27829
- }
27830
- /** One session's undelivered structural rows within the backlog, root first. */
27831
- pendingRows(sessionId, limit, before) {
27832
- return allRows(this.rowsStmt, { sessionId, limit, before });
27833
- }
27834
- /**
27835
- * Captures this machine still owes the deployment, oldest first.
27836
- *
27837
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27838
- * by a time window — see captureRowsStmt for why a window could not express
27839
- * this. `before` is the grace window that leaves a just-recorded capture to
27840
- * the live path.
27841
- */
27842
- pendingCaptureRows(limit, before) {
27843
- return allRows(this.captureRowsStmt, { limit, before });
27844
- }
27845
- /**
27846
- * Record that a capture is OWED to the deployment.
27847
- *
27848
- * Written by the attached forward path when a live send did not confirm
27849
- * delivery, and read by the drain as the whole of its eligibility test. It is
27850
- * a fact rather than an inference: the machine was attached, the send did not
27851
- * land, so the row is owed — which no time window can state, because the same
27852
- * window that holds the rows a past attachment left owed also holds every
27853
- * capture recorded while the machine was DETACHED, and those were never
27854
- * offered to anyone.
27855
- *
27856
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27857
- * out of the drain's read.
27858
- */
27859
- markCaptureOwed(id) {
27860
- this.markOwedStmt.run({ id });
27861
- }
27862
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27863
- markSynced(ids, atMs) {
27864
- this.stampAll(ids, atMs);
27865
- }
27866
- /**
27867
- * Record that a row will never be sent.
27868
- *
27869
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27870
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27871
- * is retried; marking those would turn one outage into permanent data loss.
27872
- */
27873
- markSkipped(ids) {
27874
- this.stampAll(ids, SKIPPED);
27875
- }
27876
- eachInTransaction(ids, run) {
27877
- if (ids.length === 0) return;
27878
- withTransaction(
27879
- this.db,
27880
- () => {
27881
- for (const id of ids) run(id);
27882
- },
27883
- "IMMEDIATE"
27884
- );
27885
- }
27886
- stampAll(ids, value) {
27887
- if (ids.length === 0) return;
27888
- withTransaction(
27889
- this.db,
27890
- () => {
27891
- for (const id of ids) this.stampStmt.run({ at: value, id });
27892
- },
27893
- "IMMEDIATE"
27894
- );
27895
- }
27896
- /**
27897
- * Claim rows as in-flight.
27898
- *
27899
- * Advisory in exactly the sense the lease is: it records that a send is in
27900
- * progress so a surface can say so, and a lost claim costs a row showing as
27901
- * queued while it is actually being sent. It is not exclusion — the far side
27902
- * settles a duplicate on the row id.
27903
- */
27904
- claimRows(ids, atMs) {
27905
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27906
- }
27907
- /** Give back a claim without settling — the send failed, the row is queued again. */
27908
- releaseRows(ids) {
27909
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27910
- }
27911
- /**
27912
- * Clear claims older than `staleBefore`, and report how many were cleared.
27913
- *
27914
- * A process killed between claiming and settling leaves rows claimed with
27915
- * nothing left to settle them. Without this they read as "sending" for ever.
27916
- */
27917
- releaseStaleClaims(staleBefore) {
27918
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27919
- }
27920
- /**
27921
- * Every tracked row in exactly one delivery state.
27922
- *
27923
- * Takes no boundary on purpose. The boundary answers "what should the drain
27924
- * pick up now", which is a different question from "what state is this row
27925
- * in" — and a machine that has never attached has no boundary to pass, so
27926
- * requiring one would force a caller to invent one and report the whole store
27927
- * as queued.
27928
- */
27929
- partition() {
27930
- const row = getRow(this.partitionStmt, {});
27931
- return {
27932
- queued: row?.queued ?? 0,
27933
- inProgress: row?.inProgress ?? 0,
27934
- synced: row?.synced ?? 0,
27935
- failed: row?.failed ?? 0,
27936
- total: row?.total ?? 0
27937
- };
27938
- }
27939
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27940
- counts(before) {
27941
- const row = getRow(
27942
- this.countsStmt,
27943
- { before }
27944
- );
27945
- const captures = getRow(this.captureSkipCountStmt);
27946
- return {
27947
- pending: row?.pending ?? 0,
27948
- sent: row?.sent ?? 0,
27949
- skipped: row?.skipped ?? 0,
27950
- capturesSkipped: captures?.skipped ?? 0
27951
- };
27952
- }
27953
- /**
27954
- * The deployment the current stamps were made against, and where its backlog
27955
- * ends.
27956
- *
27957
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27958
- * machine that has never drained is — and every writer below seeds the row
27959
- * before it needs one, so nothing depends on this creating it. Keeping the
27960
- * write off the gate path matters because the gate runs on every pass while a
27961
- * write has to take the database's write lock.
27962
- */
27963
- deployment() {
27964
- const row = getRow(
27965
- this.fingerprintStmt
27966
- );
27967
- return {
27968
- fingerprint: row?.fingerprint ?? void 0,
27969
- backlogBefore: row?.backlogBefore ?? void 0
27970
- };
27971
- }
27972
- /**
27973
- * Point the ledger at a different deployment, discarding what it recorded
27974
- * about the previous one.
27975
- *
27976
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
27977
- * machine has just left are undelivered as far as the new one is concerned.
27978
- * All three in one transaction, so a crash between them cannot leave stamps
27979
- * attributed to the wrong deployment, or a boundary that belongs to another.
27980
- *
27981
- * The boundary is written HERE and only here, which is what freezes it: a
27982
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
27983
- * unchanged, so this never runs and the backlog does not widen back over rows
27984
- * the live path has since delivered.
27985
- */
27986
- rearmFor(fingerprint, backlogBefore) {
27987
- this.ensureRowStmt.run();
27988
- withTransaction(
27989
- this.db,
27990
- () => {
27991
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
27992
- this.rearmStmt.run();
27993
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
27994
- this.disownCapturesStmt.run();
27995
- }
27996
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27997
- },
27998
- "IMMEDIATE"
27999
- );
28000
- }
28001
- /**
28002
- * End the attached period: hand its rows to the live path, and release the
28003
- * boundary so the next attachment can freeze a new one.
28004
- *
28005
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28006
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28007
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28008
- * during the detached period, because the machine is not attached. Rows
28009
- * recorded in that window sit after the boundary and before the re-attach, so
28010
- * neither path takes them, and the pending count reports none outstanding.
28011
- *
28012
- * Stamping the attached window is not a claim that every one of those rows
28013
- * reached the deployment — the live path drops on failure and says so
28014
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28015
- * status quo: they sit outside the frozen boundary today and are equally never
28016
- * re-sent. Making it explicit is what lets the boundary move.
28017
- *
28018
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28019
- * window unstamped — that half-state would re-send the whole attached period
28020
- * on the next attach, which is the failure the boundary exists to prevent.
28021
- */
28022
- closeAttachedWindow(attachedAtMs, atMs) {
28023
- this.ensureRowStmt.run();
28024
- withTransaction(
28025
- this.db,
28026
- () => {
28027
- const row = getRow(this.fingerprintStmt);
28028
- const from = row?.backlogBefore ?? attachedAtMs;
28029
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28030
- this.releaseBoundaryStmt.run();
28031
- },
28032
- "IMMEDIATE"
28033
- );
28034
- }
28035
- /**
28036
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28037
- *
28038
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28039
- * different deployment and therefore discards what was delivered to the old
28040
- * one: here the recipient is the same, so everything already sent to it stays
28041
- * sent.
28042
- */
28043
- freezeBoundary(backlogBefore) {
28044
- this.ensureRowStmt.run();
28045
- this.freezeBoundaryStmt.run({ backlogBefore });
28046
- }
28047
- /** Take the claim, or report that someone live already holds it. */
28048
- claim(pid, host, nowMs, staleAfterMs) {
28049
- this.ensureRowStmt.run();
28050
- let taken = false;
28051
- withTransaction(
28052
- this.db,
28053
- () => {
28054
- const result = this.claimStmt.run({
28055
- pid,
28056
- host,
28057
- now: nowMs,
28058
- staleBefore: nowMs - staleAfterMs
28059
- });
28060
- taken = result.changes === 1;
28061
- },
28062
- "IMMEDIATE"
28063
- );
28064
- return taken;
28065
- }
28066
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28067
- heartbeat(pid, nowMs) {
28068
- this.heartbeatStmt.run({ now: nowMs, pid });
28069
- }
28070
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28071
- release(pid) {
28072
- this.releaseStmt.run({ pid });
28073
- }
28074
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28075
- lease() {
28076
- return getRow(this.leaseStmt);
28077
- }
28078
- };
28079
-
28080
28798
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28081
28799
  var SqliteInspectionDefinitionsRepository = class {
28082
28800
  constructor(db) {
@@ -28268,7 +28986,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28268
28986
  }
28269
28987
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28270
28988
  }
28271
- function readManagedSettings(paths = managedSettingsPaths()) {
28989
+ var testOnlyManagedPaths = null;
28990
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28272
28991
  for (const path of paths) {
28273
28992
  let text;
28274
28993
  try {
@@ -28303,6 +29022,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28303
29022
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28304
29023
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28305
29024
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29025
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28306
29026
  if (values.vaultConsent !== void 0) {
28307
29027
  merged.vaultConsent = values.vaultConsent ? (
28308
29028
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30748,7 +31468,7 @@ function toUtcDateString(ms) {
30748
31468
  return new Date(ms).toISOString().slice(0, 10);
30749
31469
  }
30750
31470
  function isTimeseriesSeverity(s) {
30751
- return s === "critical" || s === "high" || s === "medium";
31471
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30752
31472
  }
30753
31473
  var SqliteSecurityRepository = class {
30754
31474
  constructor(db, now = () => Date.now()) {
@@ -30810,7 +31530,7 @@ var SqliteSecurityRepository = class {
30810
31530
  ELSE 0
30811
31531
  END) AS open_at_rest
30812
31532
  FROM inspection_findings f
30813
- JOIN audit_events e ON e.id = f.audit_event_id
31533
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30814
31534
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30815
31535
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30816
31536
  ON latest.finding_key = f.finding_key
@@ -30877,12 +31597,16 @@ var SqliteSecurityRepository = class {
30877
31597
  const now = this.now();
30878
31598
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30879
31599
  const rows = this.findingsInRange(windowStart, now);
30880
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30881
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30882
- critical: 0,
30883
- high: 0,
30884
- medium: 0
30885
- }));
31600
+ const points = Array.from(
31601
+ { length: numBuckets },
31602
+ (_, i) => ({
31603
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31604
+ critical: 0,
31605
+ high: 0,
31606
+ medium: 0,
31607
+ low: 0
31608
+ })
31609
+ );
30886
31610
  for (const r of rows) {
30887
31611
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30888
31612
  const bucket = points[idx];
@@ -31032,7 +31756,7 @@ var SqliteSecurityRepository = class {
31032
31756
  this.db.prepare(
31033
31757
  `SELECT e.repo AS repo, count(*) AS c
31034
31758
  FROM inspection_findings f
31035
- JOIN audit_events e ON e.id = f.audit_event_id
31759
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31036
31760
  WHERE e.started_at >= :from AND e.started_at < :to
31037
31761
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31038
31762
  AND e.repo IS NOT NULL
@@ -31100,6 +31824,7 @@ var SqliteSecurityRepository = class {
31100
31824
  `SELECT f.finding_key AS finding_key,
31101
31825
  d.rule_id AS rule_id,
31102
31826
  d.severity AS severity,
31827
+ e.repo AS repo,
31103
31828
  e.file_path AS path,
31104
31829
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31105
31830
  latest.resolved_at AS latest_resolved_at
@@ -31119,6 +31844,7 @@ var SqliteSecurityRepository = class {
31119
31844
  const items = rows.map((r) => ({
31120
31845
  findingKey: r.finding_key,
31121
31846
  ruleId: r.rule_id,
31847
+ repo: r.repo ?? "",
31122
31848
  severity: r.severity,
31123
31849
  path: r.path ?? "",
31124
31850
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31128,15 +31854,68 @@ var SqliteSecurityRepository = class {
31128
31854
  }));
31129
31855
  return Promise.resolve({ items });
31130
31856
  }
31857
+ /**
31858
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31859
+ *
31860
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31861
+ * list: a secret committed three weeks ago and never rotated is still the most
31862
+ * important thing to fix, and any window hides it. It carried a "newest N
31863
+ * findings" cap and then a range; the first meant a different span on every
31864
+ * machine, and the second reported "no recommendations" over live exposure.
31865
+ *
31866
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31867
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31868
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31869
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31870
+ * The two answer different questions and only this one has to match a link.
31871
+ *
31872
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31873
+ * whole-store scope costs a grouped scan rather than a row per finding.
31874
+ */
31875
+ recommendationInputs() {
31876
+ const rows = allRows(
31877
+ this.db.prepare(
31878
+ `SELECT d.rule_id AS rule_id,
31879
+ d.category AS category,
31880
+ d.severity AS severity,
31881
+ COUNT(*) AS count
31882
+ FROM inspection_findings f
31883
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31884
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31885
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31886
+ ON latest.finding_key = f.finding_key
31887
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31888
+ AND e.event_type = 'code_change'
31889
+ AND (
31890
+ f.finding_key IS NULL
31891
+ OR latest.status IS NULL
31892
+ OR latest.status NOT IN ('resolved', 'dismissed')
31893
+ )
31894
+ GROUP BY d.rule_id, d.category, d.severity`
31895
+ )
31896
+ );
31897
+ return Promise.resolve(
31898
+ rows.map((r) => ({
31899
+ ruleId: r.rule_id,
31900
+ category: r.category,
31901
+ severity: r.severity,
31902
+ count: r.count
31903
+ }))
31904
+ );
31905
+ }
31131
31906
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31132
31907
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31133
31908
  // numeric and the JS aggregations bucket/split on ms directly.
31134
31909
  findingsInRange(fromMs, toMs) {
31135
31910
  const rows = allRows(
31136
31911
  this.db.prepare(
31137
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31912
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31913
+ // joined for `severity`, so they are two more columns off a row this read
31914
+ // already fetches. They feed the recommended-actions rollup.
31915
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31916
+ d.rule_id AS rule_id, d.category AS category
31138
31917
  FROM inspection_findings f
31139
- JOIN audit_events e ON e.id = f.audit_event_id
31918
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31140
31919
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31141
31920
  WHERE e.started_at >= :from AND e.started_at < :to
31142
31921
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31147,7 +31926,9 @@ var SqliteSecurityRepository = class {
31147
31926
  return rows.map((r) => ({
31148
31927
  occurredAt: r.occurred_at,
31149
31928
  severity: r.severity,
31150
- actionTaken: r.action_taken
31929
+ actionTaken: r.action_taken,
31930
+ ruleId: r.rule_id,
31931
+ category: r.category
31151
31932
  }));
31152
31933
  }
31153
31934
  };
@@ -31975,6 +32756,7 @@ function openWithPragmas(file2) {
31975
32756
  db.exec("PRAGMA journal_mode = WAL");
31976
32757
  db.exec("PRAGMA busy_timeout = 2000");
31977
32758
  db.exec("PRAGMA foreign_keys = ON");
32759
+ registerSqlFunctions(db);
31978
32760
  } catch (err) {
31979
32761
  closeQuietly(db);
31980
32762
  throw err;
@@ -32004,7 +32786,7 @@ function backupLegacyStore(db, file2) {
32004
32786
  discardStore(file2, backup);
32005
32787
  return backup;
32006
32788
  }
32007
- function openAndInitialize(file2, base) {
32789
+ function openAndInitialize(file2, base, skipTags) {
32008
32790
  let db = openWithPragmas(file2);
32009
32791
  try {
32010
32792
  if (isForeignSqliteLineage(db)) {
@@ -32014,7 +32796,7 @@ function openAndInitialize(file2, base) {
32014
32796
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32015
32797
  );
32016
32798
  }
32017
- applyMigrations(db, file2);
32799
+ applyMigrations(db, file2, { skipTags });
32018
32800
  tightenPerms(file2);
32019
32801
  const policies = new SqlitePoliciesRepository(db);
32020
32802
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32029,6 +32811,7 @@ function openAndInitialize(file2, base) {
32029
32811
  exceptions: new SqliteExceptionsRepository(db),
32030
32812
  resolutions: new SqliteResolutionsRepository(db),
32031
32813
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32814
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32032
32815
  security: new SqliteSecurityRepository(db),
32033
32816
  detections: new SqliteDetectionsRepository(db),
32034
32817
  shares: new SqliteSharesRepository(db),
@@ -32051,7 +32834,8 @@ function openAndInitialize(file2, base) {
32051
32834
  throw err;
32052
32835
  }
32053
32836
  }
32054
- function openLocalDatabase(dir) {
32837
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32838
+ function openLocalDatabase(dir, options = {}) {
32055
32839
  ensureDataDirSync(dir);
32056
32840
  const file2 = join7(dir, DB_FILENAME);
32057
32841
  reapStalePartials(file2);
@@ -32063,6 +32847,7 @@ function openLocalDatabase(dir) {
32063
32847
  installedPacks,
32064
32848
  scanLedger,
32065
32849
  historySync,
32850
+ bodyRetention,
32066
32851
  secretVault,
32067
32852
  exceptions,
32068
32853
  resolutions,
@@ -32086,7 +32871,8 @@ function openLocalDatabase(dir) {
32086
32871
  // `dir` is always `<base>/data` — every caller resolves it through
32087
32872
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32088
32873
  // settings/ and data/, and the pack-policy floor needs both halves.
32089
- dirname2(dir)
32874
+ dirname2(dir),
32875
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32090
32876
  );
32091
32877
  function captureRowId(event) {
32092
32878
  return captureId(
@@ -32279,6 +33065,7 @@ function openLocalDatabase(dir) {
32279
33065
  installedPacks,
32280
33066
  scanLedger,
32281
33067
  historySync,
33068
+ bodyRetention,
32282
33069
  secretVault,
32283
33070
  exceptions,
32284
33071
  resolutions,
@@ -32317,8 +33104,72 @@ function openLocalDatabase(dir) {
32317
33104
  };
32318
33105
  }
32319
33106
 
32320
- // ../../packages/persistence/src/finding-key.ts
33107
+ // ../../packages/persistence/src/egress-wire.ts
32321
33108
  import { createHash as createHash3 } from "crypto";
33109
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33110
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33111
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33112
+ var FILE_URL = /^file:\/\//i;
33113
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33114
+ var SLASH = "/".charCodeAt(0);
33115
+ var GIT_SUFFIX = ".git";
33116
+ function trimSlashes(path) {
33117
+ let start = 0;
33118
+ let end = path.length;
33119
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33120
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33121
+ return path.slice(start, end);
33122
+ }
33123
+ function canonicalGitUrl(url2) {
33124
+ const trimmed = url2.trim();
33125
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33126
+ const scheme = SCHEME_FORM.exec(trimmed);
33127
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33128
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33129
+ if (host === void 0) return trimmed;
33130
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33131
+ const bare = trimSlashes(path);
33132
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33133
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33134
+ }
33135
+ function hashProjectKey(projectKey) {
33136
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33137
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33138
+ }
33139
+ function toIngestHit(hit) {
33140
+ return {
33141
+ host: hit.host,
33142
+ kind: hit.kind,
33143
+ name: hit.name,
33144
+ category: hit.category,
33145
+ trust: hit.trust,
33146
+ network: hit.network,
33147
+ method: hit.method,
33148
+ transport: hit.transport,
33149
+ url: hit.url,
33150
+ template: hit.template,
33151
+ dataClass: hit.dataClass,
33152
+ site: {
33153
+ file: hit.site.file,
33154
+ line: hit.site.line,
33155
+ dynamic: hit.site.dynamic,
33156
+ vendored: hit.site.vendored
33157
+ }
33158
+ };
33159
+ }
33160
+ function toEgressIngestRequest(input2) {
33161
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33162
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33163
+ return {
33164
+ projectKey: hashProjectKey(input2.projectKey),
33165
+ project: input2.project,
33166
+ reconcile,
33167
+ hits: hits.map(toIngestHit)
33168
+ };
33169
+ }
33170
+
33171
+ // ../../packages/persistence/src/finding-key.ts
33172
+ import { createHash as createHash4 } from "crypto";
32322
33173
 
32323
33174
  // ../../packages/persistence/src/fingerprint.ts
32324
33175
  import { createHmac, randomBytes } from "crypto";
@@ -32359,14 +33210,50 @@ function readFingerprintKey(dataDir2) {
32359
33210
  return parseKeyFile(raw);
32360
33211
  }
32361
33212
 
32362
- // ../../packages/persistence/src/history-preview.ts
32363
- import { existsSync as existsSync4 } from "fs";
33213
+ // ../../packages/persistence/src/forward-health.ts
33214
+ import { readFileSync as readFileSync7 } from "fs";
32364
33215
  import { join as join9 } from "path";
33216
+ var FAILURES = /* @__PURE__ */ new Set([
33217
+ "unauthorized",
33218
+ "forbidden",
33219
+ "unreachable"
33220
+ ]);
33221
+ var BREAKER_COOLDOWN_MS = 3e4;
33222
+ function parseForwardHealth(raw, nowMs) {
33223
+ try {
33224
+ const parsed2 = JSON.parse(raw);
33225
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33226
+ const record2 = parsed2;
33227
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33228
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33229
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33230
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33231
+ } catch {
33232
+ return null;
33233
+ }
33234
+ }
33235
+ function isForwardPaused(health, nowMs) {
33236
+ const openedAtMs = health?.openedAtMs ?? null;
33237
+ if (openedAtMs === null) return false;
33238
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33239
+ }
33240
+
33241
+ // ../../packages/persistence/src/history-backfill.ts
33242
+ import { existsSync as existsSync4 } from "fs";
33243
+ import { join as join10 } from "path";
33244
+
33245
+ // ../../packages/persistence/src/history-preview.ts
33246
+ import { existsSync as existsSync5 } from "fs";
33247
+ import { join as join11 } from "path";
32365
33248
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32366
33249
 
33250
+ // ../../packages/persistence/src/history-sync-state.ts
33251
+ import { readFileSync as readFileSync8 } from "fs";
33252
+ import { join as join12 } from "path";
33253
+
32367
33254
  // ../../packages/persistence/src/store-symlinks.ts
32368
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32369
- import { dirname as dirname3, join as join10, resolve } from "path";
33255
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33256
+ import { dirname as dirname3, join as join13, resolve } from "path";
32370
33257
 
32371
33258
  // ../../packages/persistence/src/vault/crypto.ts
32372
33259
  import {
@@ -32380,62 +33267,26 @@ import {
32380
33267
  // ../../packages/persistence/src/vault/key-provider.ts
32381
33268
  import { execFileSync } from "child_process";
32382
33269
  import { randomBytes as randomBytes2 } from "crypto";
32383
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32384
- import { join as join11 } from "path";
33270
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33271
+ import { join as join14 } from "path";
32385
33272
 
32386
33273
  // ../../packages/persistence/src/vault/vault.ts
32387
33274
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32388
33275
 
32389
33276
  // ../../packages/persistence/src/warn-era-cap.ts
32390
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32391
- import { join as join12 } from "path";
33277
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33278
+ import { join as join15 } from "path";
32392
33279
  var MARKER = "warn-era-capped";
32393
33280
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32394
33281
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32395
- const marker = join12(dataDir2, MARKER);
32396
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33282
+ const marker = join15(dataDir2, MARKER);
33283
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32397
33284
  const capped = db.policies.capCategoryActions();
32398
33285
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32399
33286
  `, { mode: DATA_FILE_MODE });
32400
33287
  return { capped };
32401
33288
  }
32402
33289
 
32403
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32404
- function hashProjectKey(projectKey) {
32405
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32406
- }
32407
- function toIngestHit(hit) {
32408
- return {
32409
- host: hit.host,
32410
- kind: hit.kind,
32411
- name: hit.name,
32412
- category: hit.category,
32413
- trust: hit.trust,
32414
- network: hit.network,
32415
- method: hit.method,
32416
- transport: hit.transport,
32417
- url: hit.url,
32418
- template: hit.template,
32419
- dataClass: hit.dataClass,
32420
- site: {
32421
- file: hit.site.file,
32422
- line: hit.site.line,
32423
- dynamic: hit.site.dynamic,
32424
- vendored: hit.site.vendored
32425
- }
32426
- };
32427
- }
32428
- function toEgressIngestRequest(input2) {
32429
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32430
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32431
- return {
32432
- projectKey: hashProjectKey(input2.projectKey),
32433
- project: input2.project,
32434
- reconcile,
32435
- hits: hits.map(toIngestHit)
32436
- };
32437
- }
32438
-
32439
33290
  // ../../packages/remote/src/http.ts
32440
33291
  import { request as httpRequest } from "http";
32441
33292
  import { request as httpsRequest } from "https";
@@ -32619,10 +33470,10 @@ function parsed(schema, body, route) {
32619
33470
  }
32620
33471
  function withoutTrailingSlashes(endpoint) {
32621
33472
  let end = endpoint.length;
32622
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33473
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32623
33474
  return endpoint.slice(0, end);
32624
33475
  }
32625
- var SLASH = "/".charCodeAt(0);
33476
+ var SLASH2 = "/".charCodeAt(0);
32626
33477
  function createRemoteClient(options) {
32627
33478
  const base = withoutTrailingSlashes(options.endpoint);
32628
33479
  const url2 = (route) => `${base}${route}`;
@@ -32715,6 +33566,7 @@ function createRemoteClient(options) {
32715
33566
  url: url2(ROUTES.shares),
32716
33567
  body: JSON.stringify(validated.data)
32717
33568
  });
33569
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32718
33570
  okBody(response);
32719
33571
  },
32720
33572
  async pollCommand() {
@@ -32737,19 +33589,51 @@ function createRemoteClient(options) {
32737
33589
  };
32738
33590
  }
32739
33591
 
32740
- // ../../packages/plugin-runtime/src/attached/failure.ts
33592
+ // ../../packages/remote/src/failure-kind.ts
32741
33593
  function statusOf(err) {
32742
33594
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32743
33595
  const { status } = err;
32744
33596
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32745
33597
  return status >= 100 && status <= 599 ? status : null;
32746
33598
  }
32747
- function classifyFailure(err) {
32748
- switch (statusOf(err)) {
33599
+ function nameOf(err) {
33600
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33601
+ return typeof err.name === "string" ? err.name : null;
33602
+ }
33603
+ function classifyRemoteFailure(err) {
33604
+ switch (nameOf(err)) {
33605
+ case "RemoteRouteAbsent":
33606
+ return "route-absent";
33607
+ case "RemoteRequestInvalid":
33608
+ return "invalid-request";
33609
+ case "RemoteResponseInvalid":
33610
+ return "rejected";
33611
+ default:
33612
+ break;
33613
+ }
33614
+ const status = statusOf(err);
33615
+ if (status === null) return "unreachable";
33616
+ switch (status) {
32749
33617
  case 401:
32750
33618
  return "unauthorized";
32751
33619
  case 403:
32752
33620
  return "forbidden";
33621
+ case 429:
33622
+ return "unreachable";
33623
+ case 404:
33624
+ return "unreachable";
33625
+ default:
33626
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33627
+ }
33628
+ }
33629
+
33630
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33631
+ function classifyFailure(err) {
33632
+ switch (classifyRemoteFailure(err)) {
33633
+ case "unauthorized":
33634
+ return "unauthorized";
33635
+ case "forbidden":
33636
+ return "forbidden";
32753
33637
  default:
32754
33638
  return "unreachable";
32755
33639
  }
@@ -32771,11 +33655,11 @@ function withTimeout(promise2, ms) {
32771
33655
  }
32772
33656
 
32773
33657
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32774
- import { readFileSync as readFileSync8 } from "fs";
32775
- import { join as join13 } from "path";
33658
+ import { readFileSync as readFileSync10 } from "fs";
33659
+ import { join as join16 } from "path";
32776
33660
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32777
33661
  function forwardDropsPath(dataDir2) {
32778
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33662
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
32779
33663
  }
32780
33664
  function recordForwardDrops(dataDir2, count, nowMs) {
32781
33665
  if (count <= 0) return;
@@ -32793,7 +33677,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
32793
33677
  }
32794
33678
  function readForwardDrops(dataDir2) {
32795
33679
  try {
32796
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33680
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
32797
33681
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
32798
33682
  const record2 = parsed2;
32799
33683
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -32811,13 +33695,12 @@ function readForwardDrops(dataDir2) {
32811
33695
 
32812
33696
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32813
33697
  import { randomUUID as randomUUID15 } from "crypto";
32814
- import { readFileSync as readFileSync14 } from "fs";
32815
33698
  import { readFile, rename, writeFile } from "fs/promises";
32816
- import { join as join22 } from "path";
33699
+ import { join as join26 } from "path";
32817
33700
 
32818
33701
  // ../../packages/plugin-sdk/src/config.ts
32819
- import { existsSync as existsSync7 } from "fs";
32820
- import { join as join14 } from "path";
33702
+ import { existsSync as existsSync8 } from "fs";
33703
+ import { join as join17 } from "path";
32821
33704
 
32822
33705
  // ../../packages/plugin-sdk/src/provider-env.ts
32823
33706
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -32871,8 +33754,8 @@ function resolveProvider() {
32871
33754
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32872
33755
  try {
32873
33756
  ensureLayoutDirSync(base);
32874
- const settingsFile = join14(settingsDir(base), "settings.json");
32875
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33757
+ const settingsFile = join17(settingsDir(base), "settings.json");
33758
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
32876
33759
  } catch {
32877
33760
  }
32878
33761
  migrateLegacyLayout(base);
@@ -32895,9 +33778,9 @@ function resolveProviderSafe(resolveProviderFn) {
32895
33778
  }
32896
33779
 
32897
33780
  // ../../packages/plugin-sdk/src/config-inventory.ts
32898
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33781
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32899
33782
  import { homedir as homedir2 } from "os";
32900
- import { basename as basename3, join as join16 } from "path";
33783
+ import { basename as basename3, join as join19 } from "path";
32901
33784
 
32902
33785
  // ../../packages/detections/src/egress/registry.ts
32903
33786
  var EXTRACTOR_VERSION = "1";
@@ -35680,24 +36563,20 @@ function bundledDetections() {
35680
36563
  }
35681
36564
 
35682
36565
  // ../../packages/plugin-sdk/src/repo.ts
35683
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
35684
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36566
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
36567
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
35685
36568
 
35686
36569
  // ../../packages/plugin-sdk/src/events.ts
35687
36570
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
35688
36571
 
35689
36572
  // ../../packages/plugin-sdk/src/isolated-scan.ts
35690
- import { existsSync as existsSync9 } from "fs";
36573
+ import { existsSync as existsSync10 } from "fs";
35691
36574
  import { fileURLToPath } from "url";
35692
36575
  import { Worker } from "worker_threads";
35693
36576
 
35694
- // ../../packages/plugin-sdk/src/ignore-layers.ts
35695
- var import_ignore = __toESM(require_ignore(), 1);
35696
- import { readFileSync as readFileSync11 } from "fs";
35697
- import { join as join17 } from "path";
35698
-
35699
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
35700
- import { arch, hostname as hostname4, platform, release } from "os";
36577
+ // ../../packages/plugin-sdk/src/host-floor.ts
36578
+ import { readFileSync as readFileSync14 } from "fs";
36579
+ import { join as join21 } from "path";
35701
36580
 
35702
36581
  // ../../packages/plugin-sdk/src/model-governance.ts
35703
36582
  import {
@@ -35705,24 +36584,50 @@ import {
35705
36584
  fstatSync,
35706
36585
  mkdirSync as mkdirSync2,
35707
36586
  openSync as openSync2,
35708
- readFileSync as readFileSync12,
36587
+ readFileSync as readFileSync13,
35709
36588
  readSync,
35710
36589
  writeFileSync as writeFileSync5
35711
36590
  } from "fs";
35712
- import { join as join18 } from "path";
36591
+ import { join as join20 } from "path";
35713
36592
  var TAIL_BYTES = 256 * 1024;
35714
36593
 
36594
+ // ../../packages/plugin-sdk/src/host-floor.ts
36595
+ var HOST_FEATURE = {
36596
+ ModelSwitch: "model-switch",
36597
+ VaultPointerDisplay: "vault-pointer-display"
36598
+ };
36599
+ var HOST_FLOORS = {
36600
+ [HOST_FEATURE.ModelSwitch]: {
36601
+ label: "model-switch protection",
36602
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
36603
+ since: "2.1.251"
36604
+ },
36605
+ [HOST_FEATURE.VaultPointerDisplay]: {
36606
+ label: "vault pointer display",
36607
+ hookEvents: ["MessageDisplay"],
36608
+ since: "2.1.152"
36609
+ }
36610
+ };
36611
+
36612
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
36613
+ var import_ignore = __toESM(require_ignore(), 1);
36614
+ import { readFileSync as readFileSync15 } from "fs";
36615
+ import { join as join22 } from "path";
36616
+
36617
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
36618
+ import { arch, hostname as hostname4, platform, release } from "os";
36619
+
35715
36620
  // ../../packages/plugin-sdk/src/nudge.ts
35716
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
35717
- import { join as join19 } from "path";
36621
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
36622
+ import { join as join23 } from "path";
35718
36623
 
35719
36624
  // ../../packages/plugin-sdk/src/paths.ts
35720
36625
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
35721
36626
  import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
35722
36627
 
35723
36628
  // ../../packages/plugin-sdk/src/project-files.ts
35724
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
35725
- import { basename as basename5, join as join20 } from "path";
36629
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36630
+ import { basename as basename5, join as join24 } from "path";
35726
36631
 
35727
36632
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35728
36633
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35758,7 +36663,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
35758
36663
 
35759
36664
  // ../../packages/plugin-sdk/src/throttle.ts
35760
36665
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35761
- import { join as join21 } from "path";
36666
+ import { join as join25 } from "path";
35762
36667
 
35763
36668
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35764
36669
  function isInvalidRequest(err) {
@@ -35774,31 +36679,12 @@ function isServerRejection(err) {
35774
36679
  var FORWARD_BUDGET_MS = 1500;
35775
36680
  var DECISION_PATH_BUDGET_MS = 800;
35776
36681
  var BREAKER_FAILURE_THRESHOLD = 3;
35777
- var BREAKER_COOLDOWN_MS = 3e4;
35778
36682
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
35779
- var FAILURES = /* @__PURE__ */ new Set([
35780
- "unauthorized",
35781
- "forbidden",
35782
- "unreachable"
35783
- ]);
35784
36683
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
35785
36684
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
35786
- function parseBreakerState(raw, nowMs) {
35787
- try {
35788
- const parsed2 = JSON.parse(raw);
35789
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
35790
- const record2 = parsed2;
35791
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
35792
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
35793
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
35794
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
35795
- } catch {
35796
- return null;
35797
- }
35798
- }
35799
36685
  function createForwardPolicy(deps) {
35800
36686
  const now = deps.now ?? (() => Date.now());
35801
- const file2 = join22(deps.dir, STATE_FILENAME);
36687
+ const file2 = join26(deps.dir, STATE_FILENAME);
35802
36688
  let state = null;
35803
36689
  let loading = null;
35804
36690
  async function readState() {
@@ -35808,7 +36694,7 @@ function createForwardPolicy(deps) {
35808
36694
  } catch {
35809
36695
  return { ...CLOSED };
35810
36696
  }
35811
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
36697
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
35812
36698
  }
35813
36699
  async function load() {
35814
36700
  if (state !== null) return state;
@@ -35854,7 +36740,7 @@ function createForwardPolicy(deps) {
35854
36740
  };
35855
36741
  const at = now();
35856
36742
  if (current.openedAtMs !== null) {
35857
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
36743
+ if (isForwardPaused(current, at)) {
35858
36744
  return { ok: false, reason: "breaker-open" };
35859
36745
  }
35860
36746
  await persist({
@@ -36391,7 +37277,18 @@ var AttachedDataGateway = class {
36391
37277
  // and the spread above would otherwise drop the field silently — which is
36392
37278
  // exactly what it did, leaving the whole control inert on every device
36393
37279
  // while every test around it stayed green.
36394
- prohibitedModels: cached2.prohibitedModels
37280
+ prohibitedModels: cached2.prohibitedModels,
37281
+ // NAMED for the same reason as the line above, and it is the same defect
37282
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
37283
+ // only the cache carries is dropped in silence. That is what left
37284
+ // `prohibitedModels` inert on every attached device with every test
37285
+ // around it green.
37286
+ //
37287
+ // Taken from the cache rather than merged here, because merging it needs
37288
+ // the device's own SETTING — which is not a bundle field and is not in
37289
+ // scope at this seam. The runtime does that merge, raise-only, where both
37290
+ // values are in hand (createPluginRuntime's ensureInitialized).
37291
+ redactFallback: cached2.redactFallback
36395
37292
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
36396
37293
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
36397
37294
  // it emits, so an 'authored' policy arriving from the control plane
@@ -36519,10 +37416,6 @@ function toolAuditEvent(input2) {
36519
37416
  };
36520
37417
  }
36521
37418
 
36522
- // ../../packages/plugin-runtime/src/attached/history-state.ts
36523
- import { readFileSync as readFileSync15 } from "fs";
36524
- import { join as join23 } from "path";
36525
-
36526
37419
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36527
37420
  import { createHash as createHash6 } from "crypto";
36528
37421
  import { hostname as hostname5 } from "os";
@@ -36531,6 +37424,10 @@ import { hostname as hostname5 } from "os";
36531
37424
  var CORRELATION_ID = EventMetadata.shape.correlationId;
36532
37425
  var TRACE_ID = EventMetadata.shape.traceId;
36533
37426
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37427
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
37428
+
37429
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
37430
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
36534
37431
 
36535
37432
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36536
37433
  import { spawn } from "child_process";
@@ -36538,7 +37435,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
36538
37435
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
36539
37436
 
36540
37437
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
36541
- import { readFileSync as readFileSync16 } from "fs";
37438
+ import { readFileSync as readFileSync17 } from "fs";
36542
37439
  function createPluginBlock(build, policyStore) {
36543
37440
  return async () => {
36544
37441
  const cached2 = await policyStore.read();
@@ -36557,7 +37454,7 @@ function createPluginBlock(build, policyStore) {
36557
37454
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36558
37455
  import { randomUUID as randomUUID16 } from "crypto";
36559
37456
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36560
- import { join as join24 } from "path";
37457
+ import { join as join27 } from "path";
36561
37458
 
36562
37459
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36563
37460
  import { rename as rename2 } from "fs/promises";
@@ -36581,7 +37478,7 @@ async function publishByRename(tmp, file2, move = rename2) {
36581
37478
 
36582
37479
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36583
37480
  function createPolicyStore(dir = dataDir()) {
36584
- const file2 = join24(dir, "policy-cache.json");
37481
+ const file2 = join27(dir, "policy-cache.json");
36585
37482
  async function read() {
36586
37483
  try {
36587
37484
  const raw = await readFile2(file2, "utf8");
@@ -36812,11 +37709,11 @@ function readStorePosture(dbPath2) {
36812
37709
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
36813
37710
  import { randomUUID as randomUUID17 } from "crypto";
36814
37711
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
36815
- import { join as join25 } from "path";
37712
+ import { join as join28 } from "path";
36816
37713
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
36817
37714
  function createPostureStore(dir = settingsDir(), legacyDir) {
36818
- const file2 = join25(dir, "posture-state.json");
36819
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
37715
+ const file2 = join28(dir, "posture-state.json");
37716
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
36820
37717
  async function persist(state) {
36821
37718
  await ensureDataDir(dir);
36822
37719
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -36884,8 +37781,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
36884
37781
  }
36885
37782
 
36886
37783
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
36887
- import { readFileSync as readFileSync17 } from "fs";
36888
- import { join as join26 } from "path";
37784
+ import { readFileSync as readFileSync18 } from "fs";
37785
+ import { join as join29 } from "path";
36889
37786
 
36890
37787
  // ../../packages/plugin-runtime/src/attached/status.ts
36891
37788
  var REFUSAL_LINES = {
@@ -36906,6 +37803,14 @@ import { spawn as spawn2 } from "child_process";
36906
37803
  import { fileURLToPath as fileURLToPath3 } from "url";
36907
37804
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
36908
37805
 
37806
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
37807
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
37808
+
37809
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
37810
+ import { spawn as spawn3 } from "child_process";
37811
+ import { fileURLToPath as fileURLToPath4 } from "url";
37812
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
37813
+
36909
37814
  // ../../packages/plugin-runtime/src/attached/factory.ts
36910
37815
  import { hostname as hostname6 } from "os";
36911
37816
 
@@ -37381,7 +38286,7 @@ async function readStdin() {
37381
38286
 
37382
38287
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
37383
38288
  import { writeFileSync as writeFileSync8 } from "fs";
37384
- import { join as join27 } from "path";
38289
+ import { join as join30 } from "path";
37385
38290
 
37386
38291
  // ../../packages/setup-wizard/src/triage/merge.ts
37387
38292
  var RANK = Object.fromEntries(
@@ -37389,9 +38294,9 @@ var RANK = Object.fromEntries(
37389
38294
  );
37390
38295
 
37391
38296
  // ../../packages/setup-wizard/src/triage/plan-file.ts
37392
- import { mkdtempSync, readFileSync as readFileSync18, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
38297
+ import { mkdtempSync, readFileSync as readFileSync19, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
37393
38298
  import { tmpdir } from "os";
37394
- import { basename as basename6, dirname as dirname6, join as join28 } from "path";
38299
+ import { basename as basename6, dirname as dirname6, join as join31 } from "path";
37395
38300
  var SuppressionEntrySchema = external_exports.object({
37396
38301
  ruleId: external_exports.string(),
37397
38302
  category: DetectionCategory,
@@ -37434,8 +38339,8 @@ var PersistedPlanSchema = external_exports.object({
37434
38339
 
37435
38340
  // src/command-registry.ts
37436
38341
  import { readdirSync as readdirSync5 } from "fs";
37437
- import { fileURLToPath as fileURLToPath4 } from "url";
37438
- var COMMANDS_DIR = fileURLToPath4(new URL("../commands", import.meta.url));
38342
+ import { fileURLToPath as fileURLToPath5 } from "url";
38343
+ var COMMANDS_DIR = fileURLToPath5(new URL("../commands", import.meta.url));
37439
38344
 
37440
38345
  // src/present.ts
37441
38346
  var SHADE = {
@@ -37477,11 +38382,6 @@ var SEVERITY_GLYPH = {
37477
38382
  low: SHADE.light
37478
38383
  };
37479
38384
  var CATEGORY_ORDER2 = DetectionCategory.options;
37480
- function healthScore(summary) {
37481
- const handled = summary.byAction.block + summary.byAction.redact + summary.byAction.warn;
37482
- const handledRatio = summary.findings === 0 ? 1 : handled / summary.findings;
37483
- return Math.round(100 * (0.6 * summary.coverage + 0.4 * handledRatio));
37484
- }
37485
38385
  function renderStatusBar(s, opts = {}) {
37486
38386
  const u = s.unreviewed;
37487
38387
  if (opts.color !== true) {
@@ -37500,13 +38400,6 @@ function renderStatusBar(s, opts = {}) {
37500
38400
  function renderStatusLine(summary) {
37501
38401
  return renderStatusBar(findingStatus(summary), { color: true });
37502
38402
  }
37503
- function findingStatus(summary) {
37504
- return {
37505
- score: healthScore(summary),
37506
- unreviewed: { ...summary.bySeverity },
37507
- openFindings: summary.findings
37508
- };
37509
- }
37510
38403
 
37511
38404
  // src/statusline.ts
37512
38405
  try {