@akasecurity/ai-tc-codex 0.9.10 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -491,9 +491,6 @@ var require_ignore = __commonJS({
491
491
  }
492
492
  });
493
493
 
494
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
495
- import { createHash as createHash4 } from "crypto";
496
-
497
494
  // ../../packages/persistence/src/attached-derived.ts
498
495
  import { rmSync } from "fs";
499
496
  import { join } from "path";
@@ -505,6 +502,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
505
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
506
503
  import { join as join2 } from "path";
507
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
508
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
509
514
  var SQLITE_MIGRATIONS = [
510
515
  {
@@ -622,6 +627,30 @@ var SQLITE_MIGRATIONS = [
622
627
  {
623
628
  tag: "0028_activity_session_probe_indexes",
624
629
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
625
654
  }
626
655
  ];
627
656
 
@@ -20669,6 +20698,15 @@ var FindingCategory = external_exports.enum([
20669
20698
  ]).meta({ id: "FindingCategory" });
20670
20699
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20671
20700
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20701
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20702
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20703
+ var FindingDelivery = external_exports.object({
20704
+ state: FindingDeliveryState,
20705
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20706
+ at: external_exports.iso.datetime().optional(),
20707
+ // Only on `not_sent`, and only when a known reason was recorded.
20708
+ reason: SyncFailureReason.optional()
20709
+ }).meta({ id: "FindingDelivery" });
20672
20710
  var ResolutionMethod = external_exports.enum([
20673
20711
  "enforced-in-flight",
20674
20712
  "fixed-at-source",
@@ -20725,7 +20763,10 @@ var FindingInstance = external_exports.object({
20725
20763
  // The session that event belongs to, when it has one — the seam a
20726
20764
  // per-instance "view session" link needs. Absent for events captured
20727
20765
  // outside a session.
20728
- sessionId: external_exports.string().optional()
20766
+ sessionId: external_exports.string().optional(),
20767
+ // The delivery state of the event above (see FindingDelivery). Optional so
20768
+ // readers that do not project it stay valid.
20769
+ delivery: FindingDelivery.optional()
20729
20770
  }).meta({ id: "FindingInstance" });
20730
20771
  var FindingGroup = external_exports.object({
20731
20772
  id: external_exports.string(),
@@ -20742,13 +20783,11 @@ var FindingGroup = external_exports.object({
20742
20783
  latestDetectedAt: external_exports.iso.datetime(),
20743
20784
  instances: external_exports.array(FindingInstance),
20744
20785
  // Derived from instances' statuses with open-dominates precedence (see
20745
- // buildFindingGroups). Undefined only when no instance carries a status.
20786
+ // foldGroupStatus). Undefined only when no instance carries a status.
20746
20787
  status: FindingStatus.optional(),
20747
- // The distinct people across the WHOLE group, not just the `instances`
20748
- // preview — from the store's whole-group aggregate when it supplies one,
20749
- // else folded from the rows (see buildFindingGroups). Undefined when no
20750
- // instance carries a user, or when the store supplied whole-group folds
20751
- // without one.
20788
+ // The distinct people across the WHOLE group, not just the instances
20789
+ // carried here. Undefined when no instance carries a user, or when the
20790
+ // store supplied whole-group folds without one.
20752
20791
  users: external_exports.array(FindingUser).optional()
20753
20792
  }).meta({ id: "FindingGroup" });
20754
20793
  var FindingStats = external_exports.object({
@@ -20777,21 +20816,34 @@ var FindingFacets = external_exports.object({
20777
20816
  // counted under no value.
20778
20817
  status: external_exports.array(FindingFacetItem),
20779
20818
  // Host tool (attributes.tool_name). Present only on the instance-level
20780
- // reads, which can filter by it; the grouped read omits the dimension
20819
+ // reads, which can filter by it; the type-level read omits the dimension
20781
20820
  // because a group spans tools.
20782
- tool: external_exports.array(FindingFacetItem).optional()
20821
+ tool: external_exports.array(FindingFacetItem).optional(),
20822
+ // Delivery states (FindingDeliveryState). Present only on the
20823
+ // instance-level reads, like `tool`.
20824
+ deployment: external_exports.array(FindingFacetItem).optional()
20783
20825
  }).meta({ id: "FindingFacets" });
20784
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20785
- var ListGroupedFindingsQuery = external_exports.object({
20826
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20827
+ id: "FindingTypeSummary"
20828
+ });
20829
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20830
+ var MAX_FINDING_TYPES_LIMIT = 100;
20831
+ var ListFindingTypesQuery = external_exports.object({
20786
20832
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20787
- // FindingAction.
20833
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20834
+ // firing version carries, and this list pages types.
20835
+ //
20836
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20837
+ // definition versions at different severities, so a type kept by this filter
20838
+ // can hold findings that individually do not match — see totals.findings on
20839
+ // ListFindingTypesResponse, which counts them all.
20788
20840
  severity: external_exports.array(Severity).optional(),
20789
20841
  subtype: external_exports.array(external_exports.string()).optional(),
20790
20842
  provider: external_exports.array(FindingProvider).optional(),
20791
20843
  action: external_exports.array(FindingAction).optional(),
20792
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20793
- // individual instances' — so a filtered group's Status column always reads
20794
- // one of the requested values.
20844
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20845
+ // individual findings' — so a filtered row's status always reads one of the
20846
+ // requested values.
20795
20847
  status: external_exports.array(FindingStatus).optional(),
20796
20848
  q: external_exports.string().optional(),
20797
20849
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20801,23 +20853,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20801
20853
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20802
20854
  // means all time — this list has no default window.
20803
20855
  from: external_exports.iso.datetime().optional(),
20804
- // A group or instance id that must appear in the page even when the cursor
20805
- // has already advanced past its sort position. This is what keeps the
20806
- // Findings page's one-shot ?finding= deep link resolving once the list
20807
- // paginates: the target group is appended out of sort order rather than
20808
- // scanning forward for it. Never affects totals, facets or the cursor.
20856
+ // A RULE id that must appear in the page even when the cursor has already
20857
+ // advanced past its sort position. This is what keeps the selected type
20858
+ // visible in the list once it paginates: the target is appended out of sort
20859
+ // order rather than scanned forward for. Never affects totals, facets or the
20860
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20861
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20862
+ // and so is not bounded by what any page happens to hold.
20809
20863
  includeId: external_exports.string().optional(),
20810
- groupBy: external_exports.literal("type").optional(),
20811
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20864
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20812
20865
  cursor: external_exports.string().optional()
20813
20866
  });
20814
- var ListGroupedFindingsResponse = external_exports.object({
20867
+ var ListFindingTypesResponse = external_exports.object({
20815
20868
  totals: external_exports.object({
20869
+ // Findings belonging to the matching TYPES — not findings that each match
20870
+ // the filters. The filters here select types, so a type that survives
20871
+ // contributes its whole instanceCount.
20872
+ //
20873
+ // `status` is the one exception, narrowed per finding via
20874
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20875
+ // this can exceed what the instance read reports for the same filters: a
20876
+ // rule whose severity moved between versions is kept on its newest and
20877
+ // still counts its older findings. Narrowing the other three needs
20878
+ // per-dimension counts the aggregate does not carry today.
20816
20879
  findings: external_exports.number().int().nonnegative(),
20817
- groups: external_exports.number().int().nonnegative()
20880
+ // Counts TYPES, which is the unit this read pages. The instance read's
20881
+ // own totals count findings; the two deliberately answer different
20882
+ // questions and are never summed.
20883
+ types: external_exports.number().int().nonnegative()
20818
20884
  }),
20819
20885
  facets: FindingFacets,
20820
- items: external_exports.array(FindingGroup),
20886
+ items: external_exports.array(FindingTypeSummary),
20821
20887
  nextCursor: external_exports.string().nullable(),
20822
20888
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20823
20889
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20825,7 +20891,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20825
20891
  // every firing, so the two numbers legitimately differ — this map lets a
20826
20892
  // session-scoped view show both.
20827
20893
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20828
- }).meta({ id: "ListGroupedFindingsResponse" });
20894
+ }).meta({ id: "ListFindingTypesResponse" });
20829
20895
  var ApplyFindingActionRequest = external_exports.object({
20830
20896
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20831
20897
  // it, so it is excluded from the request contract. The mapping helper
@@ -20855,16 +20921,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20855
20921
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20856
20922
  var ListFindingInstancesQuery = external_exports.object({
20857
20923
  severity: external_exports.array(Severity).optional(),
20858
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20924
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20925
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20859
20926
  subtype: external_exports.array(external_exports.string()).optional(),
20860
20927
  provider: external_exports.array(FindingProvider).optional(),
20861
20928
  action: external_exports.array(FindingAction).optional(),
20862
20929
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20863
- // the grouped query's group-level fold.
20930
+ // the types query's type-level fold.
20864
20931
  status: external_exports.array(FindingStatus).optional(),
20865
20932
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20866
20933
  // where the free-text `q` can only match the rendered "via Bash" label.
20867
20934
  tool: external_exports.array(external_exports.string()).optional(),
20935
+ // The delivery state of each finding's event (see FindingDelivery).
20936
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20868
20937
  // Exact repository / file-path matches, for the drill-down out of the
20869
20938
  // locations view. A row whose event carries no repo/file matches neither.
20870
20939
  repo: external_exports.string().optional(),
@@ -20877,37 +20946,51 @@ var ListFindingInstancesQuery = external_exports.object({
20877
20946
  });
20878
20947
  var ListFindingInstancesResponse = external_exports.object({
20879
20948
  // Instances matching the filters across the whole scope, not just this
20880
- // page — cursor-independent, like the grouped list's totals.
20949
+ // page — cursor-independent, like the types list's totals.
20881
20950
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20882
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20951
+ // Counts in INSTANCES here, where the types response counts types. Each
20883
20952
  // dimension still excludes its own filter.
20884
20953
  facets: FindingFacets,
20885
20954
  items: external_exports.array(FindingInstanceDetail),
20886
20955
  nextCursor: external_exports.string().nullable()
20887
20956
  }).meta({ id: "ListFindingInstancesResponse" });
20888
- var FindingLocationFile = external_exports.object({
20889
- // Empty when the instances carried no file path (a prompt or a tool call
20890
- // with no file attribution).
20891
- file: external_exports.string(),
20892
- instanceCount: external_exports.number().int().nonnegative(),
20893
- maxSeverity: Severity,
20894
- latestDetectedAt: external_exports.iso.datetime(),
20895
- // Folded from the instances' derived statuses with the same
20896
- // open-dominates precedence a group uses.
20897
- status: FindingStatus.optional(),
20898
- // Distinct rules seen at this location, capped — the row shows them as
20899
- // chips, and the count is what conveys scale.
20900
- ruleIds: external_exports.array(external_exports.string())
20901
- }).meta({ id: "FindingLocationFile" });
20902
- var FindingLocationRepo = external_exports.object({
20957
+ var ListFindingInstancesPage = external_exports.object({
20958
+ items: external_exports.array(FindingInstanceDetail),
20959
+ nextCursor: external_exports.string().nullable()
20960
+ }).meta({ id: "ListFindingInstancesPage" });
20961
+ var FindingLocationSummary = external_exports.object({
20962
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20963
+ // because a location's identity is two values and a URL param carries one:
20964
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20965
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20966
+ // client's page dedupe — never decoded, and never a sort key.
20967
+ id: external_exports.string(),
20903
20968
  /** Empty when the instances carried no repo attribute. */
20904
20969
  repo: external_exports.string(),
20970
+ // Empty when the instances carried no file path (a prompt, or a tool call
20971
+ // with no file attribution). Both halves empty is a real location — usually
20972
+ // the largest one in a store — and is selectable like any other.
20973
+ file: external_exports.string(),
20905
20974
  instanceCount: external_exports.number().int().nonnegative(),
20975
+ // The WORST severity present, not the first row's. It is this list's primary
20976
+ // sort key, so it is also what explains why a row is where it is, and it is
20977
+ // how a reader decides what to open without opening everything.
20906
20978
  maxSeverity: Severity,
20907
20979
  latestDetectedAt: external_exports.iso.datetime(),
20980
+ // Folded from the instances' derived statuses with the same open-dominates
20981
+ // precedence a group uses, so it answers "is anything left to do here" and
20982
+ // not much more: a location holding 1 open among 40 resolved reads like one
20983
+ // holding 40 open. That loss is accepted — the panel beside this list
20984
+ // carries each finding's own status, and instanceCount sits next to the
20985
+ // badge.
20908
20986
  status: FindingStatus.optional(),
20909
- files: external_exports.array(FindingLocationFile)
20910
- }).meta({ id: "FindingLocationRepo" });
20987
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20988
+ // tally rather than a sample and a row can say how many there are. Bounded
20989
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20990
+ ruleIds: external_exports.array(external_exports.string())
20991
+ }).meta({ id: "FindingLocationSummary" });
20992
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20993
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20911
20994
  var ListFindingLocationsQuery = external_exports.object({
20912
20995
  severity: external_exports.array(Severity).optional(),
20913
20996
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20917,21 +21000,47 @@ var ListFindingLocationsQuery = external_exports.object({
20917
21000
  // instances that match, and folds its status from those.
20918
21001
  status: external_exports.array(FindingStatus).optional(),
20919
21002
  tool: external_exports.array(external_exports.string()).optional(),
21003
+ // The delivery state of each finding's event (see FindingDelivery).
21004
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20920
21005
  q: external_exports.string().optional(),
20921
21006
  sessionId: external_exports.string().optional(),
20922
21007
  from: external_exports.iso.datetime().optional(),
20923
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21008
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21009
+ // even when the cursor has already advanced past its sort position — the
21010
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21011
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21012
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21013
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21014
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21015
+ includeId: external_exports.string().optional(),
21016
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21017
+ cursor: external_exports.string().optional()
20924
21018
  });
20925
21019
  var ListFindingLocationsResponse = external_exports.object({
20926
21020
  totals: external_exports.object({
21021
+ // Findings matching the filters across the whole scope. Unlike the types
21022
+ // read's same-named field this needs no caveat: the filters here narrow
21023
+ // per finding, so this is the sum of every row's instanceCount.
20927
21024
  findings: external_exports.number().int().nonnegative(),
20928
- repos: external_exports.number().int().nonnegative(),
20929
- files: external_exports.number().int().nonnegative()
21025
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21026
+ // states. The facets beside it count FINDINGS (see below); a surface
21027
+ // showing both says which is which.
21028
+ locations: external_exports.number().int().nonnegative()
20930
21029
  }),
20931
- /** Sorted by max severity, then most recent. */
20932
- items: external_exports.array(FindingLocationRepo),
20933
- /** Whether `limit` truncated the repo list. */
20934
- hasMore: external_exports.boolean()
21030
+ // Counts in FINDINGS, where the types response counts types, each dimension
21031
+ // still excluding its own filter. Deliberately not locations: counting those
21032
+ // needs a set of location keys per dimension per value — memory tracking the
21033
+ // store times the vocabulary, in a read whose scan promises flat memory —
21034
+ // and the cheap per-location version is not an approximation but WRONG. A
21035
+ // location holding {claudecode, block} and {codex, warn} would survive
21036
+ // provider=claudecode AND action=warn, under which no single finding
21037
+ // matches, so the facet would contradict the instanceCount this whole view
21038
+ // rests on. Findings also keep the toolbar in the same unit as the page
21039
+ // tally and the panel it sits above.
21040
+ facets: FindingFacets,
21041
+ /** Sorted by max severity, then most recent, then (repo, file). */
21042
+ items: external_exports.array(FindingLocationSummary),
21043
+ nextCursor: external_exports.string().nullable()
20935
21044
  }).meta({ id: "ListFindingLocationsResponse" });
20936
21045
 
20937
21046
  // ../../packages/schema/src/zod/meta.ts
@@ -21095,6 +21204,10 @@ var CaptureAttributes = external_exports.object({
21095
21204
  // to 'allow' — the enforcement audit trail's link back to the grant that
21096
21205
  // authorized the bypass.
21097
21206
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21207
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21208
+ // join back to the `llm_call` leaf for the same assistant turn.
21209
+ message_id: external_exports.string().optional(),
21210
+ conversation_id: external_exports.string().optional(),
21098
21211
  // Whole milliseconds this capture's inspection blocked its caller — the
21099
21212
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21100
21213
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21103,7 +21216,19 @@ var CaptureAttributes = external_exports.object({
21103
21216
  // inline json_extract and is not itself an optimization.
21104
21217
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21105
21218
  // before the measurement shipped — never present as a placeholder 0.
21106
- inspection_ms: external_exports.number().int().nonnegative().optional()
21219
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21220
+ // What a `redact` this capture could not carry out became instead (see
21221
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21222
+ // degrade actually happened, so absence is the ordinary case rather than a
21223
+ // reader having to distinguish it from a zero.
21224
+ //
21225
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21226
+ // so on a multi-finding row this does not say which finding degraded, and
21227
+ // its presence does not mean the fallback decided the capture's action. A
21228
+ // capture denied by another finding's own Block policy carries `block`
21229
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21230
+ // repeated rather than referenced because a store reader opens this file.
21231
+ redact_degraded_to: ActionTaken.optional()
21107
21232
  }).catchall(external_exports.unknown());
21108
21233
  var ToolCallInspection = external_exports.object({
21109
21234
  ruleId: external_exports.string().min(1),
@@ -21302,7 +21427,17 @@ var AuditEvent = external_exports.object({
21302
21427
  /** `share` to a first-party/internal destination. */
21303
21428
  internal: external_exports.boolean(),
21304
21429
  /** Event needs review (e.g. unverified egress). */
21305
- flagged: external_exports.boolean()
21430
+ flagged: external_exports.boolean(),
21431
+ /**
21432
+ * The body this event's `title` is drawn from was cleared by local body
21433
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21434
+ *
21435
+ * A separate flag rather than a sentinel written into `title`: the title is
21436
+ * rendered text, and a store-layer module that invented display copy for it
21437
+ * would be choosing words the view is supposed to choose. Additive and
21438
+ * defaulted, so an older producer still validates.
21439
+ */
21440
+ bodyExpired: external_exports.boolean().default(false)
21306
21441
  }).meta({ id: "ActivityAuditEvent" });
21307
21442
  var ActivitySessionSummary = external_exports.object({
21308
21443
  id: external_exports.string(),
@@ -22100,6 +22235,14 @@ var ControlPlaneErrorBody = external_exports.object({
22100
22235
  message: external_exports.string().optional()
22101
22236
  }).optional()
22102
22237
  });
22238
+ var RemoteFailureKind = external_exports.enum([
22239
+ "unauthorized",
22240
+ "forbidden",
22241
+ "route-absent",
22242
+ "invalid-request",
22243
+ "rejected",
22244
+ "unreachable"
22245
+ ]);
22103
22246
  var AttachDeviceRequest = external_exports.object({
22104
22247
  // This machine's own continuity id, so re-attaching ROTATES the credential
22105
22248
  // on one machine record instead of producing a second one. Client-minted
@@ -22635,6 +22778,12 @@ var EventMetadata = external_exports.object({
22635
22778
  // to 'allow' — the enforcement audit trail's link back to the grant that
22636
22779
  // authorized the bypass. Absent on captures where no exception applied.
22637
22780
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22781
+ // The assistant message this capture belongs to, and the conversation it sits
22782
+ // in — set by the browser extension's network capture so a stored `response`
22783
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22784
+ // on every other capture path, which has no such id.
22785
+ messageId: external_exports.string().optional(),
22786
+ conversationId: external_exports.string().optional(),
22638
22787
  // How long THIS capture's inspection blocked its caller, in whole
22639
22788
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22640
22789
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22647,7 +22796,37 @@ var EventMetadata = external_exports.object({
22647
22796
  // Absent is also what every pre-measurement client writes, and what a
22648
22797
  // clock failure degrades to — a reader must treat absence as "not measured"
22649
22798
  // and never as a zero, which would read as "inspection is free".
22650
- inspectionMs: external_exports.number().int().nonnegative().optional()
22799
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22800
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22801
+ // workspace's `redactFallback`, applied because the field could not be
22802
+ // masked in place (a shell command, a URL, or any argument on a host whose
22803
+ // hook contract offers no rewrite channel).
22804
+ //
22805
+ // It exists because the action alone cannot say why. A finding recorded as
22806
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22807
+ // assigned Redact on a field that could not take one — and those are
22808
+ // different facts about the same row: the first is a policy the user chose,
22809
+ // the second is a masking the host could not perform. Absent means no
22810
+ // degrade happened, which is every ordinary capture.
22811
+ //
22812
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22813
+ // is the CAPTURE while `actionTaken` is per FINDING:
22814
+ //
22815
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22816
+ // `redact` alongside a finding ASSIGNED the same action stores both
22817
+ // identically and one reason for the pair; attributing it to both
22818
+ // describes the assigned one wrongly, and to neither loses the degrade.
22819
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22820
+ // became, not the reason the capture ended as it did — a capture denied
22821
+ // by some other finding's own Block policy still carries `block` here,
22822
+ // and clearing the workspace's fallback would not have let it through.
22823
+ // Gate on the value against what a fallback can produce; never read the
22824
+ // field's presence as "this was the fallback's doing".
22825
+ //
22826
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22827
+ // Closing either means moving the reason onto the finding row, which
22828
+ // already carries its own action.
22829
+ redactDegradedTo: ActionTaken.optional()
22651
22830
  }).meta({ id: "EventMetadata" });
22652
22831
  var Event = external_exports.object({
22653
22832
  id: external_exports.guid(),
@@ -22757,7 +22936,32 @@ var RotateKeyInput = external_exports.object({
22757
22936
  confirmation: external_exports.string()
22758
22937
  });
22759
22938
 
22939
+ // ../../packages/schema/src/zod/finding-delivery.ts
22940
+ var KNOWN_REASONS = SyncFailureReason.options;
22941
+ function knownReason(value) {
22942
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22943
+ }
22944
+ function deriveFindingDelivery(row) {
22945
+ if (row.kind === "code_change") return { state: "local_scan" };
22946
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22947
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22948
+ }
22949
+ if (row.syncedAt !== null) {
22950
+ const reason = knownReason(row.syncFailure);
22951
+ return {
22952
+ state: "not_sent",
22953
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22954
+ ...reason === void 0 ? {} : { reason }
22955
+ };
22956
+ }
22957
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22958
+ return { state: "never_offered" };
22959
+ }
22960
+
22760
22961
  // ../../packages/schema/src/zod/findings-group-build.ts
22962
+ function lookupOwn(map2, key) {
22963
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22964
+ }
22761
22965
  function toApiAction(dbVal) {
22762
22966
  const map2 = {
22763
22967
  log: "monitored",
@@ -22766,7 +22970,7 @@ function toApiAction(dbVal) {
22766
22970
  warn: "warned",
22767
22971
  allow: "allowed"
22768
22972
  };
22769
- return map2[dbVal] ?? "allowed";
22973
+ return lookupOwn(map2, dbVal) ?? "allowed";
22770
22974
  }
22771
22975
  function toApiCategory(dbVal) {
22772
22976
  if (dbVal === "code_context") return "source_code";
@@ -22774,13 +22978,18 @@ function toApiCategory(dbVal) {
22774
22978
  return parsed2.success ? parsed2.data : "custom";
22775
22979
  }
22776
22980
  function toApiProvider(sourceTool) {
22777
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22981
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22778
22982
  }
22779
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22983
+ var FINDING_STATUS_PRECEDENCE = [
22984
+ "open",
22985
+ "handled",
22986
+ "dismissed",
22987
+ "resolved"
22988
+ ];
22780
22989
  function foldGroupStatus(instanceStatuses) {
22781
22990
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22782
22991
  if (statuses.size === 0) return void 0;
22783
- for (const candidate of STATUS_PRECEDENCE) {
22992
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22784
22993
  if (statuses.has(candidate)) return candidate;
22785
22994
  }
22786
22995
  return void 0;
@@ -22793,139 +23002,62 @@ function deriveFindingStatus(row) {
22793
23002
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22794
23003
  return "open";
22795
23004
  }
22796
- function distinctUsers(instances) {
22797
- const seen = /* @__PURE__ */ new Set();
22798
- const users = [];
22799
- for (const i of instances) {
22800
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22801
- seen.add(i.user.id);
22802
- users.push(i.user);
22803
- }
22804
- return users;
22805
- }
22806
23005
  function sortUsers(users) {
22807
23006
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22808
23007
  }
22809
- function buildFindingGroups(rows, opts = {}) {
22810
- const overrides = opts.overrides;
23008
+ function buildFindingTypes(aggregates, opts = {}) {
22811
23009
  const packNames = opts.packNames;
22812
- const aggregates = opts.aggregates;
22813
- const byRuleId = /* @__PURE__ */ new Map();
22814
- for (const row of rows) {
22815
- const existing = byRuleId.get(row.ruleId);
22816
- if (existing) existing.push(row);
22817
- else byRuleId.set(row.ruleId, [row]);
22818
- }
22819
- const groups = [];
22820
- for (const [ruleId, ruleRows] of byRuleId) {
22821
- const instances = ruleRows.map((r) => {
22822
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22823
- return {
22824
- id: r.id,
22825
- provider: toApiProvider(r.sourceTool),
22826
- repo: r.repo,
22827
- file: r.file,
22828
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22829
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22830
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22831
- ...r.user === void 0 ? {} : { user: r.user },
22832
- action: toApiAction(effectiveDbAction),
22833
- detectedAt: r.occurredAt,
22834
- confidence: r.confidence,
22835
- status: r.status
22836
- };
22837
- });
22838
- const agg = aggregates?.get(ruleId);
22839
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22840
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22841
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22842
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22843
- );
22844
- const seenProviders = /* @__PURE__ */ new Set();
22845
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22846
- if (seenProviders.has(p)) return false;
22847
- seenProviders.add(p);
22848
- return true;
22849
- });
22850
- const actionSet = new Set(
22851
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22852
- );
23010
+ const types = [];
23011
+ for (const [ruleId, agg] of aggregates) {
23012
+ const users = sortUsers(agg.users ?? []);
23013
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23014
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22853
23015
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22854
- const severity = ruleRows[0]?.severity ?? "low";
22855
- const detection = {
22856
- id: ruleId,
22857
- name: packNames?.get(ruleId) ?? null
22858
- };
22859
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22860
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22861
- const match = {
22862
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22863
- contextPrefix: ""
22864
- // empty (pending privacy review)
22865
- };
22866
- const status = foldGroupStatus(
22867
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22868
- );
22869
- const group = {
23016
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23017
+ const type = {
22870
23018
  id: ruleId,
22871
23019
  category: apiCategory,
22872
23020
  subtype: ruleId,
22873
23021
  // human label comes with pack metadata later
22874
- severity,
22875
- match,
22876
- detection,
22877
- policy,
22878
- instanceCount: agg?.instanceCount ?? instances.length,
23022
+ severity: agg.severity ?? "low",
23023
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23024
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23025
+ instanceCount: agg.instanceCount,
22879
23026
  providers,
22880
23027
  aggregateAction,
22881
- latestDetectedAt,
22882
- instances,
22883
- status,
23028
+ latestDetectedAt: agg.latestDetectedAt,
23029
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22884
23030
  ...users.length > 0 ? { users } : {}
22885
23031
  };
22886
- if (agg) {
22887
- actionsCache.set(group, [...actionSet]);
22888
- if (agg.searchText !== void 0) {
22889
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22890
- }
23032
+ actionsCache.set(type, [...actionSet]);
23033
+ if (agg.searchText !== void 0) {
23034
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22891
23035
  }
22892
- groups.push(group);
23036
+ types.push(type);
22893
23037
  }
22894
- return groups;
23038
+ return types;
22895
23039
  }
22896
23040
  var haystackCache = /* @__PURE__ */ new WeakMap();
22897
- function buildHaystack(g, extra) {
23041
+ function buildHaystack(t, extra) {
22898
23042
  return [
22899
- g.subtype,
22900
- g.category,
22901
- g.match.maskedValue,
22902
- g.policy.name,
22903
- g.id,
22904
- ...g.instances.map((i) => i.repo),
22905
- ...g.instances.map((i) => i.file),
22906
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22907
- ...g.instances.map((i) => i.id),
22908
- // The people: the whole group's list when the store folded one, plus the
22909
- // preview's own — the two overlap, and a haystack does not mind.
22910
- ...(g.users ?? []).map((u) => u.name),
22911
- ...g.instances.map((i) => i.user?.name ?? ""),
23043
+ t.subtype,
23044
+ t.category,
23045
+ t.policy.name,
23046
+ t.id,
23047
+ ...(t.users ?? []).map((u) => u.name),
22912
23048
  ...extra === void 0 ? [] : [extra]
22913
23049
  ].join(" ").toLowerCase();
22914
23050
  }
22915
- function groupHaystack(g) {
22916
- const cached2 = haystackCache.get(g);
23051
+ function typeHaystack(t) {
23052
+ const cached2 = haystackCache.get(t);
22917
23053
  if (cached2 !== void 0) return cached2;
22918
- const haystack = buildHaystack(g);
22919
- haystackCache.set(g, haystack);
23054
+ const haystack = buildHaystack(t);
23055
+ haystackCache.set(t, haystack);
22920
23056
  return haystack;
22921
23057
  }
22922
23058
  var actionsCache = /* @__PURE__ */ new WeakMap();
22923
- function groupActions(g) {
22924
- const cached2 = actionsCache.get(g);
22925
- if (cached2 !== void 0) return cached2;
22926
- const actions = [...new Set(g.instances.map((i) => i.action))];
22927
- actionsCache.set(g, actions);
22928
- return actions;
23059
+ function typeActions(t) {
23060
+ return actionsCache.get(t) ?? [];
22929
23061
  }
22930
23062
  function countInstancesByStatus(statusInputs, statuses) {
22931
23063
  const statusSet = new Set(statuses);
@@ -22936,8 +23068,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22936
23068
  }
22937
23069
  return sum;
22938
23070
  }
22939
- function applyFindingFilters(groups, opts) {
22940
- let filtered = groups;
23071
+ function applyFindingFilters(types, opts) {
23072
+ let filtered = types;
22941
23073
  if (opts.severity && opts.severity.length > 0) {
22942
23074
  const sevSet = new Set(opts.severity);
22943
23075
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22948,7 +23080,7 @@ function applyFindingFilters(groups, opts) {
22948
23080
  }
22949
23081
  if (opts.actions && opts.actions.length > 0) {
22950
23082
  const actionSet = new Set(opts.actions);
22951
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23083
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22952
23084
  }
22953
23085
  if (opts.subtype && opts.subtype.length > 0) {
22954
23086
  const subtypeSet = new Set(opts.subtype);
@@ -22960,26 +23092,31 @@ function applyFindingFilters(groups, opts) {
22960
23092
  }
22961
23093
  if (opts.q) {
22962
23094
  const q = opts.q.toLowerCase();
22963
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23095
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22964
23096
  }
22965
23097
  return filtered;
22966
23098
  }
22967
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22968
- var SEVERITY_RANK = SEVERITY_ORDER;
23099
+ function rankByOrder(members2) {
23100
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23101
+ }
23102
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23103
+ function severityRank(severity) {
23104
+ return lookupOwn(SEVERITY_RANK, severity);
23105
+ }
22969
23106
  function compareFindingGroupOrder(a, b) {
22970
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22971
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23107
+ const rankA = severityRank(a.severity) ?? -1;
23108
+ const rankB = severityRank(b.severity) ?? -1;
22972
23109
  const severityDiff = rankA - rankB;
22973
23110
  if (severityDiff !== 0) return severityDiff;
22974
23111
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22975
23112
  if (recencyDiff !== 0) return recencyDiff;
22976
23113
  return a.id.localeCompare(b.id);
22977
23114
  }
22978
- function sortFindingGroups(groups) {
22979
- return [...groups].sort(compareFindingGroupOrder);
23115
+ function sortFindingTypes(types) {
23116
+ return [...types].sort(compareFindingGroupOrder);
22980
23117
  }
22981
- function computeFindingFacets(allGroups, opts) {
22982
- const forSeverity = applyFindingFilters(allGroups, {
23118
+ function computeFindingFacets(allTypes, opts) {
23119
+ const forSeverity = applyFindingFilters(allTypes, {
22983
23120
  providers: opts.providers,
22984
23121
  actions: opts.actions,
22985
23122
  statuses: opts.statuses,
@@ -22990,7 +23127,7 @@ function computeFindingFacets(allGroups, opts) {
22990
23127
  for (const g of forSeverity) {
22991
23128
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22992
23129
  }
22993
- const forProvider = applyFindingFilters(allGroups, {
23130
+ const forProvider = applyFindingFilters(allTypes, {
22994
23131
  actions: opts.actions,
22995
23132
  statuses: opts.statuses,
22996
23133
  q: opts.q,
@@ -23001,7 +23138,7 @@ function computeFindingFacets(allGroups, opts) {
23001
23138
  for (const g of forProvider) {
23002
23139
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23003
23140
  }
23004
- const forAction = applyFindingFilters(allGroups, {
23141
+ const forAction = applyFindingFilters(allTypes, {
23005
23142
  providers: opts.providers,
23006
23143
  statuses: opts.statuses,
23007
23144
  q: opts.q,
@@ -23010,9 +23147,9 @@ function computeFindingFacets(allGroups, opts) {
23010
23147
  });
23011
23148
  const actionMap = /* @__PURE__ */ new Map();
23012
23149
  for (const g of forAction) {
23013
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23150
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23014
23151
  }
23015
- const forSubtype = applyFindingFilters(allGroups, {
23152
+ const forSubtype = applyFindingFilters(allTypes, {
23016
23153
  providers: opts.providers,
23017
23154
  actions: opts.actions,
23018
23155
  statuses: opts.statuses,
@@ -23021,7 +23158,7 @@ function computeFindingFacets(allGroups, opts) {
23021
23158
  });
23022
23159
  const subtypeMap = /* @__PURE__ */ new Map();
23023
23160
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23024
- const forStatus = applyFindingFilters(allGroups, {
23161
+ const forStatus = applyFindingFilters(allTypes, {
23025
23162
  providers: opts.providers,
23026
23163
  actions: opts.actions,
23027
23164
  q: opts.q,
@@ -23043,6 +23180,20 @@ function computeFindingFacets(allGroups, opts) {
23043
23180
  }
23044
23181
 
23045
23182
  // ../../packages/schema/src/zod/findings-flat-build.ts
23183
+ function compareCodePoints(a, b) {
23184
+ const aIter = a[Symbol.iterator]();
23185
+ const bIter = b[Symbol.iterator]();
23186
+ for (; ; ) {
23187
+ const aNext = aIter.next();
23188
+ const bNext = bIter.next();
23189
+ if (aNext.done && bNext.done) return 0;
23190
+ if (aNext.done) return -1;
23191
+ if (bNext.done) return 1;
23192
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23193
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23194
+ if (aPoint !== bPoint) return aPoint - bPoint;
23195
+ }
23196
+ }
23046
23197
  function rowHaystack(row) {
23047
23198
  return [
23048
23199
  row.ruleId,
@@ -23067,12 +23218,24 @@ function matchesDimension(row, opts, dimension) {
23067
23218
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23068
23219
  case "statuses":
23069
23220
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23221
+ case "deliveries":
23222
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23070
23223
  case "tools":
23071
23224
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23225
+ // An EMPTY value is a real filter here, not an absent one. The location
23226
+ // list buckets a finding whose event recorded no repo — or no file — under
23227
+ // the empty string, and selecting that bucket has to narrow the panel to
23228
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23229
+ // row omits the key, which every call site already does.
23230
+ //
23231
+ // Reading '' as unset is what this replaced, and it failed in the one place
23232
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23233
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23234
+ // — a row reading 3 findings beside a panel listing every finding there is.
23072
23235
  case "repo":
23073
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23236
+ return opts.repo === void 0 || row.repo === opts.repo;
23074
23237
  case "file":
23075
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23238
+ return opts.file === void 0 || row.file === opts.file;
23076
23239
  case "q":
23077
23240
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23078
23241
  }
@@ -23083,6 +23246,7 @@ var DIMENSIONS = [
23083
23246
  "providers",
23084
23247
  "actions",
23085
23248
  "statuses",
23249
+ "deliveries",
23086
23250
  "tools",
23087
23251
  "repo",
23088
23252
  "file",
@@ -23096,10 +23260,19 @@ function matchesInstanceFilters(row, opts, except) {
23096
23260
  return true;
23097
23261
  }
23098
23262
  function toItems(counts) {
23099
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23263
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23264
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23265
+ // NFD spelling of the same text) as equal, so a count tie between
23266
+ // them would otherwise be ordered by whichever the Map iteration
23267
+ // produced. compareCodePoints breaks that tie deterministically, which
23268
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23269
+ // which it need not: foldFacetTuples runs this same sort over grouped
23270
+ // tuples, so both paths order facets identically by construction.
23271
+ compareCodePoints(a.value, b.value)
23272
+ );
23100
23273
  }
23101
- function bump(counts, value) {
23102
- counts.set(value, (counts.get(value) ?? 0) + 1);
23274
+ function bump(counts, value, by = 1) {
23275
+ counts.set(value, (counts.get(value) ?? 0) + by);
23103
23276
  }
23104
23277
  function createInstanceFacetAccumulator(opts) {
23105
23278
  const severity = /* @__PURE__ */ new Map();
@@ -23108,6 +23281,7 @@ function createInstanceFacetAccumulator(opts) {
23108
23281
  const action = /* @__PURE__ */ new Map();
23109
23282
  const status = /* @__PURE__ */ new Map();
23110
23283
  const tool = /* @__PURE__ */ new Map();
23284
+ const deployment = /* @__PURE__ */ new Map();
23111
23285
  return {
23112
23286
  add(row) {
23113
23287
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23122,6 +23296,9 @@ function createInstanceFacetAccumulator(opts) {
23122
23296
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23123
23297
  bump(tool, row.toolName);
23124
23298
  }
23299
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23300
+ bump(deployment, row.delivery.state);
23301
+ }
23125
23302
  },
23126
23303
  facets: () => ({
23127
23304
  severity: toItems(severity),
@@ -23129,7 +23306,8 @@ function createInstanceFacetAccumulator(opts) {
23129
23306
  provider: toItems(provider),
23130
23307
  action: toItems(action),
23131
23308
  status: toItems(status),
23132
- tool: toItems(tool)
23309
+ tool: toItems(tool),
23310
+ deployment: toItems(deployment)
23133
23311
  })
23134
23312
  };
23135
23313
  }
@@ -23143,6 +23321,7 @@ function toInstanceDetail(row) {
23143
23321
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23144
23322
  eventId: row.eventId,
23145
23323
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23324
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23146
23325
  ...row.user === void 0 ? {} : { user: row.user },
23147
23326
  action: toApiAction(row.actionTaken),
23148
23327
  detectedAt: row.occurredAt,
@@ -23157,12 +23336,6 @@ function toInstanceDetail(row) {
23157
23336
  policy: { id: `category:${category}`, name: category }
23158
23337
  };
23159
23338
  }
23160
- var SEVERITY_ORDER2 = {
23161
- critical: 0,
23162
- high: 1,
23163
- medium: 2,
23164
- low: 3
23165
- };
23166
23339
  function newLocationAccumulator() {
23167
23340
  return {
23168
23341
  instanceCount: 0,
@@ -23177,7 +23350,7 @@ function newLocationAccumulator() {
23177
23350
  }
23178
23351
  function addToLocation(acc, row) {
23179
23352
  acc.instanceCount += 1;
23180
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23353
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23181
23354
  if (rank < acc.maxSeverityRank) {
23182
23355
  acc.maxSeverityRank = rank;
23183
23356
  acc.maxSeverity = row.severity;
@@ -23186,6 +23359,23 @@ function addToLocation(acc, row) {
23186
23359
  acc.statuses.push(row.status);
23187
23360
  acc.ruleIds.add(row.ruleId);
23188
23361
  }
23362
+ function compareLocationOrder(a, b) {
23363
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23364
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23365
+ if (rankA !== rankB) return rankA - rankB;
23366
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23367
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23368
+ }
23369
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23370
+ if (repoDiff !== 0) return repoDiff;
23371
+ return compareCodePoints(a.file, b.file);
23372
+ }
23373
+ function encodeLocationId(repo, file2) {
23374
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23375
+ }
23376
+ function encodePart(value) {
23377
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23378
+ }
23189
23379
 
23190
23380
  // ../../packages/schema/src/zod/installed-pack.ts
23191
23381
  var InstalledPack = external_exports.object({
@@ -23253,6 +23443,11 @@ var Policy = external_exports.object({
23253
23443
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23254
23444
  provenance: PolicyProvenance.optional()
23255
23445
  }).meta({ id: "Policy" });
23446
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23447
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23448
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23449
+ id: "RedactFallback"
23450
+ });
23256
23451
  var PolicyBundle = external_exports.object({
23257
23452
  version: external_exports.string(),
23258
23453
  policies: external_exports.array(Policy),
@@ -23300,6 +23495,16 @@ var PolicyBundle = external_exports.object({
23300
23495
  // control plane), so no name resolution stands between the decision and the
23301
23496
  // comparison.
23302
23497
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23498
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23499
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23500
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23501
+ // a control plane can tighten a machine and never loosen one — the same
23502
+ // direction `mergeRaiseOnly` enforces for policies.
23503
+ //
23504
+ // Optional so an older backend, and an older on-disk cache, still parses;
23505
+ // absent leaves the device's own setting in force, which is the behaviour
23506
+ // that predates the field and the safe direction to default.
23507
+ redactFallback: RedactFallback.optional(),
23303
23508
  customKeywords: external_exports.array(external_exports.string()),
23304
23509
  fetchedAt: external_exports.iso.datetime()
23305
23510
  }).meta({ id: "PolicyBundle" });
@@ -23329,11 +23534,6 @@ function severityFloorPolicy(category) {
23329
23534
  const peak = CATEGORY_PEAK_SEVERITY[category];
23330
23535
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23331
23536
  }
23332
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23333
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23334
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23335
- id: "RedactFallback"
23336
- });
23337
23537
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23338
23538
  var BUILTIN_POLICY_SPECS = {
23339
23539
  monitor: {
@@ -23389,6 +23589,11 @@ function isActionAtLeast(action, floor) {
23389
23589
  function strongerAction(a, b) {
23390
23590
  return actionRank(a) >= actionRank(b) ? a : b;
23391
23591
  }
23592
+ function strongerRedactFallback(local, remote) {
23593
+ if (remote === void 0) return local;
23594
+ const localAction = builtinPolicyToAction(local);
23595
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23596
+ }
23392
23597
  function weakestBuiltinAtLeast(floor) {
23393
23598
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23394
23599
  }
@@ -23629,7 +23834,7 @@ var VaultConsent = external_exports.object({
23629
23834
  });
23630
23835
 
23631
23836
  // ../../packages/schema/src/zod/local.ts
23632
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23837
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23633
23838
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23634
23839
  var RunMode = external_exports.enum(["standalone", "attached"]);
23635
23840
  var ControlPlaneConnection = external_exports.object({
@@ -23649,6 +23854,15 @@ var HistorySyncConsent = external_exports.object({
23649
23854
  payloadVersion: external_exports.number().int().positive(),
23650
23855
  endpoint: external_exports.string()
23651
23856
  });
23857
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23858
+ var BodyRetention = external_exports.object({
23859
+ enabled: external_exports.boolean().default(false),
23860
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23861
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23862
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23863
+ // candidate set that is already bounded by "delivered, or never owed".
23864
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23865
+ }).meta({ id: "BodyRetention" });
23652
23866
  var WorkspaceSettings = external_exports.object({
23653
23867
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23654
23868
  runMode: RunMode.default("standalone"),
@@ -23692,12 +23906,18 @@ var WorkspaceSettings = external_exports.object({
23692
23906
  // covers the current payload and must be re-granted.
23693
23907
  modelJudgeConsent: ModelJudgeConsent.optional(),
23694
23908
  // Records that the user consented to the DEFERRED send — the outbox — along
23695
- // with the payload shape and the endpoint they agreed to. Since payload v2
23696
- // that covers both the pre-attach backlog and undelivered captures (which
23697
- // carry prompt/reply text in `content`); the key name predates the widening.
23698
- // Absent until granted, and a grant for a different endpoint or an older
23699
- // payload no longer counts.
23700
- historySyncConsent: HistorySyncConsent.optional()
23909
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23910
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23911
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23912
+ // both widenings. Absent until granted, and a grant for a different endpoint
23913
+ // or an older payload no longer counts.
23914
+ historySyncConsent: HistorySyncConsent.optional(),
23915
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23916
+ // body never removes the row or its findings.
23917
+ bodyRetention: BodyRetention.default({
23918
+ enabled: false,
23919
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23920
+ })
23701
23921
  });
23702
23922
  function defaultWorkspaceSettings() {
23703
23923
  return WorkspaceSettings.parse({});
@@ -23792,12 +24012,15 @@ function toCaptureAttributes(event) {
23792
24012
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23793
24013
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23794
24014
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24015
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23795
24016
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23796
24017
  // has ever populated either), but every legacy metadata key still rides
23797
24018
  // the bag rather than being silently dropped — CaptureAttributes'
23798
24019
  // `.catchall(z.unknown())` carries the long tail.
23799
24020
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23800
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24021
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24022
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24023
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23801
24024
  };
23802
24025
  }
23803
24026
  function captureDefinitionVersion(finding) {
@@ -23825,10 +24048,22 @@ var ManagedSettingKey = external_exports.enum([
23825
24048
  "vaultInlineReveal",
23826
24049
  "modelJudgeConsent",
23827
24050
  "dataSharesInPlace",
23828
- "redactFallback"
24051
+ "redactFallback",
24052
+ // Pins the toggle and the day count together — see BodyRetention on why the
24053
+ // two are one unit. An administrator mandating a window wants the count
24054
+ // enforced with it, not one a user can widen while the toggle stays on.
24055
+ "bodyRetention"
23829
24056
  ]).meta({ id: "ManagedSettingKey" });
24057
+ function isManagedSettingKey(value) {
24058
+ return ManagedSettingKey.safeParse(value).success;
24059
+ }
23830
24060
  var ManagedSettingsValues = external_exports.object({
23831
24061
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24062
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24063
+ // plain, non-strict objects: a key under either that this build does not know
24064
+ // is stripped and nothing reports it. The unknown-value split in
24065
+ // ManagedSettings below classifies top-level names only, so it stops at
24066
+ // these boundaries.
23832
24067
  controlPlane: external_exports.object({
23833
24068
  endpoint: external_exports.string().min(1),
23834
24069
  label: external_exports.string().min(1).optional()
@@ -23839,7 +24074,8 @@ var ManagedSettingsValues = external_exports.object({
23839
24074
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23840
24075
  modelJudgeConsent: external_exports.boolean().optional(),
23841
24076
  dataSharesInPlace: external_exports.boolean().optional(),
23842
- redactFallback: RedactFallback.optional()
24077
+ redactFallback: RedactFallback.optional(),
24078
+ bodyRetention: BodyRetention.optional()
23843
24079
  }).meta({ id: "ManagedSettingsValues" });
23844
24080
  var ManagedSettings = external_exports.object({
23845
24081
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23847,11 +24083,59 @@ var ManagedSettings = external_exports.object({
23847
24083
  // decision from a bug. Absent renders as a generic "your organization".
23848
24084
  organization: external_exports.string().min(1).optional(),
23849
24085
  // What the administrator pinned.
23850
- values: ManagedSettingsValues.default({}),
24086
+ //
24087
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24088
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24089
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24090
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24091
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24092
+ // exactly the file an administrator is most likely to write while a fleet
24093
+ // is mid-upgrade.
24094
+ //
24095
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24096
+ // file, which is the outcome the lock half already rejected — an older
24097
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24098
+ // value still fails, because the nested schema is re-run over the known
24099
+ // subset and its issues are re-raised on this parse.
24100
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23851
24101
  // Which of those the user may not change. A key here with no matching value
23852
24102
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23853
24103
  // the user may still override. The two are separable on purpose.
23854
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24104
+ //
24105
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24106
+ // build does not know is dropped from the locked set and reported, never a
24107
+ // reason to refuse the file. The same shape reaches an older build whenever
24108
+ // an administrator locks a key a newer build added, and refusing it there
24109
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24110
+ // the fleets most likely to carry a version skew. A name outside the enum
24111
+ // is still never HONOURED: the lockable set stays explicit above.
24112
+ lockedFields: external_exports.array(external_exports.string()).default([])
24113
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24114
+ const known = [];
24115
+ const unknown2 = [];
24116
+ for (const name of lockedFields) {
24117
+ if (isManagedSettingKey(name)) known.push(name);
24118
+ else unknown2.push(name);
24119
+ }
24120
+ const knownValues = /* @__PURE__ */ Object.create(null);
24121
+ const unknownValues = [];
24122
+ for (const [name, value] of Object.entries(values)) {
24123
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24124
+ else unknownValues.push(name);
24125
+ }
24126
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24127
+ if (!pinned.success) {
24128
+ for (const issue2 of pinned.error.issues)
24129
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24130
+ return external_exports.NEVER;
24131
+ }
24132
+ return {
24133
+ ...rest,
24134
+ values: pinned.data,
24135
+ lockedFields: known,
24136
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24137
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24138
+ };
23855
24139
  }).meta({ id: "ManagedSettings" });
23856
24140
 
23857
24141
  // ../../packages/schema/src/zod/project-files.ts
@@ -23975,7 +24259,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23975
24259
  timestamp: external_exports.iso.date(),
23976
24260
  critical: external_exports.number().int().nonnegative(),
23977
24261
  high: external_exports.number().int().nonnegative(),
23978
- medium: external_exports.number().int().nonnegative()
24262
+ medium: external_exports.number().int().nonnegative(),
24263
+ // Optional and additive, so a producer written against the earlier
24264
+ // three-series contract keeps validating. A consumer plotting it resolves the
24265
+ // absent case itself — the chart point requires a number.
24266
+ low: external_exports.number().int().nonnegative().optional()
23979
24267
  }).meta({ id: "FindingsTimeseriesPoint" });
23980
24268
  var FindingsTimeseriesResponse = external_exports.object({
23981
24269
  range: TimeRange,
@@ -24001,6 +24289,10 @@ var ResolvedFeedItem = external_exports.object({
24001
24289
  findingKey: external_exports.string(),
24002
24290
  ruleId: external_exports.string(),
24003
24291
  severity: Severity,
24292
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24293
+ // identifies the file: a bare path matches the same name in every repo.
24294
+ // Optional and additive; empty when the event carried no repo.
24295
+ repo: external_exports.string().optional(),
24004
24296
  path: external_exports.string(),
24005
24297
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24006
24298
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24106,7 +24398,23 @@ var SaveSettingsInput = external_exports.object({
24106
24398
  modelJudgeConsent: ModelJudgeConsentChoice,
24107
24399
  historySyncConsent: HistorySyncConsentChoice,
24108
24400
  vaultConsent: external_exports.string(),
24109
- vaultInlineReveal: external_exports.string()
24401
+ vaultInlineReveal: external_exports.string(),
24402
+ // Widened to `string` like its neighbours rather than typed as
24403
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24404
+ // the call site, so the domain check receives the type it was written for.
24405
+ //
24406
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24407
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24408
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24409
+ // trade against. The real cost runs the other way and is the part worth
24410
+ // knowing: a value this schema admits and the domain enum then rejects lands
24411
+ // on the action's shared refusal, which names NO field, where a shape
24412
+ // rejection reaches `malformedInput` and names the schema key.
24413
+ redactFallback: external_exports.string(),
24414
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24415
+ // `BodyRetention`'s and the action checks it there, so there is one place
24416
+ // that decides what a legal horizon is rather than two that can drift.
24417
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24110
24418
  });
24111
24419
  var AttachInput = external_exports.object({
24112
24420
  endpoint: external_exports.string(),
@@ -24278,6 +24586,52 @@ function reviewSeverityRank(reasons) {
24278
24586
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24279
24587
  }
24280
24588
 
24589
+ // ../../packages/schema/src/zod/web-capture.ts
24590
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24591
+ var WebUsage = external_exports.object({
24592
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24593
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24594
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24595
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24596
+ });
24597
+ var WebToolCall = external_exports.object({
24598
+ toolUseId: external_exports.string().min(1),
24599
+ toolName: external_exports.string().min(1),
24600
+ target: external_exports.string().optional(),
24601
+ isError: external_exports.boolean().optional(),
24602
+ inputSize: external_exports.number().int().nonnegative().optional(),
24603
+ outputSize: external_exports.number().int().nonnegative().optional()
24604
+ });
24605
+ var WebExchange = external_exports.object({
24606
+ messageId: external_exports.string().min(1),
24607
+ startedAt: external_exports.iso.datetime(),
24608
+ model: external_exports.string().optional(),
24609
+ usage: WebUsage.optional(),
24610
+ usageSource: WebUsageSource,
24611
+ stopReason: external_exports.string().optional(),
24612
+ conversationId: external_exports.string().optional(),
24613
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24614
+ toolCalls: external_exports.array(WebToolCall).default([]),
24615
+ // Absent when the adapter recovered no text. Capped by the caller at
24616
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24617
+ // short capture is never mistaken for a short reply.
24618
+ responseText: external_exports.string().optional(),
24619
+ truncated: external_exports.boolean().default(false)
24620
+ });
24621
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24622
+ var WebCaptureStatus = external_exports.object({
24623
+ patched: external_exports.boolean(),
24624
+ live: external_exports.boolean(),
24625
+ blind: external_exports.boolean(),
24626
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24627
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24628
+ parseFailures: external_exports.number().int().nonnegative(),
24629
+ unparsedBodies: external_exports.number().int().nonnegative(),
24630
+ // The adapter-declared JSON key paths that were absent from a real payload —
24631
+ // the earliest signal that a site's contract moved.
24632
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24633
+ });
24634
+
24281
24635
  // ../../packages/persistence/src/paths.ts
24282
24636
  import {
24283
24637
  chmodSync,
@@ -24638,6 +24992,22 @@ function discardStore(file2, backup) {
24638
24992
  }
24639
24993
  }
24640
24994
 
24995
+ // ../../packages/persistence/src/internal/sql-functions.ts
24996
+ var utf8 = new TextDecoder();
24997
+ function akaLower(value) {
24998
+ if (value === null) return null;
24999
+ if (typeof value === "string") return value.toLowerCase();
25000
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25001
+ return utf8.decode(value).toLowerCase();
25002
+ }
25003
+ function registerSqlFunctions(db) {
25004
+ db.function(
25005
+ "aka_lower",
25006
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25007
+ akaLower
25008
+ );
25009
+ }
25010
+
24641
25011
  // ../../packages/persistence/src/internal/sql-text.ts
24642
25012
  function escapeLikePattern(s) {
24643
25013
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24722,6 +25092,11 @@ function schemaObjectExists(db, kind, name) {
24722
25092
  function indexExists(db, name) {
24723
25093
  return schemaObjectExists(db, "index", name);
24724
25094
  }
25095
+ function indexColumns(db, name) {
25096
+ if (!indexExists(db, name)) return [];
25097
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25098
+ return columns.map((c) => c.name).filter((c) => c !== null);
25099
+ }
24725
25100
  function columnNames(db, table, opts) {
24726
25101
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24727
25102
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24783,141 +25158,783 @@ function mapRowsTolerant(rows, map2) {
24783
25158
  return out;
24784
25159
  }
24785
25160
 
24786
- // ../../packages/persistence/src/migrations.ts
24787
- function describeObject(object2) {
24788
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24789
- }
24790
- function splitStatements(sql) {
24791
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24792
- }
24793
- function createdIndexName(statement) {
24794
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24795
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25161
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25162
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25163
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25164
+
25165
+ // ../../packages/persistence/src/sync-failure.ts
25166
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25167
+ function syncFailureRejectCondition(column = "sync_failure") {
25168
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25169
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24796
25170
  }
24797
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24798
- function applyMigrations(db, file2) {
24799
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24800
- db.exec(
24801
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24802
- );
24803
- const applied = new Set(
24804
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24805
- );
24806
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24807
- const record2 = db.prepare(
24808
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24809
- );
24810
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24811
- if (applied.has(migration.tag)) continue;
24812
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24813
- const evidence = evidenceObjects(migration.sql);
24814
- const present = evidence.filter((o) => evidenceExists(db, o));
24815
- if (present.length > 0 && present.length < evidence.length) {
24816
- const missing = evidence.filter((o) => !present.includes(o));
24817
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24818
- akaWarn(message);
24819
- throw new Error(`[aka] ${message}`);
24820
- }
24821
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24822
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24823
- const statements = splitStatements(migration.sql);
24824
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24825
- try {
24826
- withTransaction(
24827
- db,
24828
- () => {
24829
- for (const statement of statements) {
24830
- const indexName = createdIndexName(statement);
24831
- if (indexName === void 0) {
24832
- if (alreadyApplied) continue;
24833
- } else if (indexExists(db, indexName)) {
24834
- continue;
24835
- }
24836
- db.exec(statement);
24837
- }
24838
- if (wantsFkOff && !alreadyApplied) {
24839
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24840
- if (violations.length > 0) {
24841
- throw new Error(
24842
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24843
- );
24844
- }
24845
- }
24846
- record2.run(migration.tag, Date.now());
24847
- },
24848
- "IMMEDIATE"
24849
- );
24850
- } finally {
24851
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24852
- }
25171
+
25172
+ // ../../packages/persistence/src/repositories/history-sync.ts
25173
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25174
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25175
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25176
+ var COUNTED_EVENT_TYPES = [
25177
+ ...STRUCTURAL_EVENT_TYPES,
25178
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25179
+ ];
25180
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25181
+ var PARTITION_BUCKETS = `
25182
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25183
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25184
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25185
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25186
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25187
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25188
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25189
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25190
+ -- added later lands in no bucket and fails the sum assertion, instead
25191
+ -- of silently joining this one.
25192
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25193
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25194
+ THEN 1 ELSE 0 END) AS failed,
25195
+ COUNT(*) AS total`;
25196
+ var COUNTED_SCOPE = `
25197
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25198
+ AND (
25199
+ event_type IN (${TYPE_LIST})
25200
+ OR synced_at IS NOT NULL
25201
+ OR outbox_owed = 1
25202
+ )`;
25203
+ var SKIPPED = -1;
25204
+ var ROW_COLUMNS = `id,
25205
+ parent_id AS parentId,
25206
+ root_session_id AS rootSessionId,
25207
+ event_type AS eventType,
25208
+ host_id AS hostId,
25209
+ harness_id AS harnessId,
25210
+ source_project_id AS sourceProjectId,
25211
+ started_at AS startedAt,
25212
+ ended_at AS endedAt,
25213
+ severity,
25214
+ priority,
25215
+ content,
25216
+ content_hash AS contentHash,
25217
+ attributes`;
25218
+ var SqliteHistorySyncRepository = class {
25219
+ constructor(db) {
25220
+ this.db = db;
25221
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25222
+ this.sessionsStmt = db.prepare(
25223
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25224
+ FROM audit_events
25225
+ WHERE synced_at IS NULL
25226
+ AND event_type IN (${TYPE_LIST})
25227
+ AND started_at < :before
25228
+ GROUP BY sessionId
25229
+ ORDER BY earliest
25230
+ LIMIT :limit`
25231
+ );
25232
+ this.rowsStmt = db.prepare(
25233
+ `SELECT ${ROW_COLUMNS}
25234
+ FROM audit_events
25235
+ WHERE synced_at IS NULL
25236
+ AND event_type IN (${TYPE_LIST})
25237
+ AND started_at < :before
25238
+ AND COALESCE(root_session_id, id) = :sessionId
25239
+ ORDER BY (event_type = 'session') DESC, started_at
25240
+ LIMIT :limit`
25241
+ );
25242
+ this.captureRowsStmt = db.prepare(
25243
+ `SELECT ${ROW_COLUMNS}
25244
+ FROM audit_events
25245
+ WHERE synced_at IS NULL
25246
+ AND sync_claimed_at IS NULL
25247
+ AND outbox_owed = 1
25248
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25249
+ AND started_at < :before
25250
+ ORDER BY started_at
25251
+ LIMIT :limit`
25252
+ );
25253
+ this.markOwedStmt = db.prepare(
25254
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25255
+ );
25256
+ this.markCaptureBacklogOwedStmt = db.prepare(
25257
+ `UPDATE audit_events SET outbox_owed = 1
25258
+ WHERE synced_at IS NULL
25259
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25260
+ AND started_at < :before`
25261
+ );
25262
+ this.stampStmt = db.prepare(
25263
+ `UPDATE audit_events
25264
+ SET synced_at = :at,
25265
+ sync_claimed_at = NULL,
25266
+ sync_failed_at = :failedAt,
25267
+ sync_failure = :failure
25268
+ WHERE id = :id`
25269
+ );
25270
+ this.claimRowStmt = db.prepare(
25271
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25272
+ );
25273
+ this.releaseRowStmt = db.prepare(
25274
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25275
+ );
25276
+ this.releaseStaleClaimsStmt = db.prepare(
25277
+ `UPDATE audit_events SET sync_claimed_at = NULL
25278
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25279
+ );
25280
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25281
+ FROM audit_events${COUNTED_SCOPE}`);
25282
+ this.partitionByKindStmt = db.prepare(
25283
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25284
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25285
+ GROUP BY event_type`
25286
+ );
25287
+ this.countsStmt = db.prepare(
25288
+ `SELECT
25289
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25290
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25291
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25292
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25293
+ THEN 1 ELSE 0 END) AS skipped,
25294
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25295
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25296
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25297
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25298
+ FROM audit_events
25299
+ WHERE event_type IN (${TYPE_LIST})`
25300
+ );
25301
+ this.captureSkipCountStmt = db.prepare(
25302
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25303
+ // way the structural totals are. The split exists because a refusal is
25304
+ // terminal only against the deployment that gave it, and the structural
25305
+ // re-arm frees it on a change of deployment. The capture lane has no such
25306
+ // escape: re-arming a capture would offer one deployment's undelivered
25307
+ // prompts, with their text, to a deployment that never saw them, which is
25308
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25309
+ // reasons mean the same thing — this row will not be sent — and splitting
25310
+ // them would put refused captures in a bucket nothing reads and nothing
25311
+ // frees.
25312
+ `SELECT COUNT(*) AS skipped
25313
+ FROM audit_events
25314
+ WHERE synced_at = ${String(SKIPPED)}
25315
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25316
+ );
25317
+ this.fingerprintStmt = db.prepare(
25318
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25319
+ FROM history_sync WHERE id = 1`
25320
+ );
25321
+ this.setFingerprintStmt = db.prepare(
25322
+ `UPDATE history_sync
25323
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25324
+ WHERE id = 1`
25325
+ );
25326
+ this.disownCapturesStmt = db.prepare(
25327
+ `UPDATE audit_events SET outbox_owed = NULL
25328
+ WHERE outbox_owed IS NOT NULL
25329
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25330
+ AND started_at < :attachedAt`
25331
+ );
25332
+ this.rearmStmt = db.prepare(
25333
+ `UPDATE audit_events
25334
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25335
+ WHERE (synced_at > 0
25336
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25337
+ AND event_type IN (${TYPE_LIST})`
25338
+ );
25339
+ this.claimStmt = db.prepare(
25340
+ `UPDATE history_sync
25341
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25342
+ WHERE id = 1
25343
+ AND (owner_pid IS NULL
25344
+ OR heartbeat_at IS NULL
25345
+ OR heartbeat_at < :staleBefore
25346
+ OR heartbeat_at > :now)`
25347
+ );
25348
+ this.heartbeatStmt = db.prepare(
25349
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25350
+ );
25351
+ this.releaseStmt = db.prepare(
25352
+ `UPDATE history_sync
25353
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25354
+ WHERE id = 1 AND owner_pid = :pid`
25355
+ );
25356
+ this.closeWindowStmt = db.prepare(
25357
+ `UPDATE audit_events
25358
+ SET synced_at = ${String(SKIPPED)},
25359
+ sync_failed_at = :at,
25360
+ sync_failure = 'detached_undelivered'
25361
+ WHERE synced_at IS NULL
25362
+ AND event_type IN (${TYPE_LIST})
25363
+ AND started_at >= :attachedAt`
25364
+ );
25365
+ this.releaseBoundaryStmt = db.prepare(
25366
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25367
+ );
25368
+ this.freezeBoundaryStmt = db.prepare(
25369
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25370
+ );
25371
+ this.leaseStmt = db.prepare(
25372
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25373
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25374
+ FROM history_sync WHERE id = 1`
25375
+ );
25376
+ this.inspectionsStmt = db.prepare(
25377
+ `SELECT d.rule_id AS ruleId,
25378
+ d.name AS ruleName,
25379
+ d.version AS ruleVersion,
25380
+ d.category AS category,
25381
+ d.severity AS severity,
25382
+ f.span_start AS spanStart,
25383
+ f.span_end AS spanEnd,
25384
+ f.masked_match AS maskedMatch,
25385
+ f.action_taken AS actionTaken,
25386
+ f.confidence AS confidence
25387
+ FROM inspection_findings f
25388
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25389
+ WHERE f.audit_event_id = :auditEventId
25390
+ ORDER BY f.span_start, f.id`
25391
+ );
24853
25392
  }
24854
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24855
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25393
+ db;
25394
+ ensureRowStmt;
25395
+ sessionsStmt;
25396
+ rowsStmt;
25397
+ stampStmt;
25398
+ countsStmt;
25399
+ fingerprintStmt;
25400
+ setFingerprintStmt;
25401
+ rearmStmt;
25402
+ claimStmt;
25403
+ heartbeatStmt;
25404
+ releaseStmt;
25405
+ leaseStmt;
25406
+ inspectionsStmt;
25407
+ closeWindowStmt;
25408
+ releaseBoundaryStmt;
25409
+ freezeBoundaryStmt;
25410
+ captureRowsStmt;
25411
+ markOwedStmt;
25412
+ markCaptureBacklogOwedStmt;
25413
+ captureSkipCountStmt;
25414
+ disownCapturesStmt;
25415
+ partitionStmt;
25416
+ partitionByKindStmt;
25417
+ claimRowStmt;
25418
+ releaseRowStmt;
25419
+ releaseStaleClaimsStmt;
25420
+ /**
25421
+ * The masked detections recorded against one tool call.
25422
+ *
25423
+ * These travel with the event because a tool call's target is not
25424
+ * re-inspectable from the event alone — unlike a capture, where the text
25425
+ * itself is re-scannable. What crosses is the masked match and the rule that
25426
+ * produced it, never the value.
25427
+ */
25428
+ inspectionsFor(auditEventId) {
25429
+ return allRows(this.inspectionsStmt, { auditEventId });
24856
25430
  }
24857
- ensureSyncedAtColumn(db, "audit_events");
24858
- ensureScanLedgerTable(db);
24859
- ensureHistorySyncTable(db);
24860
- ensureBlockedDetectionsTable(db);
24861
- ensureRuleProbeCacheTable(db);
24862
- ensureWriteGateTrigger(db);
24863
- ensureTokenUsageColumns(db);
24864
- reconcileSourceProjectIds(db);
24865
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24866
- const drained = runLegacyHistoryBackfill(db);
24867
- if (drained) applyLegacyDropMigration(db, file2);
25431
+ /**
25432
+ * Sessions with structural rows still to send, oldest first.
25433
+ *
25434
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25435
+ * read. Anything recorded after the machine attached is the live forward
25436
+ * path's to deliver; this drain exists for what was recorded before it, and a
25437
+ * row both paths send is at best a duplicate request and at worst — for a
25438
+ * session root — an overwrite of the inventory ids the live path resolved.
25439
+ */
25440
+ pendingSessions(limit, before) {
25441
+ return allRows(this.sessionsStmt, { limit, before }).map(
25442
+ (r) => r.sessionId
25443
+ );
24868
25444
  }
24869
- }
24870
- function readLegacyTables(db) {
24871
- let holdsRows = false;
24872
- const marks = [];
24873
- for (const table of ["events", "findings"]) {
24874
- try {
24875
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24876
- if (row === void 0) {
24877
- holdsRows = true;
24878
- marks.push(`${table}:unreadable`);
24879
- continue;
24880
- }
24881
- if (row.n > 0) holdsRows = true;
24882
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24883
- } catch {
24884
- holdsRows = true;
24885
- marks.push(`${table}:unreadable`);
24886
- }
25445
+ /** One session's undelivered structural rows within the backlog, root first. */
25446
+ pendingRows(sessionId, limit, before) {
25447
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24887
25448
  }
24888
- return { holdsRows, mark: marks.join("|") };
24889
- }
24890
- function applyLegacyDropMigration(db, file2) {
24891
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24892
- if (!migration) return;
24893
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24894
- if (file2 !== void 0 && before?.holdsRows === true) {
24895
- try {
24896
- backupBeforeLegacyDrop(db, file2);
24897
- } catch (error61) {
24898
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24899
- return;
24900
- }
25449
+ /**
25450
+ * Captures this machine still owes the deployment, oldest first.
25451
+ *
25452
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25453
+ * by a time window — see captureRowsStmt for why a window could not express
25454
+ * this. `before` is the grace window that leaves a just-recorded capture to
25455
+ * the live path.
25456
+ */
25457
+ pendingCaptureRows(limit, before) {
25458
+ return allRows(this.captureRowsStmt, { limit, before });
24901
25459
  }
24902
- try {
25460
+ /**
25461
+ * Record that a capture is OWED to the deployment.
25462
+ *
25463
+ * Written by the attached forward path when a live send did not confirm
25464
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25465
+ * a fact rather than an inference: the machine was attached, the send did not
25466
+ * land, so the row is owed — which no time window can state, because the same
25467
+ * window that holds the rows a past attachment left owed also holds every
25468
+ * capture recorded while the machine was DETACHED, and those were never
25469
+ * offered to anyone.
25470
+ *
25471
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25472
+ * out of the drain's read.
25473
+ */
25474
+ markCaptureOwed(id) {
25475
+ this.markOwedStmt.run({ id });
25476
+ }
25477
+ /**
25478
+ * Mark every capture already on disk as owed, as of `before`.
25479
+ *
25480
+ * The consent-time backfill, called once from `aka attach` when a human
25481
+ * grants existing-history consent — never from an ongoing drain pass, and
25482
+ * never inferred from a boundary that could later move. `before` is the
25483
+ * caller's own "now" at the moment consent was granted, so what this marks
25484
+ * is exactly the backlog the consent prompt already counted, not whatever a
25485
+ * later re-attach or key rotation might widen it to.
25486
+ *
25487
+ * Returns how many rows matched, for the caller to log or test against. Not a
25488
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25489
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25490
+ */
25491
+ markCaptureBacklogOwed(before) {
25492
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25493
+ }
25494
+ /**
25495
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25496
+ *
25497
+ * CLEARS any failure reason in the same statement. A row that failed against
25498
+ * one deployment and then landed is delivered, and leaving the reason behind
25499
+ * would leave the store holding two contradictory answers about one row —
25500
+ * with the surface free to render either.
25501
+ */
25502
+ markSynced(ids, atMs) {
25503
+ this.stampAll(ids, atMs, null);
25504
+ }
25505
+ /**
25506
+ * Record that THIS MACHINE cannot express the row on the wire.
25507
+ *
25508
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25509
+ * payload, or a body the client itself refused to send. It fails identically
25510
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25511
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25512
+ * is retried; marking those would turn one outage into permanent data loss.
25513
+ */
25514
+ markSkipped(ids, atMs) {
25515
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25516
+ }
25517
+ /**
25518
+ * Record that THIS DEPLOYMENT refused the row.
25519
+ *
25520
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25521
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25522
+ * row is outstanding rather than why. What separates them is the reason, and
25523
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25524
+ * on one body, so it is terminal only for as long as this machine points at
25525
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25526
+ *
25527
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25528
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25529
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25530
+ */
25531
+ markRefused(ids, atMs) {
25532
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25533
+ }
25534
+ eachInTransaction(ids, run) {
25535
+ if (ids.length === 0) return;
24903
25536
  withTransaction(
24904
- db,
25537
+ this.db,
24905
25538
  () => {
24906
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24907
- if (alreadyDropped) return;
24908
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24909
- akaWarn(
24910
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24911
- );
24912
- return;
24913
- }
24914
- for (const statement of splitStatements(migration.sql)) {
24915
- db.exec(statement);
24916
- }
24917
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24918
- migration.tag,
24919
- Date.now()
24920
- );
25539
+ for (const id of ids) run(id);
25540
+ },
25541
+ "IMMEDIATE"
25542
+ );
25543
+ }
25544
+ stampAll(ids, value, failure, failedAtMs) {
25545
+ if (ids.length === 0) return;
25546
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25547
+ withTransaction(
25548
+ this.db,
25549
+ () => {
25550
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25551
+ },
25552
+ "IMMEDIATE"
25553
+ );
25554
+ }
25555
+ /**
25556
+ * Claim rows as in-flight.
25557
+ *
25558
+ * Advisory in exactly the sense the lease is: it records that a send is in
25559
+ * progress so a surface can say so, and a lost claim costs a row showing as
25560
+ * queued while it is actually being sent. It is not exclusion — the far side
25561
+ * settles a duplicate on the row id.
25562
+ */
25563
+ claimRows(ids, atMs) {
25564
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25565
+ }
25566
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25567
+ releaseRows(ids) {
25568
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25569
+ }
25570
+ /**
25571
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25572
+ *
25573
+ * A process killed between claiming and settling leaves rows claimed with
25574
+ * nothing left to settle them. Without this they read as "sending" for ever.
25575
+ */
25576
+ releaseStaleClaims(staleBefore) {
25577
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25578
+ }
25579
+ /**
25580
+ * Every tracked row in exactly one delivery state.
25581
+ *
25582
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25583
+ * pick up now", which is a different question from "what state is this row
25584
+ * in" — and a machine that has never attached has no boundary to pass, so
25585
+ * requiring one would force a caller to invent one and report the whole store
25586
+ * as queued.
25587
+ */
25588
+ /**
25589
+ * The same partition, one row per kind that a lane carries.
25590
+ *
25591
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25592
+ * scope decides which rows exist at all, so a kind that has never been
25593
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25594
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25595
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25596
+ * different things.
25597
+ */
25598
+ partitionByKind() {
25599
+ return allRows(
25600
+ this.partitionByKindStmt,
25601
+ {}
25602
+ ).map((row) => ({
25603
+ kind: row.kind,
25604
+ queued: row.queued ?? 0,
25605
+ inProgress: row.inProgress ?? 0,
25606
+ synced: row.synced ?? 0,
25607
+ failed: row.failed ?? 0,
25608
+ refused: row.refused ?? 0,
25609
+ detached: row.detached ?? 0,
25610
+ total: row.total ?? 0
25611
+ }));
25612
+ }
25613
+ partition() {
25614
+ const row = getRow(this.partitionStmt, {});
25615
+ return {
25616
+ queued: row?.queued ?? 0,
25617
+ inProgress: row?.inProgress ?? 0,
25618
+ synced: row?.synced ?? 0,
25619
+ failed: row?.failed ?? 0,
25620
+ refused: row?.refused ?? 0,
25621
+ detached: row?.detached ?? 0,
25622
+ total: row?.total ?? 0
25623
+ };
25624
+ }
25625
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25626
+ counts(before) {
25627
+ const row = getRow(this.countsStmt, { before });
25628
+ const captures = getRow(this.captureSkipCountStmt);
25629
+ return {
25630
+ pending: row?.pending ?? 0,
25631
+ sent: row?.sent ?? 0,
25632
+ skipped: row?.skipped ?? 0,
25633
+ refused: row?.refused ?? 0,
25634
+ detached: row?.detached ?? 0,
25635
+ capturesSkipped: captures?.skipped ?? 0
25636
+ };
25637
+ }
25638
+ /**
25639
+ * The deployment the current stamps were made against, and where its backlog
25640
+ * ends.
25641
+ *
25642
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25643
+ * machine that has never drained is — and every writer below seeds the row
25644
+ * before it needs one, so nothing depends on this creating it. Keeping the
25645
+ * write off the gate path matters because the gate runs on every pass while a
25646
+ * write has to take the database's write lock.
25647
+ */
25648
+ deployment() {
25649
+ const row = getRow(
25650
+ this.fingerprintStmt
25651
+ );
25652
+ return {
25653
+ fingerprint: row?.fingerprint ?? void 0,
25654
+ backlogBefore: row?.backlogBefore ?? void 0
25655
+ };
25656
+ }
25657
+ /**
25658
+ * Point the ledger at a different deployment, discarding what it recorded
25659
+ * about the previous one.
25660
+ *
25661
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25662
+ * machine has just left are undelivered as far as the new one is concerned.
25663
+ * All four in one transaction, so a crash between them cannot leave stamps
25664
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25665
+ * a disown with no re-mark to follow it.
25666
+ *
25667
+ * The boundary is written HERE and only here, which is what freezes it: a
25668
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25669
+ * unchanged, so this never runs and the backlog does not widen back over rows
25670
+ * the live path has since delivered.
25671
+ *
25672
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25673
+ * granted existing-history consent for the deployment this call is arming —
25674
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25675
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25676
+ * apart. Passed only when that grant is valid, since this method has no way
25677
+ * to check consent itself and must not mark a row owed for a machine that
25678
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25679
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25680
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25681
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25682
+ * on the cleared side of that bound — and the re-mark in the same
25683
+ * transaction is what puts those rows back. A crash between the two cannot
25684
+ * strand the ledger disowned with nothing re-marked — the transaction either
25685
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25686
+ * committed re-enters this method on the very next pass. Omit it (the
25687
+ * structural-only tests do) to exercise the disown in isolation.
25688
+ *
25689
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25690
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25691
+ * live path can mark a capture owed from the moment `aka attach` writes the
25692
+ * descriptor, before the drain's first pass ever reaches this method, and
25693
+ * such a row sits at or after the bound rather than below it. What keeps the
25694
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25695
+ * bound — disown runs first, re-mark second, both inside the one
25696
+ * transaction above.
25697
+ */
25698
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25699
+ this.ensureRowStmt.run();
25700
+ withTransaction(
25701
+ this.db,
25702
+ () => {
25703
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25704
+ this.rearmStmt.run();
25705
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25706
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25707
+ }
25708
+ if (backfillCapturesBefore !== void 0) {
25709
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25710
+ }
25711
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25712
+ },
25713
+ "IMMEDIATE"
25714
+ );
25715
+ }
25716
+ /**
25717
+ * End the attached period: hand its rows to the live path, and release the
25718
+ * boundary so the next attachment can freeze a new one.
25719
+ *
25720
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25721
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25722
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25723
+ * during the detached period, because the machine is not attached. Rows
25724
+ * recorded in that window sit after the boundary and before the re-attach, so
25725
+ * neither path takes them, and the pending count reports none outstanding.
25726
+ *
25727
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25728
+ * closing attachment's to deliver and are no longer outstanding — that is what
25729
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25730
+ * distinction is not academic: this used to write a delivery TIME, which every
25731
+ * read treats as delivery, so one detach turned a window of undelivered rows
25732
+ * into a window of delivered ones and no surface could tell. It writes the
25733
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25734
+ * "received" stop being the same fact.
25735
+ *
25736
+ * A change of deployment still frees them (see the re-arm), because the next
25737
+ * deployment has seen none of this machine's history — so the rows reach it
25738
+ * exactly as they did when this wrote a delivery time.
25739
+ *
25740
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25741
+ * window unstamped — that half-state would re-send the whole attached period
25742
+ * on the next attach, which is the failure the boundary exists to prevent.
25743
+ */
25744
+ closeAttachedWindow(attachedAtMs, atMs) {
25745
+ this.ensureRowStmt.run();
25746
+ withTransaction(
25747
+ this.db,
25748
+ () => {
25749
+ const row = getRow(this.fingerprintStmt);
25750
+ const from = row?.backlogBefore ?? attachedAtMs;
25751
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25752
+ this.releaseBoundaryStmt.run();
25753
+ },
25754
+ "IMMEDIATE"
25755
+ );
25756
+ }
25757
+ /**
25758
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25759
+ *
25760
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25761
+ * different deployment and therefore discards what was delivered to the old
25762
+ * one: here the recipient is the same, so everything already sent to it stays
25763
+ * sent.
25764
+ */
25765
+ freezeBoundary(backlogBefore) {
25766
+ this.ensureRowStmt.run();
25767
+ this.freezeBoundaryStmt.run({ backlogBefore });
25768
+ }
25769
+ /** Take the claim, or report that someone live already holds it. */
25770
+ claim(pid, host, nowMs, staleAfterMs) {
25771
+ this.ensureRowStmt.run();
25772
+ let taken = false;
25773
+ withTransaction(
25774
+ this.db,
25775
+ () => {
25776
+ const result = this.claimStmt.run({
25777
+ pid,
25778
+ host,
25779
+ now: nowMs,
25780
+ staleBefore: nowMs - staleAfterMs
25781
+ });
25782
+ taken = result.changes === 1;
25783
+ },
25784
+ "IMMEDIATE"
25785
+ );
25786
+ return taken;
25787
+ }
25788
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25789
+ heartbeat(pid, nowMs) {
25790
+ this.heartbeatStmt.run({ now: nowMs, pid });
25791
+ }
25792
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25793
+ release(pid) {
25794
+ this.releaseStmt.run({ pid });
25795
+ }
25796
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25797
+ lease() {
25798
+ return getRow(this.leaseStmt);
25799
+ }
25800
+ };
25801
+
25802
+ // ../../packages/persistence/src/migrations.ts
25803
+ function describeObject(object2) {
25804
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25805
+ }
25806
+ function splitStatements(sql) {
25807
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25808
+ }
25809
+ function createdIndexName(statement) {
25810
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25811
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25812
+ }
25813
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25814
+ function applyMigrations(db, file2, options = {}) {
25815
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25816
+ db.exec(
25817
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25818
+ );
25819
+ const applied = new Set(
25820
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25821
+ );
25822
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25823
+ const record2 = db.prepare(
25824
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25825
+ );
25826
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25827
+ if (applied.has(migration.tag)) continue;
25828
+ if (options.skipTags?.has(migration.tag) === true) continue;
25829
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25830
+ const evidence = evidenceObjects(migration.sql);
25831
+ const present = evidence.filter((o) => evidenceExists(db, o));
25832
+ if (present.length > 0 && present.length < evidence.length) {
25833
+ const missing = evidence.filter((o) => !present.includes(o));
25834
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25835
+ akaWarn(message);
25836
+ throw new Error(`[aka] ${message}`);
25837
+ }
25838
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25839
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25840
+ const statements = splitStatements(migration.sql);
25841
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25842
+ try {
25843
+ withTransaction(
25844
+ db,
25845
+ () => {
25846
+ for (const statement of statements) {
25847
+ const indexName = createdIndexName(statement);
25848
+ if (indexName === void 0) {
25849
+ if (alreadyApplied) continue;
25850
+ } else if (indexExists(db, indexName)) {
25851
+ continue;
25852
+ }
25853
+ db.exec(statement);
25854
+ }
25855
+ if (wantsFkOff && !alreadyApplied) {
25856
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25857
+ if (violations.length > 0) {
25858
+ throw new Error(
25859
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25860
+ );
25861
+ }
25862
+ }
25863
+ record2.run(migration.tag, Date.now());
25864
+ },
25865
+ "IMMEDIATE"
25866
+ );
25867
+ } finally {
25868
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25869
+ }
25870
+ }
25871
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25872
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25873
+ }
25874
+ ensureSyncedAtColumn(db, "audit_events");
25875
+ ensureScanLedgerTable(db);
25876
+ ensureHistorySyncTable(db);
25877
+ ensureBlockedDetectionsTable(db);
25878
+ ensureRuleProbeCacheTable(db);
25879
+ ensureWriteGateTrigger(db);
25880
+ ensureTokenUsageColumns(db);
25881
+ reconcileSourceProjectIds(db);
25882
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25883
+ const drained = runLegacyHistoryBackfill(db);
25884
+ if (drained) applyLegacyDropMigration(db, file2);
25885
+ }
25886
+ }
25887
+ function readLegacyTables(db) {
25888
+ let holdsRows = false;
25889
+ const marks = [];
25890
+ for (const table of ["events", "findings"]) {
25891
+ try {
25892
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25893
+ if (row === void 0) {
25894
+ holdsRows = true;
25895
+ marks.push(`${table}:unreadable`);
25896
+ continue;
25897
+ }
25898
+ if (row.n > 0) holdsRows = true;
25899
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25900
+ } catch {
25901
+ holdsRows = true;
25902
+ marks.push(`${table}:unreadable`);
25903
+ }
25904
+ }
25905
+ return { holdsRows, mark: marks.join("|") };
25906
+ }
25907
+ function applyLegacyDropMigration(db, file2) {
25908
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25909
+ if (!migration) return;
25910
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25911
+ if (file2 !== void 0 && before?.holdsRows === true) {
25912
+ try {
25913
+ backupBeforeLegacyDrop(db, file2);
25914
+ } catch (error61) {
25915
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25916
+ return;
25917
+ }
25918
+ }
25919
+ try {
25920
+ withTransaction(
25921
+ db,
25922
+ () => {
25923
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25924
+ if (alreadyDropped) return;
25925
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25926
+ akaWarn(
25927
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25928
+ );
25929
+ return;
25930
+ }
25931
+ for (const statement of splitStatements(migration.sql)) {
25932
+ db.exec(statement);
25933
+ }
25934
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25935
+ migration.tag,
25936
+ Date.now()
25937
+ );
24921
25938
  },
24922
25939
  "IMMEDIATE"
24923
25940
  );
@@ -25215,10 +26232,62 @@ function ensureSyncedAtColumn(db, table) {
25215
26232
  if (!columns.includes("outbox_owed")) {
25216
26233
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25217
26234
  }
26235
+ if (!columns.includes("sync_failed_at")) {
26236
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26237
+ }
26238
+ if (!columns.includes("sync_failure")) {
26239
+ withTransaction(
26240
+ db,
26241
+ () => {
26242
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26243
+ db.exec(
26244
+ `UPDATE ${table} SET synced_at = NULL
26245
+ WHERE synced_at = -1
26246
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26247
+ );
26248
+ },
26249
+ "IMMEDIATE"
26250
+ );
26251
+ }
25218
26252
  db.exec(
25219
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25220
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26253
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26254
+ BEFORE UPDATE OF sync_failure ON ${table}
26255
+ WHEN ${syncFailureRejectCondition()}
26256
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25221
26257
  );
26258
+ const syncIndexColumns = [
26259
+ "event_type",
26260
+ "synced_at",
26261
+ "sync_claimed_at",
26262
+ "started_at",
26263
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26264
+ // has to be in the index for the read to stay covered — but putting it
26265
+ // ahead of `started_at` would reorder the prefix the structural drain's
26266
+ // reads match on.
26267
+ "sync_failure"
26268
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26269
+ //
26270
+ // The delivery-state read tests it — a capture's state depends on whether a
26271
+ // live forward marked it owed — so carrying it here makes that read covering
26272
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26273
+ // But a sixth column changes what the planner charges for this index, and
26274
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26275
+ // then stops choosing the per-session index for the token rollup and walks
26276
+ // every `llm_call` in the store through the event-type index instead. That
26277
+ // read grows with the store; this one does not.
26278
+ //
26279
+ // 40 ms on the largest store measured, once per render, is a cost worth
26280
+ // paying to leave every other read's plan where it was.
26281
+ ];
26282
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26283
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26284
+ if (!syncIndexMatches) {
26285
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26286
+ db.exec(
26287
+ `CREATE INDEX idx_audit_events_sync
26288
+ ON audit_events (${syncIndexColumns.join(", ")})`
26289
+ );
26290
+ }
25222
26291
  db.exec(
25223
26292
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25224
26293
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25440,7 +26509,11 @@ function buildAuditEvent(row) {
25440
26509
  link: linkParsed?.success ? linkParsed.data : null,
25441
26510
  targetId: row.target_id,
25442
26511
  internal: intToBool(row.internal),
25443
- flagged: intToBool(row.flagged)
26512
+ flagged: intToBool(row.flagged),
26513
+ // Only meaningful when the title came out empty — a row whose body was
26514
+ // expired but whose title fell back to `tool_name` still has something to
26515
+ // render, and flagging it would make the view apologise for nothing.
26516
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25444
26517
  };
25445
26518
  }
25446
26519
  var TIMELINE_COLUMNS = `
@@ -25448,6 +26521,7 @@ var TIMELINE_COLUMNS = `
25448
26521
  event_type,
25449
26522
  started_at,
25450
26523
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26524
+ content_expired_at,
25451
26525
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25452
26526
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25453
26527
  json_extract(attributes, '$.severity') AS severity,
@@ -25574,7 +26648,8 @@ var SqliteActivityRepository = class {
25574
26648
  SELECT 1 FROM audit_events d
25575
26649
  WHERE d.root_session_id = audit_events.id
25576
26650
  AND (d.content LIKE ? ESCAPE '\\'
25577
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26651
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26652
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25578
26653
  );
25579
26654
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25580
26655
  }
@@ -26112,6 +27187,88 @@ var SqliteAuditEventsRepository = class {
26112
27187
  }
26113
27188
  };
26114
27189
 
27190
+ // ../../packages/persistence/src/repositories/body-retention.ts
27191
+ var DEFAULT_BATCH_SIZE = 500;
27192
+ var DEFAULT_MAX_ROWS = 5e4;
27193
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27194
+ var SqliteBodyRetentionRepository = class {
27195
+ constructor(db) {
27196
+ this.db = db;
27197
+ const select = (laneClause) => `
27198
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27199
+ FROM audit_events
27200
+ WHERE content IS NOT NULL
27201
+ AND started_at < :cutoff
27202
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27203
+ ${laneClause}
27204
+ ORDER BY started_at
27205
+ LIMIT :limit`;
27206
+ this.candidatesStmt = this.db.prepare(select(""));
27207
+ this.candidatesSyncSafeStmt = this.db.prepare(
27208
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27209
+ );
27210
+ this.heldBySyncStmt = this.db.prepare(`
27211
+ SELECT COUNT(*) AS n
27212
+ FROM audit_events
27213
+ WHERE content IS NOT NULL
27214
+ AND started_at < :cutoff
27215
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27216
+ AND synced_at IS NULL`);
27217
+ this.expireStmt = this.db.prepare(
27218
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27219
+ );
27220
+ }
27221
+ db;
27222
+ candidatesStmt;
27223
+ candidatesSyncSafeStmt;
27224
+ heldBySyncStmt;
27225
+ expireStmt;
27226
+ /** How many bytes a pass with these options would free, changing nothing. */
27227
+ preview(opts) {
27228
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27229
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27230
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27231
+ return {
27232
+ rowsExpired: rows.length,
27233
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27234
+ rowsHeldBySync: this.countHeldBySync(opts)
27235
+ };
27236
+ }
27237
+ /** Clear eligible bodies, in bounded batches. */
27238
+ expire(opts) {
27239
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27240
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27241
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27242
+ let rowsExpired = 0;
27243
+ let bytesFreed = 0;
27244
+ let done = true;
27245
+ while (rowsExpired < maxRows) {
27246
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27247
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27248
+ if (batch.length === 0) break;
27249
+ withTransaction(
27250
+ this.db,
27251
+ () => {
27252
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27253
+ },
27254
+ "IMMEDIATE"
27255
+ );
27256
+ rowsExpired += batch.length;
27257
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27258
+ if (batch.length < remaining) break;
27259
+ if (rowsExpired >= maxRows) {
27260
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27261
+ }
27262
+ }
27263
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27264
+ }
27265
+ countHeldBySync(opts) {
27266
+ if (opts.sweepSyncLane) return 0;
27267
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27268
+ return row.n;
27269
+ }
27270
+ };
27271
+
26115
27272
  // ../../packages/persistence/src/repositories/classified-data.ts
26116
27273
  var SqliteClassifiedDataRepository = class {
26117
27274
  constructor(db) {
@@ -26912,23 +28069,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26912
28069
  )`;
26913
28070
 
26914
28071
  // ../../packages/persistence/src/repositories/findings.ts
26915
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26916
- var DEFAULT_LOCATIONS_LIMIT = 100;
26917
- var LOCATION_RULE_IDS_CAP = 20;
26918
- function compareLocationOrder(a, b) {
26919
- return compareFindingGroupOrder(
26920
- {
26921
- severity: a.maxSeverity,
26922
- latestDetectedAt: a.latestDetectedAt,
26923
- id: ""
26924
- },
26925
- {
26926
- severity: b.maxSeverity,
26927
- latestDetectedAt: b.latestDetectedAt,
26928
- id: ""
26929
- }
26930
- );
26931
- }
26932
28072
  var CONCAT_SEP = ",";
26933
28073
  var TUPLE_SEP = "|";
26934
28074
  function splitConcat(value) {
@@ -26957,7 +28097,15 @@ function toFlatFindingRow(r) {
26957
28097
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26958
28098
  eventId: r.event_id,
26959
28099
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26960
- status: deriveInstanceStatus(r)
28100
+ status: deriveInstanceStatus(r),
28101
+ delivery: deriveFindingDelivery({
28102
+ kind: r.kind,
28103
+ syncedAt: r.synced_at,
28104
+ syncClaimedAt: r.sync_claimed_at,
28105
+ syncFailedAt: r.sync_failed_at,
28106
+ syncFailure: r.sync_failure,
28107
+ outboxOwed: r.outbox_owed
28108
+ })
26961
28109
  };
26962
28110
  }
26963
28111
  function encodeGroupCursor(group) {
@@ -26980,13 +28128,51 @@ function decodeGroupCursor(cursor) {
26980
28128
  return null;
26981
28129
  }
26982
28130
  function firstAfter(sorted, cursor) {
26983
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28131
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26984
28132
  return index === -1 ? sorted.length : index;
26985
28133
  }
26986
28134
  function findDeepLinked(sorted, page, id) {
26987
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26988
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28135
+ if (page.some((t) => t.id === id)) return void 0;
28136
+ return sorted.find((t) => t.id === id);
28137
+ }
28138
+ function encodeLocationCursor(location) {
28139
+ const payload = {
28140
+ sev: location.maxSeverity,
28141
+ t: location.latestDetectedAt,
28142
+ r: location.repo,
28143
+ f: location.file
28144
+ };
28145
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28146
+ }
28147
+ function decodeLocationCursor(cursor) {
28148
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28149
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28150
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28151
+ }
28152
+ return null;
28153
+ }
28154
+ function firstLocationAfter(sorted, cursor) {
28155
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28156
+ return index === -1 ? sorted.length : index;
26989
28157
  }
28158
+ function findDeepLinkedLocation(sorted, page, id) {
28159
+ if (page.some((l) => l.id === id)) return void 0;
28160
+ return sorted.find((l) => l.id === id);
28161
+ }
28162
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28163
+ d.severity AS severity, f.masked_match AS masked_match,
28164
+ f.action_taken AS action_taken, f.confidence AS confidence,
28165
+ e.started_at AS occurred_at,
28166
+ e.source_tool AS source_tool,
28167
+ e.repo AS repo,
28168
+ e.file_path AS file,
28169
+ e.tool_name AS tool_name,
28170
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28171
+ e.event_type AS kind, f.finding_key AS finding_key,
28172
+ ${latestResolutionStatusSql("f")} AS latest_status,
28173
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28174
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28175
+ e.outbox_owed AS outbox_owed`;
26990
28176
  var DAY_MS3 = 864e5;
26991
28177
  var SqliteFindingsRepository = class {
26992
28178
  constructor(db) {
@@ -27107,30 +28293,26 @@ var SqliteFindingsRepository = class {
27107
28293
  );
27108
28294
  }
27109
28295
  /**
27110
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27111
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27112
- * attributes bag, rule_id/category/severity from the definition), scoped to
27113
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27114
- * rows this list must never surface), groups by ruleId, computes
27115
- * per-filter-excluded facets, applies the requested filters, and sorts by
27116
- * severity then recency. Filtering
27117
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27118
- * reflect the full filtered set; `items` is the requested
27119
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27120
- * filter, `totals.findings` counts only instances whose derived status was
27121
- * requested, and each item's instance preview is narrowed the same way.
28296
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28297
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28298
+ * list must never surface), with per-filter-excluded facets, the requested
28299
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28300
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28301
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28302
+ * Under a `status` filter, `totals.findings` counts only findings whose
28303
+ * derived status was requested.
28304
+ *
28305
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28306
+ * folding EVERY finding into the numbers a type row and the filters need
28307
+ * (count, severity, category, providers, actions, statuses, latest, search
28308
+ * text). The findings OF a type come from listFindingInstances scoped to
28309
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27122
28310
  *
27123
- * Two reads, neither of which materializes a row per finding:
27124
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27125
- * the group and the filters need (count, providers, actions, statuses,
27126
- * latest, search text);
27127
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27128
- * populate `instances` for the table's expanded rows.
27129
28311
  * The aggregates carry raw DB values and are translated by the same
27130
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27131
- * rule is ever restated in SQL.
28312
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28313
+ * status rule is ever restated in SQL.
27132
28314
  */
27133
- listGroupedFindings(query) {
28315
+ listFindingTypes(query) {
27134
28316
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27135
28317
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27136
28318
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27143,12 +28325,7 @@ var SqliteFindingsRepository = class {
27143
28325
  predicate,
27144
28326
  params: sessionParams
27145
28327
  });
27146
- const rows = this.previewRows(aggregates, {
27147
- sessionId: query.sessionId,
27148
- from: query.from
27149
- });
27150
- const groupable = rows.map(toFlatFindingRow);
27151
- const allGroups = buildFindingGroups(groupable, { aggregates });
28328
+ const allTypes = buildFindingTypes(aggregates);
27152
28329
  const filterOpts = {
27153
28330
  severity: query.severity,
27154
28331
  providers: query.provider,
@@ -27157,30 +28334,25 @@ var SqliteFindingsRepository = class {
27157
28334
  subtype: query.subtype,
27158
28335
  q: query.q
27159
28336
  };
27160
- const facets = computeFindingFacets(allGroups, filterOpts);
27161
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28337
+ const facets = computeFindingFacets(allTypes, filterOpts);
28338
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27162
28339
  const statusFilter = query.status ?? [];
27163
28340
  const totals = {
27164
- findings: sorted.reduce((acc, g) => {
27165
- if (statusFilter.length === 0) return acc + g.instanceCount;
27166
- const agg = aggregates.get(g.id);
27167
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28341
+ findings: sorted.reduce((acc, t) => {
28342
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28343
+ const agg = aggregates.get(t.id);
28344
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27168
28345
  }, 0),
27169
- groups: sorted.length
28346
+ types: sorted.length
27170
28347
  };
27171
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28348
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27172
28349
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27173
28350
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27174
28351
  const page = sorted.slice(start, start + limit);
27175
28352
  const lastOnPage = page.at(-1);
27176
28353
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27177
28354
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27178
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27179
- const narrow = (g) => statusSet ? {
27180
- ...g,
27181
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27182
- } : g;
27183
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28355
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27184
28356
  return Promise.resolve({
27185
28357
  totals,
27186
28358
  facets,
@@ -27191,7 +28363,7 @@ var SqliteFindingsRepository = class {
27191
28363
  }
27192
28364
  /**
27193
28365
  * One row per rule_id, folding EVERY instance of the group into the values
27194
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28366
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27195
28367
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27196
28368
  *
27197
28369
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27245,6 +28417,7 @@ var SqliteFindingsRepository = class {
27245
28417
  providers: query.provider,
27246
28418
  actions: query.action,
27247
28419
  statuses: query.status,
28420
+ deliveries: query.deployment,
27248
28421
  tools: query.tool,
27249
28422
  repo: query.repo,
27250
28423
  file: query.file,
@@ -27285,13 +28458,25 @@ var SqliteFindingsRepository = class {
27285
28458
  });
27286
28459
  }
27287
28460
  /**
27288
- * The same findings folded by location: repository, then file within it.
28461
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27289
28462
  *
27290
28463
  * The grouping keys come from the capturing event's attributes, which is what
27291
- * the local store relates a finding to — there is no finding↔asset row to
27292
- * group by instead. A repo or file the event did not record folds into the
27293
- * empty-string bucket, which the view renders but does not link, since no
27294
- * filter can name it.
28464
+ * the local store relates a finding to; there is no finding↔asset row to group
28465
+ * by instead. A repo or file the event did not record folds into the
28466
+ * empty-string bucket, which is a real location like any other: it is listed,
28467
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28468
+ *
28469
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28470
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28471
+ * list was rebuilt to remove — and two-level pagination inside an
28472
+ * expand/collapse table is what pushed that view to master/detail in the first
28473
+ * place.
28474
+ *
28475
+ * Every filter narrows the FINDINGS and the locations fall out of what
28476
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28477
+ * reports for the same filters scoped to that pair. The view depends on it:
28478
+ * one toolbar sits over both panels precisely because a location owns none of
28479
+ * its fields.
27295
28480
  */
27296
28481
  listFindingLocations(query) {
27297
28482
  const opts = {
@@ -27300,16 +28485,20 @@ var SqliteFindingsRepository = class {
27300
28485
  providers: query.provider,
27301
28486
  actions: query.action,
27302
28487
  statuses: query.status,
28488
+ deliveries: query.deployment,
27303
28489
  tools: query.tool,
27304
28490
  q: query.q
27305
28491
  };
27306
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28492
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28493
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27307
28494
  const byRepo = /* @__PURE__ */ new Map();
28495
+ const accumulator = createInstanceFacetAccumulator(opts);
27308
28496
  let total = 0;
27309
28497
  for (const row of this.scanFindingRows({
27310
28498
  sessionId: query.sessionId,
27311
28499
  from: query.from
27312
28500
  })) {
28501
+ accumulator.add(row);
27313
28502
  if (!matchesInstanceFilters(row, opts)) continue;
27314
28503
  total += 1;
27315
28504
  let files = byRepo.get(row.repo);
@@ -27324,103 +28513,35 @@ var SqliteFindingsRepository = class {
27324
28513
  }
27325
28514
  addToLocation(acc, row);
27326
28515
  }
27327
- let fileCount = 0;
27328
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27329
- fileCount += files.size;
27330
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27331
- file: file2,
27332
- instanceCount: acc.instanceCount,
27333
- maxSeverity: acc.maxSeverity,
27334
- latestDetectedAt: acc.latestDetectedAt,
27335
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27336
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27337
- })).sort(compareLocationOrder);
27338
- const rollup = fileRows.reduce(
27339
- (a, f) => ({
27340
- instanceCount: a.instanceCount + f.instanceCount,
27341
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27342
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27343
- }),
27344
- {
27345
- instanceCount: 0,
27346
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27347
- latestDetectedAt: ""
27348
- }
27349
- );
27350
- const statuses = fileRows.map((f) => f.status);
27351
- const folded = foldGroupStatus(statuses);
27352
- return {
27353
- repo,
27354
- instanceCount: rollup.instanceCount,
27355
- maxSeverity: rollup.maxSeverity,
27356
- latestDetectedAt: rollup.latestDetectedAt,
27357
- ...folded === void 0 ? {} : { status: folded },
27358
- files: fileRows
27359
- };
27360
- });
27361
- repos.sort(compareLocationOrder);
28516
+ const sorted = [];
28517
+ for (const [repo, files] of byRepo) {
28518
+ for (const [file2, acc] of files) {
28519
+ const status = foldGroupStatus(acc.statuses);
28520
+ sorted.push({
28521
+ id: encodeLocationId(repo, file2),
28522
+ repo,
28523
+ file: file2,
28524
+ instanceCount: acc.instanceCount,
28525
+ maxSeverity: acc.maxSeverity,
28526
+ latestDetectedAt: acc.latestDetectedAt,
28527
+ ...status === void 0 ? {} : { status },
28528
+ ruleIds: [...acc.ruleIds]
28529
+ });
28530
+ }
28531
+ }
28532
+ sorted.sort(compareLocationOrder);
28533
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28534
+ const page = sorted.slice(start, start + limit);
28535
+ const lastOnPage = page.at(-1);
28536
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28537
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27362
28538
  return Promise.resolve({
27363
- totals: { findings: total, repos: repos.length, files: fileCount },
27364
- items: repos.slice(0, limit),
27365
- hasMore: repos.length > limit
28539
+ totals: { findings: total, locations: sorted.length },
28540
+ facets: accumulator.facets(),
28541
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28542
+ nextCursor
27366
28543
  });
27367
28544
  }
27368
- /**
27369
- * Each group's newest instances, for the table's expanded rows.
27370
- *
27371
- * ONE index-ordered scan with early termination, and the shape is the point.
27372
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27373
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27374
- * through a temp B-tree to keep a bounded preview of each group, and then
27375
- * sorts the survivors again for the page order. Both sorts grow with the
27376
- * store while the answer does not.
27377
- *
27378
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27379
- * (or the session or window index the scope names — see `findingScanSql`),
27380
- * which is already the order the page wants, and keeps rows per rule until
27381
- * each rule has as many as it can show. The aggregate the caller already holds
27382
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27383
- * per rule, summed, is the number of rows this scan has to find, and it stops
27384
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27385
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27386
- * store with many firing rules widens it. The bound that DOES hold
27387
- * unconditionally is the sorted form's floor: this scan visits at most as
27388
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27389
- * sorted, and stops the moment every rule has its cap, where the sorted form
27390
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27391
- * wanted instances sitting at the tail of the scope — is one pass over
27392
- * everything in scope with a block sort of the id tie-break only, never a
27393
- * sort of the scope, which is still that floor.
27394
- *
27395
- * A row whose rule the aggregate did not see is skipped: the two statements
27396
- * run without a shared snapshot, so a capture landing between them can add a
27397
- * rule here that has no counts there, and the counts are what the group is
27398
- * built from.
27399
- */
27400
- previewRows(aggregates, scope) {
27401
- const wanted = /* @__PURE__ */ new Map();
27402
- let remaining = 0;
27403
- for (const [ruleId, agg] of aggregates) {
27404
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27405
- wanted.set(ruleId, n);
27406
- remaining += n;
27407
- }
27408
- const rows = [];
27409
- if (remaining === 0) return rows;
27410
- const { sql, params } = this.findingScanSql(scope);
27411
- const taken = /* @__PURE__ */ new Map();
27412
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27413
- const want = wanted.get(r.rule_id);
27414
- if (want === void 0) continue;
27415
- const have = taken.get(r.rule_id) ?? 0;
27416
- if (have >= want) continue;
27417
- taken.set(r.rule_id, have + 1);
27418
- rows.push(r);
27419
- remaining -= 1;
27420
- if (remaining === 0) break;
27421
- }
27422
- return rows;
27423
- }
27424
28545
  /**
27425
28546
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27426
28547
  *
@@ -27447,6 +28568,33 @@ var SqliteFindingsRepository = class {
27447
28568
  yield toFlatFindingRow(r);
27448
28569
  }
27449
28570
  }
28571
+ /**
28572
+ * One finding by its own id, or null when no such row exists.
28573
+ *
28574
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28575
+ * the store — and, unlike anything derived from a list page, it resolves a
28576
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28577
+ * deep link needs: the id it carries may name a finding thousands of rows
28578
+ * older than anything a first page holds.
28579
+ *
28580
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28581
+ * RESOLVES an id; whether that row would survive the list's current filters is
28582
+ * a different question, and hiding the target because a filter excludes it is
28583
+ * worse than showing it.
28584
+ *
28585
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28586
+ * type should the list select?" and "what does the drawer show?".
28587
+ */
28588
+ findingInstance(id) {
28589
+ const row = this.db.prepare(
28590
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28591
+ FROM inspection_findings f
28592
+ JOIN audit_events e ON e.id = f.audit_event_id
28593
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28594
+ WHERE f.id = ?`
28595
+ ).get(id);
28596
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28597
+ }
27450
28598
  /**
27451
28599
  * The one statement both instance-level scans run: every finding in scope,
27452
28600
  * joined to its event and definition, newest first.
@@ -27480,17 +28628,7 @@ var SqliteFindingsRepository = class {
27480
28628
  conditions.push("e.started_at >= ?");
27481
28629
  params.push(isoToEpochMillis(scope.from));
27482
28630
  }
27483
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27484
- d.severity AS severity, f.masked_match AS masked_match,
27485
- f.action_taken AS action_taken, f.confidence AS confidence,
27486
- e.started_at AS occurred_at,
27487
- e.source_tool AS source_tool,
27488
- e.repo AS repo,
27489
- e.file_path AS file,
27490
- e.tool_name AS tool_name,
27491
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27492
- e.event_type AS kind, f.finding_key AS finding_key,
27493
- ${latestResolutionStatusSql("f")} AS latest_status
28631
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27494
28632
  FROM audit_events e
27495
28633
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27496
28634
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27504,6 +28642,26 @@ var SqliteFindingsRepository = class {
27504
28642
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27505
28643
  const rows = this.db.prepare(
27506
28644
  `SELECT rule_id,
28645
+ -- BARE columns beside max(latest_at), which is deliberate and
28646
+ -- is SQLite's documented behaviour: with a single min()/max()
28647
+ -- in an aggregate query, every bare column takes its value from
28648
+ -- the row that produced the extremum. So these are the severity
28649
+ -- and category of the definition whose finding is NEWEST, which
28650
+ -- is what the row-based build they replaced read off its first
28651
+ -- (newest-first) row.
28652
+ --
28653
+ -- min() is WRONG here and was the defect: inspection_definitions
28654
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28655
+ -- mints a new row), so a rule whose severity moved between
28656
+ -- versions has several, and min() picks the ALPHABETICALLY
28657
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28658
+ -- That is arbitrary in direction, and it feeds the badge, the
28659
+ -- filter, the facet counts and the primary sort key.
28660
+ --
28661
+ -- Adding a second min()/max() aggregate here would make these
28662
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28663
+ severity,
28664
+ category,
27507
28665
  sum(tuple_count) AS instance_count,
27508
28666
  max(latest_at) AS latest_at,
27509
28667
  group_concat(source_tools) AS source_tools,
@@ -27514,6 +28672,14 @@ var SqliteFindingsRepository = class {
27514
28672
  group_concat(tool_names) AS tool_names
27515
28673
  FROM (
27516
28674
  SELECT d.rule_id AS rule_id,
28675
+ -- Severity and category are columns of the DEFINITION, and
28676
+ -- a rule can have SEVERAL definitions (one per version), so
28677
+ -- these are grouped on below and resolved to the newest
28678
+ -- firing version by the outer query's bare-column select.
28679
+ -- They ride the aggregate because the type build has no rows
28680
+ -- to read them off \u2014 see buildFindingTypes.
28681
+ d.severity AS severity,
28682
+ d.category AS category,
27517
28683
  e.event_type || '${TUPLE_SEP}' ||
27518
28684
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27519
28685
  coalesce(latest.status, '') AS status_tuple,
@@ -27528,7 +28694,7 @@ var SqliteFindingsRepository = class {
27528
28694
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27529
28695
  ON latest.finding_key = f.finding_key
27530
28696
  ${scope.predicate}
27531
- GROUP BY d.rule_id, status_tuple
28697
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27532
28698
  )
27533
28699
  GROUP BY rule_id`
27534
28700
  ).all(scope.params);
@@ -27537,6 +28703,8 @@ var SqliteFindingsRepository = class {
27537
28703
  r.rule_id,
27538
28704
  {
27539
28705
  instanceCount: r.instance_count,
28706
+ severity: r.severity,
28707
+ category: r.category,
27540
28708
  sourceTools: splitConcat(r.source_tools),
27541
28709
  actionsTaken: splitConcat(r.actions_taken),
27542
28710
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27553,7 +28721,7 @@ var SqliteFindingsRepository = class {
27553
28721
  latestDetectedAt: epochMillisToIso(r.latest_at),
27554
28722
  // Free text only — joined and substring-matched, so group_concat's
27555
28723
  // commas need no unpicking (a repo/path containing one still matches).
27556
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28724
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27557
28725
  // tell "no q this request" from "a group with no repo/file at all"
27558
28726
  // and skip priming a haystack nothing will read.
27559
28727
  ...withSearchText ? {
@@ -27581,7 +28749,9 @@ var SqliteFindingsRepository = class {
27581
28749
  )
27582
28750
  );
27583
28751
  for (const row of grouped) {
27584
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28752
+ if (Object.hasOwn(byAction, row.action_taken)) {
28753
+ byAction[row.action_taken] = row.c;
28754
+ }
27585
28755
  }
27586
28756
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27587
28757
  const sevRows = allRows(
@@ -27598,7 +28768,9 @@ var SqliteFindingsRepository = class {
27598
28768
  )
27599
28769
  );
27600
28770
  for (const row of sevRows) {
27601
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28771
+ if (Object.hasOwn(bySeverity, row.severity)) {
28772
+ bySeverity[row.severity] = row.c;
28773
+ }
27602
28774
  }
27603
28775
  const categories = ENFORCEABLE_CATEGORIES;
27604
28776
  const enabledRows = allRows(
@@ -27647,469 +28819,6 @@ function isoDay(ms) {
27647
28819
  return new Date(ms).toISOString().slice(0, 10);
27648
28820
  }
27649
28821
 
27650
- // ../../packages/persistence/src/repositories/history-sync.ts
27651
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27652
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27653
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27654
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27655
- var SKIPPED = -1;
27656
- var ROW_COLUMNS = `id,
27657
- parent_id AS parentId,
27658
- root_session_id AS rootSessionId,
27659
- event_type AS eventType,
27660
- host_id AS hostId,
27661
- harness_id AS harnessId,
27662
- source_project_id AS sourceProjectId,
27663
- started_at AS startedAt,
27664
- ended_at AS endedAt,
27665
- severity,
27666
- priority,
27667
- content,
27668
- content_hash AS contentHash,
27669
- attributes`;
27670
- var SqliteHistorySyncRepository = class {
27671
- constructor(db) {
27672
- this.db = db;
27673
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27674
- this.sessionsStmt = db.prepare(
27675
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27676
- FROM audit_events
27677
- WHERE synced_at IS NULL
27678
- AND event_type IN (${TYPE_LIST})
27679
- AND started_at < :before
27680
- GROUP BY sessionId
27681
- ORDER BY earliest
27682
- LIMIT :limit`
27683
- );
27684
- this.rowsStmt = db.prepare(
27685
- `SELECT ${ROW_COLUMNS}
27686
- FROM audit_events
27687
- WHERE synced_at IS NULL
27688
- AND event_type IN (${TYPE_LIST})
27689
- AND started_at < :before
27690
- AND COALESCE(root_session_id, id) = :sessionId
27691
- ORDER BY (event_type = 'session') DESC, started_at
27692
- LIMIT :limit`
27693
- );
27694
- this.captureRowsStmt = db.prepare(
27695
- `SELECT ${ROW_COLUMNS}
27696
- FROM audit_events
27697
- WHERE synced_at IS NULL
27698
- AND sync_claimed_at IS NULL
27699
- AND outbox_owed = 1
27700
- AND event_type IN (${CAPTURE_TYPE_LIST})
27701
- AND started_at < :before
27702
- ORDER BY started_at
27703
- LIMIT :limit`
27704
- );
27705
- this.markOwedStmt = db.prepare(
27706
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27707
- );
27708
- this.stampStmt = db.prepare(
27709
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27710
- );
27711
- this.claimRowStmt = db.prepare(
27712
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27713
- );
27714
- this.releaseRowStmt = db.prepare(
27715
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27716
- );
27717
- this.releaseStaleClaimsStmt = db.prepare(
27718
- `UPDATE audit_events SET sync_claimed_at = NULL
27719
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27720
- );
27721
- this.partitionStmt = db.prepare(
27722
- `SELECT
27723
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27724
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27725
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27726
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27727
- COUNT(*) AS total
27728
- FROM audit_events
27729
- WHERE event_type IN (${TYPE_LIST})`
27730
- );
27731
- this.countsStmt = db.prepare(
27732
- `SELECT
27733
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27734
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27735
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27736
- FROM audit_events
27737
- WHERE event_type IN (${TYPE_LIST})`
27738
- );
27739
- this.captureSkipCountStmt = db.prepare(
27740
- `SELECT COUNT(*) AS skipped
27741
- FROM audit_events
27742
- WHERE synced_at = ${String(SKIPPED)}
27743
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27744
- );
27745
- this.fingerprintStmt = db.prepare(
27746
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27747
- FROM history_sync WHERE id = 1`
27748
- );
27749
- this.setFingerprintStmt = db.prepare(
27750
- `UPDATE history_sync
27751
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27752
- WHERE id = 1`
27753
- );
27754
- this.disownCapturesStmt = db.prepare(
27755
- `UPDATE audit_events SET outbox_owed = NULL
27756
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27757
- );
27758
- this.rearmStmt = db.prepare(
27759
- `UPDATE audit_events SET synced_at = NULL
27760
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27761
- );
27762
- this.claimStmt = db.prepare(
27763
- `UPDATE history_sync
27764
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27765
- WHERE id = 1
27766
- AND (owner_pid IS NULL
27767
- OR heartbeat_at IS NULL
27768
- OR heartbeat_at < :staleBefore
27769
- OR heartbeat_at > :now)`
27770
- );
27771
- this.heartbeatStmt = db.prepare(
27772
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27773
- );
27774
- this.releaseStmt = db.prepare(
27775
- `UPDATE history_sync
27776
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27777
- WHERE id = 1 AND owner_pid = :pid`
27778
- );
27779
- this.closeWindowStmt = db.prepare(
27780
- `UPDATE audit_events SET synced_at = :at
27781
- WHERE synced_at IS NULL
27782
- AND event_type IN (${TYPE_LIST})
27783
- AND started_at >= :attachedAt`
27784
- );
27785
- this.releaseBoundaryStmt = db.prepare(
27786
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27787
- );
27788
- this.freezeBoundaryStmt = db.prepare(
27789
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27790
- );
27791
- this.leaseStmt = db.prepare(
27792
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27793
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27794
- FROM history_sync WHERE id = 1`
27795
- );
27796
- this.inspectionsStmt = db.prepare(
27797
- `SELECT d.rule_id AS ruleId,
27798
- d.name AS ruleName,
27799
- d.version AS ruleVersion,
27800
- d.category AS category,
27801
- d.severity AS severity,
27802
- f.span_start AS spanStart,
27803
- f.span_end AS spanEnd,
27804
- f.masked_match AS maskedMatch,
27805
- f.action_taken AS actionTaken,
27806
- f.confidence AS confidence
27807
- FROM inspection_findings f
27808
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27809
- WHERE f.audit_event_id = :auditEventId
27810
- ORDER BY f.span_start, f.id`
27811
- );
27812
- }
27813
- db;
27814
- ensureRowStmt;
27815
- sessionsStmt;
27816
- rowsStmt;
27817
- stampStmt;
27818
- countsStmt;
27819
- fingerprintStmt;
27820
- setFingerprintStmt;
27821
- rearmStmt;
27822
- claimStmt;
27823
- heartbeatStmt;
27824
- releaseStmt;
27825
- leaseStmt;
27826
- inspectionsStmt;
27827
- closeWindowStmt;
27828
- releaseBoundaryStmt;
27829
- freezeBoundaryStmt;
27830
- captureRowsStmt;
27831
- markOwedStmt;
27832
- captureSkipCountStmt;
27833
- disownCapturesStmt;
27834
- partitionStmt;
27835
- claimRowStmt;
27836
- releaseRowStmt;
27837
- releaseStaleClaimsStmt;
27838
- /**
27839
- * The masked detections recorded against one tool call.
27840
- *
27841
- * These travel with the event because a tool call's target is not
27842
- * re-inspectable from the event alone — unlike a capture, where the text
27843
- * itself is re-scannable. What crosses is the masked match and the rule that
27844
- * produced it, never the value.
27845
- */
27846
- inspectionsFor(auditEventId) {
27847
- return allRows(this.inspectionsStmt, { auditEventId });
27848
- }
27849
- /**
27850
- * Sessions with structural rows still to send, oldest first.
27851
- *
27852
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27853
- * read. Anything recorded after the machine attached is the live forward
27854
- * path's to deliver; this drain exists for what was recorded before it, and a
27855
- * row both paths send is at best a duplicate request and at worst — for a
27856
- * session root — an overwrite of the inventory ids the live path resolved.
27857
- */
27858
- pendingSessions(limit, before) {
27859
- return allRows(this.sessionsStmt, { limit, before }).map(
27860
- (r) => r.sessionId
27861
- );
27862
- }
27863
- /** One session's undelivered structural rows within the backlog, root first. */
27864
- pendingRows(sessionId, limit, before) {
27865
- return allRows(this.rowsStmt, { sessionId, limit, before });
27866
- }
27867
- /**
27868
- * Captures this machine still owes the deployment, oldest first.
27869
- *
27870
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27871
- * by a time window — see captureRowsStmt for why a window could not express
27872
- * this. `before` is the grace window that leaves a just-recorded capture to
27873
- * the live path.
27874
- */
27875
- pendingCaptureRows(limit, before) {
27876
- return allRows(this.captureRowsStmt, { limit, before });
27877
- }
27878
- /**
27879
- * Record that a capture is OWED to the deployment.
27880
- *
27881
- * Written by the attached forward path when a live send did not confirm
27882
- * delivery, and read by the drain as the whole of its eligibility test. It is
27883
- * a fact rather than an inference: the machine was attached, the send did not
27884
- * land, so the row is owed — which no time window can state, because the same
27885
- * window that holds the rows a past attachment left owed also holds every
27886
- * capture recorded while the machine was DETACHED, and those were never
27887
- * offered to anyone.
27888
- *
27889
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27890
- * out of the drain's read.
27891
- */
27892
- markCaptureOwed(id) {
27893
- this.markOwedStmt.run({ id });
27894
- }
27895
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27896
- markSynced(ids, atMs) {
27897
- this.stampAll(ids, atMs);
27898
- }
27899
- /**
27900
- * Record that a row will never be sent.
27901
- *
27902
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27903
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27904
- * is retried; marking those would turn one outage into permanent data loss.
27905
- */
27906
- markSkipped(ids) {
27907
- this.stampAll(ids, SKIPPED);
27908
- }
27909
- eachInTransaction(ids, run) {
27910
- if (ids.length === 0) return;
27911
- withTransaction(
27912
- this.db,
27913
- () => {
27914
- for (const id of ids) run(id);
27915
- },
27916
- "IMMEDIATE"
27917
- );
27918
- }
27919
- stampAll(ids, value) {
27920
- if (ids.length === 0) return;
27921
- withTransaction(
27922
- this.db,
27923
- () => {
27924
- for (const id of ids) this.stampStmt.run({ at: value, id });
27925
- },
27926
- "IMMEDIATE"
27927
- );
27928
- }
27929
- /**
27930
- * Claim rows as in-flight.
27931
- *
27932
- * Advisory in exactly the sense the lease is: it records that a send is in
27933
- * progress so a surface can say so, and a lost claim costs a row showing as
27934
- * queued while it is actually being sent. It is not exclusion — the far side
27935
- * settles a duplicate on the row id.
27936
- */
27937
- claimRows(ids, atMs) {
27938
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27939
- }
27940
- /** Give back a claim without settling — the send failed, the row is queued again. */
27941
- releaseRows(ids) {
27942
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27943
- }
27944
- /**
27945
- * Clear claims older than `staleBefore`, and report how many were cleared.
27946
- *
27947
- * A process killed between claiming and settling leaves rows claimed with
27948
- * nothing left to settle them. Without this they read as "sending" for ever.
27949
- */
27950
- releaseStaleClaims(staleBefore) {
27951
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27952
- }
27953
- /**
27954
- * Every tracked row in exactly one delivery state.
27955
- *
27956
- * Takes no boundary on purpose. The boundary answers "what should the drain
27957
- * pick up now", which is a different question from "what state is this row
27958
- * in" — and a machine that has never attached has no boundary to pass, so
27959
- * requiring one would force a caller to invent one and report the whole store
27960
- * as queued.
27961
- */
27962
- partition() {
27963
- const row = getRow(this.partitionStmt, {});
27964
- return {
27965
- queued: row?.queued ?? 0,
27966
- inProgress: row?.inProgress ?? 0,
27967
- synced: row?.synced ?? 0,
27968
- failed: row?.failed ?? 0,
27969
- total: row?.total ?? 0
27970
- };
27971
- }
27972
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27973
- counts(before) {
27974
- const row = getRow(
27975
- this.countsStmt,
27976
- { before }
27977
- );
27978
- const captures = getRow(this.captureSkipCountStmt);
27979
- return {
27980
- pending: row?.pending ?? 0,
27981
- sent: row?.sent ?? 0,
27982
- skipped: row?.skipped ?? 0,
27983
- capturesSkipped: captures?.skipped ?? 0
27984
- };
27985
- }
27986
- /**
27987
- * The deployment the current stamps were made against, and where its backlog
27988
- * ends.
27989
- *
27990
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27991
- * machine that has never drained is — and every writer below seeds the row
27992
- * before it needs one, so nothing depends on this creating it. Keeping the
27993
- * write off the gate path matters because the gate runs on every pass while a
27994
- * write has to take the database's write lock.
27995
- */
27996
- deployment() {
27997
- const row = getRow(
27998
- this.fingerprintStmt
27999
- );
28000
- return {
28001
- fingerprint: row?.fingerprint ?? void 0,
28002
- backlogBefore: row?.backlogBefore ?? void 0
28003
- };
28004
- }
28005
- /**
28006
- * Point the ledger at a different deployment, discarding what it recorded
28007
- * about the previous one.
28008
- *
28009
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28010
- * machine has just left are undelivered as far as the new one is concerned.
28011
- * All three in one transaction, so a crash between them cannot leave stamps
28012
- * attributed to the wrong deployment, or a boundary that belongs to another.
28013
- *
28014
- * The boundary is written HERE and only here, which is what freezes it: a
28015
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28016
- * unchanged, so this never runs and the backlog does not widen back over rows
28017
- * the live path has since delivered.
28018
- */
28019
- rearmFor(fingerprint, backlogBefore) {
28020
- this.ensureRowStmt.run();
28021
- withTransaction(
28022
- this.db,
28023
- () => {
28024
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28025
- this.rearmStmt.run();
28026
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28027
- this.disownCapturesStmt.run();
28028
- }
28029
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28030
- },
28031
- "IMMEDIATE"
28032
- );
28033
- }
28034
- /**
28035
- * End the attached period: hand its rows to the live path, and release the
28036
- * boundary so the next attachment can freeze a new one.
28037
- *
28038
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28039
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28040
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28041
- * during the detached period, because the machine is not attached. Rows
28042
- * recorded in that window sit after the boundary and before the re-attach, so
28043
- * neither path takes them, and the pending count reports none outstanding.
28044
- *
28045
- * Stamping the attached window is not a claim that every one of those rows
28046
- * reached the deployment — the live path drops on failure and says so
28047
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28048
- * status quo: they sit outside the frozen boundary today and are equally never
28049
- * re-sent. Making it explicit is what lets the boundary move.
28050
- *
28051
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28052
- * window unstamped — that half-state would re-send the whole attached period
28053
- * on the next attach, which is the failure the boundary exists to prevent.
28054
- */
28055
- closeAttachedWindow(attachedAtMs, atMs) {
28056
- this.ensureRowStmt.run();
28057
- withTransaction(
28058
- this.db,
28059
- () => {
28060
- const row = getRow(this.fingerprintStmt);
28061
- const from = row?.backlogBefore ?? attachedAtMs;
28062
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28063
- this.releaseBoundaryStmt.run();
28064
- },
28065
- "IMMEDIATE"
28066
- );
28067
- }
28068
- /**
28069
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28070
- *
28071
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28072
- * different deployment and therefore discards what was delivered to the old
28073
- * one: here the recipient is the same, so everything already sent to it stays
28074
- * sent.
28075
- */
28076
- freezeBoundary(backlogBefore) {
28077
- this.ensureRowStmt.run();
28078
- this.freezeBoundaryStmt.run({ backlogBefore });
28079
- }
28080
- /** Take the claim, or report that someone live already holds it. */
28081
- claim(pid, host, nowMs, staleAfterMs) {
28082
- this.ensureRowStmt.run();
28083
- let taken = false;
28084
- withTransaction(
28085
- this.db,
28086
- () => {
28087
- const result = this.claimStmt.run({
28088
- pid,
28089
- host,
28090
- now: nowMs,
28091
- staleBefore: nowMs - staleAfterMs
28092
- });
28093
- taken = result.changes === 1;
28094
- },
28095
- "IMMEDIATE"
28096
- );
28097
- return taken;
28098
- }
28099
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28100
- heartbeat(pid, nowMs) {
28101
- this.heartbeatStmt.run({ now: nowMs, pid });
28102
- }
28103
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28104
- release(pid) {
28105
- this.releaseStmt.run({ pid });
28106
- }
28107
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28108
- lease() {
28109
- return getRow(this.leaseStmt);
28110
- }
28111
- };
28112
-
28113
28822
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28114
28823
  var SqliteInspectionDefinitionsRepository = class {
28115
28824
  constructor(db) {
@@ -28304,7 +29013,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28304
29013
  }
28305
29014
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28306
29015
  }
28307
- function readManagedSettings(paths = managedSettingsPaths()) {
29016
+ var testOnlyManagedPaths = null;
29017
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28308
29018
  for (const path of paths) {
28309
29019
  let text;
28310
29020
  try {
@@ -28339,6 +29049,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28339
29049
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28340
29050
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28341
29051
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29052
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28342
29053
  if (values.vaultConsent !== void 0) {
28343
29054
  merged.vaultConsent = values.vaultConsent ? (
28344
29055
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30784,7 +31495,7 @@ function toUtcDateString(ms) {
30784
31495
  return new Date(ms).toISOString().slice(0, 10);
30785
31496
  }
30786
31497
  function isTimeseriesSeverity(s) {
30787
- return s === "critical" || s === "high" || s === "medium";
31498
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30788
31499
  }
30789
31500
  var SqliteSecurityRepository = class {
30790
31501
  constructor(db, now = () => Date.now()) {
@@ -30846,7 +31557,7 @@ var SqliteSecurityRepository = class {
30846
31557
  ELSE 0
30847
31558
  END) AS open_at_rest
30848
31559
  FROM inspection_findings f
30849
- JOIN audit_events e ON e.id = f.audit_event_id
31560
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30850
31561
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30851
31562
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30852
31563
  ON latest.finding_key = f.finding_key
@@ -30913,12 +31624,16 @@ var SqliteSecurityRepository = class {
30913
31624
  const now = this.now();
30914
31625
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30915
31626
  const rows = this.findingsInRange(windowStart, now);
30916
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30917
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30918
- critical: 0,
30919
- high: 0,
30920
- medium: 0
30921
- }));
31627
+ const points = Array.from(
31628
+ { length: numBuckets },
31629
+ (_, i) => ({
31630
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31631
+ critical: 0,
31632
+ high: 0,
31633
+ medium: 0,
31634
+ low: 0
31635
+ })
31636
+ );
30922
31637
  for (const r of rows) {
30923
31638
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30924
31639
  const bucket = points[idx];
@@ -31068,7 +31783,7 @@ var SqliteSecurityRepository = class {
31068
31783
  this.db.prepare(
31069
31784
  `SELECT e.repo AS repo, count(*) AS c
31070
31785
  FROM inspection_findings f
31071
- JOIN audit_events e ON e.id = f.audit_event_id
31786
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31072
31787
  WHERE e.started_at >= :from AND e.started_at < :to
31073
31788
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31074
31789
  AND e.repo IS NOT NULL
@@ -31136,6 +31851,7 @@ var SqliteSecurityRepository = class {
31136
31851
  `SELECT f.finding_key AS finding_key,
31137
31852
  d.rule_id AS rule_id,
31138
31853
  d.severity AS severity,
31854
+ e.repo AS repo,
31139
31855
  e.file_path AS path,
31140
31856
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31141
31857
  latest.resolved_at AS latest_resolved_at
@@ -31155,6 +31871,7 @@ var SqliteSecurityRepository = class {
31155
31871
  const items = rows.map((r) => ({
31156
31872
  findingKey: r.finding_key,
31157
31873
  ruleId: r.rule_id,
31874
+ repo: r.repo ?? "",
31158
31875
  severity: r.severity,
31159
31876
  path: r.path ?? "",
31160
31877
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31164,15 +31881,68 @@ var SqliteSecurityRepository = class {
31164
31881
  }));
31165
31882
  return Promise.resolve({ items });
31166
31883
  }
31884
+ /**
31885
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31886
+ *
31887
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31888
+ * list: a secret committed three weeks ago and never rotated is still the most
31889
+ * important thing to fix, and any window hides it. It carried a "newest N
31890
+ * findings" cap and then a range; the first meant a different span on every
31891
+ * machine, and the second reported "no recommendations" over live exposure.
31892
+ *
31893
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31894
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31895
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31896
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31897
+ * The two answer different questions and only this one has to match a link.
31898
+ *
31899
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31900
+ * whole-store scope costs a grouped scan rather than a row per finding.
31901
+ */
31902
+ recommendationInputs() {
31903
+ const rows = allRows(
31904
+ this.db.prepare(
31905
+ `SELECT d.rule_id AS rule_id,
31906
+ d.category AS category,
31907
+ d.severity AS severity,
31908
+ COUNT(*) AS count
31909
+ FROM inspection_findings f
31910
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31911
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31912
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31913
+ ON latest.finding_key = f.finding_key
31914
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31915
+ AND e.event_type = 'code_change'
31916
+ AND (
31917
+ f.finding_key IS NULL
31918
+ OR latest.status IS NULL
31919
+ OR latest.status NOT IN ('resolved', 'dismissed')
31920
+ )
31921
+ GROUP BY d.rule_id, d.category, d.severity`
31922
+ )
31923
+ );
31924
+ return Promise.resolve(
31925
+ rows.map((r) => ({
31926
+ ruleId: r.rule_id,
31927
+ category: r.category,
31928
+ severity: r.severity,
31929
+ count: r.count
31930
+ }))
31931
+ );
31932
+ }
31167
31933
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31168
31934
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31169
31935
  // numeric and the JS aggregations bucket/split on ms directly.
31170
31936
  findingsInRange(fromMs, toMs) {
31171
31937
  const rows = allRows(
31172
31938
  this.db.prepare(
31173
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31939
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31940
+ // joined for `severity`, so they are two more columns off a row this read
31941
+ // already fetches. They feed the recommended-actions rollup.
31942
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31943
+ d.rule_id AS rule_id, d.category AS category
31174
31944
  FROM inspection_findings f
31175
- JOIN audit_events e ON e.id = f.audit_event_id
31945
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31176
31946
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31177
31947
  WHERE e.started_at >= :from AND e.started_at < :to
31178
31948
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31183,7 +31953,9 @@ var SqliteSecurityRepository = class {
31183
31953
  return rows.map((r) => ({
31184
31954
  occurredAt: r.occurred_at,
31185
31955
  severity: r.severity,
31186
- actionTaken: r.action_taken
31956
+ actionTaken: r.action_taken,
31957
+ ruleId: r.rule_id,
31958
+ category: r.category
31187
31959
  }));
31188
31960
  }
31189
31961
  };
@@ -32011,6 +32783,7 @@ function openWithPragmas(file2) {
32011
32783
  db.exec("PRAGMA journal_mode = WAL");
32012
32784
  db.exec("PRAGMA busy_timeout = 2000");
32013
32785
  db.exec("PRAGMA foreign_keys = ON");
32786
+ registerSqlFunctions(db);
32014
32787
  } catch (err) {
32015
32788
  closeQuietly(db);
32016
32789
  throw err;
@@ -32040,7 +32813,7 @@ function backupLegacyStore(db, file2) {
32040
32813
  discardStore(file2, backup);
32041
32814
  return backup;
32042
32815
  }
32043
- function openAndInitialize(file2, base) {
32816
+ function openAndInitialize(file2, base, skipTags) {
32044
32817
  let db = openWithPragmas(file2);
32045
32818
  try {
32046
32819
  if (isForeignSqliteLineage(db)) {
@@ -32050,7 +32823,7 @@ function openAndInitialize(file2, base) {
32050
32823
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32051
32824
  );
32052
32825
  }
32053
- applyMigrations(db, file2);
32826
+ applyMigrations(db, file2, { skipTags });
32054
32827
  tightenPerms(file2);
32055
32828
  const policies = new SqlitePoliciesRepository(db);
32056
32829
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32065,6 +32838,7 @@ function openAndInitialize(file2, base) {
32065
32838
  exceptions: new SqliteExceptionsRepository(db),
32066
32839
  resolutions: new SqliteResolutionsRepository(db),
32067
32840
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32841
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32068
32842
  security: new SqliteSecurityRepository(db),
32069
32843
  detections: new SqliteDetectionsRepository(db),
32070
32844
  shares: new SqliteSharesRepository(db),
@@ -32087,7 +32861,8 @@ function openAndInitialize(file2, base) {
32087
32861
  throw err;
32088
32862
  }
32089
32863
  }
32090
- function openLocalDatabase(dir) {
32864
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32865
+ function openLocalDatabase(dir, options = {}) {
32091
32866
  ensureDataDirSync(dir);
32092
32867
  const file2 = join7(dir, DB_FILENAME);
32093
32868
  reapStalePartials(file2);
@@ -32099,6 +32874,7 @@ function openLocalDatabase(dir) {
32099
32874
  installedPacks,
32100
32875
  scanLedger,
32101
32876
  historySync,
32877
+ bodyRetention,
32102
32878
  secretVault,
32103
32879
  exceptions,
32104
32880
  resolutions,
@@ -32122,7 +32898,8 @@ function openLocalDatabase(dir) {
32122
32898
  // `dir` is always `<base>/data` — every caller resolves it through
32123
32899
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32124
32900
  // settings/ and data/, and the pack-policy floor needs both halves.
32125
- dirname2(dir)
32901
+ dirname2(dir),
32902
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32126
32903
  );
32127
32904
  function captureRowId(event) {
32128
32905
  return captureId(
@@ -32315,6 +33092,7 @@ function openLocalDatabase(dir) {
32315
33092
  installedPacks,
32316
33093
  scanLedger,
32317
33094
  historySync,
33095
+ bodyRetention,
32318
33096
  secretVault,
32319
33097
  exceptions,
32320
33098
  resolutions,
@@ -32353,230 +33131,37 @@ function openLocalDatabase(dir) {
32353
33131
  };
32354
33132
  }
32355
33133
 
32356
- // ../../packages/persistence/src/finding-key.ts
33134
+ // ../../packages/persistence/src/egress-wire.ts
32357
33135
  import { createHash as createHash3 } from "crypto";
32358
- function normalizeFilePath(filePath) {
32359
- return filePath.replaceAll("\\", "/");
32360
- }
32361
- function computeFindingKey(input2) {
32362
- const normalizedPath = normalizeFilePath(input2.filePath);
32363
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32364
- }
32365
-
32366
- // ../../packages/persistence/src/fingerprint.ts
32367
- import { createHmac, randomBytes } from "crypto";
32368
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32369
- import { join as join8 } from "path";
32370
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
32371
- var EXCEPTION_KEY_FILENAME = "exception.key";
32372
- var KEY_MATERIAL_BYTES = 32;
32373
- function keyFilePath(dataDir2) {
32374
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
32375
- }
32376
- function parseKeyFile(raw) {
32377
- const parsed2 = JSON.parse(raw);
32378
- if (typeof parsed2 !== "object" || parsed2 === null) {
32379
- throw new Error("exception key file is corrupt: not a JSON object");
32380
- }
32381
- const { version: version2, material } = parsed2;
32382
- if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
32383
- throw new Error("exception key file is corrupt: bad version");
32384
- }
32385
- if (typeof material !== "string") {
32386
- throw new Error("exception key file is corrupt: bad material");
32387
- }
32388
- const bytes = Buffer.from(material, "base64");
32389
- if (bytes.length !== KEY_MATERIAL_BYTES) {
32390
- throw new Error("exception key file is corrupt: bad material length");
32391
- }
32392
- return { version: version2, material: bytes };
32393
- }
32394
- var KEY_VERSION_COLUMNS = {
32395
- exceptions: "key_version",
32396
- blocked_detections: "key_version",
32397
- secret_vault: "fingerprint_key_version"
32398
- };
32399
- var SQLITE_ERROR = 1;
32400
- var FLOOR_BUSY_TIMEOUT_MS = 250;
32401
- var FloorUnreadableError = class extends Error {
32402
- code = "floor-unreadable";
32403
- constructor(cause) {
32404
- super(
32405
- `cannot read the stored fingerprint key versions: ${cause instanceof Error ? cause.message : String(cause)}`,
32406
- { cause }
32407
- );
32408
- this.name = "FloorUnreadableError";
32409
- }
32410
- };
32411
- function storedKeyVersionFloor(dataDir2) {
32412
- const file2 = join8(dataDir2, DB_FILENAME);
32413
- if (!existsSync3(file2)) return 0;
32414
- let db;
32415
- try {
32416
- db = new DatabaseSync2(file2, { readOnly: true });
32417
- db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
32418
- let floor = 0;
32419
- for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
32420
- try {
32421
- const row = getRow(
32422
- db.prepare(`SELECT MAX(${column}) AS v FROM ${table}`)
32423
- );
32424
- floor = Math.max(floor, row?.v ?? 0);
32425
- } catch (err) {
32426
- if (err.errcode !== SQLITE_ERROR) {
32427
- throw new FloorUnreadableError(err);
32428
- }
32429
- }
32430
- }
32431
- return floor;
32432
- } catch (err) {
32433
- throw err instanceof FloorUnreadableError ? err : new FloorUnreadableError(err);
32434
- } finally {
32435
- db?.close();
32436
- }
32437
- }
32438
- function serializeKey(key) {
32439
- return JSON.stringify({ version: key.version, material: key.material.toString("base64") });
32440
- }
32441
- function createKeyFile(dataDir2, key) {
32442
- ensureDataDirSync(dataDir2);
32443
- const file2 = keyFilePath(dataDir2);
32444
- if (createOwnerOnlyFileSync(file2, `${serializeKey(key)}
32445
- `)) return key;
32446
- const winner = readFingerprintKey(dataDir2);
32447
- if (winner) {
32448
- tightenFile(file2);
32449
- return winner;
32450
- }
32451
- const occupant = classifyOccupant(file2);
32452
- throw new KeyUnclaimableError(occupantMessage(file2, occupant.kind), occupant.cause);
32453
- }
32454
- function occupantMessage(file2, kind) {
32455
- switch (kind) {
32456
- case "symlink":
32457
- return `exception key file is a symlink (${file2}); remove it so a key can be created`;
32458
- case "gone":
32459
- return "exception key file was removed while it was being created";
32460
- case "unknown":
32461
- return `exception key file (${file2}) is occupied but cannot be inspected; check the permissions on its directory`;
32462
- }
32463
- }
32464
- function readFingerprintKey(dataDir2) {
32465
- let raw;
32466
- try {
32467
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
32468
- } catch (err) {
32469
- if (err.code === "ENOENT") return null;
32470
- throw err instanceof Error ? err : new Error(String(err));
32471
- }
32472
- return parseKeyFile(raw);
32473
- }
32474
- function loadOrCreateFingerprintKey(dataDir2) {
32475
- const existing = readFingerprintKey(dataDir2);
32476
- if (existing) {
32477
- tightenFile(keyFilePath(dataDir2));
32478
- return existing;
32479
- }
32480
- return createKeyFile(dataDir2, {
32481
- version: storedKeyVersionFloor(dataDir2) + 1,
32482
- material: randomBytes(KEY_MATERIAL_BYTES)
32483
- });
32484
- }
32485
- function fingerprintValue(key, raw) {
32486
- return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32487
- }
32488
-
32489
- // ../../packages/persistence/src/history-preview.ts
32490
- import { existsSync as existsSync4 } from "fs";
32491
- import { join as join9 } from "path";
32492
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32493
-
32494
- // ../../packages/persistence/src/store-symlinks.ts
32495
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32496
- import { dirname as dirname3, join as join10, resolve } from "path";
32497
- var STORE_DB = "the store database (including the prompt corpus)";
32498
- var STORE_SETTINGS = "your settings file";
32499
- function storeContents(home) {
32500
- return /* @__PURE__ */ new Map([
32501
- [home, "the store (including the prompt corpus in aka.db)"],
32502
- [settingsDir(home), STORE_SETTINGS],
32503
- [dataDir(home), STORE_DB],
32504
- [keysDir(home), "the vault key"],
32505
- [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
32506
- [dbPath(home), STORE_DB]
32507
- ]);
32508
- }
32509
- function symlinkedStorePaths(home, platform2 = process.platform) {
32510
- return [...storeContents(home)].flatMap(([path, holds]) => {
32511
- try {
32512
- if (!lstatSync3(path).isSymbolicLink()) return [];
32513
- return [
32514
- {
32515
- path,
32516
- target: linkTarget(path),
32517
- holds,
32518
- // existsSync follows the link, so a target that is gone reads as
32519
- // absent here while lstat above still sees the link itself.
32520
- missing: !existsSync5(path),
32521
- mode: targetMode(path, platform2)
32522
- }
32523
- ];
32524
- } catch {
32525
- return [];
32526
- }
32527
- });
32528
- }
32529
- function linkTarget(path) {
32530
- try {
32531
- return realpathSync(path);
32532
- } catch {
32533
- return resolve(dirname3(path), readlinkSync(path));
32534
- }
32535
- }
32536
- function targetMode(path, platform2) {
32537
- if (platform2 === "win32") return void 0;
32538
- try {
32539
- return statSync4(path).mode & 511;
32540
- } catch {
32541
- return void 0;
32542
- }
32543
- }
32544
-
32545
- // ../../packages/persistence/src/vault/crypto.ts
32546
- import {
32547
- createCipheriv,
32548
- createDecipheriv,
32549
- createHmac as createHmac2,
32550
- hkdfSync,
32551
- timingSafeEqual
32552
- } from "crypto";
32553
-
32554
- // ../../packages/persistence/src/vault/key-provider.ts
32555
- import { execFileSync } from "child_process";
32556
- import { randomBytes as randomBytes2 } from "crypto";
32557
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32558
- import { join as join11 } from "path";
32559
-
32560
- // ../../packages/persistence/src/vault/vault.ts
32561
- import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32562
-
32563
- // ../../packages/persistence/src/warn-era-cap.ts
32564
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32565
- import { join as join12 } from "path";
32566
- var MARKER = "warn-era-capped";
32567
- function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32568
- if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32569
- const marker = join12(dataDir2, MARKER);
32570
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32571
- const capped = db.policies.capCategoryActions();
32572
- writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32573
- `, { mode: DATA_FILE_MODE });
32574
- return { capped };
33136
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33137
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33138
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33139
+ var FILE_URL = /^file:\/\//i;
33140
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33141
+ var SLASH = "/".charCodeAt(0);
33142
+ var GIT_SUFFIX = ".git";
33143
+ function trimSlashes(path) {
33144
+ let start = 0;
33145
+ let end = path.length;
33146
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33147
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33148
+ return path.slice(start, end);
33149
+ }
33150
+ function canonicalGitUrl(url2) {
33151
+ const trimmed = url2.trim();
33152
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33153
+ const scheme = SCHEME_FORM.exec(trimmed);
33154
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33155
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33156
+ if (host === void 0) return trimmed;
33157
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33158
+ const bare = trimSlashes(path);
33159
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33160
+ return cleaned === "" ? host : `${host}/${cleaned}`;
32575
33161
  }
32576
-
32577
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32578
33162
  function hashProjectKey(projectKey) {
32579
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
33163
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33164
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32580
33165
  }
32581
33166
  function toIngestHit(hit) {
32582
33167
  return {
@@ -32610,6 +33195,263 @@ function toEgressIngestRequest(input2) {
32610
33195
  };
32611
33196
  }
32612
33197
 
33198
+ // ../../packages/persistence/src/finding-key.ts
33199
+ import { createHash as createHash4 } from "crypto";
33200
+ function normalizeFilePath(filePath) {
33201
+ return filePath.replaceAll("\\", "/");
33202
+ }
33203
+ function computeFindingKey(input2) {
33204
+ const normalizedPath = normalizeFilePath(input2.filePath);
33205
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
33206
+ }
33207
+
33208
+ // ../../packages/persistence/src/fingerprint.ts
33209
+ import { createHmac, randomBytes } from "crypto";
33210
+ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
33211
+ import { join as join8 } from "path";
33212
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
33213
+ var EXCEPTION_KEY_FILENAME = "exception.key";
33214
+ var KEY_MATERIAL_BYTES = 32;
33215
+ function keyFilePath(dataDir2) {
33216
+ return join8(dataDir2, EXCEPTION_KEY_FILENAME);
33217
+ }
33218
+ function parseKeyFile(raw) {
33219
+ const parsed2 = JSON.parse(raw);
33220
+ if (typeof parsed2 !== "object" || parsed2 === null) {
33221
+ throw new Error("exception key file is corrupt: not a JSON object");
33222
+ }
33223
+ const { version: version2, material } = parsed2;
33224
+ if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
33225
+ throw new Error("exception key file is corrupt: bad version");
33226
+ }
33227
+ if (typeof material !== "string") {
33228
+ throw new Error("exception key file is corrupt: bad material");
33229
+ }
33230
+ const bytes = Buffer.from(material, "base64");
33231
+ if (bytes.length !== KEY_MATERIAL_BYTES) {
33232
+ throw new Error("exception key file is corrupt: bad material length");
33233
+ }
33234
+ return { version: version2, material: bytes };
33235
+ }
33236
+ var KEY_VERSION_COLUMNS = {
33237
+ exceptions: "key_version",
33238
+ blocked_detections: "key_version",
33239
+ secret_vault: "fingerprint_key_version"
33240
+ };
33241
+ var SQLITE_ERROR = 1;
33242
+ var FLOOR_BUSY_TIMEOUT_MS = 250;
33243
+ var FloorUnreadableError = class extends Error {
33244
+ code = "floor-unreadable";
33245
+ constructor(cause) {
33246
+ super(
33247
+ `cannot read the stored fingerprint key versions: ${cause instanceof Error ? cause.message : String(cause)}`,
33248
+ { cause }
33249
+ );
33250
+ this.name = "FloorUnreadableError";
33251
+ }
33252
+ };
33253
+ function storedKeyVersionFloor(dataDir2) {
33254
+ const file2 = join8(dataDir2, DB_FILENAME);
33255
+ if (!existsSync3(file2)) return 0;
33256
+ let db;
33257
+ try {
33258
+ db = new DatabaseSync2(file2, { readOnly: true });
33259
+ db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
33260
+ let floor = 0;
33261
+ for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
33262
+ try {
33263
+ const row = getRow(
33264
+ db.prepare(`SELECT MAX(${column}) AS v FROM ${table}`)
33265
+ );
33266
+ floor = Math.max(floor, row?.v ?? 0);
33267
+ } catch (err) {
33268
+ if (err.errcode !== SQLITE_ERROR) {
33269
+ throw new FloorUnreadableError(err);
33270
+ }
33271
+ }
33272
+ }
33273
+ return floor;
33274
+ } catch (err) {
33275
+ throw err instanceof FloorUnreadableError ? err : new FloorUnreadableError(err);
33276
+ } finally {
33277
+ db?.close();
33278
+ }
33279
+ }
33280
+ function serializeKey(key) {
33281
+ return JSON.stringify({ version: key.version, material: key.material.toString("base64") });
33282
+ }
33283
+ function createKeyFile(dataDir2, key) {
33284
+ ensureDataDirSync(dataDir2);
33285
+ const file2 = keyFilePath(dataDir2);
33286
+ if (createOwnerOnlyFileSync(file2, `${serializeKey(key)}
33287
+ `)) return key;
33288
+ const winner = readFingerprintKey(dataDir2);
33289
+ if (winner) {
33290
+ tightenFile(file2);
33291
+ return winner;
33292
+ }
33293
+ const occupant = classifyOccupant(file2);
33294
+ throw new KeyUnclaimableError(occupantMessage(file2, occupant.kind), occupant.cause);
33295
+ }
33296
+ function occupantMessage(file2, kind) {
33297
+ switch (kind) {
33298
+ case "symlink":
33299
+ return `exception key file is a symlink (${file2}); remove it so a key can be created`;
33300
+ case "gone":
33301
+ return "exception key file was removed while it was being created";
33302
+ case "unknown":
33303
+ return `exception key file (${file2}) is occupied but cannot be inspected; check the permissions on its directory`;
33304
+ }
33305
+ }
33306
+ function readFingerprintKey(dataDir2) {
33307
+ let raw;
33308
+ try {
33309
+ raw = readFileSync6(keyFilePath(dataDir2), "utf8");
33310
+ } catch (err) {
33311
+ if (err.code === "ENOENT") return null;
33312
+ throw err instanceof Error ? err : new Error(String(err));
33313
+ }
33314
+ return parseKeyFile(raw);
33315
+ }
33316
+ function loadOrCreateFingerprintKey(dataDir2) {
33317
+ const existing = readFingerprintKey(dataDir2);
33318
+ if (existing) {
33319
+ tightenFile(keyFilePath(dataDir2));
33320
+ return existing;
33321
+ }
33322
+ return createKeyFile(dataDir2, {
33323
+ version: storedKeyVersionFloor(dataDir2) + 1,
33324
+ material: randomBytes(KEY_MATERIAL_BYTES)
33325
+ });
33326
+ }
33327
+ function fingerprintValue(key, raw) {
33328
+ return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
33329
+ }
33330
+
33331
+ // ../../packages/persistence/src/forward-health.ts
33332
+ import { readFileSync as readFileSync7 } from "fs";
33333
+ import { join as join9 } from "path";
33334
+ var FAILURES = /* @__PURE__ */ new Set([
33335
+ "unauthorized",
33336
+ "forbidden",
33337
+ "unreachable"
33338
+ ]);
33339
+ var BREAKER_COOLDOWN_MS = 3e4;
33340
+ function parseForwardHealth(raw, nowMs) {
33341
+ try {
33342
+ const parsed2 = JSON.parse(raw);
33343
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33344
+ const record2 = parsed2;
33345
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33346
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33347
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33348
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33349
+ } catch {
33350
+ return null;
33351
+ }
33352
+ }
33353
+ function isForwardPaused(health, nowMs) {
33354
+ const openedAtMs = health?.openedAtMs ?? null;
33355
+ if (openedAtMs === null) return false;
33356
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33357
+ }
33358
+
33359
+ // ../../packages/persistence/src/history-backfill.ts
33360
+ import { existsSync as existsSync4 } from "fs";
33361
+ import { join as join10 } from "path";
33362
+
33363
+ // ../../packages/persistence/src/history-preview.ts
33364
+ import { existsSync as existsSync5 } from "fs";
33365
+ import { join as join11 } from "path";
33366
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
33367
+
33368
+ // ../../packages/persistence/src/history-sync-state.ts
33369
+ import { readFileSync as readFileSync8 } from "fs";
33370
+ import { join as join12 } from "path";
33371
+
33372
+ // ../../packages/persistence/src/store-symlinks.ts
33373
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33374
+ import { dirname as dirname3, join as join13, resolve } from "path";
33375
+ var STORE_DB = "the store database (including the prompt corpus)";
33376
+ var STORE_SETTINGS = "your settings file";
33377
+ function storeContents(home) {
33378
+ return /* @__PURE__ */ new Map([
33379
+ [home, "the store (including the prompt corpus in aka.db)"],
33380
+ [settingsDir(home), STORE_SETTINGS],
33381
+ [dataDir(home), STORE_DB],
33382
+ [keysDir(home), "the vault key"],
33383
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
33384
+ [dbPath(home), STORE_DB]
33385
+ ]);
33386
+ }
33387
+ function symlinkedStorePaths(home, platform2 = process.platform) {
33388
+ return [...storeContents(home)].flatMap(([path, holds]) => {
33389
+ try {
33390
+ if (!lstatSync3(path).isSymbolicLink()) return [];
33391
+ return [
33392
+ {
33393
+ path,
33394
+ target: linkTarget(path),
33395
+ holds,
33396
+ // existsSync follows the link, so a target that is gone reads as
33397
+ // absent here while lstat above still sees the link itself.
33398
+ missing: !existsSync6(path),
33399
+ mode: targetMode(path, platform2)
33400
+ }
33401
+ ];
33402
+ } catch {
33403
+ return [];
33404
+ }
33405
+ });
33406
+ }
33407
+ function linkTarget(path) {
33408
+ try {
33409
+ return realpathSync(path);
33410
+ } catch {
33411
+ return resolve(dirname3(path), readlinkSync(path));
33412
+ }
33413
+ }
33414
+ function targetMode(path, platform2) {
33415
+ if (platform2 === "win32") return void 0;
33416
+ try {
33417
+ return statSync4(path).mode & 511;
33418
+ } catch {
33419
+ return void 0;
33420
+ }
33421
+ }
33422
+
33423
+ // ../../packages/persistence/src/vault/crypto.ts
33424
+ import {
33425
+ createCipheriv,
33426
+ createDecipheriv,
33427
+ createHmac as createHmac2,
33428
+ hkdfSync,
33429
+ timingSafeEqual
33430
+ } from "crypto";
33431
+
33432
+ // ../../packages/persistence/src/vault/key-provider.ts
33433
+ import { execFileSync } from "child_process";
33434
+ import { randomBytes as randomBytes2 } from "crypto";
33435
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33436
+ import { join as join14 } from "path";
33437
+
33438
+ // ../../packages/persistence/src/vault/vault.ts
33439
+ import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
33440
+
33441
+ // ../../packages/persistence/src/warn-era-cap.ts
33442
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33443
+ import { join as join15 } from "path";
33444
+ var MARKER = "warn-era-capped";
33445
+ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33446
+ if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33447
+ const marker = join15(dataDir2, MARKER);
33448
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33449
+ const capped = db.policies.capCategoryActions();
33450
+ writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
33451
+ `, { mode: DATA_FILE_MODE });
33452
+ return { capped };
33453
+ }
33454
+
32613
33455
  // ../../packages/remote/src/http.ts
32614
33456
  import { request as httpRequest } from "http";
32615
33457
  import { request as httpsRequest } from "https";
@@ -32793,10 +33635,10 @@ function parsed(schema, body, route) {
32793
33635
  }
32794
33636
  function withoutTrailingSlashes(endpoint) {
32795
33637
  let end = endpoint.length;
32796
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33638
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32797
33639
  return endpoint.slice(0, end);
32798
33640
  }
32799
- var SLASH = "/".charCodeAt(0);
33641
+ var SLASH2 = "/".charCodeAt(0);
32800
33642
  function createRemoteClient(options) {
32801
33643
  const base = withoutTrailingSlashes(options.endpoint);
32802
33644
  const url2 = (route) => `${base}${route}`;
@@ -32889,6 +33731,7 @@ function createRemoteClient(options) {
32889
33731
  url: url2(ROUTES.shares),
32890
33732
  body: JSON.stringify(validated.data)
32891
33733
  });
33734
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32892
33735
  okBody(response);
32893
33736
  },
32894
33737
  async pollCommand() {
@@ -32911,19 +33754,51 @@ function createRemoteClient(options) {
32911
33754
  };
32912
33755
  }
32913
33756
 
32914
- // ../../packages/plugin-runtime/src/attached/failure.ts
33757
+ // ../../packages/remote/src/failure-kind.ts
32915
33758
  function statusOf(err) {
32916
33759
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32917
33760
  const { status } = err;
32918
33761
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32919
33762
  return status >= 100 && status <= 599 ? status : null;
32920
33763
  }
32921
- function classifyFailure(err) {
32922
- switch (statusOf(err)) {
33764
+ function nameOf(err) {
33765
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33766
+ return typeof err.name === "string" ? err.name : null;
33767
+ }
33768
+ function classifyRemoteFailure(err) {
33769
+ switch (nameOf(err)) {
33770
+ case "RemoteRouteAbsent":
33771
+ return "route-absent";
33772
+ case "RemoteRequestInvalid":
33773
+ return "invalid-request";
33774
+ case "RemoteResponseInvalid":
33775
+ return "rejected";
33776
+ default:
33777
+ break;
33778
+ }
33779
+ const status = statusOf(err);
33780
+ if (status === null) return "unreachable";
33781
+ switch (status) {
32923
33782
  case 401:
32924
33783
  return "unauthorized";
32925
33784
  case 403:
32926
33785
  return "forbidden";
33786
+ case 429:
33787
+ return "unreachable";
33788
+ case 404:
33789
+ return "unreachable";
33790
+ default:
33791
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33792
+ }
33793
+ }
33794
+
33795
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33796
+ function classifyFailure(err) {
33797
+ switch (classifyRemoteFailure(err)) {
33798
+ case "unauthorized":
33799
+ return "unauthorized";
33800
+ case "forbidden":
33801
+ return "forbidden";
32927
33802
  default:
32928
33803
  return "unreachable";
32929
33804
  }
@@ -32945,11 +33820,11 @@ function withTimeout(promise2, ms) {
32945
33820
  }
32946
33821
 
32947
33822
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32948
- import { readFileSync as readFileSync8 } from "fs";
32949
- import { join as join13 } from "path";
33823
+ import { readFileSync as readFileSync10 } from "fs";
33824
+ import { join as join16 } from "path";
32950
33825
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32951
33826
  function forwardDropsPath(dataDir2) {
32952
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33827
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
32953
33828
  }
32954
33829
  function recordForwardDrops(dataDir2, count, nowMs) {
32955
33830
  if (count <= 0) return;
@@ -32967,7 +33842,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
32967
33842
  }
32968
33843
  function readForwardDrops(dataDir2) {
32969
33844
  try {
32970
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33845
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
32971
33846
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
32972
33847
  const record2 = parsed2;
32973
33848
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -32985,13 +33860,12 @@ function readForwardDrops(dataDir2) {
32985
33860
 
32986
33861
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32987
33862
  import { randomUUID as randomUUID15 } from "crypto";
32988
- import { readFileSync as readFileSync14 } from "fs";
32989
33863
  import { readFile, rename, writeFile } from "fs/promises";
32990
- import { join as join22 } from "path";
33864
+ import { join as join26 } from "path";
32991
33865
 
32992
33866
  // ../../packages/plugin-sdk/src/config.ts
32993
- import { existsSync as existsSync7 } from "fs";
32994
- import { join as join14 } from "path";
33867
+ import { existsSync as existsSync8 } from "fs";
33868
+ import { join as join17 } from "path";
32995
33869
 
32996
33870
  // ../../packages/plugin-sdk/src/provider-env.ts
32997
33871
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33045,8 +33919,8 @@ function resolveProvider() {
33045
33919
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33046
33920
  try {
33047
33921
  ensureLayoutDirSync(base);
33048
- const settingsFile = join14(settingsDir(base), "settings.json");
33049
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33922
+ const settingsFile = join17(settingsDir(base), "settings.json");
33923
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33050
33924
  } catch {
33051
33925
  }
33052
33926
  migrateLegacyLayout(base);
@@ -33069,9 +33943,9 @@ function resolveProviderSafe(resolveProviderFn) {
33069
33943
  }
33070
33944
 
33071
33945
  // ../../packages/plugin-sdk/src/config-inventory.ts
33072
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33946
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33073
33947
  import { homedir as homedir2 } from "os";
33074
- import { basename as basename3, join as join16 } from "path";
33948
+ import { basename as basename3, join as join19 } from "path";
33075
33949
 
33076
33950
  // ../../packages/detections/src/egress/registry.ts
33077
33951
  var EXTRACTOR_VERSION = "1";
@@ -36163,8 +37037,8 @@ function uniqueRuleIds(findings) {
36163
37037
  }
36164
37038
 
36165
37039
  // ../../packages/plugin-sdk/src/repo.ts
36166
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36167
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37040
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37041
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36168
37042
  function resolveRepo(cwd) {
36169
37043
  try {
36170
37044
  const root = findGitRoot(cwd);
@@ -36179,36 +37053,36 @@ function resolveRepo(cwd) {
36179
37053
  function findGitRoot(start) {
36180
37054
  let dir = start;
36181
37055
  for (; ; ) {
36182
- if (existsSync8(join15(dir, ".git"))) return dir;
37056
+ if (existsSync9(join18(dir, ".git"))) return dir;
36183
37057
  const parent = dirname4(dir);
36184
37058
  if (parent === dir) return void 0;
36185
37059
  dir = parent;
36186
37060
  }
36187
37061
  }
36188
37062
  function resolveGitContext(root) {
36189
- const dotGit = join15(root, ".git");
37063
+ const dotGit = join18(root, ".git");
36190
37064
  try {
36191
37065
  if (statSync6(dotGit).isDirectory()) {
36192
- return { configPath: join15(dotGit, "config"), headRoot: root };
37066
+ return { configPath: join18(dotGit, "config"), headRoot: root };
36193
37067
  }
36194
37068
  } catch {
36195
37069
  return void 0;
36196
37070
  }
36197
37071
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36198
37072
  if (!target) return void 0;
36199
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36200
- if (existsSync8(join15(gitdir, "config"))) {
36201
- return { configPath: join15(gitdir, "config"), headRoot: root };
37073
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
37074
+ if (existsSync9(join18(gitdir, "config"))) {
37075
+ return { configPath: join18(gitdir, "config"), headRoot: root };
36202
37076
  }
36203
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
37077
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
36204
37078
  if (!commonRaw) return void 0;
36205
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
37079
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
36206
37080
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36207
- return { configPath: join15(commonGitDir, "config"), headRoot };
37081
+ return { configPath: join18(commonGitDir, "config"), headRoot };
36208
37082
  }
36209
37083
  function safeRead(path) {
36210
37084
  try {
36211
- return readFileSync9(path, "utf8");
37085
+ return readFileSync11(path, "utf8");
36212
37086
  } catch {
36213
37087
  return void 0;
36214
37088
  }
@@ -36274,7 +37148,7 @@ function buildIngestEvent(input2) {
36274
37148
  }
36275
37149
 
36276
37150
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36277
- import { existsSync as existsSync9 } from "fs";
37151
+ import { existsSync as existsSync10 } from "fs";
36278
37152
  import { fileURLToPath } from "url";
36279
37153
  import { Worker } from "worker_threads";
36280
37154
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -36288,7 +37162,7 @@ function resolveWorkerUrl() {
36288
37162
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
36289
37163
  const candidate = new URL(name, import.meta.url);
36290
37164
  try {
36291
- if (existsSync9(fileURLToPath(candidate))) {
37165
+ if (existsSync10(fileURLToPath(candidate))) {
36292
37166
  resolvedWorkerUrl = candidate;
36293
37167
  return candidate;
36294
37168
  }
@@ -36751,13 +37625,9 @@ function createGuardedScanner(partition, gateway, opts) {
36751
37625
  };
36752
37626
  }
36753
37627
 
36754
- // ../../packages/plugin-sdk/src/ignore-layers.ts
36755
- var import_ignore = __toESM(require_ignore(), 1);
36756
- import { readFileSync as readFileSync11 } from "fs";
36757
- import { join as join17 } from "path";
36758
-
36759
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
36760
- import { arch, hostname as hostname4, platform, release } from "os";
37628
+ // ../../packages/plugin-sdk/src/host-floor.ts
37629
+ import { readFileSync as readFileSync14 } from "fs";
37630
+ import { join as join21 } from "path";
36761
37631
 
36762
37632
  // ../../packages/plugin-sdk/src/model-governance.ts
36763
37633
  import {
@@ -36765,16 +37635,42 @@ import {
36765
37635
  fstatSync,
36766
37636
  mkdirSync as mkdirSync2,
36767
37637
  openSync as openSync2,
36768
- readFileSync as readFileSync12,
37638
+ readFileSync as readFileSync13,
36769
37639
  readSync,
36770
37640
  writeFileSync as writeFileSync5
36771
37641
  } from "fs";
36772
- import { join as join18 } from "path";
37642
+ import { join as join20 } from "path";
36773
37643
  var TAIL_BYTES = 256 * 1024;
36774
37644
 
37645
+ // ../../packages/plugin-sdk/src/host-floor.ts
37646
+ var HOST_FEATURE = {
37647
+ ModelSwitch: "model-switch",
37648
+ VaultPointerDisplay: "vault-pointer-display"
37649
+ };
37650
+ var HOST_FLOORS = {
37651
+ [HOST_FEATURE.ModelSwitch]: {
37652
+ label: "model-switch protection",
37653
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37654
+ since: "2.1.251"
37655
+ },
37656
+ [HOST_FEATURE.VaultPointerDisplay]: {
37657
+ label: "vault pointer display",
37658
+ hookEvents: ["MessageDisplay"],
37659
+ since: "2.1.152"
37660
+ }
37661
+ };
37662
+
37663
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
37664
+ var import_ignore = __toESM(require_ignore(), 1);
37665
+ import { readFileSync as readFileSync15 } from "fs";
37666
+ import { join as join22 } from "path";
37667
+
37668
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
37669
+ import { arch, hostname as hostname4, platform, release } from "os";
37670
+
36775
37671
  // ../../packages/plugin-sdk/src/nudge.ts
36776
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36777
- import { join as join19 } from "path";
37672
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
37673
+ import { join as join23 } from "path";
36778
37674
 
36779
37675
  // ../../packages/plugin-sdk/src/paths.ts
36780
37676
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -36816,8 +37712,8 @@ function createPolicyResolver(bundle) {
36816
37712
  }
36817
37713
 
36818
37714
  // ../../packages/plugin-sdk/src/project-files.ts
36819
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36820
- import { basename as basename5, join as join20 } from "path";
37715
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37716
+ import { basename as basename5, join as join24 } from "path";
36821
37717
 
36822
37718
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36823
37719
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -36848,6 +37744,14 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
36848
37744
  // ../../packages/plugin-sdk/src/runtime.ts
36849
37745
  import { randomUUID as randomUUID14 } from "crypto";
36850
37746
  var ENFORCEMENT_CEILING_ENABLED = false;
37747
+ function applyEnforcementCeiling(action, policyMode, enabled) {
37748
+ if (!enabled || policyMode !== "warn") return action;
37749
+ return action === "block" || action === "redact" ? "warn" : action;
37750
+ }
37751
+ function resolveEnforcedAction(action, opts) {
37752
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
37753
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
37754
+ }
36851
37755
  function startTiming() {
36852
37756
  try {
36853
37757
  return performance.now();
@@ -36884,7 +37788,7 @@ function createPluginRuntime(gateway, settings, opts) {
36884
37788
  bundlesPacked = true;
36885
37789
  }
36886
37790
  const policyMode = settings.policy;
36887
- const redactFallback = settings.redactFallback;
37791
+ let redactFallback = settings.redactFallback;
36888
37792
  const dataDir2 = opts?.dataDir;
36889
37793
  let rules = [];
36890
37794
  let scanner;
@@ -36928,6 +37832,7 @@ function createPluginRuntime(gateway, settings, opts) {
36928
37832
  rules = [...verified, ...unverified];
36929
37833
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
36930
37834
  bundleExceptions = bundle.exceptions ?? [];
37835
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
36931
37836
  initialized = true;
36932
37837
  }
36933
37838
  let cachedKey;
@@ -36956,21 +37861,23 @@ function createPluginRuntime(gateway, settings, opts) {
36956
37861
  }
36957
37862
  function actionForFinding(finding, excepted, rewritable = true) {
36958
37863
  if (excepted?.has(finding)) return "allow";
36959
- const action = resolveAction(finding.ruleId, finding.category);
36960
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
36961
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
36962
- return "warn";
36963
- }
36964
- return action;
37864
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
37865
+ policyMode,
37866
+ redactFallback,
37867
+ rewritable,
37868
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
37869
+ });
36965
37870
  }
36966
37871
  function decide(findings, text, excepted, rewritable = true) {
36967
37872
  if (findings.length === 0) return { action: "log", text, findings: [] };
36968
37873
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
37874
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
37875
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
36969
37876
  let worst = "log";
36970
37877
  for (const finding of findings) {
36971
37878
  worst = strongerAction(worst, actionFor(finding));
36972
37879
  }
36973
- if (worst === "block") return { action: "block", text: null, findings };
37880
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
36974
37881
  if (worst === "redact") {
36975
37882
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
36976
37883
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -36980,9 +37887,13 @@ function createPluginRuntime(gateway, settings, opts) {
36980
37887
  findings,
36981
37888
  enforcedFindings: redactFindings,
36982
37889
  reversibleFindings
37890
+ // No `degraded` here, and it is not an omission: `rewritable` is per
37891
+ // CAPTURE, so on an unrewritable field every redact has already become
37892
+ // the fallback and this branch is unreachable. Spreading it would read
37893
+ // as a case that can happen.
36983
37894
  };
36984
37895
  }
36985
- return { action: worst, text, findings };
37896
+ return { action: worst, text, findings, ...degraded };
36986
37897
  }
36987
37898
  function fingerprintOf(key, finding, cache) {
36988
37899
  let fp = cache.get(finding);
@@ -37111,8 +38022,8 @@ function createPluginRuntime(gateway, settings, opts) {
37111
38022
  };
37112
38023
  }
37113
38024
  }
37114
- async function processText(text, context) {
37115
- return (await evaluate(text, context, {})).decision;
38025
+ async function processText(text, context, opts2 = {}) {
38026
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
37116
38027
  }
37117
38028
  async function capture(input2, opts2 = {}) {
37118
38029
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -37135,10 +38046,12 @@ function createPluginRuntime(gateway, settings, opts) {
37135
38046
  );
37136
38047
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
37137
38048
  const inspectionMs = elapsedMs(timingStartedAt);
37138
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
38049
+ const redactDegradedTo = decision.redactDegradedTo;
38050
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
37139
38051
  ...input2.metadata,
37140
38052
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
37141
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
38053
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
38054
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
37142
38055
  } : input2.metadata;
37143
38056
  const event = buildIngestEvent({
37144
38057
  kind: input2.kind,
@@ -37210,7 +38123,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37210
38123
 
37211
38124
  // ../../packages/plugin-sdk/src/throttle.ts
37212
38125
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37213
- import { join as join21 } from "path";
38126
+ import { join as join25 } from "path";
37214
38127
 
37215
38128
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
37216
38129
  function isInvalidRequest(err) {
@@ -37226,31 +38139,12 @@ function isServerRejection(err) {
37226
38139
  var FORWARD_BUDGET_MS = 1500;
37227
38140
  var DECISION_PATH_BUDGET_MS = 800;
37228
38141
  var BREAKER_FAILURE_THRESHOLD = 3;
37229
- var BREAKER_COOLDOWN_MS = 3e4;
37230
38142
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
37231
- var FAILURES = /* @__PURE__ */ new Set([
37232
- "unauthorized",
37233
- "forbidden",
37234
- "unreachable"
37235
- ]);
37236
38143
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
37237
38144
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
37238
- function parseBreakerState(raw, nowMs) {
37239
- try {
37240
- const parsed2 = JSON.parse(raw);
37241
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
37242
- const record2 = parsed2;
37243
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
37244
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
37245
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
37246
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
37247
- } catch {
37248
- return null;
37249
- }
37250
- }
37251
38145
  function createForwardPolicy(deps) {
37252
38146
  const now = deps.now ?? (() => Date.now());
37253
- const file2 = join22(deps.dir, STATE_FILENAME);
38147
+ const file2 = join26(deps.dir, STATE_FILENAME);
37254
38148
  let state = null;
37255
38149
  let loading = null;
37256
38150
  async function readState() {
@@ -37260,7 +38154,7 @@ function createForwardPolicy(deps) {
37260
38154
  } catch {
37261
38155
  return { ...CLOSED };
37262
38156
  }
37263
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
38157
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
37264
38158
  }
37265
38159
  async function load() {
37266
38160
  if (state !== null) return state;
@@ -37306,7 +38200,7 @@ function createForwardPolicy(deps) {
37306
38200
  };
37307
38201
  const at = now();
37308
38202
  if (current.openedAtMs !== null) {
37309
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
38203
+ if (isForwardPaused(current, at)) {
37310
38204
  return { ok: false, reason: "breaker-open" };
37311
38205
  }
37312
38206
  await persist({
@@ -37843,7 +38737,18 @@ var AttachedDataGateway = class {
37843
38737
  // and the spread above would otherwise drop the field silently — which is
37844
38738
  // exactly what it did, leaving the whole control inert on every device
37845
38739
  // while every test around it stayed green.
37846
- prohibitedModels: cached2.prohibitedModels
38740
+ prohibitedModels: cached2.prohibitedModels,
38741
+ // NAMED for the same reason as the line above, and it is the same defect
38742
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
38743
+ // only the cache carries is dropped in silence. That is what left
38744
+ // `prohibitedModels` inert on every attached device with every test
38745
+ // around it green.
38746
+ //
38747
+ // Taken from the cache rather than merged here, because merging it needs
38748
+ // the device's own SETTING — which is not a bundle field and is not in
38749
+ // scope at this seam. The runtime does that merge, raise-only, where both
38750
+ // values are in hand (createPluginRuntime's ensureInitialized).
38751
+ redactFallback: cached2.redactFallback
37847
38752
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
37848
38753
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
37849
38754
  // it emits, so an 'authored' policy arriving from the control plane
@@ -37971,10 +38876,6 @@ function toolAuditEvent(input2) {
37971
38876
  };
37972
38877
  }
37973
38878
 
37974
- // ../../packages/plugin-runtime/src/attached/history-state.ts
37975
- import { readFileSync as readFileSync15 } from "fs";
37976
- import { join as join23 } from "path";
37977
-
37978
38879
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37979
38880
  import { createHash as createHash6 } from "crypto";
37980
38881
  import { hostname as hostname5 } from "os";
@@ -37983,6 +38884,10 @@ import { hostname as hostname5 } from "os";
37983
38884
  var CORRELATION_ID = EventMetadata.shape.correlationId;
37984
38885
  var TRACE_ID = EventMetadata.shape.traceId;
37985
38886
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
38887
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
38888
+
38889
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
38890
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
37986
38891
 
37987
38892
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37988
38893
  import { spawn } from "child_process";
@@ -37990,7 +38895,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
37990
38895
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
37991
38896
 
37992
38897
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37993
- import { readFileSync as readFileSync16 } from "fs";
38898
+ import { readFileSync as readFileSync17 } from "fs";
37994
38899
  function createPluginBlock(build, policyStore) {
37995
38900
  return async () => {
37996
38901
  const cached2 = await policyStore.read();
@@ -38009,7 +38914,7 @@ function createPluginBlock(build, policyStore) {
38009
38914
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38010
38915
  import { randomUUID as randomUUID16 } from "crypto";
38011
38916
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38012
- import { join as join24 } from "path";
38917
+ import { join as join27 } from "path";
38013
38918
 
38014
38919
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38015
38920
  import { rename as rename2 } from "fs/promises";
@@ -38033,7 +38938,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38033
38938
 
38034
38939
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38035
38940
  function createPolicyStore(dir = dataDir()) {
38036
- const file2 = join24(dir, "policy-cache.json");
38941
+ const file2 = join27(dir, "policy-cache.json");
38037
38942
  async function read() {
38038
38943
  try {
38039
38944
  const raw = await readFile2(file2, "utf8");
@@ -38264,11 +39169,11 @@ function readStorePosture(dbPath2) {
38264
39169
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38265
39170
  import { randomUUID as randomUUID17 } from "crypto";
38266
39171
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38267
- import { join as join25 } from "path";
39172
+ import { join as join28 } from "path";
38268
39173
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38269
39174
  function createPostureStore(dir = settingsDir(), legacyDir) {
38270
- const file2 = join25(dir, "posture-state.json");
38271
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
39175
+ const file2 = join28(dir, "posture-state.json");
39176
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
38272
39177
  async function persist(state) {
38273
39178
  await ensureDataDir(dir);
38274
39179
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38336,8 +39241,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38336
39241
  }
38337
39242
 
38338
39243
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38339
- import { readFileSync as readFileSync17 } from "fs";
38340
- import { join as join26 } from "path";
39244
+ import { readFileSync as readFileSync18 } from "fs";
39245
+ import { join as join29 } from "path";
38341
39246
 
38342
39247
  // ../../packages/plugin-runtime/src/attached/status.ts
38343
39248
  var REFUSAL_LINES = {
@@ -38358,6 +39263,14 @@ import { spawn as spawn2 } from "child_process";
38358
39263
  import { fileURLToPath as fileURLToPath3 } from "url";
38359
39264
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
38360
39265
 
39266
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
39267
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39268
+
39269
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
39270
+ import { spawn as spawn3 } from "child_process";
39271
+ import { fileURLToPath as fileURLToPath4 } from "url";
39272
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
39273
+
38361
39274
  // ../../packages/plugin-runtime/src/attached/factory.ts
38362
39275
  import { hostname as hostname6 } from "os";
38363
39276
 
@@ -38969,8 +39882,8 @@ function baseMetadata(input2) {
38969
39882
  }
38970
39883
 
38971
39884
  // src/hooks/store-health.ts
38972
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "fs";
38973
- import { dirname as dirname6, join as join27 } from "path";
39885
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync19, writeFileSync as writeFileSync8 } from "fs";
39886
+ import { dirname as dirname6, join as join30 } from "path";
38974
39887
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
38975
39888
  function markerDirs(dataDir2) {
38976
39889
  return [dataDir2, dirname6(dataDir2)];
@@ -38978,7 +39891,7 @@ function markerDirs(dataDir2) {
38978
39891
  function alreadyClaimed(dirs, marker, sessionId) {
38979
39892
  return dirs.some((dir) => {
38980
39893
  try {
38981
- return readFileSync18(join27(dir, marker), "utf8") === sessionId;
39894
+ return readFileSync19(join30(dir, marker), "utf8") === sessionId;
38982
39895
  } catch {
38983
39896
  return false;
38984
39897
  }
@@ -38988,7 +39901,7 @@ function recordClaim(dirs, marker, sessionId) {
38988
39901
  for (const dir of dirs) {
38989
39902
  try {
38990
39903
  mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
38991
- writeFileSync8(join27(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39904
+ writeFileSync8(join30(dir, marker), sessionId, { mode: DATA_FILE_MODE });
38992
39905
  return;
38993
39906
  } catch {
38994
39907
  }