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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,8 +492,8 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/remediation/entry.ts
495
- import { readFileSync as readFileSync22 } from "fs";
496
- import { fileURLToPath as fileURLToPath5 } from "url";
495
+ import { readFileSync as readFileSync23 } from "fs";
496
+ import { fileURLToPath as fileURLToPath6 } from "url";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20670,6 +20702,15 @@ var FindingCategory = external_exports.enum([
20670
20702
  ]).meta({ id: "FindingCategory" });
20671
20703
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20672
20704
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20705
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20706
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20707
+ var FindingDelivery = external_exports.object({
20708
+ state: FindingDeliveryState,
20709
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20710
+ at: external_exports.iso.datetime().optional(),
20711
+ // Only on `not_sent`, and only when a known reason was recorded.
20712
+ reason: SyncFailureReason.optional()
20713
+ }).meta({ id: "FindingDelivery" });
20673
20714
  var ResolutionMethod = external_exports.enum([
20674
20715
  "enforced-in-flight",
20675
20716
  "fixed-at-source",
@@ -20726,7 +20767,10 @@ var FindingInstance = external_exports.object({
20726
20767
  // The session that event belongs to, when it has one — the seam a
20727
20768
  // per-instance "view session" link needs. Absent for events captured
20728
20769
  // outside a session.
20729
- sessionId: external_exports.string().optional()
20770
+ sessionId: external_exports.string().optional(),
20771
+ // The delivery state of the event above (see FindingDelivery). Optional so
20772
+ // readers that do not project it stay valid.
20773
+ delivery: FindingDelivery.optional()
20730
20774
  }).meta({ id: "FindingInstance" });
20731
20775
  var FindingGroup = external_exports.object({
20732
20776
  id: external_exports.string(),
@@ -20743,13 +20787,11 @@ var FindingGroup = external_exports.object({
20743
20787
  latestDetectedAt: external_exports.iso.datetime(),
20744
20788
  instances: external_exports.array(FindingInstance),
20745
20789
  // Derived from instances' statuses with open-dominates precedence (see
20746
- // buildFindingGroups). Undefined only when no instance carries a status.
20790
+ // foldGroupStatus). Undefined only when no instance carries a status.
20747
20791
  status: FindingStatus.optional(),
20748
- // The distinct people across the WHOLE group, not just the `instances`
20749
- // preview — from the store's whole-group aggregate when it supplies one,
20750
- // else folded from the rows (see buildFindingGroups). Undefined when no
20751
- // instance carries a user, or when the store supplied whole-group folds
20752
- // without one.
20792
+ // The distinct people across the WHOLE group, not just the instances
20793
+ // carried here. Undefined when no instance carries a user, or when the
20794
+ // store supplied whole-group folds without one.
20753
20795
  users: external_exports.array(FindingUser).optional()
20754
20796
  }).meta({ id: "FindingGroup" });
20755
20797
  var FindingStats = external_exports.object({
@@ -20778,21 +20820,34 @@ var FindingFacets = external_exports.object({
20778
20820
  // counted under no value.
20779
20821
  status: external_exports.array(FindingFacetItem),
20780
20822
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
- // reads, which can filter by it; the grouped read omits the dimension
20823
+ // reads, which can filter by it; the type-level read omits the dimension
20782
20824
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20825
+ tool: external_exports.array(FindingFacetItem).optional(),
20826
+ // Delivery states (FindingDeliveryState). Present only on the
20827
+ // instance-level reads, like `tool`.
20828
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20829
  }).meta({ id: "FindingFacets" });
20785
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20786
- var ListGroupedFindingsQuery = external_exports.object({
20830
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20831
+ id: "FindingTypeSummary"
20832
+ });
20833
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20834
+ var MAX_FINDING_TYPES_LIMIT = 100;
20835
+ var ListFindingTypesQuery = external_exports.object({
20787
20836
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20788
- // FindingAction.
20837
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20838
+ // firing version carries, and this list pages types.
20839
+ //
20840
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20841
+ // definition versions at different severities, so a type kept by this filter
20842
+ // can hold findings that individually do not match — see totals.findings on
20843
+ // ListFindingTypesResponse, which counts them all.
20789
20844
  severity: external_exports.array(Severity).optional(),
20790
20845
  subtype: external_exports.array(external_exports.string()).optional(),
20791
20846
  provider: external_exports.array(FindingProvider).optional(),
20792
20847
  action: external_exports.array(FindingAction).optional(),
20793
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20794
- // individual instances' — so a filtered group's Status column always reads
20795
- // one of the requested values.
20848
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20849
+ // individual findings' — so a filtered row's status always reads one of the
20850
+ // requested values.
20796
20851
  status: external_exports.array(FindingStatus).optional(),
20797
20852
  q: external_exports.string().optional(),
20798
20853
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20802,23 +20857,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20802
20857
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20803
20858
  // means all time — this list has no default window.
20804
20859
  from: external_exports.iso.datetime().optional(),
20805
- // A group or instance id that must appear in the page even when the cursor
20806
- // has already advanced past its sort position. This is what keeps the
20807
- // Findings page's one-shot ?finding= deep link resolving once the list
20808
- // paginates: the target group is appended out of sort order rather than
20809
- // scanning forward for it. Never affects totals, facets or the cursor.
20860
+ // A RULE id that must appear in the page even when the cursor has already
20861
+ // advanced past its sort position. This is what keeps the selected type
20862
+ // visible in the list once it paginates: the target is appended out of sort
20863
+ // order rather than scanned forward for. Never affects totals, facets or the
20864
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20865
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20866
+ // and so is not bounded by what any page happens to hold.
20810
20867
  includeId: external_exports.string().optional(),
20811
- groupBy: external_exports.literal("type").optional(),
20812
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20868
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20813
20869
  cursor: external_exports.string().optional()
20814
20870
  });
20815
- var ListGroupedFindingsResponse = external_exports.object({
20871
+ var ListFindingTypesResponse = external_exports.object({
20816
20872
  totals: external_exports.object({
20873
+ // Findings belonging to the matching TYPES — not findings that each match
20874
+ // the filters. The filters here select types, so a type that survives
20875
+ // contributes its whole instanceCount.
20876
+ //
20877
+ // `status` is the one exception, narrowed per finding via
20878
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20879
+ // this can exceed what the instance read reports for the same filters: a
20880
+ // rule whose severity moved between versions is kept on its newest and
20881
+ // still counts its older findings. Narrowing the other three needs
20882
+ // per-dimension counts the aggregate does not carry today.
20817
20883
  findings: external_exports.number().int().nonnegative(),
20818
- groups: external_exports.number().int().nonnegative()
20884
+ // Counts TYPES, which is the unit this read pages. The instance read's
20885
+ // own totals count findings; the two deliberately answer different
20886
+ // questions and are never summed.
20887
+ types: external_exports.number().int().nonnegative()
20819
20888
  }),
20820
20889
  facets: FindingFacets,
20821
- items: external_exports.array(FindingGroup),
20890
+ items: external_exports.array(FindingTypeSummary),
20822
20891
  nextCursor: external_exports.string().nullable(),
20823
20892
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20824
20893
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20826,7 +20895,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20826
20895
  // every firing, so the two numbers legitimately differ — this map lets a
20827
20896
  // session-scoped view show both.
20828
20897
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20829
- }).meta({ id: "ListGroupedFindingsResponse" });
20898
+ }).meta({ id: "ListFindingTypesResponse" });
20830
20899
  var ApplyFindingActionRequest = external_exports.object({
20831
20900
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20832
20901
  // it, so it is excluded from the request contract. The mapping helper
@@ -20856,16 +20925,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20856
20925
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20857
20926
  var ListFindingInstancesQuery = external_exports.object({
20858
20927
  severity: external_exports.array(Severity).optional(),
20859
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20928
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20929
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20860
20930
  subtype: external_exports.array(external_exports.string()).optional(),
20861
20931
  provider: external_exports.array(FindingProvider).optional(),
20862
20932
  action: external_exports.array(FindingAction).optional(),
20863
20933
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20864
- // the grouped query's group-level fold.
20934
+ // the types query's type-level fold.
20865
20935
  status: external_exports.array(FindingStatus).optional(),
20866
20936
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20867
20937
  // where the free-text `q` can only match the rendered "via Bash" label.
20868
20938
  tool: external_exports.array(external_exports.string()).optional(),
20939
+ // The delivery state of each finding's event (see FindingDelivery).
20940
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20869
20941
  // Exact repository / file-path matches, for the drill-down out of the
20870
20942
  // locations view. A row whose event carries no repo/file matches neither.
20871
20943
  repo: external_exports.string().optional(),
@@ -20878,37 +20950,51 @@ var ListFindingInstancesQuery = external_exports.object({
20878
20950
  });
20879
20951
  var ListFindingInstancesResponse = external_exports.object({
20880
20952
  // Instances matching the filters across the whole scope, not just this
20881
- // page — cursor-independent, like the grouped list's totals.
20953
+ // page — cursor-independent, like the types list's totals.
20882
20954
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20883
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20955
+ // Counts in INSTANCES here, where the types response counts types. Each
20884
20956
  // dimension still excludes its own filter.
20885
20957
  facets: FindingFacets,
20886
20958
  items: external_exports.array(FindingInstanceDetail),
20887
20959
  nextCursor: external_exports.string().nullable()
20888
20960
  }).meta({ id: "ListFindingInstancesResponse" });
20889
- var FindingLocationFile = external_exports.object({
20890
- // Empty when the instances carried no file path (a prompt or a tool call
20891
- // with no file attribution).
20892
- file: external_exports.string(),
20893
- instanceCount: external_exports.number().int().nonnegative(),
20894
- maxSeverity: Severity,
20895
- latestDetectedAt: external_exports.iso.datetime(),
20896
- // Folded from the instances' derived statuses with the same
20897
- // open-dominates precedence a group uses.
20898
- status: FindingStatus.optional(),
20899
- // Distinct rules seen at this location, capped — the row shows them as
20900
- // chips, and the count is what conveys scale.
20901
- ruleIds: external_exports.array(external_exports.string())
20902
- }).meta({ id: "FindingLocationFile" });
20903
- var FindingLocationRepo = external_exports.object({
20961
+ var ListFindingInstancesPage = external_exports.object({
20962
+ items: external_exports.array(FindingInstanceDetail),
20963
+ nextCursor: external_exports.string().nullable()
20964
+ }).meta({ id: "ListFindingInstancesPage" });
20965
+ var FindingLocationSummary = external_exports.object({
20966
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20967
+ // because a location's identity is two values and a URL param carries one:
20968
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20969
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20970
+ // client's page dedupe — never decoded, and never a sort key.
20971
+ id: external_exports.string(),
20904
20972
  /** Empty when the instances carried no repo attribute. */
20905
20973
  repo: external_exports.string(),
20974
+ // Empty when the instances carried no file path (a prompt, or a tool call
20975
+ // with no file attribution). Both halves empty is a real location — usually
20976
+ // the largest one in a store — and is selectable like any other.
20977
+ file: external_exports.string(),
20906
20978
  instanceCount: external_exports.number().int().nonnegative(),
20979
+ // The WORST severity present, not the first row's. It is this list's primary
20980
+ // sort key, so it is also what explains why a row is where it is, and it is
20981
+ // how a reader decides what to open without opening everything.
20907
20982
  maxSeverity: Severity,
20908
20983
  latestDetectedAt: external_exports.iso.datetime(),
20984
+ // Folded from the instances' derived statuses with the same open-dominates
20985
+ // precedence a group uses, so it answers "is anything left to do here" and
20986
+ // not much more: a location holding 1 open among 40 resolved reads like one
20987
+ // holding 40 open. That loss is accepted — the panel beside this list
20988
+ // carries each finding's own status, and instanceCount sits next to the
20989
+ // badge.
20909
20990
  status: FindingStatus.optional(),
20910
- files: external_exports.array(FindingLocationFile)
20911
- }).meta({ id: "FindingLocationRepo" });
20991
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20992
+ // tally rather than a sample and a row can say how many there are. Bounded
20993
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20994
+ ruleIds: external_exports.array(external_exports.string())
20995
+ }).meta({ id: "FindingLocationSummary" });
20996
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20997
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20912
20998
  var ListFindingLocationsQuery = external_exports.object({
20913
20999
  severity: external_exports.array(Severity).optional(),
20914
21000
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20918,21 +21004,47 @@ var ListFindingLocationsQuery = external_exports.object({
20918
21004
  // instances that match, and folds its status from those.
20919
21005
  status: external_exports.array(FindingStatus).optional(),
20920
21006
  tool: external_exports.array(external_exports.string()).optional(),
21007
+ // The delivery state of each finding's event (see FindingDelivery).
21008
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20921
21009
  q: external_exports.string().optional(),
20922
21010
  sessionId: external_exports.string().optional(),
20923
21011
  from: external_exports.iso.datetime().optional(),
20924
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21012
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21013
+ // even when the cursor has already advanced past its sort position — the
21014
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21015
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21016
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21017
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21018
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21019
+ includeId: external_exports.string().optional(),
21020
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21021
+ cursor: external_exports.string().optional()
20925
21022
  });
20926
21023
  var ListFindingLocationsResponse = external_exports.object({
20927
21024
  totals: external_exports.object({
21025
+ // Findings matching the filters across the whole scope. Unlike the types
21026
+ // read's same-named field this needs no caveat: the filters here narrow
21027
+ // per finding, so this is the sum of every row's instanceCount.
20928
21028
  findings: external_exports.number().int().nonnegative(),
20929
- repos: external_exports.number().int().nonnegative(),
20930
- files: external_exports.number().int().nonnegative()
21029
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21030
+ // states. The facets beside it count FINDINGS (see below); a surface
21031
+ // showing both says which is which.
21032
+ locations: external_exports.number().int().nonnegative()
20931
21033
  }),
20932
- /** Sorted by max severity, then most recent. */
20933
- items: external_exports.array(FindingLocationRepo),
20934
- /** Whether `limit` truncated the repo list. */
20935
- hasMore: external_exports.boolean()
21034
+ // Counts in FINDINGS, where the types response counts types, each dimension
21035
+ // still excluding its own filter. Deliberately not locations: counting those
21036
+ // needs a set of location keys per dimension per value — memory tracking the
21037
+ // store times the vocabulary, in a read whose scan promises flat memory —
21038
+ // and the cheap per-location version is not an approximation but WRONG. A
21039
+ // location holding {claudecode, block} and {codex, warn} would survive
21040
+ // provider=claudecode AND action=warn, under which no single finding
21041
+ // matches, so the facet would contradict the instanceCount this whole view
21042
+ // rests on. Findings also keep the toolbar in the same unit as the page
21043
+ // tally and the panel it sits above.
21044
+ facets: FindingFacets,
21045
+ /** Sorted by max severity, then most recent, then (repo, file). */
21046
+ items: external_exports.array(FindingLocationSummary),
21047
+ nextCursor: external_exports.string().nullable()
20936
21048
  }).meta({ id: "ListFindingLocationsResponse" });
20937
21049
 
20938
21050
  // ../../packages/schema/src/zod/meta.ts
@@ -21096,6 +21208,10 @@ var CaptureAttributes = external_exports.object({
21096
21208
  // to 'allow' — the enforcement audit trail's link back to the grant that
21097
21209
  // authorized the bypass.
21098
21210
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21211
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21212
+ // join back to the `llm_call` leaf for the same assistant turn.
21213
+ message_id: external_exports.string().optional(),
21214
+ conversation_id: external_exports.string().optional(),
21099
21215
  // Whole milliseconds this capture's inspection blocked its caller — the
21100
21216
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21101
21217
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21104,7 +21220,19 @@ var CaptureAttributes = external_exports.object({
21104
21220
  // inline json_extract and is not itself an optimization.
21105
21221
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21106
21222
  // before the measurement shipped — never present as a placeholder 0.
21107
- inspection_ms: external_exports.number().int().nonnegative().optional()
21223
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21224
+ // What a `redact` this capture could not carry out became instead (see
21225
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21226
+ // degrade actually happened, so absence is the ordinary case rather than a
21227
+ // reader having to distinguish it from a zero.
21228
+ //
21229
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21230
+ // so on a multi-finding row this does not say which finding degraded, and
21231
+ // its presence does not mean the fallback decided the capture's action. A
21232
+ // capture denied by another finding's own Block policy carries `block`
21233
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21234
+ // repeated rather than referenced because a store reader opens this file.
21235
+ redact_degraded_to: ActionTaken.optional()
21108
21236
  }).catchall(external_exports.unknown());
21109
21237
  var ToolCallInspection = external_exports.object({
21110
21238
  ruleId: external_exports.string().min(1),
@@ -21303,7 +21431,17 @@ var AuditEvent = external_exports.object({
21303
21431
  /** `share` to a first-party/internal destination. */
21304
21432
  internal: external_exports.boolean(),
21305
21433
  /** Event needs review (e.g. unverified egress). */
21306
- flagged: external_exports.boolean()
21434
+ flagged: external_exports.boolean(),
21435
+ /**
21436
+ * The body this event's `title` is drawn from was cleared by local body
21437
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21438
+ *
21439
+ * A separate flag rather than a sentinel written into `title`: the title is
21440
+ * rendered text, and a store-layer module that invented display copy for it
21441
+ * would be choosing words the view is supposed to choose. Additive and
21442
+ * defaulted, so an older producer still validates.
21443
+ */
21444
+ bodyExpired: external_exports.boolean().default(false)
21307
21445
  }).meta({ id: "ActivityAuditEvent" });
21308
21446
  var ActivitySessionSummary = external_exports.object({
21309
21447
  id: external_exports.string(),
@@ -22101,6 +22239,14 @@ var ControlPlaneErrorBody = external_exports.object({
22101
22239
  message: external_exports.string().optional()
22102
22240
  }).optional()
22103
22241
  });
22242
+ var RemoteFailureKind = external_exports.enum([
22243
+ "unauthorized",
22244
+ "forbidden",
22245
+ "route-absent",
22246
+ "invalid-request",
22247
+ "rejected",
22248
+ "unreachable"
22249
+ ]);
22104
22250
  var AttachDeviceRequest = external_exports.object({
22105
22251
  // This machine's own continuity id, so re-attaching ROTATES the credential
22106
22252
  // on one machine record instead of producing a second one. Client-minted
@@ -22636,6 +22782,12 @@ var EventMetadata = external_exports.object({
22636
22782
  // to 'allow' — the enforcement audit trail's link back to the grant that
22637
22783
  // authorized the bypass. Absent on captures where no exception applied.
22638
22784
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22785
+ // The assistant message this capture belongs to, and the conversation it sits
22786
+ // in — set by the browser extension's network capture so a stored `response`
22787
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22788
+ // on every other capture path, which has no such id.
22789
+ messageId: external_exports.string().optional(),
22790
+ conversationId: external_exports.string().optional(),
22639
22791
  // How long THIS capture's inspection blocked its caller, in whole
22640
22792
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22641
22793
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22648,7 +22800,37 @@ var EventMetadata = external_exports.object({
22648
22800
  // Absent is also what every pre-measurement client writes, and what a
22649
22801
  // clock failure degrades to — a reader must treat absence as "not measured"
22650
22802
  // and never as a zero, which would read as "inspection is free".
22651
- inspectionMs: external_exports.number().int().nonnegative().optional()
22803
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22804
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22805
+ // workspace's `redactFallback`, applied because the field could not be
22806
+ // masked in place (a shell command, a URL, or any argument on a host whose
22807
+ // hook contract offers no rewrite channel).
22808
+ //
22809
+ // It exists because the action alone cannot say why. A finding recorded as
22810
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22811
+ // assigned Redact on a field that could not take one — and those are
22812
+ // different facts about the same row: the first is a policy the user chose,
22813
+ // the second is a masking the host could not perform. Absent means no
22814
+ // degrade happened, which is every ordinary capture.
22815
+ //
22816
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22817
+ // is the CAPTURE while `actionTaken` is per FINDING:
22818
+ //
22819
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22820
+ // `redact` alongside a finding ASSIGNED the same action stores both
22821
+ // identically and one reason for the pair; attributing it to both
22822
+ // describes the assigned one wrongly, and to neither loses the degrade.
22823
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22824
+ // became, not the reason the capture ended as it did — a capture denied
22825
+ // by some other finding's own Block policy still carries `block` here,
22826
+ // and clearing the workspace's fallback would not have let it through.
22827
+ // Gate on the value against what a fallback can produce; never read the
22828
+ // field's presence as "this was the fallback's doing".
22829
+ //
22830
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22831
+ // Closing either means moving the reason onto the finding row, which
22832
+ // already carries its own action.
22833
+ redactDegradedTo: ActionTaken.optional()
22652
22834
  }).meta({ id: "EventMetadata" });
22653
22835
  var Event = external_exports.object({
22654
22836
  id: external_exports.guid(),
@@ -22758,7 +22940,32 @@ var RotateKeyInput = external_exports.object({
22758
22940
  confirmation: external_exports.string()
22759
22941
  });
22760
22942
 
22943
+ // ../../packages/schema/src/zod/finding-delivery.ts
22944
+ var KNOWN_REASONS = SyncFailureReason.options;
22945
+ function knownReason(value) {
22946
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22947
+ }
22948
+ function deriveFindingDelivery(row) {
22949
+ if (row.kind === "code_change") return { state: "local_scan" };
22950
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22951
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22952
+ }
22953
+ if (row.syncedAt !== null) {
22954
+ const reason = knownReason(row.syncFailure);
22955
+ return {
22956
+ state: "not_sent",
22957
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22958
+ ...reason === void 0 ? {} : { reason }
22959
+ };
22960
+ }
22961
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22962
+ return { state: "never_offered" };
22963
+ }
22964
+
22761
22965
  // ../../packages/schema/src/zod/findings-group-build.ts
22966
+ function lookupOwn(map2, key) {
22967
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22968
+ }
22762
22969
  function toApiAction(dbVal) {
22763
22970
  const map2 = {
22764
22971
  log: "monitored",
@@ -22767,7 +22974,7 @@ function toApiAction(dbVal) {
22767
22974
  warn: "warned",
22768
22975
  allow: "allowed"
22769
22976
  };
22770
- return map2[dbVal] ?? "allowed";
22977
+ return lookupOwn(map2, dbVal) ?? "allowed";
22771
22978
  }
22772
22979
  function toApiCategory(dbVal) {
22773
22980
  if (dbVal === "code_context") return "source_code";
@@ -22775,13 +22982,18 @@ function toApiCategory(dbVal) {
22775
22982
  return parsed2.success ? parsed2.data : "custom";
22776
22983
  }
22777
22984
  function toApiProvider(sourceTool) {
22778
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22985
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22779
22986
  }
22780
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22987
+ var FINDING_STATUS_PRECEDENCE = [
22988
+ "open",
22989
+ "handled",
22990
+ "dismissed",
22991
+ "resolved"
22992
+ ];
22781
22993
  function foldGroupStatus(instanceStatuses) {
22782
22994
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22783
22995
  if (statuses.size === 0) return void 0;
22784
- for (const candidate of STATUS_PRECEDENCE) {
22996
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22785
22997
  if (statuses.has(candidate)) return candidate;
22786
22998
  }
22787
22999
  return void 0;
@@ -22794,139 +23006,62 @@ function deriveFindingStatus(row) {
22794
23006
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22795
23007
  return "open";
22796
23008
  }
22797
- function distinctUsers(instances) {
22798
- const seen = /* @__PURE__ */ new Set();
22799
- const users = [];
22800
- for (const i of instances) {
22801
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22802
- seen.add(i.user.id);
22803
- users.push(i.user);
22804
- }
22805
- return users;
22806
- }
22807
23009
  function sortUsers(users) {
22808
23010
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22809
23011
  }
22810
- function buildFindingGroups(rows, opts = {}) {
22811
- const overrides = opts.overrides;
23012
+ function buildFindingTypes(aggregates, opts = {}) {
22812
23013
  const packNames = opts.packNames;
22813
- const aggregates = opts.aggregates;
22814
- const byRuleId = /* @__PURE__ */ new Map();
22815
- for (const row of rows) {
22816
- const existing = byRuleId.get(row.ruleId);
22817
- if (existing) existing.push(row);
22818
- else byRuleId.set(row.ruleId, [row]);
22819
- }
22820
- const groups = [];
22821
- for (const [ruleId, ruleRows] of byRuleId) {
22822
- const instances = ruleRows.map((r) => {
22823
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22824
- return {
22825
- id: r.id,
22826
- provider: toApiProvider(r.sourceTool),
22827
- repo: r.repo,
22828
- file: r.file,
22829
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22830
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22831
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22832
- ...r.user === void 0 ? {} : { user: r.user },
22833
- action: toApiAction(effectiveDbAction),
22834
- detectedAt: r.occurredAt,
22835
- confidence: r.confidence,
22836
- status: r.status
22837
- };
22838
- });
22839
- const agg = aggregates?.get(ruleId);
22840
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22841
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22842
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22843
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22844
- );
22845
- const seenProviders = /* @__PURE__ */ new Set();
22846
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22847
- if (seenProviders.has(p)) return false;
22848
- seenProviders.add(p);
22849
- return true;
22850
- });
22851
- const actionSet = new Set(
22852
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22853
- );
23014
+ const types = [];
23015
+ for (const [ruleId, agg] of aggregates) {
23016
+ const users = sortUsers(agg.users ?? []);
23017
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23018
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22854
23019
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22855
- const severity = ruleRows[0]?.severity ?? "low";
22856
- const detection = {
22857
- id: ruleId,
22858
- name: packNames?.get(ruleId) ?? null
22859
- };
22860
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22861
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22862
- const match = {
22863
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22864
- contextPrefix: ""
22865
- // empty (pending privacy review)
22866
- };
22867
- const status = foldGroupStatus(
22868
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22869
- );
22870
- const group = {
23020
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23021
+ const type = {
22871
23022
  id: ruleId,
22872
23023
  category: apiCategory,
22873
23024
  subtype: ruleId,
22874
23025
  // human label comes with pack metadata later
22875
- severity,
22876
- match,
22877
- detection,
22878
- policy,
22879
- instanceCount: agg?.instanceCount ?? instances.length,
23026
+ severity: agg.severity ?? "low",
23027
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23028
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23029
+ instanceCount: agg.instanceCount,
22880
23030
  providers,
22881
23031
  aggregateAction,
22882
- latestDetectedAt,
22883
- instances,
22884
- status,
23032
+ latestDetectedAt: agg.latestDetectedAt,
23033
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22885
23034
  ...users.length > 0 ? { users } : {}
22886
23035
  };
22887
- if (agg) {
22888
- actionsCache.set(group, [...actionSet]);
22889
- if (agg.searchText !== void 0) {
22890
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22891
- }
23036
+ actionsCache.set(type, [...actionSet]);
23037
+ if (agg.searchText !== void 0) {
23038
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22892
23039
  }
22893
- groups.push(group);
23040
+ types.push(type);
22894
23041
  }
22895
- return groups;
23042
+ return types;
22896
23043
  }
22897
23044
  var haystackCache = /* @__PURE__ */ new WeakMap();
22898
- function buildHaystack(g, extra) {
23045
+ function buildHaystack(t, extra) {
22899
23046
  return [
22900
- g.subtype,
22901
- g.category,
22902
- g.match.maskedValue,
22903
- g.policy.name,
22904
- g.id,
22905
- ...g.instances.map((i) => i.repo),
22906
- ...g.instances.map((i) => i.file),
22907
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22908
- ...g.instances.map((i) => i.id),
22909
- // The people: the whole group's list when the store folded one, plus the
22910
- // preview's own — the two overlap, and a haystack does not mind.
22911
- ...(g.users ?? []).map((u) => u.name),
22912
- ...g.instances.map((i) => i.user?.name ?? ""),
23047
+ t.subtype,
23048
+ t.category,
23049
+ t.policy.name,
23050
+ t.id,
23051
+ ...(t.users ?? []).map((u) => u.name),
22913
23052
  ...extra === void 0 ? [] : [extra]
22914
23053
  ].join(" ").toLowerCase();
22915
23054
  }
22916
- function groupHaystack(g) {
22917
- const cached2 = haystackCache.get(g);
23055
+ function typeHaystack(t) {
23056
+ const cached2 = haystackCache.get(t);
22918
23057
  if (cached2 !== void 0) return cached2;
22919
- const haystack = buildHaystack(g);
22920
- haystackCache.set(g, haystack);
23058
+ const haystack = buildHaystack(t);
23059
+ haystackCache.set(t, haystack);
22921
23060
  return haystack;
22922
23061
  }
22923
23062
  var actionsCache = /* @__PURE__ */ new WeakMap();
22924
- function groupActions(g) {
22925
- const cached2 = actionsCache.get(g);
22926
- if (cached2 !== void 0) return cached2;
22927
- const actions = [...new Set(g.instances.map((i) => i.action))];
22928
- actionsCache.set(g, actions);
22929
- return actions;
23063
+ function typeActions(t) {
23064
+ return actionsCache.get(t) ?? [];
22930
23065
  }
22931
23066
  function countInstancesByStatus(statusInputs, statuses) {
22932
23067
  const statusSet = new Set(statuses);
@@ -22937,8 +23072,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22937
23072
  }
22938
23073
  return sum;
22939
23074
  }
22940
- function applyFindingFilters(groups, opts) {
22941
- let filtered = groups;
23075
+ function applyFindingFilters(types, opts) {
23076
+ let filtered = types;
22942
23077
  if (opts.severity && opts.severity.length > 0) {
22943
23078
  const sevSet = new Set(opts.severity);
22944
23079
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22949,7 +23084,7 @@ function applyFindingFilters(groups, opts) {
22949
23084
  }
22950
23085
  if (opts.actions && opts.actions.length > 0) {
22951
23086
  const actionSet = new Set(opts.actions);
22952
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23087
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22953
23088
  }
22954
23089
  if (opts.subtype && opts.subtype.length > 0) {
22955
23090
  const subtypeSet = new Set(opts.subtype);
@@ -22961,26 +23096,31 @@ function applyFindingFilters(groups, opts) {
22961
23096
  }
22962
23097
  if (opts.q) {
22963
23098
  const q = opts.q.toLowerCase();
22964
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23099
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22965
23100
  }
22966
23101
  return filtered;
22967
23102
  }
22968
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22969
- var SEVERITY_RANK = SEVERITY_ORDER;
23103
+ function rankByOrder(members2) {
23104
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23105
+ }
23106
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23107
+ function severityRank(severity) {
23108
+ return lookupOwn(SEVERITY_RANK, severity);
23109
+ }
22970
23110
  function compareFindingGroupOrder(a, b) {
22971
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22972
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23111
+ const rankA = severityRank(a.severity) ?? -1;
23112
+ const rankB = severityRank(b.severity) ?? -1;
22973
23113
  const severityDiff = rankA - rankB;
22974
23114
  if (severityDiff !== 0) return severityDiff;
22975
23115
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22976
23116
  if (recencyDiff !== 0) return recencyDiff;
22977
23117
  return a.id.localeCompare(b.id);
22978
23118
  }
22979
- function sortFindingGroups(groups) {
22980
- return [...groups].sort(compareFindingGroupOrder);
23119
+ function sortFindingTypes(types) {
23120
+ return [...types].sort(compareFindingGroupOrder);
22981
23121
  }
22982
- function computeFindingFacets(allGroups, opts) {
22983
- const forSeverity = applyFindingFilters(allGroups, {
23122
+ function computeFindingFacets(allTypes, opts) {
23123
+ const forSeverity = applyFindingFilters(allTypes, {
22984
23124
  providers: opts.providers,
22985
23125
  actions: opts.actions,
22986
23126
  statuses: opts.statuses,
@@ -22991,7 +23131,7 @@ function computeFindingFacets(allGroups, opts) {
22991
23131
  for (const g of forSeverity) {
22992
23132
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22993
23133
  }
22994
- const forProvider = applyFindingFilters(allGroups, {
23134
+ const forProvider = applyFindingFilters(allTypes, {
22995
23135
  actions: opts.actions,
22996
23136
  statuses: opts.statuses,
22997
23137
  q: opts.q,
@@ -23002,7 +23142,7 @@ function computeFindingFacets(allGroups, opts) {
23002
23142
  for (const g of forProvider) {
23003
23143
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23004
23144
  }
23005
- const forAction = applyFindingFilters(allGroups, {
23145
+ const forAction = applyFindingFilters(allTypes, {
23006
23146
  providers: opts.providers,
23007
23147
  statuses: opts.statuses,
23008
23148
  q: opts.q,
@@ -23011,9 +23151,9 @@ function computeFindingFacets(allGroups, opts) {
23011
23151
  });
23012
23152
  const actionMap = /* @__PURE__ */ new Map();
23013
23153
  for (const g of forAction) {
23014
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23154
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23015
23155
  }
23016
- const forSubtype = applyFindingFilters(allGroups, {
23156
+ const forSubtype = applyFindingFilters(allTypes, {
23017
23157
  providers: opts.providers,
23018
23158
  actions: opts.actions,
23019
23159
  statuses: opts.statuses,
@@ -23022,7 +23162,7 @@ function computeFindingFacets(allGroups, opts) {
23022
23162
  });
23023
23163
  const subtypeMap = /* @__PURE__ */ new Map();
23024
23164
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23025
- const forStatus = applyFindingFilters(allGroups, {
23165
+ const forStatus = applyFindingFilters(allTypes, {
23026
23166
  providers: opts.providers,
23027
23167
  actions: opts.actions,
23028
23168
  q: opts.q,
@@ -23044,6 +23184,20 @@ function computeFindingFacets(allGroups, opts) {
23044
23184
  }
23045
23185
 
23046
23186
  // ../../packages/schema/src/zod/findings-flat-build.ts
23187
+ function compareCodePoints(a, b) {
23188
+ const aIter = a[Symbol.iterator]();
23189
+ const bIter = b[Symbol.iterator]();
23190
+ for (; ; ) {
23191
+ const aNext = aIter.next();
23192
+ const bNext = bIter.next();
23193
+ if (aNext.done && bNext.done) return 0;
23194
+ if (aNext.done) return -1;
23195
+ if (bNext.done) return 1;
23196
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23197
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23198
+ if (aPoint !== bPoint) return aPoint - bPoint;
23199
+ }
23200
+ }
23047
23201
  function rowHaystack(row) {
23048
23202
  return [
23049
23203
  row.ruleId,
@@ -23068,12 +23222,24 @@ function matchesDimension(row, opts, dimension) {
23068
23222
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23069
23223
  case "statuses":
23070
23224
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23225
+ case "deliveries":
23226
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23071
23227
  case "tools":
23072
23228
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23229
+ // An EMPTY value is a real filter here, not an absent one. The location
23230
+ // list buckets a finding whose event recorded no repo — or no file — under
23231
+ // the empty string, and selecting that bucket has to narrow the panel to
23232
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23233
+ // row omits the key, which every call site already does.
23234
+ //
23235
+ // Reading '' as unset is what this replaced, and it failed in the one place
23236
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23237
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23238
+ // — a row reading 3 findings beside a panel listing every finding there is.
23073
23239
  case "repo":
23074
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23240
+ return opts.repo === void 0 || row.repo === opts.repo;
23075
23241
  case "file":
23076
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23242
+ return opts.file === void 0 || row.file === opts.file;
23077
23243
  case "q":
23078
23244
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23079
23245
  }
@@ -23084,6 +23250,7 @@ var DIMENSIONS = [
23084
23250
  "providers",
23085
23251
  "actions",
23086
23252
  "statuses",
23253
+ "deliveries",
23087
23254
  "tools",
23088
23255
  "repo",
23089
23256
  "file",
@@ -23097,10 +23264,19 @@ function matchesInstanceFilters(row, opts, except) {
23097
23264
  return true;
23098
23265
  }
23099
23266
  function toItems(counts) {
23100
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23267
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23268
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23269
+ // NFD spelling of the same text) as equal, so a count tie between
23270
+ // them would otherwise be ordered by whichever the Map iteration
23271
+ // produced. compareCodePoints breaks that tie deterministically, which
23272
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23273
+ // which it need not: foldFacetTuples runs this same sort over grouped
23274
+ // tuples, so both paths order facets identically by construction.
23275
+ compareCodePoints(a.value, b.value)
23276
+ );
23101
23277
  }
23102
- function bump(counts, value) {
23103
- counts.set(value, (counts.get(value) ?? 0) + 1);
23278
+ function bump(counts, value, by = 1) {
23279
+ counts.set(value, (counts.get(value) ?? 0) + by);
23104
23280
  }
23105
23281
  function createInstanceFacetAccumulator(opts) {
23106
23282
  const severity = /* @__PURE__ */ new Map();
@@ -23109,6 +23285,7 @@ function createInstanceFacetAccumulator(opts) {
23109
23285
  const action = /* @__PURE__ */ new Map();
23110
23286
  const status = /* @__PURE__ */ new Map();
23111
23287
  const tool = /* @__PURE__ */ new Map();
23288
+ const deployment = /* @__PURE__ */ new Map();
23112
23289
  return {
23113
23290
  add(row) {
23114
23291
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23123,6 +23300,9 @@ function createInstanceFacetAccumulator(opts) {
23123
23300
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23124
23301
  bump(tool, row.toolName);
23125
23302
  }
23303
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23304
+ bump(deployment, row.delivery.state);
23305
+ }
23126
23306
  },
23127
23307
  facets: () => ({
23128
23308
  severity: toItems(severity),
@@ -23130,7 +23310,8 @@ function createInstanceFacetAccumulator(opts) {
23130
23310
  provider: toItems(provider),
23131
23311
  action: toItems(action),
23132
23312
  status: toItems(status),
23133
- tool: toItems(tool)
23313
+ tool: toItems(tool),
23314
+ deployment: toItems(deployment)
23134
23315
  })
23135
23316
  };
23136
23317
  }
@@ -23144,6 +23325,7 @@ function toInstanceDetail(row) {
23144
23325
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23145
23326
  eventId: row.eventId,
23146
23327
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23328
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23147
23329
  ...row.user === void 0 ? {} : { user: row.user },
23148
23330
  action: toApiAction(row.actionTaken),
23149
23331
  detectedAt: row.occurredAt,
@@ -23158,12 +23340,6 @@ function toInstanceDetail(row) {
23158
23340
  policy: { id: `category:${category}`, name: category }
23159
23341
  };
23160
23342
  }
23161
- var SEVERITY_ORDER2 = {
23162
- critical: 0,
23163
- high: 1,
23164
- medium: 2,
23165
- low: 3
23166
- };
23167
23343
  function newLocationAccumulator() {
23168
23344
  return {
23169
23345
  instanceCount: 0,
@@ -23178,7 +23354,7 @@ function newLocationAccumulator() {
23178
23354
  }
23179
23355
  function addToLocation(acc, row) {
23180
23356
  acc.instanceCount += 1;
23181
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23357
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23182
23358
  if (rank < acc.maxSeverityRank) {
23183
23359
  acc.maxSeverityRank = rank;
23184
23360
  acc.maxSeverity = row.severity;
@@ -23187,6 +23363,23 @@ function addToLocation(acc, row) {
23187
23363
  acc.statuses.push(row.status);
23188
23364
  acc.ruleIds.add(row.ruleId);
23189
23365
  }
23366
+ function compareLocationOrder(a, b) {
23367
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23368
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23369
+ if (rankA !== rankB) return rankA - rankB;
23370
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23371
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23372
+ }
23373
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23374
+ if (repoDiff !== 0) return repoDiff;
23375
+ return compareCodePoints(a.file, b.file);
23376
+ }
23377
+ function encodeLocationId(repo, file2) {
23378
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23379
+ }
23380
+ function encodePart(value) {
23381
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23382
+ }
23190
23383
 
23191
23384
  // ../../packages/schema/src/zod/installed-pack.ts
23192
23385
  var InstalledPack = external_exports.object({
@@ -23254,6 +23447,11 @@ var Policy = external_exports.object({
23254
23447
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23255
23448
  provenance: PolicyProvenance.optional()
23256
23449
  }).meta({ id: "Policy" });
23450
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23451
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23452
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23453
+ id: "RedactFallback"
23454
+ });
23257
23455
  var PolicyBundle = external_exports.object({
23258
23456
  version: external_exports.string(),
23259
23457
  policies: external_exports.array(Policy),
@@ -23301,6 +23499,16 @@ var PolicyBundle = external_exports.object({
23301
23499
  // control plane), so no name resolution stands between the decision and the
23302
23500
  // comparison.
23303
23501
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23502
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23503
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23504
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23505
+ // a control plane can tighten a machine and never loosen one — the same
23506
+ // direction `mergeRaiseOnly` enforces for policies.
23507
+ //
23508
+ // Optional so an older backend, and an older on-disk cache, still parses;
23509
+ // absent leaves the device's own setting in force, which is the behaviour
23510
+ // that predates the field and the safe direction to default.
23511
+ redactFallback: RedactFallback.optional(),
23304
23512
  customKeywords: external_exports.array(external_exports.string()),
23305
23513
  fetchedAt: external_exports.iso.datetime()
23306
23514
  }).meta({ id: "PolicyBundle" });
@@ -23330,11 +23538,6 @@ function severityFloorPolicy(category) {
23330
23538
  const peak = CATEGORY_PEAK_SEVERITY[category];
23331
23539
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23332
23540
  }
23333
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23334
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23335
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23336
- id: "RedactFallback"
23337
- });
23338
23541
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23339
23542
  var BUILTIN_POLICY_SPECS = {
23340
23543
  monitor: {
@@ -23390,6 +23593,11 @@ function isActionAtLeast(action, floor) {
23390
23593
  function strongerAction(a, b) {
23391
23594
  return actionRank(a) >= actionRank(b) ? a : b;
23392
23595
  }
23596
+ function strongerRedactFallback(local, remote) {
23597
+ if (remote === void 0) return local;
23598
+ const localAction = builtinPolicyToAction(local);
23599
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23600
+ }
23393
23601
  function weakestBuiltinAtLeast(floor) {
23394
23602
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23395
23603
  }
@@ -23637,7 +23845,7 @@ function isVaultConsentValid(consent) {
23637
23845
  }
23638
23846
 
23639
23847
  // ../../packages/schema/src/zod/local.ts
23640
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23848
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23641
23849
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23642
23850
  var RunMode = external_exports.enum(["standalone", "attached"]);
23643
23851
  var ControlPlaneConnection = external_exports.object({
@@ -23657,6 +23865,15 @@ var HistorySyncConsent = external_exports.object({
23657
23865
  payloadVersion: external_exports.number().int().positive(),
23658
23866
  endpoint: external_exports.string()
23659
23867
  });
23868
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23869
+ var BodyRetention = external_exports.object({
23870
+ enabled: external_exports.boolean().default(false),
23871
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23872
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23873
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23874
+ // candidate set that is already bounded by "delivered, or never owed".
23875
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23876
+ }).meta({ id: "BodyRetention" });
23660
23877
  var WorkspaceSettings = external_exports.object({
23661
23878
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23662
23879
  runMode: RunMode.default("standalone"),
@@ -23700,12 +23917,18 @@ var WorkspaceSettings = external_exports.object({
23700
23917
  // covers the current payload and must be re-granted.
23701
23918
  modelJudgeConsent: ModelJudgeConsent.optional(),
23702
23919
  // Records that the user consented to the DEFERRED send — the outbox — along
23703
- // with the payload shape and the endpoint they agreed to. Since payload v2
23704
- // that covers both the pre-attach backlog and undelivered captures (which
23705
- // carry prompt/reply text in `content`); the key name predates the widening.
23706
- // Absent until granted, and a grant for a different endpoint or an older
23707
- // payload no longer counts.
23708
- historySyncConsent: HistorySyncConsent.optional()
23920
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23921
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23922
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23923
+ // both widenings. Absent until granted, and a grant for a different endpoint
23924
+ // or an older payload no longer counts.
23925
+ historySyncConsent: HistorySyncConsent.optional(),
23926
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23927
+ // body never removes the row or its findings.
23928
+ bodyRetention: BodyRetention.default({
23929
+ enabled: false,
23930
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23931
+ })
23709
23932
  });
23710
23933
  function defaultWorkspaceSettings() {
23711
23934
  return WorkspaceSettings.parse({});
@@ -23800,12 +24023,15 @@ function toCaptureAttributes(event) {
23800
24023
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23801
24024
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23802
24025
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24026
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23803
24027
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23804
24028
  // has ever populated either), but every legacy metadata key still rides
23805
24029
  // the bag rather than being silently dropped — CaptureAttributes'
23806
24030
  // `.catchall(z.unknown())` carries the long tail.
23807
24031
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23808
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24032
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24033
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24034
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23809
24035
  };
23810
24036
  }
23811
24037
  function captureDefinitionVersion(finding) {
@@ -23833,10 +24059,22 @@ var ManagedSettingKey = external_exports.enum([
23833
24059
  "vaultInlineReveal",
23834
24060
  "modelJudgeConsent",
23835
24061
  "dataSharesInPlace",
23836
- "redactFallback"
24062
+ "redactFallback",
24063
+ // Pins the toggle and the day count together — see BodyRetention on why the
24064
+ // two are one unit. An administrator mandating a window wants the count
24065
+ // enforced with it, not one a user can widen while the toggle stays on.
24066
+ "bodyRetention"
23837
24067
  ]).meta({ id: "ManagedSettingKey" });
24068
+ function isManagedSettingKey(value) {
24069
+ return ManagedSettingKey.safeParse(value).success;
24070
+ }
23838
24071
  var ManagedSettingsValues = external_exports.object({
23839
24072
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24073
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24074
+ // plain, non-strict objects: a key under either that this build does not know
24075
+ // is stripped and nothing reports it. The unknown-value split in
24076
+ // ManagedSettings below classifies top-level names only, so it stops at
24077
+ // these boundaries.
23840
24078
  controlPlane: external_exports.object({
23841
24079
  endpoint: external_exports.string().min(1),
23842
24080
  label: external_exports.string().min(1).optional()
@@ -23847,7 +24085,8 @@ var ManagedSettingsValues = external_exports.object({
23847
24085
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23848
24086
  modelJudgeConsent: external_exports.boolean().optional(),
23849
24087
  dataSharesInPlace: external_exports.boolean().optional(),
23850
- redactFallback: RedactFallback.optional()
24088
+ redactFallback: RedactFallback.optional(),
24089
+ bodyRetention: BodyRetention.optional()
23851
24090
  }).meta({ id: "ManagedSettingsValues" });
23852
24091
  var ManagedSettings = external_exports.object({
23853
24092
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23855,11 +24094,59 @@ var ManagedSettings = external_exports.object({
23855
24094
  // decision from a bug. Absent renders as a generic "your organization".
23856
24095
  organization: external_exports.string().min(1).optional(),
23857
24096
  // What the administrator pinned.
23858
- values: ManagedSettingsValues.default({}),
24097
+ //
24098
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24099
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24100
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24101
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24102
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24103
+ // exactly the file an administrator is most likely to write while a fleet
24104
+ // is mid-upgrade.
24105
+ //
24106
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24107
+ // file, which is the outcome the lock half already rejected — an older
24108
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24109
+ // value still fails, because the nested schema is re-run over the known
24110
+ // subset and its issues are re-raised on this parse.
24111
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23859
24112
  // Which of those the user may not change. A key here with no matching value
23860
24113
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23861
24114
  // the user may still override. The two are separable on purpose.
23862
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24115
+ //
24116
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24117
+ // build does not know is dropped from the locked set and reported, never a
24118
+ // reason to refuse the file. The same shape reaches an older build whenever
24119
+ // an administrator locks a key a newer build added, and refusing it there
24120
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24121
+ // the fleets most likely to carry a version skew. A name outside the enum
24122
+ // is still never HONOURED: the lockable set stays explicit above.
24123
+ lockedFields: external_exports.array(external_exports.string()).default([])
24124
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24125
+ const known = [];
24126
+ const unknown2 = [];
24127
+ for (const name of lockedFields) {
24128
+ if (isManagedSettingKey(name)) known.push(name);
24129
+ else unknown2.push(name);
24130
+ }
24131
+ const knownValues = /* @__PURE__ */ Object.create(null);
24132
+ const unknownValues = [];
24133
+ for (const [name, value] of Object.entries(values)) {
24134
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24135
+ else unknownValues.push(name);
24136
+ }
24137
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24138
+ if (!pinned.success) {
24139
+ for (const issue2 of pinned.error.issues)
24140
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24141
+ return external_exports.NEVER;
24142
+ }
24143
+ return {
24144
+ ...rest,
24145
+ values: pinned.data,
24146
+ lockedFields: known,
24147
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24148
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24149
+ };
23863
24150
  }).meta({ id: "ManagedSettings" });
23864
24151
 
23865
24152
  // ../../packages/schema/src/zod/project-files.ts
@@ -23983,7 +24270,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23983
24270
  timestamp: external_exports.iso.date(),
23984
24271
  critical: external_exports.number().int().nonnegative(),
23985
24272
  high: external_exports.number().int().nonnegative(),
23986
- medium: external_exports.number().int().nonnegative()
24273
+ medium: external_exports.number().int().nonnegative(),
24274
+ // Optional and additive, so a producer written against the earlier
24275
+ // three-series contract keeps validating. A consumer plotting it resolves the
24276
+ // absent case itself — the chart point requires a number.
24277
+ low: external_exports.number().int().nonnegative().optional()
23987
24278
  }).meta({ id: "FindingsTimeseriesPoint" });
23988
24279
  var FindingsTimeseriesResponse = external_exports.object({
23989
24280
  range: TimeRange,
@@ -24009,6 +24300,10 @@ var ResolvedFeedItem = external_exports.object({
24009
24300
  findingKey: external_exports.string(),
24010
24301
  ruleId: external_exports.string(),
24011
24302
  severity: Severity,
24303
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24304
+ // identifies the file: a bare path matches the same name in every repo.
24305
+ // Optional and additive; empty when the event carried no repo.
24306
+ repo: external_exports.string().optional(),
24012
24307
  path: external_exports.string(),
24013
24308
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24014
24309
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24114,7 +24409,23 @@ var SaveSettingsInput = external_exports.object({
24114
24409
  modelJudgeConsent: ModelJudgeConsentChoice,
24115
24410
  historySyncConsent: HistorySyncConsentChoice,
24116
24411
  vaultConsent: external_exports.string(),
24117
- vaultInlineReveal: external_exports.string()
24412
+ vaultInlineReveal: external_exports.string(),
24413
+ // Widened to `string` like its neighbours rather than typed as
24414
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24415
+ // the call site, so the domain check receives the type it was written for.
24416
+ //
24417
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24418
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24419
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24420
+ // trade against. The real cost runs the other way and is the part worth
24421
+ // knowing: a value this schema admits and the domain enum then rejects lands
24422
+ // on the action's shared refusal, which names NO field, where a shape
24423
+ // rejection reaches `malformedInput` and names the schema key.
24424
+ redactFallback: external_exports.string(),
24425
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24426
+ // `BodyRetention`'s and the action checks it there, so there is one place
24427
+ // that decides what a legal horizon is rather than two that can drift.
24428
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24118
24429
  });
24119
24430
  var AttachInput = external_exports.object({
24120
24431
  endpoint: external_exports.string(),
@@ -24286,6 +24597,52 @@ function reviewSeverityRank(reasons) {
24286
24597
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24287
24598
  }
24288
24599
 
24600
+ // ../../packages/schema/src/zod/web-capture.ts
24601
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24602
+ var WebUsage = external_exports.object({
24603
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24604
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24605
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24606
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24607
+ });
24608
+ var WebToolCall = external_exports.object({
24609
+ toolUseId: external_exports.string().min(1),
24610
+ toolName: external_exports.string().min(1),
24611
+ target: external_exports.string().optional(),
24612
+ isError: external_exports.boolean().optional(),
24613
+ inputSize: external_exports.number().int().nonnegative().optional(),
24614
+ outputSize: external_exports.number().int().nonnegative().optional()
24615
+ });
24616
+ var WebExchange = external_exports.object({
24617
+ messageId: external_exports.string().min(1),
24618
+ startedAt: external_exports.iso.datetime(),
24619
+ model: external_exports.string().optional(),
24620
+ usage: WebUsage.optional(),
24621
+ usageSource: WebUsageSource,
24622
+ stopReason: external_exports.string().optional(),
24623
+ conversationId: external_exports.string().optional(),
24624
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24625
+ toolCalls: external_exports.array(WebToolCall).default([]),
24626
+ // Absent when the adapter recovered no text. Capped by the caller at
24627
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24628
+ // short capture is never mistaken for a short reply.
24629
+ responseText: external_exports.string().optional(),
24630
+ truncated: external_exports.boolean().default(false)
24631
+ });
24632
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24633
+ var WebCaptureStatus = external_exports.object({
24634
+ patched: external_exports.boolean(),
24635
+ live: external_exports.boolean(),
24636
+ blind: external_exports.boolean(),
24637
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24638
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24639
+ parseFailures: external_exports.number().int().nonnegative(),
24640
+ unparsedBodies: external_exports.number().int().nonnegative(),
24641
+ // The adapter-declared JSON key paths that were absent from a real payload —
24642
+ // the earliest signal that a site's contract moved.
24643
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24644
+ });
24645
+
24289
24646
  // ../../packages/persistence/src/paths.ts
24290
24647
  import {
24291
24648
  chmodSync,
@@ -24646,6 +25003,22 @@ function discardStore(file2, backup) {
24646
25003
  }
24647
25004
  }
24648
25005
 
25006
+ // ../../packages/persistence/src/internal/sql-functions.ts
25007
+ var utf8 = new TextDecoder();
25008
+ function akaLower(value) {
25009
+ if (value === null) return null;
25010
+ if (typeof value === "string") return value.toLowerCase();
25011
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25012
+ return utf8.decode(value).toLowerCase();
25013
+ }
25014
+ function registerSqlFunctions(db) {
25015
+ db.function(
25016
+ "aka_lower",
25017
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25018
+ akaLower
25019
+ );
25020
+ }
25021
+
24649
25022
  // ../../packages/persistence/src/internal/sql-text.ts
24650
25023
  function escapeLikePattern(s) {
24651
25024
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24730,6 +25103,11 @@ function schemaObjectExists(db, kind, name) {
24730
25103
  function indexExists(db, name) {
24731
25104
  return schemaObjectExists(db, "index", name);
24732
25105
  }
25106
+ function indexColumns(db, name) {
25107
+ if (!indexExists(db, name)) return [];
25108
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25109
+ return columns.map((c) => c.name).filter((c) => c !== null);
25110
+ }
24733
25111
  function columnNames(db, table2, opts) {
24734
25112
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24735
25113
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24791,139 +25169,781 @@ function mapRowsTolerant(rows, map2) {
24791
25169
  return out;
24792
25170
  }
24793
25171
 
24794
- // ../../packages/persistence/src/migrations.ts
24795
- function describeObject(object2) {
24796
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24797
- }
24798
- function splitStatements(sql) {
24799
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24800
- }
24801
- function createdIndexName(statement) {
24802
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24803
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25172
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25173
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25174
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25175
+
25176
+ // ../../packages/persistence/src/sync-failure.ts
25177
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25178
+ function syncFailureRejectCondition(column = "sync_failure") {
25179
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25180
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24804
25181
  }
24805
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24806
- function applyMigrations(db, file2) {
24807
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24808
- db.exec(
24809
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24810
- );
24811
- const applied = new Set(
24812
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24813
- );
24814
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24815
- const record2 = db.prepare(
24816
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24817
- );
24818
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24819
- if (applied.has(migration.tag)) continue;
24820
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24821
- const evidence = evidenceObjects(migration.sql);
24822
- const present2 = evidence.filter((o) => evidenceExists(db, o));
24823
- if (present2.length > 0 && present2.length < evidence.length) {
24824
- const missing = evidence.filter((o) => !present2.includes(o));
24825
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present2.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24826
- akaWarn(message);
24827
- throw new Error(`[aka] ${message}`);
24828
- }
24829
- const alreadyApplied = evidence.length > 0 ? present2.length === evidence.length : preLedgerStore && index < legacyCount;
24830
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24831
- const statements = splitStatements(migration.sql);
24832
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24833
- try {
24834
- withTransaction(
24835
- db,
24836
- () => {
24837
- for (const statement of statements) {
24838
- const indexName = createdIndexName(statement);
24839
- if (indexName === void 0) {
24840
- if (alreadyApplied) continue;
24841
- } else if (indexExists(db, indexName)) {
24842
- continue;
24843
- }
24844
- db.exec(statement);
24845
- }
24846
- if (wantsFkOff && !alreadyApplied) {
24847
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24848
- if (violations.length > 0) {
24849
- throw new Error(
24850
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24851
- );
24852
- }
24853
- }
24854
- record2.run(migration.tag, Date.now());
24855
- },
24856
- "IMMEDIATE"
24857
- );
24858
- } finally {
24859
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24860
- }
25182
+
25183
+ // ../../packages/persistence/src/repositories/history-sync.ts
25184
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25185
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25186
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25187
+ var COUNTED_EVENT_TYPES = [
25188
+ ...STRUCTURAL_EVENT_TYPES,
25189
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25190
+ ];
25191
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25192
+ var PARTITION_BUCKETS = `
25193
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25194
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25195
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25196
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25197
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25198
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25199
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25200
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25201
+ -- added later lands in no bucket and fails the sum assertion, instead
25202
+ -- of silently joining this one.
25203
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25204
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25205
+ THEN 1 ELSE 0 END) AS failed,
25206
+ COUNT(*) AS total`;
25207
+ var COUNTED_SCOPE = `
25208
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25209
+ AND (
25210
+ event_type IN (${TYPE_LIST})
25211
+ OR synced_at IS NOT NULL
25212
+ OR outbox_owed = 1
25213
+ )`;
25214
+ var SKIPPED = -1;
25215
+ var ROW_COLUMNS = `id,
25216
+ parent_id AS parentId,
25217
+ root_session_id AS rootSessionId,
25218
+ event_type AS eventType,
25219
+ host_id AS hostId,
25220
+ harness_id AS harnessId,
25221
+ source_project_id AS sourceProjectId,
25222
+ started_at AS startedAt,
25223
+ ended_at AS endedAt,
25224
+ severity,
25225
+ priority,
25226
+ content,
25227
+ content_hash AS contentHash,
25228
+ attributes`;
25229
+ var SqliteHistorySyncRepository = class {
25230
+ constructor(db) {
25231
+ this.db = db;
25232
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25233
+ this.sessionsStmt = db.prepare(
25234
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25235
+ FROM audit_events
25236
+ WHERE synced_at IS NULL
25237
+ AND event_type IN (${TYPE_LIST})
25238
+ AND started_at < :before
25239
+ GROUP BY sessionId
25240
+ ORDER BY earliest
25241
+ LIMIT :limit`
25242
+ );
25243
+ this.rowsStmt = db.prepare(
25244
+ `SELECT ${ROW_COLUMNS}
25245
+ FROM audit_events
25246
+ WHERE synced_at IS NULL
25247
+ AND event_type IN (${TYPE_LIST})
25248
+ AND started_at < :before
25249
+ AND COALESCE(root_session_id, id) = :sessionId
25250
+ ORDER BY (event_type = 'session') DESC, started_at
25251
+ LIMIT :limit`
25252
+ );
25253
+ this.captureRowsStmt = db.prepare(
25254
+ `SELECT ${ROW_COLUMNS}
25255
+ FROM audit_events
25256
+ WHERE synced_at IS NULL
25257
+ AND sync_claimed_at IS NULL
25258
+ AND outbox_owed = 1
25259
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25260
+ AND started_at < :before
25261
+ ORDER BY started_at
25262
+ LIMIT :limit`
25263
+ );
25264
+ this.markOwedStmt = db.prepare(
25265
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25266
+ );
25267
+ this.markCaptureBacklogOwedStmt = db.prepare(
25268
+ `UPDATE audit_events SET outbox_owed = 1
25269
+ WHERE synced_at IS NULL
25270
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25271
+ AND started_at < :before`
25272
+ );
25273
+ this.stampStmt = db.prepare(
25274
+ `UPDATE audit_events
25275
+ SET synced_at = :at,
25276
+ sync_claimed_at = NULL,
25277
+ sync_failed_at = :failedAt,
25278
+ sync_failure = :failure
25279
+ WHERE id = :id`
25280
+ );
25281
+ this.claimRowStmt = db.prepare(
25282
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25283
+ );
25284
+ this.releaseRowStmt = db.prepare(
25285
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25286
+ );
25287
+ this.releaseStaleClaimsStmt = db.prepare(
25288
+ `UPDATE audit_events SET sync_claimed_at = NULL
25289
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25290
+ );
25291
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25292
+ FROM audit_events${COUNTED_SCOPE}`);
25293
+ this.partitionByKindStmt = db.prepare(
25294
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25295
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25296
+ GROUP BY event_type`
25297
+ );
25298
+ this.countsStmt = db.prepare(
25299
+ `SELECT
25300
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25301
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25302
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25303
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25304
+ THEN 1 ELSE 0 END) AS skipped,
25305
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25306
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25307
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25308
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25309
+ FROM audit_events
25310
+ WHERE event_type IN (${TYPE_LIST})`
25311
+ );
25312
+ this.captureSkipCountStmt = db.prepare(
25313
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25314
+ // way the structural totals are. The split exists because a refusal is
25315
+ // terminal only against the deployment that gave it, and the structural
25316
+ // re-arm frees it on a change of deployment. The capture lane has no such
25317
+ // escape: re-arming a capture would offer one deployment's undelivered
25318
+ // prompts, with their text, to a deployment that never saw them, which is
25319
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25320
+ // reasons mean the same thing — this row will not be sent — and splitting
25321
+ // them would put refused captures in a bucket nothing reads and nothing
25322
+ // frees.
25323
+ `SELECT COUNT(*) AS skipped
25324
+ FROM audit_events
25325
+ WHERE synced_at = ${String(SKIPPED)}
25326
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25327
+ );
25328
+ this.fingerprintStmt = db.prepare(
25329
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25330
+ FROM history_sync WHERE id = 1`
25331
+ );
25332
+ this.setFingerprintStmt = db.prepare(
25333
+ `UPDATE history_sync
25334
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25335
+ WHERE id = 1`
25336
+ );
25337
+ this.disownCapturesStmt = db.prepare(
25338
+ `UPDATE audit_events SET outbox_owed = NULL
25339
+ WHERE outbox_owed IS NOT NULL
25340
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25341
+ AND started_at < :attachedAt`
25342
+ );
25343
+ this.rearmStmt = db.prepare(
25344
+ `UPDATE audit_events
25345
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25346
+ WHERE (synced_at > 0
25347
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25348
+ AND event_type IN (${TYPE_LIST})`
25349
+ );
25350
+ this.claimStmt = db.prepare(
25351
+ `UPDATE history_sync
25352
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25353
+ WHERE id = 1
25354
+ AND (owner_pid IS NULL
25355
+ OR heartbeat_at IS NULL
25356
+ OR heartbeat_at < :staleBefore
25357
+ OR heartbeat_at > :now)`
25358
+ );
25359
+ this.heartbeatStmt = db.prepare(
25360
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25361
+ );
25362
+ this.releaseStmt = db.prepare(
25363
+ `UPDATE history_sync
25364
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25365
+ WHERE id = 1 AND owner_pid = :pid`
25366
+ );
25367
+ this.closeWindowStmt = db.prepare(
25368
+ `UPDATE audit_events
25369
+ SET synced_at = ${String(SKIPPED)},
25370
+ sync_failed_at = :at,
25371
+ sync_failure = 'detached_undelivered'
25372
+ WHERE synced_at IS NULL
25373
+ AND event_type IN (${TYPE_LIST})
25374
+ AND started_at >= :attachedAt`
25375
+ );
25376
+ this.releaseBoundaryStmt = db.prepare(
25377
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25378
+ );
25379
+ this.freezeBoundaryStmt = db.prepare(
25380
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25381
+ );
25382
+ this.leaseStmt = db.prepare(
25383
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25384
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25385
+ FROM history_sync WHERE id = 1`
25386
+ );
25387
+ this.inspectionsStmt = db.prepare(
25388
+ `SELECT d.rule_id AS ruleId,
25389
+ d.name AS ruleName,
25390
+ d.version AS ruleVersion,
25391
+ d.category AS category,
25392
+ d.severity AS severity,
25393
+ f.span_start AS spanStart,
25394
+ f.span_end AS spanEnd,
25395
+ f.masked_match AS maskedMatch,
25396
+ f.action_taken AS actionTaken,
25397
+ f.confidence AS confidence
25398
+ FROM inspection_findings f
25399
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25400
+ WHERE f.audit_event_id = :auditEventId
25401
+ ORDER BY f.span_start, f.id`
25402
+ );
24861
25403
  }
24862
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24863
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25404
+ db;
25405
+ ensureRowStmt;
25406
+ sessionsStmt;
25407
+ rowsStmt;
25408
+ stampStmt;
25409
+ countsStmt;
25410
+ fingerprintStmt;
25411
+ setFingerprintStmt;
25412
+ rearmStmt;
25413
+ claimStmt;
25414
+ heartbeatStmt;
25415
+ releaseStmt;
25416
+ leaseStmt;
25417
+ inspectionsStmt;
25418
+ closeWindowStmt;
25419
+ releaseBoundaryStmt;
25420
+ freezeBoundaryStmt;
25421
+ captureRowsStmt;
25422
+ markOwedStmt;
25423
+ markCaptureBacklogOwedStmt;
25424
+ captureSkipCountStmt;
25425
+ disownCapturesStmt;
25426
+ partitionStmt;
25427
+ partitionByKindStmt;
25428
+ claimRowStmt;
25429
+ releaseRowStmt;
25430
+ releaseStaleClaimsStmt;
25431
+ /**
25432
+ * The masked detections recorded against one tool call.
25433
+ *
25434
+ * These travel with the event because a tool call's target is not
25435
+ * re-inspectable from the event alone — unlike a capture, where the text
25436
+ * itself is re-scannable. What crosses is the masked match and the rule that
25437
+ * produced it, never the value.
25438
+ */
25439
+ inspectionsFor(auditEventId) {
25440
+ return allRows(this.inspectionsStmt, { auditEventId });
24864
25441
  }
24865
- ensureSyncedAtColumn(db, "audit_events");
24866
- ensureScanLedgerTable(db);
24867
- ensureHistorySyncTable(db);
24868
- ensureBlockedDetectionsTable(db);
24869
- ensureRuleProbeCacheTable(db);
24870
- ensureWriteGateTrigger(db);
24871
- ensureTokenUsageColumns(db);
24872
- reconcileSourceProjectIds(db);
24873
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24874
- const drained = runLegacyHistoryBackfill(db);
24875
- if (drained) applyLegacyDropMigration(db, file2);
25442
+ /**
25443
+ * Sessions with structural rows still to send, oldest first.
25444
+ *
25445
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25446
+ * read. Anything recorded after the machine attached is the live forward
25447
+ * path's to deliver; this drain exists for what was recorded before it, and a
25448
+ * row both paths send is at best a duplicate request and at worst — for a
25449
+ * session root — an overwrite of the inventory ids the live path resolved.
25450
+ */
25451
+ pendingSessions(limit, before) {
25452
+ return allRows(this.sessionsStmt, { limit, before }).map(
25453
+ (r) => r.sessionId
25454
+ );
24876
25455
  }
24877
- }
24878
- function readLegacyTables(db) {
24879
- let holdsRows = false;
24880
- const marks = [];
24881
- for (const table2 of ["events", "findings"]) {
24882
- try {
24883
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
24884
- if (row === void 0) {
24885
- holdsRows = true;
24886
- marks.push(`${table2}:unreadable`);
24887
- continue;
24888
- }
24889
- if (row.n > 0) holdsRows = true;
24890
- marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
24891
- } catch {
24892
- holdsRows = true;
24893
- marks.push(`${table2}:unreadable`);
24894
- }
25456
+ /** One session's undelivered structural rows within the backlog, root first. */
25457
+ pendingRows(sessionId, limit, before) {
25458
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24895
25459
  }
24896
- return { holdsRows, mark: marks.join("|") };
24897
- }
24898
- function applyLegacyDropMigration(db, file2) {
24899
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24900
- if (!migration) return;
24901
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24902
- if (file2 !== void 0 && before?.holdsRows === true) {
24903
- try {
24904
- backupBeforeLegacyDrop(db, file2);
24905
- } catch (error61) {
24906
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24907
- return;
24908
- }
25460
+ /**
25461
+ * Captures this machine still owes the deployment, oldest first.
25462
+ *
25463
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25464
+ * by a time window — see captureRowsStmt for why a window could not express
25465
+ * this. `before` is the grace window that leaves a just-recorded capture to
25466
+ * the live path.
25467
+ */
25468
+ pendingCaptureRows(limit, before) {
25469
+ return allRows(this.captureRowsStmt, { limit, before });
24909
25470
  }
24910
- try {
25471
+ /**
25472
+ * Record that a capture is OWED to the deployment.
25473
+ *
25474
+ * Written by the attached forward path when a live send did not confirm
25475
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25476
+ * a fact rather than an inference: the machine was attached, the send did not
25477
+ * land, so the row is owed — which no time window can state, because the same
25478
+ * window that holds the rows a past attachment left owed also holds every
25479
+ * capture recorded while the machine was DETACHED, and those were never
25480
+ * offered to anyone.
25481
+ *
25482
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25483
+ * out of the drain's read.
25484
+ */
25485
+ markCaptureOwed(id) {
25486
+ this.markOwedStmt.run({ id });
25487
+ }
25488
+ /**
25489
+ * Mark every capture already on disk as owed, as of `before`.
25490
+ *
25491
+ * The consent-time backfill, called once from `aka attach` when a human
25492
+ * grants existing-history consent — never from an ongoing drain pass, and
25493
+ * never inferred from a boundary that could later move. `before` is the
25494
+ * caller's own "now" at the moment consent was granted, so what this marks
25495
+ * is exactly the backlog the consent prompt already counted, not whatever a
25496
+ * later re-attach or key rotation might widen it to.
25497
+ *
25498
+ * Returns how many rows matched, for the caller to log or test against. Not a
25499
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25500
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25501
+ */
25502
+ markCaptureBacklogOwed(before) {
25503
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25504
+ }
25505
+ /**
25506
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25507
+ *
25508
+ * CLEARS any failure reason in the same statement. A row that failed against
25509
+ * one deployment and then landed is delivered, and leaving the reason behind
25510
+ * would leave the store holding two contradictory answers about one row —
25511
+ * with the surface free to render either.
25512
+ */
25513
+ markSynced(ids, atMs) {
25514
+ this.stampAll(ids, atMs, null);
25515
+ }
25516
+ /**
25517
+ * Record that THIS MACHINE cannot express the row on the wire.
25518
+ *
25519
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25520
+ * payload, or a body the client itself refused to send. It fails identically
25521
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25522
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25523
+ * is retried; marking those would turn one outage into permanent data loss.
25524
+ */
25525
+ markSkipped(ids, atMs) {
25526
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25527
+ }
25528
+ /**
25529
+ * Record that THIS DEPLOYMENT refused the row.
25530
+ *
25531
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25532
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25533
+ * row is outstanding rather than why. What separates them is the reason, and
25534
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25535
+ * on one body, so it is terminal only for as long as this machine points at
25536
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25537
+ *
25538
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25539
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25540
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25541
+ */
25542
+ markRefused(ids, atMs) {
25543
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25544
+ }
25545
+ eachInTransaction(ids, run) {
25546
+ if (ids.length === 0) return;
24911
25547
  withTransaction(
24912
- db,
25548
+ this.db,
24913
25549
  () => {
24914
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24915
- if (alreadyDropped) return;
24916
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24917
- akaWarn(
24918
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24919
- );
24920
- return;
24921
- }
24922
- for (const statement of splitStatements(migration.sql)) {
24923
- db.exec(statement);
24924
- }
24925
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24926
- migration.tag,
25550
+ for (const id of ids) run(id);
25551
+ },
25552
+ "IMMEDIATE"
25553
+ );
25554
+ }
25555
+ stampAll(ids, value, failure, failedAtMs) {
25556
+ if (ids.length === 0) return;
25557
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25558
+ withTransaction(
25559
+ this.db,
25560
+ () => {
25561
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25562
+ },
25563
+ "IMMEDIATE"
25564
+ );
25565
+ }
25566
+ /**
25567
+ * Claim rows as in-flight.
25568
+ *
25569
+ * Advisory in exactly the sense the lease is: it records that a send is in
25570
+ * progress so a surface can say so, and a lost claim costs a row showing as
25571
+ * queued while it is actually being sent. It is not exclusion — the far side
25572
+ * settles a duplicate on the row id.
25573
+ */
25574
+ claimRows(ids, atMs) {
25575
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25576
+ }
25577
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25578
+ releaseRows(ids) {
25579
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25580
+ }
25581
+ /**
25582
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25583
+ *
25584
+ * A process killed between claiming and settling leaves rows claimed with
25585
+ * nothing left to settle them. Without this they read as "sending" for ever.
25586
+ */
25587
+ releaseStaleClaims(staleBefore) {
25588
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25589
+ }
25590
+ /**
25591
+ * Every tracked row in exactly one delivery state.
25592
+ *
25593
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25594
+ * pick up now", which is a different question from "what state is this row
25595
+ * in" — and a machine that has never attached has no boundary to pass, so
25596
+ * requiring one would force a caller to invent one and report the whole store
25597
+ * as queued.
25598
+ */
25599
+ /**
25600
+ * The same partition, one row per kind that a lane carries.
25601
+ *
25602
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25603
+ * scope decides which rows exist at all, so a kind that has never been
25604
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25605
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25606
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25607
+ * different things.
25608
+ */
25609
+ partitionByKind() {
25610
+ return allRows(
25611
+ this.partitionByKindStmt,
25612
+ {}
25613
+ ).map((row) => ({
25614
+ kind: row.kind,
25615
+ queued: row.queued ?? 0,
25616
+ inProgress: row.inProgress ?? 0,
25617
+ synced: row.synced ?? 0,
25618
+ failed: row.failed ?? 0,
25619
+ refused: row.refused ?? 0,
25620
+ detached: row.detached ?? 0,
25621
+ total: row.total ?? 0
25622
+ }));
25623
+ }
25624
+ partition() {
25625
+ const row = getRow(this.partitionStmt, {});
25626
+ return {
25627
+ queued: row?.queued ?? 0,
25628
+ inProgress: row?.inProgress ?? 0,
25629
+ synced: row?.synced ?? 0,
25630
+ failed: row?.failed ?? 0,
25631
+ refused: row?.refused ?? 0,
25632
+ detached: row?.detached ?? 0,
25633
+ total: row?.total ?? 0
25634
+ };
25635
+ }
25636
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25637
+ counts(before) {
25638
+ const row = getRow(this.countsStmt, { before });
25639
+ const captures = getRow(this.captureSkipCountStmt);
25640
+ return {
25641
+ pending: row?.pending ?? 0,
25642
+ sent: row?.sent ?? 0,
25643
+ skipped: row?.skipped ?? 0,
25644
+ refused: row?.refused ?? 0,
25645
+ detached: row?.detached ?? 0,
25646
+ capturesSkipped: captures?.skipped ?? 0
25647
+ };
25648
+ }
25649
+ /**
25650
+ * The deployment the current stamps were made against, and where its backlog
25651
+ * ends.
25652
+ *
25653
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25654
+ * machine that has never drained is — and every writer below seeds the row
25655
+ * before it needs one, so nothing depends on this creating it. Keeping the
25656
+ * write off the gate path matters because the gate runs on every pass while a
25657
+ * write has to take the database's write lock.
25658
+ */
25659
+ deployment() {
25660
+ const row = getRow(
25661
+ this.fingerprintStmt
25662
+ );
25663
+ return {
25664
+ fingerprint: row?.fingerprint ?? void 0,
25665
+ backlogBefore: row?.backlogBefore ?? void 0
25666
+ };
25667
+ }
25668
+ /**
25669
+ * Point the ledger at a different deployment, discarding what it recorded
25670
+ * about the previous one.
25671
+ *
25672
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25673
+ * machine has just left are undelivered as far as the new one is concerned.
25674
+ * All four in one transaction, so a crash between them cannot leave stamps
25675
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25676
+ * a disown with no re-mark to follow it.
25677
+ *
25678
+ * The boundary is written HERE and only here, which is what freezes it: a
25679
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25680
+ * unchanged, so this never runs and the backlog does not widen back over rows
25681
+ * the live path has since delivered.
25682
+ *
25683
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25684
+ * granted existing-history consent for the deployment this call is arming —
25685
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25686
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25687
+ * apart. Passed only when that grant is valid, since this method has no way
25688
+ * to check consent itself and must not mark a row owed for a machine that
25689
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25690
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25691
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25692
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25693
+ * on the cleared side of that bound — and the re-mark in the same
25694
+ * transaction is what puts those rows back. A crash between the two cannot
25695
+ * strand the ledger disowned with nothing re-marked — the transaction either
25696
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25697
+ * committed re-enters this method on the very next pass. Omit it (the
25698
+ * structural-only tests do) to exercise the disown in isolation.
25699
+ *
25700
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25701
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25702
+ * live path can mark a capture owed from the moment `aka attach` writes the
25703
+ * descriptor, before the drain's first pass ever reaches this method, and
25704
+ * such a row sits at or after the bound rather than below it. What keeps the
25705
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25706
+ * bound — disown runs first, re-mark second, both inside the one
25707
+ * transaction above.
25708
+ */
25709
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25710
+ this.ensureRowStmt.run();
25711
+ withTransaction(
25712
+ this.db,
25713
+ () => {
25714
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25715
+ this.rearmStmt.run();
25716
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25717
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25718
+ }
25719
+ if (backfillCapturesBefore !== void 0) {
25720
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25721
+ }
25722
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25723
+ },
25724
+ "IMMEDIATE"
25725
+ );
25726
+ }
25727
+ /**
25728
+ * End the attached period: hand its rows to the live path, and release the
25729
+ * boundary so the next attachment can freeze a new one.
25730
+ *
25731
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25732
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25733
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25734
+ * during the detached period, because the machine is not attached. Rows
25735
+ * recorded in that window sit after the boundary and before the re-attach, so
25736
+ * neither path takes them, and the pending count reports none outstanding.
25737
+ *
25738
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25739
+ * closing attachment's to deliver and are no longer outstanding — that is what
25740
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25741
+ * distinction is not academic: this used to write a delivery TIME, which every
25742
+ * read treats as delivery, so one detach turned a window of undelivered rows
25743
+ * into a window of delivered ones and no surface could tell. It writes the
25744
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25745
+ * "received" stop being the same fact.
25746
+ *
25747
+ * A change of deployment still frees them (see the re-arm), because the next
25748
+ * deployment has seen none of this machine's history — so the rows reach it
25749
+ * exactly as they did when this wrote a delivery time.
25750
+ *
25751
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25752
+ * window unstamped — that half-state would re-send the whole attached period
25753
+ * on the next attach, which is the failure the boundary exists to prevent.
25754
+ */
25755
+ closeAttachedWindow(attachedAtMs, atMs) {
25756
+ this.ensureRowStmt.run();
25757
+ withTransaction(
25758
+ this.db,
25759
+ () => {
25760
+ const row = getRow(this.fingerprintStmt);
25761
+ const from = row?.backlogBefore ?? attachedAtMs;
25762
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25763
+ this.releaseBoundaryStmt.run();
25764
+ },
25765
+ "IMMEDIATE"
25766
+ );
25767
+ }
25768
+ /**
25769
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25770
+ *
25771
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25772
+ * different deployment and therefore discards what was delivered to the old
25773
+ * one: here the recipient is the same, so everything already sent to it stays
25774
+ * sent.
25775
+ */
25776
+ freezeBoundary(backlogBefore) {
25777
+ this.ensureRowStmt.run();
25778
+ this.freezeBoundaryStmt.run({ backlogBefore });
25779
+ }
25780
+ /** Take the claim, or report that someone live already holds it. */
25781
+ claim(pid, host, nowMs, staleAfterMs) {
25782
+ this.ensureRowStmt.run();
25783
+ let taken = false;
25784
+ withTransaction(
25785
+ this.db,
25786
+ () => {
25787
+ const result = this.claimStmt.run({
25788
+ pid,
25789
+ host,
25790
+ now: nowMs,
25791
+ staleBefore: nowMs - staleAfterMs
25792
+ });
25793
+ taken = result.changes === 1;
25794
+ },
25795
+ "IMMEDIATE"
25796
+ );
25797
+ return taken;
25798
+ }
25799
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25800
+ heartbeat(pid, nowMs) {
25801
+ this.heartbeatStmt.run({ now: nowMs, pid });
25802
+ }
25803
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25804
+ release(pid) {
25805
+ this.releaseStmt.run({ pid });
25806
+ }
25807
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25808
+ lease() {
25809
+ return getRow(this.leaseStmt);
25810
+ }
25811
+ };
25812
+
25813
+ // ../../packages/persistence/src/migrations.ts
25814
+ function describeObject(object2) {
25815
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25816
+ }
25817
+ function splitStatements(sql) {
25818
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25819
+ }
25820
+ function createdIndexName(statement) {
25821
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25822
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25823
+ }
25824
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25825
+ function applyMigrations(db, file2, options = {}) {
25826
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25827
+ db.exec(
25828
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25829
+ );
25830
+ const applied = new Set(
25831
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25832
+ );
25833
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25834
+ const record2 = db.prepare(
25835
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25836
+ );
25837
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25838
+ if (applied.has(migration.tag)) continue;
25839
+ if (options.skipTags?.has(migration.tag) === true) continue;
25840
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25841
+ const evidence = evidenceObjects(migration.sql);
25842
+ const present2 = evidence.filter((o) => evidenceExists(db, o));
25843
+ if (present2.length > 0 && present2.length < evidence.length) {
25844
+ const missing = evidence.filter((o) => !present2.includes(o));
25845
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present2.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25846
+ akaWarn(message);
25847
+ throw new Error(`[aka] ${message}`);
25848
+ }
25849
+ const alreadyApplied = evidence.length > 0 ? present2.length === evidence.length : preLedgerStore && index < legacyCount;
25850
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25851
+ const statements = splitStatements(migration.sql);
25852
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25853
+ try {
25854
+ withTransaction(
25855
+ db,
25856
+ () => {
25857
+ for (const statement of statements) {
25858
+ const indexName = createdIndexName(statement);
25859
+ if (indexName === void 0) {
25860
+ if (alreadyApplied) continue;
25861
+ } else if (indexExists(db, indexName)) {
25862
+ continue;
25863
+ }
25864
+ db.exec(statement);
25865
+ }
25866
+ if (wantsFkOff && !alreadyApplied) {
25867
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25868
+ if (violations.length > 0) {
25869
+ throw new Error(
25870
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25871
+ );
25872
+ }
25873
+ }
25874
+ record2.run(migration.tag, Date.now());
25875
+ },
25876
+ "IMMEDIATE"
25877
+ );
25878
+ } finally {
25879
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25880
+ }
25881
+ }
25882
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25883
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25884
+ }
25885
+ ensureSyncedAtColumn(db, "audit_events");
25886
+ ensureScanLedgerTable(db);
25887
+ ensureHistorySyncTable(db);
25888
+ ensureBlockedDetectionsTable(db);
25889
+ ensureRuleProbeCacheTable(db);
25890
+ ensureWriteGateTrigger(db);
25891
+ ensureTokenUsageColumns(db);
25892
+ reconcileSourceProjectIds(db);
25893
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25894
+ const drained = runLegacyHistoryBackfill(db);
25895
+ if (drained) applyLegacyDropMigration(db, file2);
25896
+ }
25897
+ }
25898
+ function readLegacyTables(db) {
25899
+ let holdsRows = false;
25900
+ const marks = [];
25901
+ for (const table2 of ["events", "findings"]) {
25902
+ try {
25903
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
25904
+ if (row === void 0) {
25905
+ holdsRows = true;
25906
+ marks.push(`${table2}:unreadable`);
25907
+ continue;
25908
+ }
25909
+ if (row.n > 0) holdsRows = true;
25910
+ marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
25911
+ } catch {
25912
+ holdsRows = true;
25913
+ marks.push(`${table2}:unreadable`);
25914
+ }
25915
+ }
25916
+ return { holdsRows, mark: marks.join("|") };
25917
+ }
25918
+ function applyLegacyDropMigration(db, file2) {
25919
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25920
+ if (!migration) return;
25921
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25922
+ if (file2 !== void 0 && before?.holdsRows === true) {
25923
+ try {
25924
+ backupBeforeLegacyDrop(db, file2);
25925
+ } catch (error61) {
25926
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25927
+ return;
25928
+ }
25929
+ }
25930
+ try {
25931
+ withTransaction(
25932
+ db,
25933
+ () => {
25934
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25935
+ if (alreadyDropped) return;
25936
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25937
+ akaWarn(
25938
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25939
+ );
25940
+ return;
25941
+ }
25942
+ for (const statement of splitStatements(migration.sql)) {
25943
+ db.exec(statement);
25944
+ }
25945
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25946
+ migration.tag,
24927
25947
  Date.now()
24928
25948
  );
24929
25949
  },
@@ -25223,10 +26243,62 @@ function ensureSyncedAtColumn(db, table2) {
25223
26243
  if (!columns.includes("outbox_owed")) {
25224
26244
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25225
26245
  }
26246
+ if (!columns.includes("sync_failed_at")) {
26247
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26248
+ }
26249
+ if (!columns.includes("sync_failure")) {
26250
+ withTransaction(
26251
+ db,
26252
+ () => {
26253
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26254
+ db.exec(
26255
+ `UPDATE ${table2} SET synced_at = NULL
26256
+ WHERE synced_at = -1
26257
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26258
+ );
26259
+ },
26260
+ "IMMEDIATE"
26261
+ );
26262
+ }
25226
26263
  db.exec(
25227
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25228
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26264
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26265
+ BEFORE UPDATE OF sync_failure ON ${table2}
26266
+ WHEN ${syncFailureRejectCondition()}
26267
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25229
26268
  );
26269
+ const syncIndexColumns = [
26270
+ "event_type",
26271
+ "synced_at",
26272
+ "sync_claimed_at",
26273
+ "started_at",
26274
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26275
+ // has to be in the index for the read to stay covered — but putting it
26276
+ // ahead of `started_at` would reorder the prefix the structural drain's
26277
+ // reads match on.
26278
+ "sync_failure"
26279
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26280
+ //
26281
+ // The delivery-state read tests it — a capture's state depends on whether a
26282
+ // live forward marked it owed — so carrying it here makes that read covering
26283
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26284
+ // But a sixth column changes what the planner charges for this index, and
26285
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26286
+ // then stops choosing the per-session index for the token rollup and walks
26287
+ // every `llm_call` in the store through the event-type index instead. That
26288
+ // read grows with the store; this one does not.
26289
+ //
26290
+ // 40 ms on the largest store measured, once per render, is a cost worth
26291
+ // paying to leave every other read's plan where it was.
26292
+ ];
26293
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26294
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26295
+ if (!syncIndexMatches) {
26296
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26297
+ db.exec(
26298
+ `CREATE INDEX idx_audit_events_sync
26299
+ ON audit_events (${syncIndexColumns.join(", ")})`
26300
+ );
26301
+ }
25230
26302
  db.exec(
25231
26303
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25232
26304
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25448,7 +26520,11 @@ function buildAuditEvent(row) {
25448
26520
  link: linkParsed?.success ? linkParsed.data : null,
25449
26521
  targetId: row.target_id,
25450
26522
  internal: intToBool(row.internal),
25451
- flagged: intToBool(row.flagged)
26523
+ flagged: intToBool(row.flagged),
26524
+ // Only meaningful when the title came out empty — a row whose body was
26525
+ // expired but whose title fell back to `tool_name` still has something to
26526
+ // render, and flagging it would make the view apologise for nothing.
26527
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25452
26528
  };
25453
26529
  }
25454
26530
  var TIMELINE_COLUMNS = `
@@ -25456,6 +26532,7 @@ var TIMELINE_COLUMNS = `
25456
26532
  event_type,
25457
26533
  started_at,
25458
26534
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26535
+ content_expired_at,
25459
26536
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25460
26537
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25461
26538
  json_extract(attributes, '$.severity') AS severity,
@@ -25582,7 +26659,8 @@ var SqliteActivityRepository = class {
25582
26659
  SELECT 1 FROM audit_events d
25583
26660
  WHERE d.root_session_id = audit_events.id
25584
26661
  AND (d.content LIKE ? ESCAPE '\\'
25585
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26662
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26663
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25586
26664
  );
25587
26665
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25588
26666
  }
@@ -26120,6 +27198,88 @@ var SqliteAuditEventsRepository = class {
26120
27198
  }
26121
27199
  };
26122
27200
 
27201
+ // ../../packages/persistence/src/repositories/body-retention.ts
27202
+ var DEFAULT_BATCH_SIZE = 500;
27203
+ var DEFAULT_MAX_ROWS = 5e4;
27204
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27205
+ var SqliteBodyRetentionRepository = class {
27206
+ constructor(db) {
27207
+ this.db = db;
27208
+ const select = (laneClause) => `
27209
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27210
+ FROM audit_events
27211
+ WHERE content IS NOT NULL
27212
+ AND started_at < :cutoff
27213
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27214
+ ${laneClause}
27215
+ ORDER BY started_at
27216
+ LIMIT :limit`;
27217
+ this.candidatesStmt = this.db.prepare(select(""));
27218
+ this.candidatesSyncSafeStmt = this.db.prepare(
27219
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27220
+ );
27221
+ this.heldBySyncStmt = this.db.prepare(`
27222
+ SELECT COUNT(*) AS n
27223
+ FROM audit_events
27224
+ WHERE content IS NOT NULL
27225
+ AND started_at < :cutoff
27226
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27227
+ AND synced_at IS NULL`);
27228
+ this.expireStmt = this.db.prepare(
27229
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27230
+ );
27231
+ }
27232
+ db;
27233
+ candidatesStmt;
27234
+ candidatesSyncSafeStmt;
27235
+ heldBySyncStmt;
27236
+ expireStmt;
27237
+ /** How many bytes a pass with these options would free, changing nothing. */
27238
+ preview(opts) {
27239
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27240
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27241
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27242
+ return {
27243
+ rowsExpired: rows.length,
27244
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27245
+ rowsHeldBySync: this.countHeldBySync(opts)
27246
+ };
27247
+ }
27248
+ /** Clear eligible bodies, in bounded batches. */
27249
+ expire(opts) {
27250
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27251
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27252
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27253
+ let rowsExpired = 0;
27254
+ let bytesFreed = 0;
27255
+ let done = true;
27256
+ while (rowsExpired < maxRows) {
27257
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27258
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27259
+ if (batch.length === 0) break;
27260
+ withTransaction(
27261
+ this.db,
27262
+ () => {
27263
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27264
+ },
27265
+ "IMMEDIATE"
27266
+ );
27267
+ rowsExpired += batch.length;
27268
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27269
+ if (batch.length < remaining) break;
27270
+ if (rowsExpired >= maxRows) {
27271
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27272
+ }
27273
+ }
27274
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27275
+ }
27276
+ countHeldBySync(opts) {
27277
+ if (opts.sweepSyncLane) return 0;
27278
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27279
+ return row.n;
27280
+ }
27281
+ };
27282
+
26123
27283
  // ../../packages/persistence/src/repositories/classified-data.ts
26124
27284
  var SqliteClassifiedDataRepository = class {
26125
27285
  constructor(db) {
@@ -26920,23 +28080,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26920
28080
  )`;
26921
28081
 
26922
28082
  // ../../packages/persistence/src/repositories/findings.ts
26923
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26924
- var DEFAULT_LOCATIONS_LIMIT = 100;
26925
- var LOCATION_RULE_IDS_CAP = 20;
26926
- function compareLocationOrder(a, b) {
26927
- return compareFindingGroupOrder(
26928
- {
26929
- severity: a.maxSeverity,
26930
- latestDetectedAt: a.latestDetectedAt,
26931
- id: ""
26932
- },
26933
- {
26934
- severity: b.maxSeverity,
26935
- latestDetectedAt: b.latestDetectedAt,
26936
- id: ""
26937
- }
26938
- );
26939
- }
26940
28083
  var CONCAT_SEP = ",";
26941
28084
  var TUPLE_SEP = "|";
26942
28085
  function splitConcat(value) {
@@ -26965,7 +28108,15 @@ function toFlatFindingRow(r) {
26965
28108
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26966
28109
  eventId: r.event_id,
26967
28110
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26968
- status: deriveInstanceStatus(r)
28111
+ status: deriveInstanceStatus(r),
28112
+ delivery: deriveFindingDelivery({
28113
+ kind: r.kind,
28114
+ syncedAt: r.synced_at,
28115
+ syncClaimedAt: r.sync_claimed_at,
28116
+ syncFailedAt: r.sync_failed_at,
28117
+ syncFailure: r.sync_failure,
28118
+ outboxOwed: r.outbox_owed
28119
+ })
26969
28120
  };
26970
28121
  }
26971
28122
  function encodeGroupCursor(group) {
@@ -26988,13 +28139,51 @@ function decodeGroupCursor(cursor) {
26988
28139
  return null;
26989
28140
  }
26990
28141
  function firstAfter(sorted, cursor) {
26991
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28142
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26992
28143
  return index === -1 ? sorted.length : index;
26993
28144
  }
26994
28145
  function findDeepLinked(sorted, page, id) {
26995
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26996
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28146
+ if (page.some((t) => t.id === id)) return void 0;
28147
+ return sorted.find((t) => t.id === id);
28148
+ }
28149
+ function encodeLocationCursor(location) {
28150
+ const payload = {
28151
+ sev: location.maxSeverity,
28152
+ t: location.latestDetectedAt,
28153
+ r: location.repo,
28154
+ f: location.file
28155
+ };
28156
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28157
+ }
28158
+ function decodeLocationCursor(cursor) {
28159
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28160
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28161
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28162
+ }
28163
+ return null;
28164
+ }
28165
+ function firstLocationAfter(sorted, cursor) {
28166
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28167
+ return index === -1 ? sorted.length : index;
28168
+ }
28169
+ function findDeepLinkedLocation(sorted, page, id) {
28170
+ if (page.some((l) => l.id === id)) return void 0;
28171
+ return sorted.find((l) => l.id === id);
26997
28172
  }
28173
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28174
+ d.severity AS severity, f.masked_match AS masked_match,
28175
+ f.action_taken AS action_taken, f.confidence AS confidence,
28176
+ e.started_at AS occurred_at,
28177
+ e.source_tool AS source_tool,
28178
+ e.repo AS repo,
28179
+ e.file_path AS file,
28180
+ e.tool_name AS tool_name,
28181
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28182
+ e.event_type AS kind, f.finding_key AS finding_key,
28183
+ ${latestResolutionStatusSql("f")} AS latest_status,
28184
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28185
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28186
+ e.outbox_owed AS outbox_owed`;
26998
28187
  var DAY_MS3 = 864e5;
26999
28188
  var SqliteFindingsRepository = class {
27000
28189
  constructor(db) {
@@ -27115,30 +28304,26 @@ var SqliteFindingsRepository = class {
27115
28304
  );
27116
28305
  }
27117
28306
  /**
27118
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27119
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27120
- * attributes bag, rule_id/category/severity from the definition), scoped to
27121
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27122
- * rows this list must never surface), groups by ruleId, computes
27123
- * per-filter-excluded facets, applies the requested filters, and sorts by
27124
- * severity then recency. Filtering
27125
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27126
- * reflect the full filtered set; `items` is the requested
27127
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27128
- * filter, `totals.findings` counts only instances whose derived status was
27129
- * requested, and each item's instance preview is narrowed the same way.
28307
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28308
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28309
+ * list must never surface), with per-filter-excluded facets, the requested
28310
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28311
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28312
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28313
+ * Under a `status` filter, `totals.findings` counts only findings whose
28314
+ * derived status was requested.
28315
+ *
28316
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28317
+ * folding EVERY finding into the numbers a type row and the filters need
28318
+ * (count, severity, category, providers, actions, statuses, latest, search
28319
+ * text). The findings OF a type come from listFindingInstances scoped to
28320
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27130
28321
  *
27131
- * Two reads, neither of which materializes a row per finding:
27132
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27133
- * the group and the filters need (count, providers, actions, statuses,
27134
- * latest, search text);
27135
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27136
- * populate `instances` for the table's expanded rows.
27137
28322
  * The aggregates carry raw DB values and are translated by the same
27138
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27139
- * rule is ever restated in SQL.
28323
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28324
+ * status rule is ever restated in SQL.
27140
28325
  */
27141
- listGroupedFindings(query) {
28326
+ listFindingTypes(query) {
27142
28327
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27143
28328
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27144
28329
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27151,12 +28336,7 @@ var SqliteFindingsRepository = class {
27151
28336
  predicate,
27152
28337
  params: sessionParams
27153
28338
  });
27154
- const rows = this.previewRows(aggregates, {
27155
- sessionId: query.sessionId,
27156
- from: query.from
27157
- });
27158
- const groupable = rows.map(toFlatFindingRow);
27159
- const allGroups = buildFindingGroups(groupable, { aggregates });
28339
+ const allTypes = buildFindingTypes(aggregates);
27160
28340
  const filterOpts = {
27161
28341
  severity: query.severity,
27162
28342
  providers: query.provider,
@@ -27165,30 +28345,25 @@ var SqliteFindingsRepository = class {
27165
28345
  subtype: query.subtype,
27166
28346
  q: query.q
27167
28347
  };
27168
- const facets = computeFindingFacets(allGroups, filterOpts);
27169
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28348
+ const facets = computeFindingFacets(allTypes, filterOpts);
28349
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27170
28350
  const statusFilter = query.status ?? [];
27171
28351
  const totals = {
27172
- findings: sorted.reduce((acc, g) => {
27173
- if (statusFilter.length === 0) return acc + g.instanceCount;
27174
- const agg = aggregates.get(g.id);
27175
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28352
+ findings: sorted.reduce((acc, t) => {
28353
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28354
+ const agg = aggregates.get(t.id);
28355
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27176
28356
  }, 0),
27177
- groups: sorted.length
28357
+ types: sorted.length
27178
28358
  };
27179
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28359
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27180
28360
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27181
28361
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27182
28362
  const page = sorted.slice(start, start + limit);
27183
28363
  const lastOnPage = page.at(-1);
27184
28364
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27185
28365
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27186
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27187
- const narrow = (g) => statusSet ? {
27188
- ...g,
27189
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27190
- } : g;
27191
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28366
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27192
28367
  return Promise.resolve({
27193
28368
  totals,
27194
28369
  facets,
@@ -27199,7 +28374,7 @@ var SqliteFindingsRepository = class {
27199
28374
  }
27200
28375
  /**
27201
28376
  * One row per rule_id, folding EVERY instance of the group into the values
27202
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28377
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27203
28378
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27204
28379
  *
27205
28380
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27253,6 +28428,7 @@ var SqliteFindingsRepository = class {
27253
28428
  providers: query.provider,
27254
28429
  actions: query.action,
27255
28430
  statuses: query.status,
28431
+ deliveries: query.deployment,
27256
28432
  tools: query.tool,
27257
28433
  repo: query.repo,
27258
28434
  file: query.file,
@@ -27293,13 +28469,25 @@ var SqliteFindingsRepository = class {
27293
28469
  });
27294
28470
  }
27295
28471
  /**
27296
- * The same findings folded by location: repository, then file within it.
28472
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27297
28473
  *
27298
28474
  * The grouping keys come from the capturing event's attributes, which is what
27299
- * the local store relates a finding to — there is no finding↔asset row to
27300
- * group by instead. A repo or file the event did not record folds into the
27301
- * empty-string bucket, which the view renders but does not link, since no
27302
- * filter can name it.
28475
+ * the local store relates a finding to; there is no finding↔asset row to group
28476
+ * by instead. A repo or file the event did not record folds into the
28477
+ * empty-string bucket, which is a real location like any other: it is listed,
28478
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28479
+ *
28480
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28481
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28482
+ * list was rebuilt to remove — and two-level pagination inside an
28483
+ * expand/collapse table is what pushed that view to master/detail in the first
28484
+ * place.
28485
+ *
28486
+ * Every filter narrows the FINDINGS and the locations fall out of what
28487
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28488
+ * reports for the same filters scoped to that pair. The view depends on it:
28489
+ * one toolbar sits over both panels precisely because a location owns none of
28490
+ * its fields.
27303
28491
  */
27304
28492
  listFindingLocations(query) {
27305
28493
  const opts = {
@@ -27308,16 +28496,20 @@ var SqliteFindingsRepository = class {
27308
28496
  providers: query.provider,
27309
28497
  actions: query.action,
27310
28498
  statuses: query.status,
28499
+ deliveries: query.deployment,
27311
28500
  tools: query.tool,
27312
28501
  q: query.q
27313
28502
  };
27314
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28503
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28504
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27315
28505
  const byRepo = /* @__PURE__ */ new Map();
28506
+ const accumulator = createInstanceFacetAccumulator(opts);
27316
28507
  let total = 0;
27317
28508
  for (const row of this.scanFindingRows({
27318
28509
  sessionId: query.sessionId,
27319
28510
  from: query.from
27320
28511
  })) {
28512
+ accumulator.add(row);
27321
28513
  if (!matchesInstanceFilters(row, opts)) continue;
27322
28514
  total += 1;
27323
28515
  let files = byRepo.get(row.repo);
@@ -27332,103 +28524,35 @@ var SqliteFindingsRepository = class {
27332
28524
  }
27333
28525
  addToLocation(acc, row);
27334
28526
  }
27335
- let fileCount = 0;
27336
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27337
- fileCount += files.size;
27338
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27339
- file: file2,
27340
- instanceCount: acc.instanceCount,
27341
- maxSeverity: acc.maxSeverity,
27342
- latestDetectedAt: acc.latestDetectedAt,
27343
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27344
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27345
- })).sort(compareLocationOrder);
27346
- const rollup = fileRows.reduce(
27347
- (a, f) => ({
27348
- instanceCount: a.instanceCount + f.instanceCount,
27349
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27350
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27351
- }),
27352
- {
27353
- instanceCount: 0,
27354
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27355
- latestDetectedAt: ""
27356
- }
27357
- );
27358
- const statuses = fileRows.map((f) => f.status);
27359
- const folded = foldGroupStatus(statuses);
27360
- return {
27361
- repo,
27362
- instanceCount: rollup.instanceCount,
27363
- maxSeverity: rollup.maxSeverity,
27364
- latestDetectedAt: rollup.latestDetectedAt,
27365
- ...folded === void 0 ? {} : { status: folded },
27366
- files: fileRows
27367
- };
27368
- });
27369
- repos.sort(compareLocationOrder);
28527
+ const sorted = [];
28528
+ for (const [repo, files] of byRepo) {
28529
+ for (const [file2, acc] of files) {
28530
+ const status = foldGroupStatus(acc.statuses);
28531
+ sorted.push({
28532
+ id: encodeLocationId(repo, file2),
28533
+ repo,
28534
+ file: file2,
28535
+ instanceCount: acc.instanceCount,
28536
+ maxSeverity: acc.maxSeverity,
28537
+ latestDetectedAt: acc.latestDetectedAt,
28538
+ ...status === void 0 ? {} : { status },
28539
+ ruleIds: [...acc.ruleIds]
28540
+ });
28541
+ }
28542
+ }
28543
+ sorted.sort(compareLocationOrder);
28544
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28545
+ const page = sorted.slice(start, start + limit);
28546
+ const lastOnPage = page.at(-1);
28547
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28548
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27370
28549
  return Promise.resolve({
27371
- totals: { findings: total, repos: repos.length, files: fileCount },
27372
- items: repos.slice(0, limit),
27373
- hasMore: repos.length > limit
28550
+ totals: { findings: total, locations: sorted.length },
28551
+ facets: accumulator.facets(),
28552
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28553
+ nextCursor
27374
28554
  });
27375
28555
  }
27376
- /**
27377
- * Each group's newest instances, for the table's expanded rows.
27378
- *
27379
- * ONE index-ordered scan with early termination, and the shape is the point.
27380
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27381
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27382
- * through a temp B-tree to keep a bounded preview of each group, and then
27383
- * sorts the survivors again for the page order. Both sorts grow with the
27384
- * store while the answer does not.
27385
- *
27386
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27387
- * (or the session or window index the scope names — see `findingScanSql`),
27388
- * which is already the order the page wants, and keeps rows per rule until
27389
- * each rule has as many as it can show. The aggregate the caller already holds
27390
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27391
- * per rule, summed, is the number of rows this scan has to find, and it stops
27392
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27393
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27394
- * store with many firing rules widens it. The bound that DOES hold
27395
- * unconditionally is the sorted form's floor: this scan visits at most as
27396
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27397
- * sorted, and stops the moment every rule has its cap, where the sorted form
27398
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27399
- * wanted instances sitting at the tail of the scope — is one pass over
27400
- * everything in scope with a block sort of the id tie-break only, never a
27401
- * sort of the scope, which is still that floor.
27402
- *
27403
- * A row whose rule the aggregate did not see is skipped: the two statements
27404
- * run without a shared snapshot, so a capture landing between them can add a
27405
- * rule here that has no counts there, and the counts are what the group is
27406
- * built from.
27407
- */
27408
- previewRows(aggregates, scope) {
27409
- const wanted = /* @__PURE__ */ new Map();
27410
- let remaining = 0;
27411
- for (const [ruleId, agg] of aggregates) {
27412
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27413
- wanted.set(ruleId, n);
27414
- remaining += n;
27415
- }
27416
- const rows = [];
27417
- if (remaining === 0) return rows;
27418
- const { sql, params } = this.findingScanSql(scope);
27419
- const taken = /* @__PURE__ */ new Map();
27420
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27421
- const want = wanted.get(r.rule_id);
27422
- if (want === void 0) continue;
27423
- const have = taken.get(r.rule_id) ?? 0;
27424
- if (have >= want) continue;
27425
- taken.set(r.rule_id, have + 1);
27426
- rows.push(r);
27427
- remaining -= 1;
27428
- if (remaining === 0) break;
27429
- }
27430
- return rows;
27431
- }
27432
28556
  /**
27433
28557
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27434
28558
  *
@@ -27455,6 +28579,33 @@ var SqliteFindingsRepository = class {
27455
28579
  yield toFlatFindingRow(r);
27456
28580
  }
27457
28581
  }
28582
+ /**
28583
+ * One finding by its own id, or null when no such row exists.
28584
+ *
28585
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28586
+ * the store — and, unlike anything derived from a list page, it resolves a
28587
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28588
+ * deep link needs: the id it carries may name a finding thousands of rows
28589
+ * older than anything a first page holds.
28590
+ *
28591
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28592
+ * RESOLVES an id; whether that row would survive the list's current filters is
28593
+ * a different question, and hiding the target because a filter excludes it is
28594
+ * worse than showing it.
28595
+ *
28596
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28597
+ * type should the list select?" and "what does the drawer show?".
28598
+ */
28599
+ findingInstance(id) {
28600
+ const row = this.db.prepare(
28601
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28602
+ FROM inspection_findings f
28603
+ JOIN audit_events e ON e.id = f.audit_event_id
28604
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28605
+ WHERE f.id = ?`
28606
+ ).get(id);
28607
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28608
+ }
27458
28609
  /**
27459
28610
  * The one statement both instance-level scans run: every finding in scope,
27460
28611
  * joined to its event and definition, newest first.
@@ -27488,17 +28639,7 @@ var SqliteFindingsRepository = class {
27488
28639
  conditions.push("e.started_at >= ?");
27489
28640
  params.push(isoToEpochMillis(scope.from));
27490
28641
  }
27491
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27492
- d.severity AS severity, f.masked_match AS masked_match,
27493
- f.action_taken AS action_taken, f.confidence AS confidence,
27494
- e.started_at AS occurred_at,
27495
- e.source_tool AS source_tool,
27496
- e.repo AS repo,
27497
- e.file_path AS file,
27498
- e.tool_name AS tool_name,
27499
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27500
- e.event_type AS kind, f.finding_key AS finding_key,
27501
- ${latestResolutionStatusSql("f")} AS latest_status
28642
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27502
28643
  FROM audit_events e
27503
28644
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27504
28645
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27512,6 +28653,26 @@ var SqliteFindingsRepository = class {
27512
28653
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27513
28654
  const rows = this.db.prepare(
27514
28655
  `SELECT rule_id,
28656
+ -- BARE columns beside max(latest_at), which is deliberate and
28657
+ -- is SQLite's documented behaviour: with a single min()/max()
28658
+ -- in an aggregate query, every bare column takes its value from
28659
+ -- the row that produced the extremum. So these are the severity
28660
+ -- and category of the definition whose finding is NEWEST, which
28661
+ -- is what the row-based build they replaced read off its first
28662
+ -- (newest-first) row.
28663
+ --
28664
+ -- min() is WRONG here and was the defect: inspection_definitions
28665
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28666
+ -- mints a new row), so a rule whose severity moved between
28667
+ -- versions has several, and min() picks the ALPHABETICALLY
28668
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28669
+ -- That is arbitrary in direction, and it feeds the badge, the
28670
+ -- filter, the facet counts and the primary sort key.
28671
+ --
28672
+ -- Adding a second min()/max() aggregate here would make these
28673
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28674
+ severity,
28675
+ category,
27515
28676
  sum(tuple_count) AS instance_count,
27516
28677
  max(latest_at) AS latest_at,
27517
28678
  group_concat(source_tools) AS source_tools,
@@ -27522,6 +28683,14 @@ var SqliteFindingsRepository = class {
27522
28683
  group_concat(tool_names) AS tool_names
27523
28684
  FROM (
27524
28685
  SELECT d.rule_id AS rule_id,
28686
+ -- Severity and category are columns of the DEFINITION, and
28687
+ -- a rule can have SEVERAL definitions (one per version), so
28688
+ -- these are grouped on below and resolved to the newest
28689
+ -- firing version by the outer query's bare-column select.
28690
+ -- They ride the aggregate because the type build has no rows
28691
+ -- to read them off \u2014 see buildFindingTypes.
28692
+ d.severity AS severity,
28693
+ d.category AS category,
27525
28694
  e.event_type || '${TUPLE_SEP}' ||
27526
28695
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27527
28696
  coalesce(latest.status, '') AS status_tuple,
@@ -27536,7 +28705,7 @@ var SqliteFindingsRepository = class {
27536
28705
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27537
28706
  ON latest.finding_key = f.finding_key
27538
28707
  ${scope.predicate}
27539
- GROUP BY d.rule_id, status_tuple
28708
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27540
28709
  )
27541
28710
  GROUP BY rule_id`
27542
28711
  ).all(scope.params);
@@ -27545,6 +28714,8 @@ var SqliteFindingsRepository = class {
27545
28714
  r.rule_id,
27546
28715
  {
27547
28716
  instanceCount: r.instance_count,
28717
+ severity: r.severity,
28718
+ category: r.category,
27548
28719
  sourceTools: splitConcat(r.source_tools),
27549
28720
  actionsTaken: splitConcat(r.actions_taken),
27550
28721
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27561,7 +28732,7 @@ var SqliteFindingsRepository = class {
27561
28732
  latestDetectedAt: epochMillisToIso(r.latest_at),
27562
28733
  // Free text only — joined and substring-matched, so group_concat's
27563
28734
  // commas need no unpicking (a repo/path containing one still matches).
27564
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28735
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27565
28736
  // tell "no q this request" from "a group with no repo/file at all"
27566
28737
  // and skip priming a haystack nothing will read.
27567
28738
  ...withSearchText ? {
@@ -27589,7 +28760,9 @@ var SqliteFindingsRepository = class {
27589
28760
  )
27590
28761
  );
27591
28762
  for (const row of grouped) {
27592
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28763
+ if (Object.hasOwn(byAction, row.action_taken)) {
28764
+ byAction[row.action_taken] = row.c;
28765
+ }
27593
28766
  }
27594
28767
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27595
28768
  const sevRows = allRows(
@@ -27606,7 +28779,9 @@ var SqliteFindingsRepository = class {
27606
28779
  )
27607
28780
  );
27608
28781
  for (const row of sevRows) {
27609
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28782
+ if (Object.hasOwn(bySeverity, row.severity)) {
28783
+ bySeverity[row.severity] = row.c;
28784
+ }
27610
28785
  }
27611
28786
  const categories = ENFORCEABLE_CATEGORIES;
27612
28787
  const enabledRows = allRows(
@@ -27655,469 +28830,6 @@ function isoDay(ms) {
27655
28830
  return new Date(ms).toISOString().slice(0, 10);
27656
28831
  }
27657
28832
 
27658
- // ../../packages/persistence/src/repositories/history-sync.ts
27659
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27660
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27661
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27662
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27663
- var SKIPPED = -1;
27664
- var ROW_COLUMNS = `id,
27665
- parent_id AS parentId,
27666
- root_session_id AS rootSessionId,
27667
- event_type AS eventType,
27668
- host_id AS hostId,
27669
- harness_id AS harnessId,
27670
- source_project_id AS sourceProjectId,
27671
- started_at AS startedAt,
27672
- ended_at AS endedAt,
27673
- severity,
27674
- priority,
27675
- content,
27676
- content_hash AS contentHash,
27677
- attributes`;
27678
- var SqliteHistorySyncRepository = class {
27679
- constructor(db) {
27680
- this.db = db;
27681
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27682
- this.sessionsStmt = db.prepare(
27683
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27684
- FROM audit_events
27685
- WHERE synced_at IS NULL
27686
- AND event_type IN (${TYPE_LIST})
27687
- AND started_at < :before
27688
- GROUP BY sessionId
27689
- ORDER BY earliest
27690
- LIMIT :limit`
27691
- );
27692
- this.rowsStmt = db.prepare(
27693
- `SELECT ${ROW_COLUMNS}
27694
- FROM audit_events
27695
- WHERE synced_at IS NULL
27696
- AND event_type IN (${TYPE_LIST})
27697
- AND started_at < :before
27698
- AND COALESCE(root_session_id, id) = :sessionId
27699
- ORDER BY (event_type = 'session') DESC, started_at
27700
- LIMIT :limit`
27701
- );
27702
- this.captureRowsStmt = db.prepare(
27703
- `SELECT ${ROW_COLUMNS}
27704
- FROM audit_events
27705
- WHERE synced_at IS NULL
27706
- AND sync_claimed_at IS NULL
27707
- AND outbox_owed = 1
27708
- AND event_type IN (${CAPTURE_TYPE_LIST})
27709
- AND started_at < :before
27710
- ORDER BY started_at
27711
- LIMIT :limit`
27712
- );
27713
- this.markOwedStmt = db.prepare(
27714
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27715
- );
27716
- this.stampStmt = db.prepare(
27717
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27718
- );
27719
- this.claimRowStmt = db.prepare(
27720
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27721
- );
27722
- this.releaseRowStmt = db.prepare(
27723
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27724
- );
27725
- this.releaseStaleClaimsStmt = db.prepare(
27726
- `UPDATE audit_events SET sync_claimed_at = NULL
27727
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27728
- );
27729
- this.partitionStmt = db.prepare(
27730
- `SELECT
27731
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27732
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27733
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27734
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27735
- COUNT(*) AS total
27736
- FROM audit_events
27737
- WHERE event_type IN (${TYPE_LIST})`
27738
- );
27739
- this.countsStmt = db.prepare(
27740
- `SELECT
27741
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27742
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27743
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27744
- FROM audit_events
27745
- WHERE event_type IN (${TYPE_LIST})`
27746
- );
27747
- this.captureSkipCountStmt = db.prepare(
27748
- `SELECT COUNT(*) AS skipped
27749
- FROM audit_events
27750
- WHERE synced_at = ${String(SKIPPED)}
27751
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27752
- );
27753
- this.fingerprintStmt = db.prepare(
27754
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27755
- FROM history_sync WHERE id = 1`
27756
- );
27757
- this.setFingerprintStmt = db.prepare(
27758
- `UPDATE history_sync
27759
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27760
- WHERE id = 1`
27761
- );
27762
- this.disownCapturesStmt = db.prepare(
27763
- `UPDATE audit_events SET outbox_owed = NULL
27764
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27765
- );
27766
- this.rearmStmt = db.prepare(
27767
- `UPDATE audit_events SET synced_at = NULL
27768
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27769
- );
27770
- this.claimStmt = db.prepare(
27771
- `UPDATE history_sync
27772
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27773
- WHERE id = 1
27774
- AND (owner_pid IS NULL
27775
- OR heartbeat_at IS NULL
27776
- OR heartbeat_at < :staleBefore
27777
- OR heartbeat_at > :now)`
27778
- );
27779
- this.heartbeatStmt = db.prepare(
27780
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27781
- );
27782
- this.releaseStmt = db.prepare(
27783
- `UPDATE history_sync
27784
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27785
- WHERE id = 1 AND owner_pid = :pid`
27786
- );
27787
- this.closeWindowStmt = db.prepare(
27788
- `UPDATE audit_events SET synced_at = :at
27789
- WHERE synced_at IS NULL
27790
- AND event_type IN (${TYPE_LIST})
27791
- AND started_at >= :attachedAt`
27792
- );
27793
- this.releaseBoundaryStmt = db.prepare(
27794
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27795
- );
27796
- this.freezeBoundaryStmt = db.prepare(
27797
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27798
- );
27799
- this.leaseStmt = db.prepare(
27800
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27801
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27802
- FROM history_sync WHERE id = 1`
27803
- );
27804
- this.inspectionsStmt = db.prepare(
27805
- `SELECT d.rule_id AS ruleId,
27806
- d.name AS ruleName,
27807
- d.version AS ruleVersion,
27808
- d.category AS category,
27809
- d.severity AS severity,
27810
- f.span_start AS spanStart,
27811
- f.span_end AS spanEnd,
27812
- f.masked_match AS maskedMatch,
27813
- f.action_taken AS actionTaken,
27814
- f.confidence AS confidence
27815
- FROM inspection_findings f
27816
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27817
- WHERE f.audit_event_id = :auditEventId
27818
- ORDER BY f.span_start, f.id`
27819
- );
27820
- }
27821
- db;
27822
- ensureRowStmt;
27823
- sessionsStmt;
27824
- rowsStmt;
27825
- stampStmt;
27826
- countsStmt;
27827
- fingerprintStmt;
27828
- setFingerprintStmt;
27829
- rearmStmt;
27830
- claimStmt;
27831
- heartbeatStmt;
27832
- releaseStmt;
27833
- leaseStmt;
27834
- inspectionsStmt;
27835
- closeWindowStmt;
27836
- releaseBoundaryStmt;
27837
- freezeBoundaryStmt;
27838
- captureRowsStmt;
27839
- markOwedStmt;
27840
- captureSkipCountStmt;
27841
- disownCapturesStmt;
27842
- partitionStmt;
27843
- claimRowStmt;
27844
- releaseRowStmt;
27845
- releaseStaleClaimsStmt;
27846
- /**
27847
- * The masked detections recorded against one tool call.
27848
- *
27849
- * These travel with the event because a tool call's target is not
27850
- * re-inspectable from the event alone — unlike a capture, where the text
27851
- * itself is re-scannable. What crosses is the masked match and the rule that
27852
- * produced it, never the value.
27853
- */
27854
- inspectionsFor(auditEventId) {
27855
- return allRows(this.inspectionsStmt, { auditEventId });
27856
- }
27857
- /**
27858
- * Sessions with structural rows still to send, oldest first.
27859
- *
27860
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27861
- * read. Anything recorded after the machine attached is the live forward
27862
- * path's to deliver; this drain exists for what was recorded before it, and a
27863
- * row both paths send is at best a duplicate request and at worst — for a
27864
- * session root — an overwrite of the inventory ids the live path resolved.
27865
- */
27866
- pendingSessions(limit, before) {
27867
- return allRows(this.sessionsStmt, { limit, before }).map(
27868
- (r) => r.sessionId
27869
- );
27870
- }
27871
- /** One session's undelivered structural rows within the backlog, root first. */
27872
- pendingRows(sessionId, limit, before) {
27873
- return allRows(this.rowsStmt, { sessionId, limit, before });
27874
- }
27875
- /**
27876
- * Captures this machine still owes the deployment, oldest first.
27877
- *
27878
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27879
- * by a time window — see captureRowsStmt for why a window could not express
27880
- * this. `before` is the grace window that leaves a just-recorded capture to
27881
- * the live path.
27882
- */
27883
- pendingCaptureRows(limit, before) {
27884
- return allRows(this.captureRowsStmt, { limit, before });
27885
- }
27886
- /**
27887
- * Record that a capture is OWED to the deployment.
27888
- *
27889
- * Written by the attached forward path when a live send did not confirm
27890
- * delivery, and read by the drain as the whole of its eligibility test. It is
27891
- * a fact rather than an inference: the machine was attached, the send did not
27892
- * land, so the row is owed — which no time window can state, because the same
27893
- * window that holds the rows a past attachment left owed also holds every
27894
- * capture recorded while the machine was DETACHED, and those were never
27895
- * offered to anyone.
27896
- *
27897
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27898
- * out of the drain's read.
27899
- */
27900
- markCaptureOwed(id) {
27901
- this.markOwedStmt.run({ id });
27902
- }
27903
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27904
- markSynced(ids, atMs) {
27905
- this.stampAll(ids, atMs);
27906
- }
27907
- /**
27908
- * Record that a row will never be sent.
27909
- *
27910
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27911
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27912
- * is retried; marking those would turn one outage into permanent data loss.
27913
- */
27914
- markSkipped(ids) {
27915
- this.stampAll(ids, SKIPPED);
27916
- }
27917
- eachInTransaction(ids, run) {
27918
- if (ids.length === 0) return;
27919
- withTransaction(
27920
- this.db,
27921
- () => {
27922
- for (const id of ids) run(id);
27923
- },
27924
- "IMMEDIATE"
27925
- );
27926
- }
27927
- stampAll(ids, value) {
27928
- if (ids.length === 0) return;
27929
- withTransaction(
27930
- this.db,
27931
- () => {
27932
- for (const id of ids) this.stampStmt.run({ at: value, id });
27933
- },
27934
- "IMMEDIATE"
27935
- );
27936
- }
27937
- /**
27938
- * Claim rows as in-flight.
27939
- *
27940
- * Advisory in exactly the sense the lease is: it records that a send is in
27941
- * progress so a surface can say so, and a lost claim costs a row showing as
27942
- * queued while it is actually being sent. It is not exclusion — the far side
27943
- * settles a duplicate on the row id.
27944
- */
27945
- claimRows(ids, atMs) {
27946
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27947
- }
27948
- /** Give back a claim without settling — the send failed, the row is queued again. */
27949
- releaseRows(ids) {
27950
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27951
- }
27952
- /**
27953
- * Clear claims older than `staleBefore`, and report how many were cleared.
27954
- *
27955
- * A process killed between claiming and settling leaves rows claimed with
27956
- * nothing left to settle them. Without this they read as "sending" for ever.
27957
- */
27958
- releaseStaleClaims(staleBefore) {
27959
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27960
- }
27961
- /**
27962
- * Every tracked row in exactly one delivery state.
27963
- *
27964
- * Takes no boundary on purpose. The boundary answers "what should the drain
27965
- * pick up now", which is a different question from "what state is this row
27966
- * in" — and a machine that has never attached has no boundary to pass, so
27967
- * requiring one would force a caller to invent one and report the whole store
27968
- * as queued.
27969
- */
27970
- partition() {
27971
- const row = getRow(this.partitionStmt, {});
27972
- return {
27973
- queued: row?.queued ?? 0,
27974
- inProgress: row?.inProgress ?? 0,
27975
- synced: row?.synced ?? 0,
27976
- failed: row?.failed ?? 0,
27977
- total: row?.total ?? 0
27978
- };
27979
- }
27980
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27981
- counts(before) {
27982
- const row = getRow(
27983
- this.countsStmt,
27984
- { before }
27985
- );
27986
- const captures = getRow(this.captureSkipCountStmt);
27987
- return {
27988
- pending: row?.pending ?? 0,
27989
- sent: row?.sent ?? 0,
27990
- skipped: row?.skipped ?? 0,
27991
- capturesSkipped: captures?.skipped ?? 0
27992
- };
27993
- }
27994
- /**
27995
- * The deployment the current stamps were made against, and where its backlog
27996
- * ends.
27997
- *
27998
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27999
- * machine that has never drained is — and every writer below seeds the row
28000
- * before it needs one, so nothing depends on this creating it. Keeping the
28001
- * write off the gate path matters because the gate runs on every pass while a
28002
- * write has to take the database's write lock.
28003
- */
28004
- deployment() {
28005
- const row = getRow(
28006
- this.fingerprintStmt
28007
- );
28008
- return {
28009
- fingerprint: row?.fingerprint ?? void 0,
28010
- backlogBefore: row?.backlogBefore ?? void 0
28011
- };
28012
- }
28013
- /**
28014
- * Point the ledger at a different deployment, discarding what it recorded
28015
- * about the previous one.
28016
- *
28017
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28018
- * machine has just left are undelivered as far as the new one is concerned.
28019
- * All three in one transaction, so a crash between them cannot leave stamps
28020
- * attributed to the wrong deployment, or a boundary that belongs to another.
28021
- *
28022
- * The boundary is written HERE and only here, which is what freezes it: a
28023
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28024
- * unchanged, so this never runs and the backlog does not widen back over rows
28025
- * the live path has since delivered.
28026
- */
28027
- rearmFor(fingerprint, backlogBefore) {
28028
- this.ensureRowStmt.run();
28029
- withTransaction(
28030
- this.db,
28031
- () => {
28032
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28033
- this.rearmStmt.run();
28034
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28035
- this.disownCapturesStmt.run();
28036
- }
28037
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28038
- },
28039
- "IMMEDIATE"
28040
- );
28041
- }
28042
- /**
28043
- * End the attached period: hand its rows to the live path, and release the
28044
- * boundary so the next attachment can freeze a new one.
28045
- *
28046
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28047
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28048
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28049
- * during the detached period, because the machine is not attached. Rows
28050
- * recorded in that window sit after the boundary and before the re-attach, so
28051
- * neither path takes them, and the pending count reports none outstanding.
28052
- *
28053
- * Stamping the attached window is not a claim that every one of those rows
28054
- * reached the deployment — the live path drops on failure and says so
28055
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28056
- * status quo: they sit outside the frozen boundary today and are equally never
28057
- * re-sent. Making it explicit is what lets the boundary move.
28058
- *
28059
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28060
- * window unstamped — that half-state would re-send the whole attached period
28061
- * on the next attach, which is the failure the boundary exists to prevent.
28062
- */
28063
- closeAttachedWindow(attachedAtMs, atMs) {
28064
- this.ensureRowStmt.run();
28065
- withTransaction(
28066
- this.db,
28067
- () => {
28068
- const row = getRow(this.fingerprintStmt);
28069
- const from = row?.backlogBefore ?? attachedAtMs;
28070
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28071
- this.releaseBoundaryStmt.run();
28072
- },
28073
- "IMMEDIATE"
28074
- );
28075
- }
28076
- /**
28077
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28078
- *
28079
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28080
- * different deployment and therefore discards what was delivered to the old
28081
- * one: here the recipient is the same, so everything already sent to it stays
28082
- * sent.
28083
- */
28084
- freezeBoundary(backlogBefore) {
28085
- this.ensureRowStmt.run();
28086
- this.freezeBoundaryStmt.run({ backlogBefore });
28087
- }
28088
- /** Take the claim, or report that someone live already holds it. */
28089
- claim(pid, host, nowMs, staleAfterMs) {
28090
- this.ensureRowStmt.run();
28091
- let taken = false;
28092
- withTransaction(
28093
- this.db,
28094
- () => {
28095
- const result = this.claimStmt.run({
28096
- pid,
28097
- host,
28098
- now: nowMs,
28099
- staleBefore: nowMs - staleAfterMs
28100
- });
28101
- taken = result.changes === 1;
28102
- },
28103
- "IMMEDIATE"
28104
- );
28105
- return taken;
28106
- }
28107
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28108
- heartbeat(pid, nowMs) {
28109
- this.heartbeatStmt.run({ now: nowMs, pid });
28110
- }
28111
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28112
- release(pid) {
28113
- this.releaseStmt.run({ pid });
28114
- }
28115
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28116
- lease() {
28117
- return getRow(this.leaseStmt);
28118
- }
28119
- };
28120
-
28121
28833
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28122
28834
  var SqliteInspectionDefinitionsRepository = class {
28123
28835
  constructor(db) {
@@ -28312,7 +29024,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28312
29024
  }
28313
29025
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28314
29026
  }
28315
- function readManagedSettings(paths = managedSettingsPaths()) {
29027
+ var testOnlyManagedPaths = null;
29028
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28316
29029
  for (const path of paths) {
28317
29030
  let text;
28318
29031
  try {
@@ -28347,6 +29060,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28347
29060
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28348
29061
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28349
29062
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29063
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28350
29064
  if (values.vaultConsent !== void 0) {
28351
29065
  merged.vaultConsent = values.vaultConsent ? (
28352
29066
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30792,7 +31506,7 @@ function toUtcDateString(ms) {
30792
31506
  return new Date(ms).toISOString().slice(0, 10);
30793
31507
  }
30794
31508
  function isTimeseriesSeverity(s) {
30795
- return s === "critical" || s === "high" || s === "medium";
31509
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30796
31510
  }
30797
31511
  var SqliteSecurityRepository = class {
30798
31512
  constructor(db, now = () => Date.now()) {
@@ -30854,7 +31568,7 @@ var SqliteSecurityRepository = class {
30854
31568
  ELSE 0
30855
31569
  END) AS open_at_rest
30856
31570
  FROM inspection_findings f
30857
- JOIN audit_events e ON e.id = f.audit_event_id
31571
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30858
31572
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30859
31573
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30860
31574
  ON latest.finding_key = f.finding_key
@@ -30921,12 +31635,16 @@ var SqliteSecurityRepository = class {
30921
31635
  const now = this.now();
30922
31636
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30923
31637
  const rows = this.findingsInRange(windowStart, now);
30924
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30925
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30926
- critical: 0,
30927
- high: 0,
30928
- medium: 0
30929
- }));
31638
+ const points = Array.from(
31639
+ { length: numBuckets },
31640
+ (_, i) => ({
31641
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31642
+ critical: 0,
31643
+ high: 0,
31644
+ medium: 0,
31645
+ low: 0
31646
+ })
31647
+ );
30930
31648
  for (const r of rows) {
30931
31649
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30932
31650
  const bucket = points[idx];
@@ -31076,7 +31794,7 @@ var SqliteSecurityRepository = class {
31076
31794
  this.db.prepare(
31077
31795
  `SELECT e.repo AS repo, count(*) AS c
31078
31796
  FROM inspection_findings f
31079
- JOIN audit_events e ON e.id = f.audit_event_id
31797
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31080
31798
  WHERE e.started_at >= :from AND e.started_at < :to
31081
31799
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31082
31800
  AND e.repo IS NOT NULL
@@ -31144,6 +31862,7 @@ var SqliteSecurityRepository = class {
31144
31862
  `SELECT f.finding_key AS finding_key,
31145
31863
  d.rule_id AS rule_id,
31146
31864
  d.severity AS severity,
31865
+ e.repo AS repo,
31147
31866
  e.file_path AS path,
31148
31867
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31149
31868
  latest.resolved_at AS latest_resolved_at
@@ -31163,6 +31882,7 @@ var SqliteSecurityRepository = class {
31163
31882
  const items = rows.map((r) => ({
31164
31883
  findingKey: r.finding_key,
31165
31884
  ruleId: r.rule_id,
31885
+ repo: r.repo ?? "",
31166
31886
  severity: r.severity,
31167
31887
  path: r.path ?? "",
31168
31888
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31172,15 +31892,68 @@ var SqliteSecurityRepository = class {
31172
31892
  }));
31173
31893
  return Promise.resolve({ items });
31174
31894
  }
31895
+ /**
31896
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31897
+ *
31898
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31899
+ * list: a secret committed three weeks ago and never rotated is still the most
31900
+ * important thing to fix, and any window hides it. It carried a "newest N
31901
+ * findings" cap and then a range; the first meant a different span on every
31902
+ * machine, and the second reported "no recommendations" over live exposure.
31903
+ *
31904
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31905
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31906
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31907
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31908
+ * The two answer different questions and only this one has to match a link.
31909
+ *
31910
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31911
+ * whole-store scope costs a grouped scan rather than a row per finding.
31912
+ */
31913
+ recommendationInputs() {
31914
+ const rows = allRows(
31915
+ this.db.prepare(
31916
+ `SELECT d.rule_id AS rule_id,
31917
+ d.category AS category,
31918
+ d.severity AS severity,
31919
+ COUNT(*) AS count
31920
+ FROM inspection_findings f
31921
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31922
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31923
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31924
+ ON latest.finding_key = f.finding_key
31925
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31926
+ AND e.event_type = 'code_change'
31927
+ AND (
31928
+ f.finding_key IS NULL
31929
+ OR latest.status IS NULL
31930
+ OR latest.status NOT IN ('resolved', 'dismissed')
31931
+ )
31932
+ GROUP BY d.rule_id, d.category, d.severity`
31933
+ )
31934
+ );
31935
+ return Promise.resolve(
31936
+ rows.map((r) => ({
31937
+ ruleId: r.rule_id,
31938
+ category: r.category,
31939
+ severity: r.severity,
31940
+ count: r.count
31941
+ }))
31942
+ );
31943
+ }
31175
31944
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31176
31945
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31177
31946
  // numeric and the JS aggregations bucket/split on ms directly.
31178
31947
  findingsInRange(fromMs, toMs) {
31179
31948
  const rows = allRows(
31180
31949
  this.db.prepare(
31181
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31950
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31951
+ // joined for `severity`, so they are two more columns off a row this read
31952
+ // already fetches. They feed the recommended-actions rollup.
31953
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31954
+ d.rule_id AS rule_id, d.category AS category
31182
31955
  FROM inspection_findings f
31183
- JOIN audit_events e ON e.id = f.audit_event_id
31956
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31184
31957
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31185
31958
  WHERE e.started_at >= :from AND e.started_at < :to
31186
31959
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31191,7 +31964,9 @@ var SqliteSecurityRepository = class {
31191
31964
  return rows.map((r) => ({
31192
31965
  occurredAt: r.occurred_at,
31193
31966
  severity: r.severity,
31194
- actionTaken: r.action_taken
31967
+ actionTaken: r.action_taken,
31968
+ ruleId: r.rule_id,
31969
+ category: r.category
31195
31970
  }));
31196
31971
  }
31197
31972
  };
@@ -32019,6 +32794,7 @@ function openWithPragmas(file2) {
32019
32794
  db.exec("PRAGMA journal_mode = WAL");
32020
32795
  db.exec("PRAGMA busy_timeout = 2000");
32021
32796
  db.exec("PRAGMA foreign_keys = ON");
32797
+ registerSqlFunctions(db);
32022
32798
  } catch (err) {
32023
32799
  closeQuietly(db);
32024
32800
  throw err;
@@ -32048,7 +32824,7 @@ function backupLegacyStore(db, file2) {
32048
32824
  discardStore(file2, backup);
32049
32825
  return backup;
32050
32826
  }
32051
- function openAndInitialize(file2, base) {
32827
+ function openAndInitialize(file2, base, skipTags) {
32052
32828
  let db = openWithPragmas(file2);
32053
32829
  try {
32054
32830
  if (isForeignSqliteLineage(db)) {
@@ -32058,7 +32834,7 @@ function openAndInitialize(file2, base) {
32058
32834
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32059
32835
  );
32060
32836
  }
32061
- applyMigrations(db, file2);
32837
+ applyMigrations(db, file2, { skipTags });
32062
32838
  tightenPerms(file2);
32063
32839
  const policies = new SqlitePoliciesRepository(db);
32064
32840
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32073,6 +32849,7 @@ function openAndInitialize(file2, base) {
32073
32849
  exceptions: new SqliteExceptionsRepository(db),
32074
32850
  resolutions: new SqliteResolutionsRepository(db),
32075
32851
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32852
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32076
32853
  security: new SqliteSecurityRepository(db),
32077
32854
  detections: new SqliteDetectionsRepository(db),
32078
32855
  shares: new SqliteSharesRepository(db),
@@ -32095,7 +32872,8 @@ function openAndInitialize(file2, base) {
32095
32872
  throw err;
32096
32873
  }
32097
32874
  }
32098
- function openLocalDatabase(dir) {
32875
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32876
+ function openLocalDatabase(dir, options = {}) {
32099
32877
  ensureDataDirSync(dir);
32100
32878
  const file2 = join7(dir, DB_FILENAME);
32101
32879
  reapStalePartials(file2);
@@ -32107,6 +32885,7 @@ function openLocalDatabase(dir) {
32107
32885
  installedPacks,
32108
32886
  scanLedger,
32109
32887
  historySync,
32888
+ bodyRetention,
32110
32889
  secretVault,
32111
32890
  exceptions,
32112
32891
  resolutions,
@@ -32130,7 +32909,8 @@ function openLocalDatabase(dir) {
32130
32909
  // `dir` is always `<base>/data` — every caller resolves it through
32131
32910
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32132
32911
  // settings/ and data/, and the pack-policy floor needs both halves.
32133
- dirname2(dir)
32912
+ dirname2(dir),
32913
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32134
32914
  );
32135
32915
  function captureRowId(event) {
32136
32916
  return captureId(
@@ -32323,6 +33103,7 @@ function openLocalDatabase(dir) {
32323
33103
  installedPacks,
32324
33104
  scanLedger,
32325
33105
  historySync,
33106
+ bodyRetention,
32326
33107
  secretVault,
32327
33108
  exceptions,
32328
33109
  resolutions,
@@ -32361,6 +33142,70 @@ function openLocalDatabase(dir) {
32361
33142
  };
32362
33143
  }
32363
33144
 
33145
+ // ../../packages/persistence/src/egress-wire.ts
33146
+ import { createHash as createHash3 } from "crypto";
33147
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33148
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33149
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33150
+ var FILE_URL = /^file:\/\//i;
33151
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33152
+ var SLASH = "/".charCodeAt(0);
33153
+ var GIT_SUFFIX = ".git";
33154
+ function trimSlashes(path) {
33155
+ let start = 0;
33156
+ let end = path.length;
33157
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33158
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33159
+ return path.slice(start, end);
33160
+ }
33161
+ function canonicalGitUrl(url2) {
33162
+ const trimmed = url2.trim();
33163
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33164
+ const scheme = SCHEME_FORM.exec(trimmed);
33165
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33166
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33167
+ if (host === void 0) return trimmed;
33168
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33169
+ const bare = trimSlashes(path);
33170
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33171
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33172
+ }
33173
+ function hashProjectKey(projectKey) {
33174
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33175
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33176
+ }
33177
+ function toIngestHit(hit) {
33178
+ return {
33179
+ host: hit.host,
33180
+ kind: hit.kind,
33181
+ name: hit.name,
33182
+ category: hit.category,
33183
+ trust: hit.trust,
33184
+ network: hit.network,
33185
+ method: hit.method,
33186
+ transport: hit.transport,
33187
+ url: hit.url,
33188
+ template: hit.template,
33189
+ dataClass: hit.dataClass,
33190
+ site: {
33191
+ file: hit.site.file,
33192
+ line: hit.site.line,
33193
+ dynamic: hit.site.dynamic,
33194
+ vendored: hit.site.vendored
33195
+ }
33196
+ };
33197
+ }
33198
+ function toEgressIngestRequest(input2) {
33199
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33200
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33201
+ return {
33202
+ projectKey: hashProjectKey(input2.projectKey),
33203
+ project: input2.project,
33204
+ reconcile,
33205
+ hits: hits.map(toIngestHit)
33206
+ };
33207
+ }
33208
+
32364
33209
  // ../../packages/persistence/src/exception-policy.ts
32365
33210
  var UserGrantPolicyProvider = class {
32366
33211
  #exceptions;
@@ -32382,13 +33227,13 @@ var UserGrantPolicyProvider = class {
32382
33227
  };
32383
33228
 
32384
33229
  // ../../packages/persistence/src/finding-key.ts
32385
- import { createHash as createHash3 } from "crypto";
33230
+ import { createHash as createHash4 } from "crypto";
32386
33231
  function normalizeFilePath(filePath) {
32387
33232
  return filePath.replaceAll("\\", "/");
32388
33233
  }
32389
33234
  function computeFindingKey(input2) {
32390
33235
  const normalizedPath = normalizeFilePath(input2.filePath);
32391
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
33236
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32392
33237
  }
32393
33238
 
32394
33239
  // ../../packages/persistence/src/fingerprint.ts
@@ -32514,14 +33359,50 @@ function fingerprintValue(key, raw) {
32514
33359
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32515
33360
  }
32516
33361
 
32517
- // ../../packages/persistence/src/history-preview.ts
32518
- import { existsSync as existsSync4 } from "fs";
33362
+ // ../../packages/persistence/src/forward-health.ts
33363
+ import { readFileSync as readFileSync7 } from "fs";
32519
33364
  import { join as join9 } from "path";
33365
+ var FAILURES = /* @__PURE__ */ new Set([
33366
+ "unauthorized",
33367
+ "forbidden",
33368
+ "unreachable"
33369
+ ]);
33370
+ var BREAKER_COOLDOWN_MS = 3e4;
33371
+ function parseForwardHealth(raw, nowMs) {
33372
+ try {
33373
+ const parsed2 = JSON.parse(raw);
33374
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33375
+ const record2 = parsed2;
33376
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33377
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33378
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33379
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33380
+ } catch {
33381
+ return null;
33382
+ }
33383
+ }
33384
+ function isForwardPaused(health, nowMs) {
33385
+ const openedAtMs = health?.openedAtMs ?? null;
33386
+ if (openedAtMs === null) return false;
33387
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33388
+ }
33389
+
33390
+ // ../../packages/persistence/src/history-backfill.ts
33391
+ import { existsSync as existsSync4 } from "fs";
33392
+ import { join as join10 } from "path";
33393
+
33394
+ // ../../packages/persistence/src/history-preview.ts
33395
+ import { existsSync as existsSync5 } from "fs";
33396
+ import { join as join11 } from "path";
32520
33397
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32521
33398
 
33399
+ // ../../packages/persistence/src/history-sync-state.ts
33400
+ import { readFileSync as readFileSync8 } from "fs";
33401
+ import { join as join12 } from "path";
33402
+
32522
33403
  // ../../packages/persistence/src/store-symlinks.ts
32523
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32524
- import { dirname as dirname3, join as join10, resolve } from "path";
33404
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33405
+ import { dirname as dirname3, join as join13, resolve } from "path";
32525
33406
 
32526
33407
  // ../../packages/persistence/src/vault/crypto.ts
32527
33408
  import {
@@ -32634,8 +33515,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32634
33515
  // ../../packages/persistence/src/vault/key-provider.ts
32635
33516
  import { execFileSync } from "child_process";
32636
33517
  import { randomBytes as randomBytes2 } from "crypto";
32637
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32638
- import { join as join11 } from "path";
33518
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33519
+ import { join as join14 } from "path";
32639
33520
  var VAULT_OCCUPANT_REASON = {
32640
33521
  symlink: "the path is a symlink; remove it so a keyring can be created",
32641
33522
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32734,7 +33615,7 @@ function claimRotationLock(lock, owner) {
32734
33615
  throw asError(err);
32735
33616
  }
32736
33617
  try {
32737
- writeFileSync3(join11(lock, LOCK_OWNER_FILE), `${owner}
33618
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32738
33619
  `, { mode: DATA_FILE_MODE });
32739
33620
  return true;
32740
33621
  } catch (err) {
@@ -32743,7 +33624,7 @@ function claimRotationLock(lock, owner) {
32743
33624
  }
32744
33625
  }
32745
33626
  function acquireRotationLock(keysDir2) {
32746
- const lock = join11(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33627
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32747
33628
  const owner = randomBytes2(16).toString("hex");
32748
33629
  if (claimRotationLock(lock, owner)) return { lock, owner };
32749
33630
  let held;
@@ -32770,7 +33651,7 @@ function acquireRotationLock(keysDir2) {
32770
33651
  }
32771
33652
  function releaseRotationLock(lease) {
32772
33653
  try {
32773
- if (readFileSync7(join11(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33654
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
32774
33655
  } catch {
32775
33656
  return;
32776
33657
  }
@@ -32791,7 +33672,7 @@ var FileKeyProvider = class {
32791
33672
  this.#keysDir = keysDir2;
32792
33673
  }
32793
33674
  get filePath() {
32794
- return join11(this.#keysDir, VAULT_KEY_FILENAME);
33675
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
32795
33676
  }
32796
33677
  loadOrCreate() {
32797
33678
  return asAsync(() => {
@@ -32821,7 +33702,7 @@ var FileKeyProvider = class {
32821
33702
  #read() {
32822
33703
  let raw;
32823
33704
  try {
32824
- raw = readFileSync7(this.filePath, "utf8");
33705
+ raw = readFileSync9(this.filePath, "utf8");
32825
33706
  } catch (err) {
32826
33707
  if (err.code === "ENOENT") return null;
32827
33708
  throw err instanceof Error ? err : new Error(String(err));
@@ -33456,13 +34337,13 @@ var SecretVault = class {
33456
34337
  };
33457
34338
 
33458
34339
  // ../../packages/persistence/src/warn-era-cap.ts
33459
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
33460
- import { join as join12 } from "path";
34340
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
34341
+ import { join as join15 } from "path";
33461
34342
  var MARKER = "warn-era-capped";
33462
34343
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33463
34344
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33464
- const marker = join12(dataDir2, MARKER);
33465
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
34345
+ const marker = join15(dataDir2, MARKER);
34346
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33466
34347
  const capped = db.policies.capCategoryActions();
33467
34348
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
33468
34349
  `, { mode: DATA_FILE_MODE });
@@ -33470,8 +34351,8 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33470
34351
  }
33471
34352
 
33472
34353
  // ../../packages/plugin-sdk/src/config.ts
33473
- import { existsSync as existsSync7 } from "fs";
33474
- import { join as join13 } from "path";
34354
+ import { existsSync as existsSync8 } from "fs";
34355
+ import { join as join16 } from "path";
33475
34356
 
33476
34357
  // ../../packages/plugin-sdk/src/provider-env.ts
33477
34358
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33525,8 +34406,8 @@ function resolveProvider() {
33525
34406
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33526
34407
  try {
33527
34408
  ensureLayoutDirSync(base);
33528
- const settingsFile = join13(settingsDir(base), "settings.json");
33529
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
34409
+ const settingsFile = join16(settingsDir(base), "settings.json");
34410
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33530
34411
  } catch {
33531
34412
  }
33532
34413
  migrateLegacyLayout(base);
@@ -33549,9 +34430,9 @@ function resolveProviderSafe(resolveProviderFn) {
33549
34430
  }
33550
34431
 
33551
34432
  // ../../packages/plugin-sdk/src/config-inventory.ts
33552
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34433
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33553
34434
  import { homedir as homedir2 } from "os";
33554
- import { basename as basename3, join as join15 } from "path";
34435
+ import { basename as basename3, join as join18 } from "path";
33555
34436
 
33556
34437
  // ../../packages/detections/src/egress/registry.ts
33557
34438
  var EXTRACTOR_VERSION = "1";
@@ -36640,8 +37521,8 @@ function bundledDetections() {
36640
37521
  }
36641
37522
 
36642
37523
  // ../../packages/plugin-sdk/src/repo.ts
36643
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36644
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
37524
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
37525
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
36645
37526
  function resolveRepo(cwd) {
36646
37527
  try {
36647
37528
  const root = findGitRoot(cwd);
@@ -36663,36 +37544,36 @@ function resolveWorktreeRoot(cwd) {
36663
37544
  function findGitRoot(start) {
36664
37545
  let dir = start;
36665
37546
  for (; ; ) {
36666
- if (existsSync8(join14(dir, ".git"))) return dir;
37547
+ if (existsSync9(join17(dir, ".git"))) return dir;
36667
37548
  const parent = dirname4(dir);
36668
37549
  if (parent === dir) return void 0;
36669
37550
  dir = parent;
36670
37551
  }
36671
37552
  }
36672
37553
  function resolveGitContext(root) {
36673
- const dotGit = join14(root, ".git");
37554
+ const dotGit = join17(root, ".git");
36674
37555
  try {
36675
37556
  if (statSync6(dotGit).isDirectory()) {
36676
- return { configPath: join14(dotGit, "config"), headRoot: root };
37557
+ return { configPath: join17(dotGit, "config"), headRoot: root };
36677
37558
  }
36678
37559
  } catch {
36679
37560
  return void 0;
36680
37561
  }
36681
37562
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36682
37563
  if (!target) return void 0;
36683
- const gitdir = isAbsolute(target) ? target : join14(root, target);
36684
- if (existsSync8(join14(gitdir, "config"))) {
36685
- return { configPath: join14(gitdir, "config"), headRoot: root };
37564
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
37565
+ if (existsSync9(join17(gitdir, "config"))) {
37566
+ return { configPath: join17(gitdir, "config"), headRoot: root };
36686
37567
  }
36687
- const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
37568
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
36688
37569
  if (!commonRaw) return void 0;
36689
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
37570
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
36690
37571
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36691
- return { configPath: join14(commonGitDir, "config"), headRoot };
37572
+ return { configPath: join17(commonGitDir, "config"), headRoot };
36692
37573
  }
36693
37574
  function safeRead(path) {
36694
37575
  try {
36695
- return readFileSync8(path, "utf8");
37576
+ return readFileSync10(path, "utf8");
36696
37577
  } catch {
36697
37578
  return void 0;
36698
37579
  }
@@ -36730,9 +37611,9 @@ function slugFromUrl(url2) {
36730
37611
  }
36731
37612
 
36732
37613
  // ../../packages/plugin-sdk/src/events.ts
36733
- import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
37614
+ import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36734
37615
  function contentHashOf(text) {
36735
- return createHash4("sha256").update(text).digest("hex");
37616
+ return createHash5("sha256").update(text).digest("hex");
36736
37617
  }
36737
37618
  function buildIngestEvent(input2) {
36738
37619
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -36758,7 +37639,7 @@ function buildIngestEvent(input2) {
36758
37639
  }
36759
37640
 
36760
37641
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36761
- import { existsSync as existsSync9 } from "fs";
37642
+ import { existsSync as existsSync10 } from "fs";
36762
37643
  import { fileURLToPath } from "url";
36763
37644
  import { Worker } from "worker_threads";
36764
37645
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -36772,7 +37653,7 @@ function resolveWorkerUrl() {
36772
37653
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
36773
37654
  const candidate = new URL(name, import.meta.url);
36774
37655
  try {
36775
- if (existsSync9(fileURLToPath(candidate))) {
37656
+ if (existsSync10(fileURLToPath(candidate))) {
36776
37657
  resolvedWorkerUrl = candidate;
36777
37658
  return candidate;
36778
37659
  }
@@ -37235,13 +38116,9 @@ function createGuardedScanner(partition, gateway, opts) {
37235
38116
  };
37236
38117
  }
37237
38118
 
37238
- // ../../packages/plugin-sdk/src/ignore-layers.ts
37239
- var import_ignore = __toESM(require_ignore(), 1);
37240
- import { readFileSync as readFileSync10 } from "fs";
37241
- import { join as join16 } from "path";
37242
-
37243
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
37244
- import { arch, hostname as hostname4, platform, release } from "os";
38119
+ // ../../packages/plugin-sdk/src/host-floor.ts
38120
+ import { readFileSync as readFileSync13 } from "fs";
38121
+ import { join as join20 } from "path";
37245
38122
 
37246
38123
  // ../../packages/plugin-sdk/src/model-governance.ts
37247
38124
  import {
@@ -37249,16 +38126,42 @@ import {
37249
38126
  fstatSync,
37250
38127
  mkdirSync as mkdirSync2,
37251
38128
  openSync as openSync2,
37252
- readFileSync as readFileSync11,
38129
+ readFileSync as readFileSync12,
37253
38130
  readSync,
37254
38131
  writeFileSync as writeFileSync5
37255
38132
  } from "fs";
37256
- import { join as join17 } from "path";
38133
+ import { join as join19 } from "path";
37257
38134
  var TAIL_BYTES = 256 * 1024;
37258
38135
 
38136
+ // ../../packages/plugin-sdk/src/host-floor.ts
38137
+ var HOST_FEATURE = {
38138
+ ModelSwitch: "model-switch",
38139
+ VaultPointerDisplay: "vault-pointer-display"
38140
+ };
38141
+ var HOST_FLOORS = {
38142
+ [HOST_FEATURE.ModelSwitch]: {
38143
+ label: "model-switch protection",
38144
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
38145
+ since: "2.1.251"
38146
+ },
38147
+ [HOST_FEATURE.VaultPointerDisplay]: {
38148
+ label: "vault pointer display",
38149
+ hookEvents: ["MessageDisplay"],
38150
+ since: "2.1.152"
38151
+ }
38152
+ };
38153
+
38154
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
38155
+ var import_ignore = __toESM(require_ignore(), 1);
38156
+ import { readFileSync as readFileSync14 } from "fs";
38157
+ import { join as join21 } from "path";
38158
+
38159
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
38160
+ import { arch, hostname as hostname4, platform, release } from "os";
38161
+
37259
38162
  // ../../packages/plugin-sdk/src/nudge.ts
37260
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
37261
- import { join as join18 } from "path";
38163
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
38164
+ import { join as join22 } from "path";
37262
38165
 
37263
38166
  // ../../packages/plugin-sdk/src/paths.ts
37264
38167
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37310,8 +38213,8 @@ function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
37310
38213
  }
37311
38214
 
37312
38215
  // ../../packages/plugin-sdk/src/project-files.ts
37313
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
37314
- import { basename as basename5, join as join19 } from "path";
38216
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
38217
+ import { basename as basename5, join as join23 } from "path";
37315
38218
 
37316
38219
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37317
38220
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37352,6 +38255,14 @@ function safeMaskedMatch(rawMatch) {
37352
38255
  // ../../packages/plugin-sdk/src/runtime.ts
37353
38256
  import { randomUUID as randomUUID14 } from "crypto";
37354
38257
  var ENFORCEMENT_CEILING_ENABLED = false;
38258
+ function applyEnforcementCeiling(action, policyMode, enabled) {
38259
+ if (!enabled || policyMode !== "warn") return action;
38260
+ return action === "block" || action === "redact" ? "warn" : action;
38261
+ }
38262
+ function resolveEnforcedAction(action, opts) {
38263
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
38264
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
38265
+ }
37355
38266
  function startTiming() {
37356
38267
  try {
37357
38268
  return performance.now();
@@ -37388,7 +38299,7 @@ function createPluginRuntime(gateway, settings, opts) {
37388
38299
  bundlesPacked = true;
37389
38300
  }
37390
38301
  const policyMode = settings.policy;
37391
- const redactFallback = settings.redactFallback;
38302
+ let redactFallback = settings.redactFallback;
37392
38303
  const dataDir2 = opts?.dataDir;
37393
38304
  let rules = [];
37394
38305
  let scanner;
@@ -37432,6 +38343,7 @@ function createPluginRuntime(gateway, settings, opts) {
37432
38343
  rules = [...verified, ...unverified];
37433
38344
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
37434
38345
  bundleExceptions = bundle.exceptions ?? [];
38346
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
37435
38347
  initialized = true;
37436
38348
  }
37437
38349
  let cachedKey;
@@ -37460,21 +38372,23 @@ function createPluginRuntime(gateway, settings, opts) {
37460
38372
  }
37461
38373
  function actionForFinding(finding, excepted, rewritable = true) {
37462
38374
  if (excepted?.has(finding)) return "allow";
37463
- const action = resolveAction(finding.ruleId, finding.category);
37464
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
37465
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
37466
- return "warn";
37467
- }
37468
- return action;
38375
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
38376
+ policyMode,
38377
+ redactFallback,
38378
+ rewritable,
38379
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
38380
+ });
37469
38381
  }
37470
38382
  function decide(findings, text, excepted, rewritable = true) {
37471
38383
  if (findings.length === 0) return { action: "log", text, findings: [] };
37472
38384
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38385
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38386
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
37473
38387
  let worst = "log";
37474
38388
  for (const finding of findings) {
37475
38389
  worst = strongerAction(worst, actionFor(finding));
37476
38390
  }
37477
- if (worst === "block") return { action: "block", text: null, findings };
38391
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
37478
38392
  if (worst === "redact") {
37479
38393
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
37480
38394
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -37484,9 +38398,13 @@ function createPluginRuntime(gateway, settings, opts) {
37484
38398
  findings,
37485
38399
  enforcedFindings: redactFindings,
37486
38400
  reversibleFindings
38401
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38402
+ // CAPTURE, so on an unrewritable field every redact has already become
38403
+ // the fallback and this branch is unreachable. Spreading it would read
38404
+ // as a case that can happen.
37487
38405
  };
37488
38406
  }
37489
- return { action: worst, text, findings };
38407
+ return { action: worst, text, findings, ...degraded };
37490
38408
  }
37491
38409
  function fingerprintOf(key, finding, cache) {
37492
38410
  let fp = cache.get(finding);
@@ -37615,8 +38533,8 @@ function createPluginRuntime(gateway, settings, opts) {
37615
38533
  };
37616
38534
  }
37617
38535
  }
37618
- async function processText(text, context) {
37619
- return (await evaluate(text, context, {})).decision;
38536
+ async function processText(text, context, opts2 = {}) {
38537
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
37620
38538
  }
37621
38539
  async function capture(input2, opts2 = {}) {
37622
38540
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -37639,10 +38557,12 @@ function createPluginRuntime(gateway, settings, opts) {
37639
38557
  );
37640
38558
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
37641
38559
  const inspectionMs = elapsedMs(timingStartedAt);
37642
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
38560
+ const redactDegradedTo = decision.redactDegradedTo;
38561
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
37643
38562
  ...input2.metadata,
37644
38563
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
37645
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
38564
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
38565
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
37646
38566
  } : input2.metadata;
37647
38567
  const event = buildIngestEvent({
37648
38568
  kind: input2.kind,
@@ -37714,7 +38634,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37714
38634
 
37715
38635
  // ../../packages/plugin-sdk/src/throttle.ts
37716
38636
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37717
- import { join as join20 } from "path";
38637
+ import { join as join24 } from "path";
37718
38638
 
37719
38639
  // ../../packages/plugin-sdk/src/tokenize.ts
37720
38640
  function redactedPlaceholder(category) {
@@ -38070,7 +38990,7 @@ function routeRemediationOption(option, handlers) {
38070
38990
 
38071
38991
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
38072
38992
  import { writeFileSync as writeFileSync8 } from "fs";
38073
- import { join as join21 } from "path";
38993
+ import { join as join25 } from "path";
38074
38994
  var GENERIC_CONSOLE_PATH = "rotate via the provider's own console";
38075
38995
  var CONSOLE_PATHS = {
38076
38996
  anthropic: "console.anthropic.com \u2192 Settings \u2192 API keys",
@@ -38170,7 +39090,7 @@ function generateRotationChecklist(input2) {
38170
39090
  try {
38171
39091
  const target = resolveRotationChecklistTarget(input2.cwd);
38172
39092
  targetDirectory = target.directory;
38173
- const filePath = join21(target.directory, "rotation-checklist.md");
39093
+ const filePath = join25(target.directory, "rotation-checklist.md");
38174
39094
  writeRotationChecklist(input2.entries, target.directory);
38175
39095
  return {
38176
39096
  status: "written",
@@ -38281,9 +39201,9 @@ var RANK = Object.fromEntries(
38281
39201
  );
38282
39202
 
38283
39203
  // ../../packages/setup-wizard/src/triage/plan-file.ts
38284
- import { mkdtempSync, readFileSync as readFileSync13, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
39204
+ import { mkdtempSync, readFileSync as readFileSync16, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
38285
39205
  import { tmpdir } from "os";
38286
- import { basename as basename6, dirname as dirname6, join as join22 } from "path";
39206
+ import { basename as basename6, dirname as dirname6, join as join26 } from "path";
38287
39207
  var SuppressionEntrySchema = external_exports.object({
38288
39208
  ruleId: external_exports.string(),
38289
39209
  category: DetectionCategory,
@@ -38487,44 +39407,7 @@ function renderRemediationDecision(findings, moreCount, registry2) {
38487
39407
  }
38488
39408
 
38489
39409
  // src/remediation/surfaced-redact.ts
38490
- import { readFileSync as readFileSync21 } from "fs";
38491
-
38492
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
38493
- import { createHash as createHash5 } from "crypto";
38494
- function hashProjectKey(projectKey) {
38495
- return createHash5("sha256").update(projectKey, "utf8").digest("hex");
38496
- }
38497
- function toIngestHit(hit) {
38498
- return {
38499
- host: hit.host,
38500
- kind: hit.kind,
38501
- name: hit.name,
38502
- category: hit.category,
38503
- trust: hit.trust,
38504
- network: hit.network,
38505
- method: hit.method,
38506
- transport: hit.transport,
38507
- url: hit.url,
38508
- template: hit.template,
38509
- dataClass: hit.dataClass,
38510
- site: {
38511
- file: hit.site.file,
38512
- line: hit.site.line,
38513
- dynamic: hit.site.dynamic,
38514
- vendored: hit.site.vendored
38515
- }
38516
- };
38517
- }
38518
- function toEgressIngestRequest(input2) {
38519
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
38520
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
38521
- return {
38522
- projectKey: hashProjectKey(input2.projectKey),
38523
- project: input2.project,
38524
- reconcile,
38525
- hits: hits.map(toIngestHit)
38526
- };
38527
- }
39410
+ import { readFileSync as readFileSync22 } from "fs";
38528
39411
 
38529
39412
  // ../../packages/remote/src/http.ts
38530
39413
  import { request as httpRequest } from "http";
@@ -38709,10 +39592,10 @@ function parsed(schema, body, route2) {
38709
39592
  }
38710
39593
  function withoutTrailingSlashes(endpoint) {
38711
39594
  let end = endpoint.length;
38712
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
39595
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
38713
39596
  return endpoint.slice(0, end);
38714
39597
  }
38715
- var SLASH = "/".charCodeAt(0);
39598
+ var SLASH2 = "/".charCodeAt(0);
38716
39599
  function createRemoteClient(options) {
38717
39600
  const base = withoutTrailingSlashes(options.endpoint);
38718
39601
  const url2 = (route2) => `${base}${route2}`;
@@ -38805,6 +39688,7 @@ function createRemoteClient(options) {
38805
39688
  url: url2(ROUTES.shares),
38806
39689
  body: JSON.stringify(validated.data)
38807
39690
  });
39691
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
38808
39692
  okBody(response);
38809
39693
  },
38810
39694
  async pollCommand() {
@@ -38827,19 +39711,51 @@ function createRemoteClient(options) {
38827
39711
  };
38828
39712
  }
38829
39713
 
38830
- // ../../packages/plugin-runtime/src/attached/failure.ts
39714
+ // ../../packages/remote/src/failure-kind.ts
38831
39715
  function statusOf(err) {
38832
39716
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
38833
39717
  const { status } = err;
38834
39718
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
38835
39719
  return status >= 100 && status <= 599 ? status : null;
38836
39720
  }
38837
- function classifyFailure(err) {
38838
- switch (statusOf(err)) {
39721
+ function nameOf(err) {
39722
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
39723
+ return typeof err.name === "string" ? err.name : null;
39724
+ }
39725
+ function classifyRemoteFailure(err) {
39726
+ switch (nameOf(err)) {
39727
+ case "RemoteRouteAbsent":
39728
+ return "route-absent";
39729
+ case "RemoteRequestInvalid":
39730
+ return "invalid-request";
39731
+ case "RemoteResponseInvalid":
39732
+ return "rejected";
39733
+ default:
39734
+ break;
39735
+ }
39736
+ const status = statusOf(err);
39737
+ if (status === null) return "unreachable";
39738
+ switch (status) {
38839
39739
  case 401:
38840
39740
  return "unauthorized";
38841
39741
  case 403:
38842
39742
  return "forbidden";
39743
+ case 429:
39744
+ return "unreachable";
39745
+ case 404:
39746
+ return "unreachable";
39747
+ default:
39748
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
39749
+ }
39750
+ }
39751
+
39752
+ // ../../packages/plugin-runtime/src/attached/failure.ts
39753
+ function classifyFailure(err) {
39754
+ switch (classifyRemoteFailure(err)) {
39755
+ case "unauthorized":
39756
+ return "unauthorized";
39757
+ case "forbidden":
39758
+ return "forbidden";
38843
39759
  default:
38844
39760
  return "unreachable";
38845
39761
  }
@@ -38861,11 +39777,11 @@ function withTimeout(promise2, ms) {
38861
39777
  }
38862
39778
 
38863
39779
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
38864
- import { readFileSync as readFileSync14 } from "fs";
38865
- import { join as join23 } from "path";
39780
+ import { readFileSync as readFileSync17 } from "fs";
39781
+ import { join as join27 } from "path";
38866
39782
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
38867
39783
  function forwardDropsPath(dataDir2) {
38868
- return join23(dataDir2, FORWARD_DROPS_FILENAME);
39784
+ return join27(dataDir2, FORWARD_DROPS_FILENAME);
38869
39785
  }
38870
39786
  function recordForwardDrops(dataDir2, count, nowMs) {
38871
39787
  if (count <= 0) return;
@@ -38883,7 +39799,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
38883
39799
  }
38884
39800
  function readForwardDrops(dataDir2) {
38885
39801
  try {
38886
- const parsed2 = JSON.parse(readFileSync14(forwardDropsPath(dataDir2), "utf8"));
39802
+ const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
38887
39803
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
38888
39804
  const record2 = parsed2;
38889
39805
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -38901,9 +39817,8 @@ function readForwardDrops(dataDir2) {
38901
39817
 
38902
39818
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
38903
39819
  import { randomUUID as randomUUID15 } from "crypto";
38904
- import { readFileSync as readFileSync15 } from "fs";
38905
39820
  import { readFile, rename, writeFile } from "fs/promises";
38906
- import { join as join24 } from "path";
39821
+ import { join as join28 } from "path";
38907
39822
  function isInvalidRequest(err) {
38908
39823
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
38909
39824
  }
@@ -38917,31 +39832,12 @@ function isServerRejection(err) {
38917
39832
  var FORWARD_BUDGET_MS = 1500;
38918
39833
  var DECISION_PATH_BUDGET_MS = 800;
38919
39834
  var BREAKER_FAILURE_THRESHOLD = 3;
38920
- var BREAKER_COOLDOWN_MS = 3e4;
38921
39835
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
38922
- var FAILURES = /* @__PURE__ */ new Set([
38923
- "unauthorized",
38924
- "forbidden",
38925
- "unreachable"
38926
- ]);
38927
39836
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
38928
39837
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
38929
- function parseBreakerState(raw, nowMs) {
38930
- try {
38931
- const parsed2 = JSON.parse(raw);
38932
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
38933
- const record2 = parsed2;
38934
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
38935
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
38936
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
38937
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
38938
- } catch {
38939
- return null;
38940
- }
38941
- }
38942
39838
  function createForwardPolicy(deps) {
38943
39839
  const now = deps.now ?? (() => Date.now());
38944
- const file2 = join24(deps.dir, STATE_FILENAME);
39840
+ const file2 = join28(deps.dir, STATE_FILENAME);
38945
39841
  let state = null;
38946
39842
  let loading = null;
38947
39843
  async function readState() {
@@ -38951,7 +39847,7 @@ function createForwardPolicy(deps) {
38951
39847
  } catch {
38952
39848
  return { ...CLOSED };
38953
39849
  }
38954
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39850
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
38955
39851
  }
38956
39852
  async function load() {
38957
39853
  if (state !== null) return state;
@@ -38997,7 +39893,7 @@ function createForwardPolicy(deps) {
38997
39893
  };
38998
39894
  const at = now();
38999
39895
  if (current.openedAtMs !== null) {
39000
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39896
+ if (isForwardPaused(current, at)) {
39001
39897
  return { ok: false, reason: "breaker-open" };
39002
39898
  }
39003
39899
  await persist({
@@ -39534,7 +40430,18 @@ var AttachedDataGateway = class {
39534
40430
  // and the spread above would otherwise drop the field silently — which is
39535
40431
  // exactly what it did, leaving the whole control inert on every device
39536
40432
  // while every test around it stayed green.
39537
- prohibitedModels: cached2.prohibitedModels
40433
+ prohibitedModels: cached2.prohibitedModels,
40434
+ // NAMED for the same reason as the line above, and it is the same defect
40435
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
40436
+ // only the cache carries is dropped in silence. That is what left
40437
+ // `prohibitedModels` inert on every attached device with every test
40438
+ // around it green.
40439
+ //
40440
+ // Taken from the cache rather than merged here, because merging it needs
40441
+ // the device's own SETTING — which is not a bundle field and is not in
40442
+ // scope at this seam. The runtime does that merge, raise-only, where both
40443
+ // values are in hand (createPluginRuntime's ensureInitialized).
40444
+ redactFallback: cached2.redactFallback
39538
40445
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39539
40446
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39540
40447
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39662,10 +40569,6 @@ function toolAuditEvent(input2) {
39662
40569
  };
39663
40570
  }
39664
40571
 
39665
- // ../../packages/plugin-runtime/src/attached/history-state.ts
39666
- import { readFileSync as readFileSync16 } from "fs";
39667
- import { join as join25 } from "path";
39668
-
39669
40572
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39670
40573
  import { createHash as createHash6 } from "crypto";
39671
40574
  import { hostname as hostname5 } from "os";
@@ -39674,6 +40577,10 @@ import { hostname as hostname5 } from "os";
39674
40577
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39675
40578
  var TRACE_ID = EventMetadata.shape.traceId;
39676
40579
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40580
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40581
+
40582
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
40583
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39677
40584
 
39678
40585
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39679
40586
  import { spawn } from "child_process";
@@ -39681,7 +40588,7 @@ import { fileURLToPath as fileURLToPath3 } from "url";
39681
40588
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
39682
40589
 
39683
40590
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
39684
- import { readFileSync as readFileSync17 } from "fs";
40591
+ import { readFileSync as readFileSync18 } from "fs";
39685
40592
  function createPluginBlock(build, policyStore) {
39686
40593
  return async () => {
39687
40594
  const cached2 = await policyStore.read();
@@ -39700,7 +40607,7 @@ function createPluginBlock(build, policyStore) {
39700
40607
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39701
40608
  import { randomUUID as randomUUID16 } from "crypto";
39702
40609
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39703
- import { join as join26 } from "path";
40610
+ import { join as join29 } from "path";
39704
40611
 
39705
40612
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39706
40613
  import { rename as rename2 } from "fs/promises";
@@ -39724,7 +40631,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39724
40631
 
39725
40632
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39726
40633
  function createPolicyStore(dir = dataDir()) {
39727
- const file2 = join26(dir, "policy-cache.json");
40634
+ const file2 = join29(dir, "policy-cache.json");
39728
40635
  async function read() {
39729
40636
  try {
39730
40637
  const raw = await readFile2(file2, "utf8");
@@ -39955,11 +40862,11 @@ function readStorePosture(dbPath2) {
39955
40862
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39956
40863
  import { randomUUID as randomUUID17 } from "crypto";
39957
40864
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39958
- import { join as join27 } from "path";
40865
+ import { join as join30 } from "path";
39959
40866
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39960
40867
  function createPostureStore(dir = settingsDir(), legacyDir) {
39961
- const file2 = join27(dir, "posture-state.json");
39962
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
40868
+ const file2 = join30(dir, "posture-state.json");
40869
+ const legacyFile = legacyDir === void 0 ? null : join30(legacyDir, "posture-state.json");
39963
40870
  async function persist(state) {
39964
40871
  await ensureDataDir(dir);
39965
40872
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -40027,8 +40934,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40027
40934
  }
40028
40935
 
40029
40936
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
40030
- import { readFileSync as readFileSync18 } from "fs";
40031
- import { join as join28 } from "path";
40937
+ import { readFileSync as readFileSync19 } from "fs";
40938
+ import { join as join31 } from "path";
40032
40939
 
40033
40940
  // ../../packages/plugin-runtime/src/attached/status.ts
40034
40941
  var REFUSAL_LINES = {
@@ -40049,6 +40956,14 @@ import { spawn as spawn2 } from "child_process";
40049
40956
  import { fileURLToPath as fileURLToPath4 } from "url";
40050
40957
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
40051
40958
 
40959
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40960
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40961
+
40962
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40963
+ import { spawn as spawn3 } from "child_process";
40964
+ import { fileURLToPath as fileURLToPath5 } from "url";
40965
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40966
+
40052
40967
  // ../../packages/plugin-runtime/src/attached/factory.ts
40053
40968
  import { hostname as hostname6 } from "os";
40054
40969
 
@@ -40499,11 +41414,11 @@ import { randomUUID as randomUUID19 } from "crypto";
40499
41414
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
40500
41415
 
40501
41416
  // src/history/transcripts.ts
40502
- import { readdirSync as readdirSync6, readFileSync as readFileSync19 } from "fs";
41417
+ import { readdirSync as readdirSync6, readFileSync as readFileSync20 } from "fs";
40503
41418
  import { homedir as homedir3 } from "os";
40504
- import { join as join29 } from "path";
41419
+ import { join as join32 } from "path";
40505
41420
  function transcriptsDir(home) {
40506
- return join29(home ?? homedir3(), ".claude", "projects");
41421
+ return join32(home ?? homedir3(), ".claude", "projects");
40507
41422
  }
40508
41423
  var DAY_MS5 = 24 * 60 * 60 * 1e3;
40509
41424
 
@@ -40511,14 +41426,14 @@ var DAY_MS5 = 24 * 60 * 60 * 1e3;
40511
41426
  import {
40512
41427
  lstatSync as lstatSync4,
40513
41428
  readdirSync as readdirSync7,
40514
- readFileSync as readFileSync20,
41429
+ readFileSync as readFileSync21,
40515
41430
  realpathSync as realpathSync4,
40516
41431
  renameSync as renameSync5,
40517
41432
  rmSync as rmSync8,
40518
41433
  statSync as statSync10,
40519
41434
  writeFileSync as writeFileSync10
40520
41435
  } from "fs";
40521
- import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join30, relative, resolve as resolve2 } from "path";
41436
+ import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join33, relative, resolve as resolve2 } from "path";
40522
41437
  var REDACTED_PLACEHOLDER = "[REDACTED:SECRET]";
40523
41438
  var REPLACE_PATTERN_SEQUENCE = /\$[$&`'<0-9]/;
40524
41439
  function replacementFor(rawValue, replacements) {
@@ -40577,7 +41492,7 @@ function sweepStrandedTemps(realPath) {
40577
41492
  const pid = Number(pidPart);
40578
41493
  if (pid !== process.pid && isProcessAlive(pid)) continue;
40579
41494
  try {
40580
- const stranded = join30(dir, name);
41495
+ const stranded = join33(dir, name);
40581
41496
  if (!lstatSync4(stranded).isFile()) continue;
40582
41497
  rmSync8(stranded, { force: true });
40583
41498
  } catch {
@@ -40602,7 +41517,7 @@ function redactLeakedKeysDetailed(targets, scope = platformRedactionScope(), rep
40602
41517
  let mode;
40603
41518
  try {
40604
41519
  mode = statSync10(filePath).mode & 511;
40605
- content = readFileSync20(filePath, "utf8");
41520
+ content = readFileSync21(filePath, "utf8");
40606
41521
  } catch {
40607
41522
  continue;
40608
41523
  }
@@ -40727,7 +41642,7 @@ async function redactSurfacedSecrets(findings, overrides = {}) {
40727
41642
  for (const [filePath, fileFindings] of byFile) {
40728
41643
  let content;
40729
41644
  try {
40730
- content = readFileSync21(filePath, "utf8");
41645
+ content = readFileSync22(filePath, "utf8");
40731
41646
  } catch {
40732
41647
  unrecovered.push(...fileFindings);
40733
41648
  continue;
@@ -40888,11 +41803,11 @@ async function route(frameText, rawOption, rawPosture) {
40888
41803
  break;
40889
41804
  }
40890
41805
  }
40891
- if (process.argv[1] && fileURLToPath5(import.meta.url) === process.argv[1]) {
41806
+ if (process.argv[1] && fileURLToPath6(import.meta.url) === process.argv[1]) {
40892
41807
  try {
40893
41808
  const argv = process.argv.slice(2);
40894
41809
  const optionIndex = argv.indexOf("--option");
40895
- const frameText = readFileSync22(0, "utf8");
41810
+ const frameText = readFileSync23(0, "utf8");
40896
41811
  if (optionIndex === -1) {
40897
41812
  present(frameText);
40898
41813
  } else {