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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,8 +492,8 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync7 } from "fs";
496
- import { join as join13 } from "path";
495
+ import { existsSync as existsSync8 } from "fs";
496
+ import { join as join16 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20670,6 +20702,15 @@ var FindingCategory = external_exports.enum([
20670
20702
  ]).meta({ id: "FindingCategory" });
20671
20703
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20672
20704
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20705
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20706
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20707
+ var FindingDelivery = external_exports.object({
20708
+ state: FindingDeliveryState,
20709
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20710
+ at: external_exports.iso.datetime().optional(),
20711
+ // Only on `not_sent`, and only when a known reason was recorded.
20712
+ reason: SyncFailureReason.optional()
20713
+ }).meta({ id: "FindingDelivery" });
20673
20714
  var ResolutionMethod = external_exports.enum([
20674
20715
  "enforced-in-flight",
20675
20716
  "fixed-at-source",
@@ -20726,7 +20767,10 @@ var FindingInstance = external_exports.object({
20726
20767
  // The session that event belongs to, when it has one — the seam a
20727
20768
  // per-instance "view session" link needs. Absent for events captured
20728
20769
  // outside a session.
20729
- sessionId: external_exports.string().optional()
20770
+ sessionId: external_exports.string().optional(),
20771
+ // The delivery state of the event above (see FindingDelivery). Optional so
20772
+ // readers that do not project it stay valid.
20773
+ delivery: FindingDelivery.optional()
20730
20774
  }).meta({ id: "FindingInstance" });
20731
20775
  var FindingGroup = external_exports.object({
20732
20776
  id: external_exports.string(),
@@ -20743,13 +20787,11 @@ var FindingGroup = external_exports.object({
20743
20787
  latestDetectedAt: external_exports.iso.datetime(),
20744
20788
  instances: external_exports.array(FindingInstance),
20745
20789
  // Derived from instances' statuses with open-dominates precedence (see
20746
- // buildFindingGroups). Undefined only when no instance carries a status.
20790
+ // foldGroupStatus). Undefined only when no instance carries a status.
20747
20791
  status: FindingStatus.optional(),
20748
- // The distinct people across the WHOLE group, not just the `instances`
20749
- // preview — from the store's whole-group aggregate when it supplies one,
20750
- // else folded from the rows (see buildFindingGroups). Undefined when no
20751
- // instance carries a user, or when the store supplied whole-group folds
20752
- // without one.
20792
+ // The distinct people across the WHOLE group, not just the instances
20793
+ // carried here. Undefined when no instance carries a user, or when the
20794
+ // store supplied whole-group folds without one.
20753
20795
  users: external_exports.array(FindingUser).optional()
20754
20796
  }).meta({ id: "FindingGroup" });
20755
20797
  var FindingStats = external_exports.object({
@@ -20778,21 +20820,34 @@ var FindingFacets = external_exports.object({
20778
20820
  // counted under no value.
20779
20821
  status: external_exports.array(FindingFacetItem),
20780
20822
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
- // reads, which can filter by it; the grouped read omits the dimension
20823
+ // reads, which can filter by it; the type-level read omits the dimension
20782
20824
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20825
+ tool: external_exports.array(FindingFacetItem).optional(),
20826
+ // Delivery states (FindingDeliveryState). Present only on the
20827
+ // instance-level reads, like `tool`.
20828
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20829
  }).meta({ id: "FindingFacets" });
20785
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20786
- var ListGroupedFindingsQuery = external_exports.object({
20830
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20831
+ id: "FindingTypeSummary"
20832
+ });
20833
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20834
+ var MAX_FINDING_TYPES_LIMIT = 100;
20835
+ var ListFindingTypesQuery = external_exports.object({
20787
20836
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20788
- // FindingAction.
20837
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20838
+ // firing version carries, and this list pages types.
20839
+ //
20840
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20841
+ // definition versions at different severities, so a type kept by this filter
20842
+ // can hold findings that individually do not match — see totals.findings on
20843
+ // ListFindingTypesResponse, which counts them all.
20789
20844
  severity: external_exports.array(Severity).optional(),
20790
20845
  subtype: external_exports.array(external_exports.string()).optional(),
20791
20846
  provider: external_exports.array(FindingProvider).optional(),
20792
20847
  action: external_exports.array(FindingAction).optional(),
20793
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20794
- // individual instances' — so a filtered group's Status column always reads
20795
- // one of the requested values.
20848
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20849
+ // individual findings' — so a filtered row's status always reads one of the
20850
+ // requested values.
20796
20851
  status: external_exports.array(FindingStatus).optional(),
20797
20852
  q: external_exports.string().optional(),
20798
20853
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20802,23 +20857,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20802
20857
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20803
20858
  // means all time — this list has no default window.
20804
20859
  from: external_exports.iso.datetime().optional(),
20805
- // A group or instance id that must appear in the page even when the cursor
20806
- // has already advanced past its sort position. This is what keeps the
20807
- // Findings page's one-shot ?finding= deep link resolving once the list
20808
- // paginates: the target group is appended out of sort order rather than
20809
- // scanning forward for it. Never affects totals, facets or the cursor.
20860
+ // A RULE id that must appear in the page even when the cursor has already
20861
+ // advanced past its sort position. This is what keeps the selected type
20862
+ // visible in the list once it paginates: the target is appended out of sort
20863
+ // order rather than scanned forward for. Never affects totals, facets or the
20864
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20865
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20866
+ // and so is not bounded by what any page happens to hold.
20810
20867
  includeId: external_exports.string().optional(),
20811
- groupBy: external_exports.literal("type").optional(),
20812
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20868
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20813
20869
  cursor: external_exports.string().optional()
20814
20870
  });
20815
- var ListGroupedFindingsResponse = external_exports.object({
20871
+ var ListFindingTypesResponse = external_exports.object({
20816
20872
  totals: external_exports.object({
20873
+ // Findings belonging to the matching TYPES — not findings that each match
20874
+ // the filters. The filters here select types, so a type that survives
20875
+ // contributes its whole instanceCount.
20876
+ //
20877
+ // `status` is the one exception, narrowed per finding via
20878
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20879
+ // this can exceed what the instance read reports for the same filters: a
20880
+ // rule whose severity moved between versions is kept on its newest and
20881
+ // still counts its older findings. Narrowing the other three needs
20882
+ // per-dimension counts the aggregate does not carry today.
20817
20883
  findings: external_exports.number().int().nonnegative(),
20818
- groups: external_exports.number().int().nonnegative()
20884
+ // Counts TYPES, which is the unit this read pages. The instance read's
20885
+ // own totals count findings; the two deliberately answer different
20886
+ // questions and are never summed.
20887
+ types: external_exports.number().int().nonnegative()
20819
20888
  }),
20820
20889
  facets: FindingFacets,
20821
- items: external_exports.array(FindingGroup),
20890
+ items: external_exports.array(FindingTypeSummary),
20822
20891
  nextCursor: external_exports.string().nullable(),
20823
20892
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20824
20893
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20826,7 +20895,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20826
20895
  // every firing, so the two numbers legitimately differ — this map lets a
20827
20896
  // session-scoped view show both.
20828
20897
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20829
- }).meta({ id: "ListGroupedFindingsResponse" });
20898
+ }).meta({ id: "ListFindingTypesResponse" });
20830
20899
  var ApplyFindingActionRequest = external_exports.object({
20831
20900
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20832
20901
  // it, so it is excluded from the request contract. The mapping helper
@@ -20856,16 +20925,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20856
20925
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20857
20926
  var ListFindingInstancesQuery = external_exports.object({
20858
20927
  severity: external_exports.array(Severity).optional(),
20859
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20928
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20929
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20860
20930
  subtype: external_exports.array(external_exports.string()).optional(),
20861
20931
  provider: external_exports.array(FindingProvider).optional(),
20862
20932
  action: external_exports.array(FindingAction).optional(),
20863
20933
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20864
- // the grouped query's group-level fold.
20934
+ // the types query's type-level fold.
20865
20935
  status: external_exports.array(FindingStatus).optional(),
20866
20936
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20867
20937
  // where the free-text `q` can only match the rendered "via Bash" label.
20868
20938
  tool: external_exports.array(external_exports.string()).optional(),
20939
+ // The delivery state of each finding's event (see FindingDelivery).
20940
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20869
20941
  // Exact repository / file-path matches, for the drill-down out of the
20870
20942
  // locations view. A row whose event carries no repo/file matches neither.
20871
20943
  repo: external_exports.string().optional(),
@@ -20878,37 +20950,51 @@ var ListFindingInstancesQuery = external_exports.object({
20878
20950
  });
20879
20951
  var ListFindingInstancesResponse = external_exports.object({
20880
20952
  // Instances matching the filters across the whole scope, not just this
20881
- // page — cursor-independent, like the grouped list's totals.
20953
+ // page — cursor-independent, like the types list's totals.
20882
20954
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20883
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20955
+ // Counts in INSTANCES here, where the types response counts types. Each
20884
20956
  // dimension still excludes its own filter.
20885
20957
  facets: FindingFacets,
20886
20958
  items: external_exports.array(FindingInstanceDetail),
20887
20959
  nextCursor: external_exports.string().nullable()
20888
20960
  }).meta({ id: "ListFindingInstancesResponse" });
20889
- var FindingLocationFile = external_exports.object({
20890
- // Empty when the instances carried no file path (a prompt or a tool call
20891
- // with no file attribution).
20892
- file: external_exports.string(),
20893
- instanceCount: external_exports.number().int().nonnegative(),
20894
- maxSeverity: Severity,
20895
- latestDetectedAt: external_exports.iso.datetime(),
20896
- // Folded from the instances' derived statuses with the same
20897
- // open-dominates precedence a group uses.
20898
- status: FindingStatus.optional(),
20899
- // Distinct rules seen at this location, capped — the row shows them as
20900
- // chips, and the count is what conveys scale.
20901
- ruleIds: external_exports.array(external_exports.string())
20902
- }).meta({ id: "FindingLocationFile" });
20903
- var FindingLocationRepo = external_exports.object({
20961
+ var ListFindingInstancesPage = external_exports.object({
20962
+ items: external_exports.array(FindingInstanceDetail),
20963
+ nextCursor: external_exports.string().nullable()
20964
+ }).meta({ id: "ListFindingInstancesPage" });
20965
+ var FindingLocationSummary = external_exports.object({
20966
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20967
+ // because a location's identity is two values and a URL param carries one:
20968
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20969
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20970
+ // client's page dedupe — never decoded, and never a sort key.
20971
+ id: external_exports.string(),
20904
20972
  /** Empty when the instances carried no repo attribute. */
20905
20973
  repo: external_exports.string(),
20974
+ // Empty when the instances carried no file path (a prompt, or a tool call
20975
+ // with no file attribution). Both halves empty is a real location — usually
20976
+ // the largest one in a store — and is selectable like any other.
20977
+ file: external_exports.string(),
20906
20978
  instanceCount: external_exports.number().int().nonnegative(),
20979
+ // The WORST severity present, not the first row's. It is this list's primary
20980
+ // sort key, so it is also what explains why a row is where it is, and it is
20981
+ // how a reader decides what to open without opening everything.
20907
20982
  maxSeverity: Severity,
20908
20983
  latestDetectedAt: external_exports.iso.datetime(),
20984
+ // Folded from the instances' derived statuses with the same open-dominates
20985
+ // precedence a group uses, so it answers "is anything left to do here" and
20986
+ // not much more: a location holding 1 open among 40 resolved reads like one
20987
+ // holding 40 open. That loss is accepted — the panel beside this list
20988
+ // carries each finding's own status, and instanceCount sits next to the
20989
+ // badge.
20909
20990
  status: FindingStatus.optional(),
20910
- files: external_exports.array(FindingLocationFile)
20911
- }).meta({ id: "FindingLocationRepo" });
20991
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20992
+ // tally rather than a sample and a row can say how many there are. Bounded
20993
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20994
+ ruleIds: external_exports.array(external_exports.string())
20995
+ }).meta({ id: "FindingLocationSummary" });
20996
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20997
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20912
20998
  var ListFindingLocationsQuery = external_exports.object({
20913
20999
  severity: external_exports.array(Severity).optional(),
20914
21000
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20918,21 +21004,47 @@ var ListFindingLocationsQuery = external_exports.object({
20918
21004
  // instances that match, and folds its status from those.
20919
21005
  status: external_exports.array(FindingStatus).optional(),
20920
21006
  tool: external_exports.array(external_exports.string()).optional(),
21007
+ // The delivery state of each finding's event (see FindingDelivery).
21008
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20921
21009
  q: external_exports.string().optional(),
20922
21010
  sessionId: external_exports.string().optional(),
20923
21011
  from: external_exports.iso.datetime().optional(),
20924
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21012
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21013
+ // even when the cursor has already advanced past its sort position — the
21014
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21015
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21016
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21017
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21018
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21019
+ includeId: external_exports.string().optional(),
21020
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21021
+ cursor: external_exports.string().optional()
20925
21022
  });
20926
21023
  var ListFindingLocationsResponse = external_exports.object({
20927
21024
  totals: external_exports.object({
21025
+ // Findings matching the filters across the whole scope. Unlike the types
21026
+ // read's same-named field this needs no caveat: the filters here narrow
21027
+ // per finding, so this is the sum of every row's instanceCount.
20928
21028
  findings: external_exports.number().int().nonnegative(),
20929
- repos: external_exports.number().int().nonnegative(),
20930
- files: external_exports.number().int().nonnegative()
21029
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21030
+ // states. The facets beside it count FINDINGS (see below); a surface
21031
+ // showing both says which is which.
21032
+ locations: external_exports.number().int().nonnegative()
20931
21033
  }),
20932
- /** Sorted by max severity, then most recent. */
20933
- items: external_exports.array(FindingLocationRepo),
20934
- /** Whether `limit` truncated the repo list. */
20935
- hasMore: external_exports.boolean()
21034
+ // Counts in FINDINGS, where the types response counts types, each dimension
21035
+ // still excluding its own filter. Deliberately not locations: counting those
21036
+ // needs a set of location keys per dimension per value — memory tracking the
21037
+ // store times the vocabulary, in a read whose scan promises flat memory —
21038
+ // and the cheap per-location version is not an approximation but WRONG. A
21039
+ // location holding {claudecode, block} and {codex, warn} would survive
21040
+ // provider=claudecode AND action=warn, under which no single finding
21041
+ // matches, so the facet would contradict the instanceCount this whole view
21042
+ // rests on. Findings also keep the toolbar in the same unit as the page
21043
+ // tally and the panel it sits above.
21044
+ facets: FindingFacets,
21045
+ /** Sorted by max severity, then most recent, then (repo, file). */
21046
+ items: external_exports.array(FindingLocationSummary),
21047
+ nextCursor: external_exports.string().nullable()
20936
21048
  }).meta({ id: "ListFindingLocationsResponse" });
20937
21049
 
20938
21050
  // ../../packages/schema/src/zod/meta.ts
@@ -21096,6 +21208,10 @@ var CaptureAttributes = external_exports.object({
21096
21208
  // to 'allow' — the enforcement audit trail's link back to the grant that
21097
21209
  // authorized the bypass.
21098
21210
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21211
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21212
+ // join back to the `llm_call` leaf for the same assistant turn.
21213
+ message_id: external_exports.string().optional(),
21214
+ conversation_id: external_exports.string().optional(),
21099
21215
  // Whole milliseconds this capture's inspection blocked its caller — the
21100
21216
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21101
21217
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21104,7 +21220,19 @@ var CaptureAttributes = external_exports.object({
21104
21220
  // inline json_extract and is not itself an optimization.
21105
21221
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21106
21222
  // before the measurement shipped — never present as a placeholder 0.
21107
- inspection_ms: external_exports.number().int().nonnegative().optional()
21223
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21224
+ // What a `redact` this capture could not carry out became instead (see
21225
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21226
+ // degrade actually happened, so absence is the ordinary case rather than a
21227
+ // reader having to distinguish it from a zero.
21228
+ //
21229
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21230
+ // so on a multi-finding row this does not say which finding degraded, and
21231
+ // its presence does not mean the fallback decided the capture's action. A
21232
+ // capture denied by another finding's own Block policy carries `block`
21233
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21234
+ // repeated rather than referenced because a store reader opens this file.
21235
+ redact_degraded_to: ActionTaken.optional()
21108
21236
  }).catchall(external_exports.unknown());
21109
21237
  var ToolCallInspection = external_exports.object({
21110
21238
  ruleId: external_exports.string().min(1),
@@ -21303,7 +21431,17 @@ var AuditEvent = external_exports.object({
21303
21431
  /** `share` to a first-party/internal destination. */
21304
21432
  internal: external_exports.boolean(),
21305
21433
  /** Event needs review (e.g. unverified egress). */
21306
- flagged: external_exports.boolean()
21434
+ flagged: external_exports.boolean(),
21435
+ /**
21436
+ * The body this event's `title` is drawn from was cleared by local body
21437
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21438
+ *
21439
+ * A separate flag rather than a sentinel written into `title`: the title is
21440
+ * rendered text, and a store-layer module that invented display copy for it
21441
+ * would be choosing words the view is supposed to choose. Additive and
21442
+ * defaulted, so an older producer still validates.
21443
+ */
21444
+ bodyExpired: external_exports.boolean().default(false)
21307
21445
  }).meta({ id: "ActivityAuditEvent" });
21308
21446
  var ActivitySessionSummary = external_exports.object({
21309
21447
  id: external_exports.string(),
@@ -22101,6 +22239,14 @@ var ControlPlaneErrorBody = external_exports.object({
22101
22239
  message: external_exports.string().optional()
22102
22240
  }).optional()
22103
22241
  });
22242
+ var RemoteFailureKind = external_exports.enum([
22243
+ "unauthorized",
22244
+ "forbidden",
22245
+ "route-absent",
22246
+ "invalid-request",
22247
+ "rejected",
22248
+ "unreachable"
22249
+ ]);
22104
22250
  var AttachDeviceRequest = external_exports.object({
22105
22251
  // This machine's own continuity id, so re-attaching ROTATES the credential
22106
22252
  // on one machine record instead of producing a second one. Client-minted
@@ -22636,6 +22782,12 @@ var EventMetadata = external_exports.object({
22636
22782
  // to 'allow' — the enforcement audit trail's link back to the grant that
22637
22783
  // authorized the bypass. Absent on captures where no exception applied.
22638
22784
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22785
+ // The assistant message this capture belongs to, and the conversation it sits
22786
+ // in — set by the browser extension's network capture so a stored `response`
22787
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22788
+ // on every other capture path, which has no such id.
22789
+ messageId: external_exports.string().optional(),
22790
+ conversationId: external_exports.string().optional(),
22639
22791
  // How long THIS capture's inspection blocked its caller, in whole
22640
22792
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22641
22793
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22648,7 +22800,37 @@ var EventMetadata = external_exports.object({
22648
22800
  // Absent is also what every pre-measurement client writes, and what a
22649
22801
  // clock failure degrades to — a reader must treat absence as "not measured"
22650
22802
  // and never as a zero, which would read as "inspection is free".
22651
- inspectionMs: external_exports.number().int().nonnegative().optional()
22803
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22804
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22805
+ // workspace's `redactFallback`, applied because the field could not be
22806
+ // masked in place (a shell command, a URL, or any argument on a host whose
22807
+ // hook contract offers no rewrite channel).
22808
+ //
22809
+ // It exists because the action alone cannot say why. A finding recorded as
22810
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22811
+ // assigned Redact on a field that could not take one — and those are
22812
+ // different facts about the same row: the first is a policy the user chose,
22813
+ // the second is a masking the host could not perform. Absent means no
22814
+ // degrade happened, which is every ordinary capture.
22815
+ //
22816
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22817
+ // is the CAPTURE while `actionTaken` is per FINDING:
22818
+ //
22819
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22820
+ // `redact` alongside a finding ASSIGNED the same action stores both
22821
+ // identically and one reason for the pair; attributing it to both
22822
+ // describes the assigned one wrongly, and to neither loses the degrade.
22823
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22824
+ // became, not the reason the capture ended as it did — a capture denied
22825
+ // by some other finding's own Block policy still carries `block` here,
22826
+ // and clearing the workspace's fallback would not have let it through.
22827
+ // Gate on the value against what a fallback can produce; never read the
22828
+ // field's presence as "this was the fallback's doing".
22829
+ //
22830
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22831
+ // Closing either means moving the reason onto the finding row, which
22832
+ // already carries its own action.
22833
+ redactDegradedTo: ActionTaken.optional()
22652
22834
  }).meta({ id: "EventMetadata" });
22653
22835
  var Event = external_exports.object({
22654
22836
  id: external_exports.guid(),
@@ -22758,7 +22940,32 @@ var RotateKeyInput = external_exports.object({
22758
22940
  confirmation: external_exports.string()
22759
22941
  });
22760
22942
 
22943
+ // ../../packages/schema/src/zod/finding-delivery.ts
22944
+ var KNOWN_REASONS = SyncFailureReason.options;
22945
+ function knownReason(value) {
22946
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22947
+ }
22948
+ function deriveFindingDelivery(row) {
22949
+ if (row.kind === "code_change") return { state: "local_scan" };
22950
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22951
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22952
+ }
22953
+ if (row.syncedAt !== null) {
22954
+ const reason = knownReason(row.syncFailure);
22955
+ return {
22956
+ state: "not_sent",
22957
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22958
+ ...reason === void 0 ? {} : { reason }
22959
+ };
22960
+ }
22961
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22962
+ return { state: "never_offered" };
22963
+ }
22964
+
22761
22965
  // ../../packages/schema/src/zod/findings-group-build.ts
22966
+ function lookupOwn(map2, key) {
22967
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22968
+ }
22762
22969
  function toApiAction(dbVal) {
22763
22970
  const map2 = {
22764
22971
  log: "monitored",
@@ -22767,7 +22974,7 @@ function toApiAction(dbVal) {
22767
22974
  warn: "warned",
22768
22975
  allow: "allowed"
22769
22976
  };
22770
- return map2[dbVal] ?? "allowed";
22977
+ return lookupOwn(map2, dbVal) ?? "allowed";
22771
22978
  }
22772
22979
  function toApiCategory(dbVal) {
22773
22980
  if (dbVal === "code_context") return "source_code";
@@ -22775,13 +22982,18 @@ function toApiCategory(dbVal) {
22775
22982
  return parsed2.success ? parsed2.data : "custom";
22776
22983
  }
22777
22984
  function toApiProvider(sourceTool) {
22778
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22985
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22779
22986
  }
22780
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22987
+ var FINDING_STATUS_PRECEDENCE = [
22988
+ "open",
22989
+ "handled",
22990
+ "dismissed",
22991
+ "resolved"
22992
+ ];
22781
22993
  function foldGroupStatus(instanceStatuses) {
22782
22994
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22783
22995
  if (statuses.size === 0) return void 0;
22784
- for (const candidate of STATUS_PRECEDENCE) {
22996
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22785
22997
  if (statuses.has(candidate)) return candidate;
22786
22998
  }
22787
22999
  return void 0;
@@ -22794,139 +23006,62 @@ function deriveFindingStatus(row) {
22794
23006
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22795
23007
  return "open";
22796
23008
  }
22797
- function distinctUsers(instances) {
22798
- const seen = /* @__PURE__ */ new Set();
22799
- const users = [];
22800
- for (const i of instances) {
22801
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22802
- seen.add(i.user.id);
22803
- users.push(i.user);
22804
- }
22805
- return users;
22806
- }
22807
23009
  function sortUsers(users) {
22808
23010
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22809
23011
  }
22810
- function buildFindingGroups(rows, opts = {}) {
22811
- const overrides = opts.overrides;
23012
+ function buildFindingTypes(aggregates, opts = {}) {
22812
23013
  const packNames = opts.packNames;
22813
- const aggregates = opts.aggregates;
22814
- const byRuleId = /* @__PURE__ */ new Map();
22815
- for (const row of rows) {
22816
- const existing = byRuleId.get(row.ruleId);
22817
- if (existing) existing.push(row);
22818
- else byRuleId.set(row.ruleId, [row]);
22819
- }
22820
- const groups = [];
22821
- for (const [ruleId, ruleRows] of byRuleId) {
22822
- const instances = ruleRows.map((r) => {
22823
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22824
- return {
22825
- id: r.id,
22826
- provider: toApiProvider(r.sourceTool),
22827
- repo: r.repo,
22828
- file: r.file,
22829
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22830
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22831
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22832
- ...r.user === void 0 ? {} : { user: r.user },
22833
- action: toApiAction(effectiveDbAction),
22834
- detectedAt: r.occurredAt,
22835
- confidence: r.confidence,
22836
- status: r.status
22837
- };
22838
- });
22839
- const agg = aggregates?.get(ruleId);
22840
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22841
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22842
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22843
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22844
- );
22845
- const seenProviders = /* @__PURE__ */ new Set();
22846
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22847
- if (seenProviders.has(p)) return false;
22848
- seenProviders.add(p);
22849
- return true;
22850
- });
22851
- const actionSet = new Set(
22852
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22853
- );
23014
+ const types = [];
23015
+ for (const [ruleId, agg] of aggregates) {
23016
+ const users = sortUsers(agg.users ?? []);
23017
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23018
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22854
23019
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22855
- const severity = ruleRows[0]?.severity ?? "low";
22856
- const detection = {
22857
- id: ruleId,
22858
- name: packNames?.get(ruleId) ?? null
22859
- };
22860
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22861
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22862
- const match = {
22863
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22864
- contextPrefix: ""
22865
- // empty (pending privacy review)
22866
- };
22867
- const status = foldGroupStatus(
22868
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22869
- );
22870
- const group = {
23020
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23021
+ const type = {
22871
23022
  id: ruleId,
22872
23023
  category: apiCategory,
22873
23024
  subtype: ruleId,
22874
23025
  // human label comes with pack metadata later
22875
- severity,
22876
- match,
22877
- detection,
22878
- policy,
22879
- instanceCount: agg?.instanceCount ?? instances.length,
23026
+ severity: agg.severity ?? "low",
23027
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23028
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23029
+ instanceCount: agg.instanceCount,
22880
23030
  providers,
22881
23031
  aggregateAction,
22882
- latestDetectedAt,
22883
- instances,
22884
- status,
23032
+ latestDetectedAt: agg.latestDetectedAt,
23033
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22885
23034
  ...users.length > 0 ? { users } : {}
22886
23035
  };
22887
- if (agg) {
22888
- actionsCache.set(group, [...actionSet]);
22889
- if (agg.searchText !== void 0) {
22890
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22891
- }
23036
+ actionsCache.set(type, [...actionSet]);
23037
+ if (agg.searchText !== void 0) {
23038
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22892
23039
  }
22893
- groups.push(group);
23040
+ types.push(type);
22894
23041
  }
22895
- return groups;
23042
+ return types;
22896
23043
  }
22897
23044
  var haystackCache = /* @__PURE__ */ new WeakMap();
22898
- function buildHaystack(g, extra) {
23045
+ function buildHaystack(t, extra) {
22899
23046
  return [
22900
- g.subtype,
22901
- g.category,
22902
- g.match.maskedValue,
22903
- g.policy.name,
22904
- g.id,
22905
- ...g.instances.map((i) => i.repo),
22906
- ...g.instances.map((i) => i.file),
22907
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22908
- ...g.instances.map((i) => i.id),
22909
- // The people: the whole group's list when the store folded one, plus the
22910
- // preview's own — the two overlap, and a haystack does not mind.
22911
- ...(g.users ?? []).map((u) => u.name),
22912
- ...g.instances.map((i) => i.user?.name ?? ""),
23047
+ t.subtype,
23048
+ t.category,
23049
+ t.policy.name,
23050
+ t.id,
23051
+ ...(t.users ?? []).map((u) => u.name),
22913
23052
  ...extra === void 0 ? [] : [extra]
22914
23053
  ].join(" ").toLowerCase();
22915
23054
  }
22916
- function groupHaystack(g) {
22917
- const cached2 = haystackCache.get(g);
23055
+ function typeHaystack(t) {
23056
+ const cached2 = haystackCache.get(t);
22918
23057
  if (cached2 !== void 0) return cached2;
22919
- const haystack = buildHaystack(g);
22920
- haystackCache.set(g, haystack);
23058
+ const haystack = buildHaystack(t);
23059
+ haystackCache.set(t, haystack);
22921
23060
  return haystack;
22922
23061
  }
22923
23062
  var actionsCache = /* @__PURE__ */ new WeakMap();
22924
- function groupActions(g) {
22925
- const cached2 = actionsCache.get(g);
22926
- if (cached2 !== void 0) return cached2;
22927
- const actions = [...new Set(g.instances.map((i) => i.action))];
22928
- actionsCache.set(g, actions);
22929
- return actions;
23063
+ function typeActions(t) {
23064
+ return actionsCache.get(t) ?? [];
22930
23065
  }
22931
23066
  function countInstancesByStatus(statusInputs, statuses) {
22932
23067
  const statusSet = new Set(statuses);
@@ -22937,8 +23072,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22937
23072
  }
22938
23073
  return sum;
22939
23074
  }
22940
- function applyFindingFilters(groups, opts) {
22941
- let filtered = groups;
23075
+ function applyFindingFilters(types, opts) {
23076
+ let filtered = types;
22942
23077
  if (opts.severity && opts.severity.length > 0) {
22943
23078
  const sevSet = new Set(opts.severity);
22944
23079
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22949,7 +23084,7 @@ function applyFindingFilters(groups, opts) {
22949
23084
  }
22950
23085
  if (opts.actions && opts.actions.length > 0) {
22951
23086
  const actionSet = new Set(opts.actions);
22952
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23087
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22953
23088
  }
22954
23089
  if (opts.subtype && opts.subtype.length > 0) {
22955
23090
  const subtypeSet = new Set(opts.subtype);
@@ -22961,26 +23096,31 @@ function applyFindingFilters(groups, opts) {
22961
23096
  }
22962
23097
  if (opts.q) {
22963
23098
  const q = opts.q.toLowerCase();
22964
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23099
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22965
23100
  }
22966
23101
  return filtered;
22967
23102
  }
22968
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22969
- var SEVERITY_RANK = SEVERITY_ORDER;
23103
+ function rankByOrder(members2) {
23104
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23105
+ }
23106
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23107
+ function severityRank(severity) {
23108
+ return lookupOwn(SEVERITY_RANK, severity);
23109
+ }
22970
23110
  function compareFindingGroupOrder(a, b) {
22971
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22972
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23111
+ const rankA = severityRank(a.severity) ?? -1;
23112
+ const rankB = severityRank(b.severity) ?? -1;
22973
23113
  const severityDiff = rankA - rankB;
22974
23114
  if (severityDiff !== 0) return severityDiff;
22975
23115
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22976
23116
  if (recencyDiff !== 0) return recencyDiff;
22977
23117
  return a.id.localeCompare(b.id);
22978
23118
  }
22979
- function sortFindingGroups(groups) {
22980
- return [...groups].sort(compareFindingGroupOrder);
23119
+ function sortFindingTypes(types) {
23120
+ return [...types].sort(compareFindingGroupOrder);
22981
23121
  }
22982
- function computeFindingFacets(allGroups, opts) {
22983
- const forSeverity = applyFindingFilters(allGroups, {
23122
+ function computeFindingFacets(allTypes, opts) {
23123
+ const forSeverity = applyFindingFilters(allTypes, {
22984
23124
  providers: opts.providers,
22985
23125
  actions: opts.actions,
22986
23126
  statuses: opts.statuses,
@@ -22991,7 +23131,7 @@ function computeFindingFacets(allGroups, opts) {
22991
23131
  for (const g of forSeverity) {
22992
23132
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22993
23133
  }
22994
- const forProvider = applyFindingFilters(allGroups, {
23134
+ const forProvider = applyFindingFilters(allTypes, {
22995
23135
  actions: opts.actions,
22996
23136
  statuses: opts.statuses,
22997
23137
  q: opts.q,
@@ -23002,7 +23142,7 @@ function computeFindingFacets(allGroups, opts) {
23002
23142
  for (const g of forProvider) {
23003
23143
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23004
23144
  }
23005
- const forAction = applyFindingFilters(allGroups, {
23145
+ const forAction = applyFindingFilters(allTypes, {
23006
23146
  providers: opts.providers,
23007
23147
  statuses: opts.statuses,
23008
23148
  q: opts.q,
@@ -23011,9 +23151,9 @@ function computeFindingFacets(allGroups, opts) {
23011
23151
  });
23012
23152
  const actionMap = /* @__PURE__ */ new Map();
23013
23153
  for (const g of forAction) {
23014
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23154
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23015
23155
  }
23016
- const forSubtype = applyFindingFilters(allGroups, {
23156
+ const forSubtype = applyFindingFilters(allTypes, {
23017
23157
  providers: opts.providers,
23018
23158
  actions: opts.actions,
23019
23159
  statuses: opts.statuses,
@@ -23022,7 +23162,7 @@ function computeFindingFacets(allGroups, opts) {
23022
23162
  });
23023
23163
  const subtypeMap = /* @__PURE__ */ new Map();
23024
23164
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23025
- const forStatus = applyFindingFilters(allGroups, {
23165
+ const forStatus = applyFindingFilters(allTypes, {
23026
23166
  providers: opts.providers,
23027
23167
  actions: opts.actions,
23028
23168
  q: opts.q,
@@ -23044,6 +23184,20 @@ function computeFindingFacets(allGroups, opts) {
23044
23184
  }
23045
23185
 
23046
23186
  // ../../packages/schema/src/zod/findings-flat-build.ts
23187
+ function compareCodePoints(a, b) {
23188
+ const aIter = a[Symbol.iterator]();
23189
+ const bIter = b[Symbol.iterator]();
23190
+ for (; ; ) {
23191
+ const aNext = aIter.next();
23192
+ const bNext = bIter.next();
23193
+ if (aNext.done && bNext.done) return 0;
23194
+ if (aNext.done) return -1;
23195
+ if (bNext.done) return 1;
23196
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23197
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23198
+ if (aPoint !== bPoint) return aPoint - bPoint;
23199
+ }
23200
+ }
23047
23201
  function rowHaystack(row) {
23048
23202
  return [
23049
23203
  row.ruleId,
@@ -23068,12 +23222,24 @@ function matchesDimension(row, opts, dimension) {
23068
23222
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23069
23223
  case "statuses":
23070
23224
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23225
+ case "deliveries":
23226
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23071
23227
  case "tools":
23072
23228
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23229
+ // An EMPTY value is a real filter here, not an absent one. The location
23230
+ // list buckets a finding whose event recorded no repo — or no file — under
23231
+ // the empty string, and selecting that bucket has to narrow the panel to
23232
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23233
+ // row omits the key, which every call site already does.
23234
+ //
23235
+ // Reading '' as unset is what this replaced, and it failed in the one place
23236
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23237
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23238
+ // — a row reading 3 findings beside a panel listing every finding there is.
23073
23239
  case "repo":
23074
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23240
+ return opts.repo === void 0 || row.repo === opts.repo;
23075
23241
  case "file":
23076
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23242
+ return opts.file === void 0 || row.file === opts.file;
23077
23243
  case "q":
23078
23244
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23079
23245
  }
@@ -23084,6 +23250,7 @@ var DIMENSIONS = [
23084
23250
  "providers",
23085
23251
  "actions",
23086
23252
  "statuses",
23253
+ "deliveries",
23087
23254
  "tools",
23088
23255
  "repo",
23089
23256
  "file",
@@ -23097,10 +23264,19 @@ function matchesInstanceFilters(row, opts, except) {
23097
23264
  return true;
23098
23265
  }
23099
23266
  function toItems(counts) {
23100
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23267
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23268
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23269
+ // NFD spelling of the same text) as equal, so a count tie between
23270
+ // them would otherwise be ordered by whichever the Map iteration
23271
+ // produced. compareCodePoints breaks that tie deterministically, which
23272
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23273
+ // which it need not: foldFacetTuples runs this same sort over grouped
23274
+ // tuples, so both paths order facets identically by construction.
23275
+ compareCodePoints(a.value, b.value)
23276
+ );
23101
23277
  }
23102
- function bump(counts, value) {
23103
- counts.set(value, (counts.get(value) ?? 0) + 1);
23278
+ function bump(counts, value, by = 1) {
23279
+ counts.set(value, (counts.get(value) ?? 0) + by);
23104
23280
  }
23105
23281
  function createInstanceFacetAccumulator(opts) {
23106
23282
  const severity = /* @__PURE__ */ new Map();
@@ -23109,6 +23285,7 @@ function createInstanceFacetAccumulator(opts) {
23109
23285
  const action = /* @__PURE__ */ new Map();
23110
23286
  const status = /* @__PURE__ */ new Map();
23111
23287
  const tool = /* @__PURE__ */ new Map();
23288
+ const deployment = /* @__PURE__ */ new Map();
23112
23289
  return {
23113
23290
  add(row) {
23114
23291
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23123,6 +23300,9 @@ function createInstanceFacetAccumulator(opts) {
23123
23300
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23124
23301
  bump(tool, row.toolName);
23125
23302
  }
23303
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23304
+ bump(deployment, row.delivery.state);
23305
+ }
23126
23306
  },
23127
23307
  facets: () => ({
23128
23308
  severity: toItems(severity),
@@ -23130,7 +23310,8 @@ function createInstanceFacetAccumulator(opts) {
23130
23310
  provider: toItems(provider),
23131
23311
  action: toItems(action),
23132
23312
  status: toItems(status),
23133
- tool: toItems(tool)
23313
+ tool: toItems(tool),
23314
+ deployment: toItems(deployment)
23134
23315
  })
23135
23316
  };
23136
23317
  }
@@ -23144,6 +23325,7 @@ function toInstanceDetail(row) {
23144
23325
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23145
23326
  eventId: row.eventId,
23146
23327
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23328
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23147
23329
  ...row.user === void 0 ? {} : { user: row.user },
23148
23330
  action: toApiAction(row.actionTaken),
23149
23331
  detectedAt: row.occurredAt,
@@ -23158,12 +23340,6 @@ function toInstanceDetail(row) {
23158
23340
  policy: { id: `category:${category}`, name: category }
23159
23341
  };
23160
23342
  }
23161
- var SEVERITY_ORDER2 = {
23162
- critical: 0,
23163
- high: 1,
23164
- medium: 2,
23165
- low: 3
23166
- };
23167
23343
  function newLocationAccumulator() {
23168
23344
  return {
23169
23345
  instanceCount: 0,
@@ -23178,7 +23354,7 @@ function newLocationAccumulator() {
23178
23354
  }
23179
23355
  function addToLocation(acc, row) {
23180
23356
  acc.instanceCount += 1;
23181
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23357
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23182
23358
  if (rank < acc.maxSeverityRank) {
23183
23359
  acc.maxSeverityRank = rank;
23184
23360
  acc.maxSeverity = row.severity;
@@ -23187,6 +23363,23 @@ function addToLocation(acc, row) {
23187
23363
  acc.statuses.push(row.status);
23188
23364
  acc.ruleIds.add(row.ruleId);
23189
23365
  }
23366
+ function compareLocationOrder(a, b) {
23367
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23368
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23369
+ if (rankA !== rankB) return rankA - rankB;
23370
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23371
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23372
+ }
23373
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23374
+ if (repoDiff !== 0) return repoDiff;
23375
+ return compareCodePoints(a.file, b.file);
23376
+ }
23377
+ function encodeLocationId(repo, file2) {
23378
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23379
+ }
23380
+ function encodePart(value) {
23381
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23382
+ }
23190
23383
 
23191
23384
  // ../../packages/schema/src/zod/installed-pack.ts
23192
23385
  var InstalledPack = external_exports.object({
@@ -23254,6 +23447,11 @@ var Policy = external_exports.object({
23254
23447
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23255
23448
  provenance: PolicyProvenance.optional()
23256
23449
  }).meta({ id: "Policy" });
23450
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23451
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23452
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23453
+ id: "RedactFallback"
23454
+ });
23257
23455
  var PolicyBundle = external_exports.object({
23258
23456
  version: external_exports.string(),
23259
23457
  policies: external_exports.array(Policy),
@@ -23301,6 +23499,16 @@ var PolicyBundle = external_exports.object({
23301
23499
  // control plane), so no name resolution stands between the decision and the
23302
23500
  // comparison.
23303
23501
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23502
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23503
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23504
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23505
+ // a control plane can tighten a machine and never loosen one — the same
23506
+ // direction `mergeRaiseOnly` enforces for policies.
23507
+ //
23508
+ // Optional so an older backend, and an older on-disk cache, still parses;
23509
+ // absent leaves the device's own setting in force, which is the behaviour
23510
+ // that predates the field and the safe direction to default.
23511
+ redactFallback: RedactFallback.optional(),
23304
23512
  customKeywords: external_exports.array(external_exports.string()),
23305
23513
  fetchedAt: external_exports.iso.datetime()
23306
23514
  }).meta({ id: "PolicyBundle" });
@@ -23330,11 +23538,6 @@ function severityFloorPolicy(category) {
23330
23538
  const peak = CATEGORY_PEAK_SEVERITY[category];
23331
23539
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23332
23540
  }
23333
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23334
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23335
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23336
- id: "RedactFallback"
23337
- });
23338
23541
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23339
23542
  var BUILTIN_POLICY_SPECS = {
23340
23543
  monitor: {
@@ -23390,6 +23593,11 @@ function isActionAtLeast(action, floor) {
23390
23593
  function strongerAction(a, b) {
23391
23594
  return actionRank(a) >= actionRank(b) ? a : b;
23392
23595
  }
23596
+ function strongerRedactFallback(local, remote) {
23597
+ if (remote === void 0) return local;
23598
+ const localAction = builtinPolicyToAction(local);
23599
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23600
+ }
23393
23601
  function weakestBuiltinAtLeast(floor) {
23394
23602
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23395
23603
  }
@@ -23638,7 +23846,7 @@ function isVaultConsentValid(consent) {
23638
23846
  }
23639
23847
 
23640
23848
  // ../../packages/schema/src/zod/local.ts
23641
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23849
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23642
23850
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23643
23851
  var RunMode = external_exports.enum(["standalone", "attached"]);
23644
23852
  var ControlPlaneConnection = external_exports.object({
@@ -23658,6 +23866,15 @@ var HistorySyncConsent = external_exports.object({
23658
23866
  payloadVersion: external_exports.number().int().positive(),
23659
23867
  endpoint: external_exports.string()
23660
23868
  });
23869
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23870
+ var BodyRetention = external_exports.object({
23871
+ enabled: external_exports.boolean().default(false),
23872
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23873
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23874
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23875
+ // candidate set that is already bounded by "delivered, or never owed".
23876
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23877
+ }).meta({ id: "BodyRetention" });
23661
23878
  var WorkspaceSettings = external_exports.object({
23662
23879
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23663
23880
  runMode: RunMode.default("standalone"),
@@ -23701,12 +23918,18 @@ var WorkspaceSettings = external_exports.object({
23701
23918
  // covers the current payload and must be re-granted.
23702
23919
  modelJudgeConsent: ModelJudgeConsent.optional(),
23703
23920
  // Records that the user consented to the DEFERRED send — the outbox — along
23704
- // with the payload shape and the endpoint they agreed to. Since payload v2
23705
- // that covers both the pre-attach backlog and undelivered captures (which
23706
- // carry prompt/reply text in `content`); the key name predates the widening.
23707
- // Absent until granted, and a grant for a different endpoint or an older
23708
- // payload no longer counts.
23709
- historySyncConsent: HistorySyncConsent.optional()
23921
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23922
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23923
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23924
+ // both widenings. Absent until granted, and a grant for a different endpoint
23925
+ // or an older payload no longer counts.
23926
+ historySyncConsent: HistorySyncConsent.optional(),
23927
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23928
+ // body never removes the row or its findings.
23929
+ bodyRetention: BodyRetention.default({
23930
+ enabled: false,
23931
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23932
+ })
23710
23933
  });
23711
23934
  function defaultWorkspaceSettings() {
23712
23935
  return WorkspaceSettings.parse({});
@@ -23801,12 +24024,15 @@ function toCaptureAttributes(event) {
23801
24024
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23802
24025
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23803
24026
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24027
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23804
24028
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23805
24029
  // has ever populated either), but every legacy metadata key still rides
23806
24030
  // the bag rather than being silently dropped — CaptureAttributes'
23807
24031
  // `.catchall(z.unknown())` carries the long tail.
23808
24032
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23809
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24033
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24034
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24035
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23810
24036
  };
23811
24037
  }
23812
24038
  function captureDefinitionVersion(finding) {
@@ -23834,10 +24060,22 @@ var ManagedSettingKey = external_exports.enum([
23834
24060
  "vaultInlineReveal",
23835
24061
  "modelJudgeConsent",
23836
24062
  "dataSharesInPlace",
23837
- "redactFallback"
24063
+ "redactFallback",
24064
+ // Pins the toggle and the day count together — see BodyRetention on why the
24065
+ // two are one unit. An administrator mandating a window wants the count
24066
+ // enforced with it, not one a user can widen while the toggle stays on.
24067
+ "bodyRetention"
23838
24068
  ]).meta({ id: "ManagedSettingKey" });
24069
+ function isManagedSettingKey(value) {
24070
+ return ManagedSettingKey.safeParse(value).success;
24071
+ }
23839
24072
  var ManagedSettingsValues = external_exports.object({
23840
24073
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24074
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24075
+ // plain, non-strict objects: a key under either that this build does not know
24076
+ // is stripped and nothing reports it. The unknown-value split in
24077
+ // ManagedSettings below classifies top-level names only, so it stops at
24078
+ // these boundaries.
23841
24079
  controlPlane: external_exports.object({
23842
24080
  endpoint: external_exports.string().min(1),
23843
24081
  label: external_exports.string().min(1).optional()
@@ -23848,7 +24086,8 @@ var ManagedSettingsValues = external_exports.object({
23848
24086
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23849
24087
  modelJudgeConsent: external_exports.boolean().optional(),
23850
24088
  dataSharesInPlace: external_exports.boolean().optional(),
23851
- redactFallback: RedactFallback.optional()
24089
+ redactFallback: RedactFallback.optional(),
24090
+ bodyRetention: BodyRetention.optional()
23852
24091
  }).meta({ id: "ManagedSettingsValues" });
23853
24092
  var ManagedSettings = external_exports.object({
23854
24093
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23856,11 +24095,59 @@ var ManagedSettings = external_exports.object({
23856
24095
  // decision from a bug. Absent renders as a generic "your organization".
23857
24096
  organization: external_exports.string().min(1).optional(),
23858
24097
  // What the administrator pinned.
23859
- values: ManagedSettingsValues.default({}),
24098
+ //
24099
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24100
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24101
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24102
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24103
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24104
+ // exactly the file an administrator is most likely to write while a fleet
24105
+ // is mid-upgrade.
24106
+ //
24107
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24108
+ // file, which is the outcome the lock half already rejected — an older
24109
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24110
+ // value still fails, because the nested schema is re-run over the known
24111
+ // subset and its issues are re-raised on this parse.
24112
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23860
24113
  // Which of those the user may not change. A key here with no matching value
23861
24114
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23862
24115
  // the user may still override. The two are separable on purpose.
23863
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24116
+ //
24117
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24118
+ // build does not know is dropped from the locked set and reported, never a
24119
+ // reason to refuse the file. The same shape reaches an older build whenever
24120
+ // an administrator locks a key a newer build added, and refusing it there
24121
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24122
+ // the fleets most likely to carry a version skew. A name outside the enum
24123
+ // is still never HONOURED: the lockable set stays explicit above.
24124
+ lockedFields: external_exports.array(external_exports.string()).default([])
24125
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24126
+ const known = [];
24127
+ const unknown2 = [];
24128
+ for (const name of lockedFields) {
24129
+ if (isManagedSettingKey(name)) known.push(name);
24130
+ else unknown2.push(name);
24131
+ }
24132
+ const knownValues = /* @__PURE__ */ Object.create(null);
24133
+ const unknownValues = [];
24134
+ for (const [name, value] of Object.entries(values)) {
24135
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24136
+ else unknownValues.push(name);
24137
+ }
24138
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24139
+ if (!pinned.success) {
24140
+ for (const issue2 of pinned.error.issues)
24141
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24142
+ return external_exports.NEVER;
24143
+ }
24144
+ return {
24145
+ ...rest,
24146
+ values: pinned.data,
24147
+ lockedFields: known,
24148
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24149
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24150
+ };
23864
24151
  }).meta({ id: "ManagedSettings" });
23865
24152
 
23866
24153
  // ../../packages/schema/src/zod/project-files.ts
@@ -23984,7 +24271,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23984
24271
  timestamp: external_exports.iso.date(),
23985
24272
  critical: external_exports.number().int().nonnegative(),
23986
24273
  high: external_exports.number().int().nonnegative(),
23987
- medium: external_exports.number().int().nonnegative()
24274
+ medium: external_exports.number().int().nonnegative(),
24275
+ // Optional and additive, so a producer written against the earlier
24276
+ // three-series contract keeps validating. A consumer plotting it resolves the
24277
+ // absent case itself — the chart point requires a number.
24278
+ low: external_exports.number().int().nonnegative().optional()
23988
24279
  }).meta({ id: "FindingsTimeseriesPoint" });
23989
24280
  var FindingsTimeseriesResponse = external_exports.object({
23990
24281
  range: TimeRange,
@@ -24010,6 +24301,10 @@ var ResolvedFeedItem = external_exports.object({
24010
24301
  findingKey: external_exports.string(),
24011
24302
  ruleId: external_exports.string(),
24012
24303
  severity: Severity,
24304
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24305
+ // identifies the file: a bare path matches the same name in every repo.
24306
+ // Optional and additive; empty when the event carried no repo.
24307
+ repo: external_exports.string().optional(),
24013
24308
  path: external_exports.string(),
24014
24309
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24015
24310
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24115,7 +24410,23 @@ var SaveSettingsInput = external_exports.object({
24115
24410
  modelJudgeConsent: ModelJudgeConsentChoice,
24116
24411
  historySyncConsent: HistorySyncConsentChoice,
24117
24412
  vaultConsent: external_exports.string(),
24118
- vaultInlineReveal: external_exports.string()
24413
+ vaultInlineReveal: external_exports.string(),
24414
+ // Widened to `string` like its neighbours rather than typed as
24415
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24416
+ // the call site, so the domain check receives the type it was written for.
24417
+ //
24418
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24419
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24420
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24421
+ // trade against. The real cost runs the other way and is the part worth
24422
+ // knowing: a value this schema admits and the domain enum then rejects lands
24423
+ // on the action's shared refusal, which names NO field, where a shape
24424
+ // rejection reaches `malformedInput` and names the schema key.
24425
+ redactFallback: external_exports.string(),
24426
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24427
+ // `BodyRetention`'s and the action checks it there, so there is one place
24428
+ // that decides what a legal horizon is rather than two that can drift.
24429
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24119
24430
  });
24120
24431
  var AttachInput = external_exports.object({
24121
24432
  endpoint: external_exports.string(),
@@ -24287,6 +24598,52 @@ function reviewSeverityRank(reasons) {
24287
24598
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24288
24599
  }
24289
24600
 
24601
+ // ../../packages/schema/src/zod/web-capture.ts
24602
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24603
+ var WebUsage = external_exports.object({
24604
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24605
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24606
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24607
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24608
+ });
24609
+ var WebToolCall = external_exports.object({
24610
+ toolUseId: external_exports.string().min(1),
24611
+ toolName: external_exports.string().min(1),
24612
+ target: external_exports.string().optional(),
24613
+ isError: external_exports.boolean().optional(),
24614
+ inputSize: external_exports.number().int().nonnegative().optional(),
24615
+ outputSize: external_exports.number().int().nonnegative().optional()
24616
+ });
24617
+ var WebExchange = external_exports.object({
24618
+ messageId: external_exports.string().min(1),
24619
+ startedAt: external_exports.iso.datetime(),
24620
+ model: external_exports.string().optional(),
24621
+ usage: WebUsage.optional(),
24622
+ usageSource: WebUsageSource,
24623
+ stopReason: external_exports.string().optional(),
24624
+ conversationId: external_exports.string().optional(),
24625
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24626
+ toolCalls: external_exports.array(WebToolCall).default([]),
24627
+ // Absent when the adapter recovered no text. Capped by the caller at
24628
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24629
+ // short capture is never mistaken for a short reply.
24630
+ responseText: external_exports.string().optional(),
24631
+ truncated: external_exports.boolean().default(false)
24632
+ });
24633
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24634
+ var WebCaptureStatus = external_exports.object({
24635
+ patched: external_exports.boolean(),
24636
+ live: external_exports.boolean(),
24637
+ blind: external_exports.boolean(),
24638
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24639
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24640
+ parseFailures: external_exports.number().int().nonnegative(),
24641
+ unparsedBodies: external_exports.number().int().nonnegative(),
24642
+ // The adapter-declared JSON key paths that were absent from a real payload —
24643
+ // the earliest signal that a site's contract moved.
24644
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24645
+ });
24646
+
24290
24647
  // ../../packages/persistence/src/paths.ts
24291
24648
  import {
24292
24649
  chmodSync,
@@ -24647,6 +25004,22 @@ function discardStore(file2, backup) {
24647
25004
  }
24648
25005
  }
24649
25006
 
25007
+ // ../../packages/persistence/src/internal/sql-functions.ts
25008
+ var utf8 = new TextDecoder();
25009
+ function akaLower(value) {
25010
+ if (value === null) return null;
25011
+ if (typeof value === "string") return value.toLowerCase();
25012
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25013
+ return utf8.decode(value).toLowerCase();
25014
+ }
25015
+ function registerSqlFunctions(db) {
25016
+ db.function(
25017
+ "aka_lower",
25018
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25019
+ akaLower
25020
+ );
25021
+ }
25022
+
24650
25023
  // ../../packages/persistence/src/internal/sql-text.ts
24651
25024
  function escapeLikePattern(s) {
24652
25025
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24731,6 +25104,11 @@ function schemaObjectExists(db, kind, name) {
24731
25104
  function indexExists(db, name) {
24732
25105
  return schemaObjectExists(db, "index", name);
24733
25106
  }
25107
+ function indexColumns(db, name) {
25108
+ if (!indexExists(db, name)) return [];
25109
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25110
+ return columns.map((c) => c.name).filter((c) => c !== null);
25111
+ }
24734
25112
  function columnNames(db, table, opts) {
24735
25113
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24736
25114
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24792,140 +25170,782 @@ function mapRowsTolerant(rows, map2) {
24792
25170
  return out;
24793
25171
  }
24794
25172
 
24795
- // ../../packages/persistence/src/migrations.ts
24796
- function describeObject(object2) {
24797
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24798
- }
24799
- function splitStatements(sql) {
24800
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24801
- }
24802
- function createdIndexName(statement) {
24803
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24804
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25173
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25174
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25175
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25176
+
25177
+ // ../../packages/persistence/src/sync-failure.ts
25178
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25179
+ function syncFailureRejectCondition(column = "sync_failure") {
25180
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25181
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24805
25182
  }
24806
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24807
- function applyMigrations(db, file2) {
24808
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24809
- db.exec(
24810
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24811
- );
24812
- const applied = new Set(
24813
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24814
- );
24815
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24816
- const record2 = db.prepare(
24817
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24818
- );
24819
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24820
- if (applied.has(migration.tag)) continue;
24821
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24822
- const evidence = evidenceObjects(migration.sql);
24823
- const present = evidence.filter((o) => evidenceExists(db, o));
24824
- if (present.length > 0 && present.length < evidence.length) {
24825
- const missing = evidence.filter((o) => !present.includes(o));
24826
- 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.`;
24827
- akaWarn(message);
24828
- throw new Error(`[aka] ${message}`);
24829
- }
24830
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24831
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24832
- const statements = splitStatements(migration.sql);
24833
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24834
- try {
24835
- withTransaction(
24836
- db,
24837
- () => {
24838
- for (const statement of statements) {
24839
- const indexName = createdIndexName(statement);
24840
- if (indexName === void 0) {
24841
- if (alreadyApplied) continue;
24842
- } else if (indexExists(db, indexName)) {
24843
- continue;
24844
- }
24845
- db.exec(statement);
24846
- }
24847
- if (wantsFkOff && !alreadyApplied) {
24848
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24849
- if (violations.length > 0) {
24850
- throw new Error(
24851
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24852
- );
24853
- }
24854
- }
24855
- record2.run(migration.tag, Date.now());
24856
- },
24857
- "IMMEDIATE"
24858
- );
24859
- } finally {
24860
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24861
- }
25183
+
25184
+ // ../../packages/persistence/src/repositories/history-sync.ts
25185
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25186
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25187
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25188
+ var COUNTED_EVENT_TYPES = [
25189
+ ...STRUCTURAL_EVENT_TYPES,
25190
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25191
+ ];
25192
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25193
+ var PARTITION_BUCKETS = `
25194
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25195
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25196
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25197
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25198
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25199
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25200
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25201
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25202
+ -- added later lands in no bucket and fails the sum assertion, instead
25203
+ -- of silently joining this one.
25204
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25205
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25206
+ THEN 1 ELSE 0 END) AS failed,
25207
+ COUNT(*) AS total`;
25208
+ var COUNTED_SCOPE = `
25209
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25210
+ AND (
25211
+ event_type IN (${TYPE_LIST})
25212
+ OR synced_at IS NOT NULL
25213
+ OR outbox_owed = 1
25214
+ )`;
25215
+ var SKIPPED = -1;
25216
+ var ROW_COLUMNS = `id,
25217
+ parent_id AS parentId,
25218
+ root_session_id AS rootSessionId,
25219
+ event_type AS eventType,
25220
+ host_id AS hostId,
25221
+ harness_id AS harnessId,
25222
+ source_project_id AS sourceProjectId,
25223
+ started_at AS startedAt,
25224
+ ended_at AS endedAt,
25225
+ severity,
25226
+ priority,
25227
+ content,
25228
+ content_hash AS contentHash,
25229
+ attributes`;
25230
+ var SqliteHistorySyncRepository = class {
25231
+ constructor(db) {
25232
+ this.db = db;
25233
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25234
+ this.sessionsStmt = db.prepare(
25235
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25236
+ FROM audit_events
25237
+ WHERE synced_at IS NULL
25238
+ AND event_type IN (${TYPE_LIST})
25239
+ AND started_at < :before
25240
+ GROUP BY sessionId
25241
+ ORDER BY earliest
25242
+ LIMIT :limit`
25243
+ );
25244
+ this.rowsStmt = db.prepare(
25245
+ `SELECT ${ROW_COLUMNS}
25246
+ FROM audit_events
25247
+ WHERE synced_at IS NULL
25248
+ AND event_type IN (${TYPE_LIST})
25249
+ AND started_at < :before
25250
+ AND COALESCE(root_session_id, id) = :sessionId
25251
+ ORDER BY (event_type = 'session') DESC, started_at
25252
+ LIMIT :limit`
25253
+ );
25254
+ this.captureRowsStmt = db.prepare(
25255
+ `SELECT ${ROW_COLUMNS}
25256
+ FROM audit_events
25257
+ WHERE synced_at IS NULL
25258
+ AND sync_claimed_at IS NULL
25259
+ AND outbox_owed = 1
25260
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25261
+ AND started_at < :before
25262
+ ORDER BY started_at
25263
+ LIMIT :limit`
25264
+ );
25265
+ this.markOwedStmt = db.prepare(
25266
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25267
+ );
25268
+ this.markCaptureBacklogOwedStmt = db.prepare(
25269
+ `UPDATE audit_events SET outbox_owed = 1
25270
+ WHERE synced_at IS NULL
25271
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25272
+ AND started_at < :before`
25273
+ );
25274
+ this.stampStmt = db.prepare(
25275
+ `UPDATE audit_events
25276
+ SET synced_at = :at,
25277
+ sync_claimed_at = NULL,
25278
+ sync_failed_at = :failedAt,
25279
+ sync_failure = :failure
25280
+ WHERE id = :id`
25281
+ );
25282
+ this.claimRowStmt = db.prepare(
25283
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25284
+ );
25285
+ this.releaseRowStmt = db.prepare(
25286
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25287
+ );
25288
+ this.releaseStaleClaimsStmt = db.prepare(
25289
+ `UPDATE audit_events SET sync_claimed_at = NULL
25290
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25291
+ );
25292
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25293
+ FROM audit_events${COUNTED_SCOPE}`);
25294
+ this.partitionByKindStmt = db.prepare(
25295
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25296
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25297
+ GROUP BY event_type`
25298
+ );
25299
+ this.countsStmt = db.prepare(
25300
+ `SELECT
25301
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25302
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25303
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25304
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25305
+ THEN 1 ELSE 0 END) AS skipped,
25306
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25307
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25308
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25309
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25310
+ FROM audit_events
25311
+ WHERE event_type IN (${TYPE_LIST})`
25312
+ );
25313
+ this.captureSkipCountStmt = db.prepare(
25314
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25315
+ // way the structural totals are. The split exists because a refusal is
25316
+ // terminal only against the deployment that gave it, and the structural
25317
+ // re-arm frees it on a change of deployment. The capture lane has no such
25318
+ // escape: re-arming a capture would offer one deployment's undelivered
25319
+ // prompts, with their text, to a deployment that never saw them, which is
25320
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25321
+ // reasons mean the same thing — this row will not be sent — and splitting
25322
+ // them would put refused captures in a bucket nothing reads and nothing
25323
+ // frees.
25324
+ `SELECT COUNT(*) AS skipped
25325
+ FROM audit_events
25326
+ WHERE synced_at = ${String(SKIPPED)}
25327
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25328
+ );
25329
+ this.fingerprintStmt = db.prepare(
25330
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25331
+ FROM history_sync WHERE id = 1`
25332
+ );
25333
+ this.setFingerprintStmt = db.prepare(
25334
+ `UPDATE history_sync
25335
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25336
+ WHERE id = 1`
25337
+ );
25338
+ this.disownCapturesStmt = db.prepare(
25339
+ `UPDATE audit_events SET outbox_owed = NULL
25340
+ WHERE outbox_owed IS NOT NULL
25341
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25342
+ AND started_at < :attachedAt`
25343
+ );
25344
+ this.rearmStmt = db.prepare(
25345
+ `UPDATE audit_events
25346
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25347
+ WHERE (synced_at > 0
25348
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25349
+ AND event_type IN (${TYPE_LIST})`
25350
+ );
25351
+ this.claimStmt = db.prepare(
25352
+ `UPDATE history_sync
25353
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25354
+ WHERE id = 1
25355
+ AND (owner_pid IS NULL
25356
+ OR heartbeat_at IS NULL
25357
+ OR heartbeat_at < :staleBefore
25358
+ OR heartbeat_at > :now)`
25359
+ );
25360
+ this.heartbeatStmt = db.prepare(
25361
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25362
+ );
25363
+ this.releaseStmt = db.prepare(
25364
+ `UPDATE history_sync
25365
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25366
+ WHERE id = 1 AND owner_pid = :pid`
25367
+ );
25368
+ this.closeWindowStmt = db.prepare(
25369
+ `UPDATE audit_events
25370
+ SET synced_at = ${String(SKIPPED)},
25371
+ sync_failed_at = :at,
25372
+ sync_failure = 'detached_undelivered'
25373
+ WHERE synced_at IS NULL
25374
+ AND event_type IN (${TYPE_LIST})
25375
+ AND started_at >= :attachedAt`
25376
+ );
25377
+ this.releaseBoundaryStmt = db.prepare(
25378
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25379
+ );
25380
+ this.freezeBoundaryStmt = db.prepare(
25381
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25382
+ );
25383
+ this.leaseStmt = db.prepare(
25384
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25385
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25386
+ FROM history_sync WHERE id = 1`
25387
+ );
25388
+ this.inspectionsStmt = db.prepare(
25389
+ `SELECT d.rule_id AS ruleId,
25390
+ d.name AS ruleName,
25391
+ d.version AS ruleVersion,
25392
+ d.category AS category,
25393
+ d.severity AS severity,
25394
+ f.span_start AS spanStart,
25395
+ f.span_end AS spanEnd,
25396
+ f.masked_match AS maskedMatch,
25397
+ f.action_taken AS actionTaken,
25398
+ f.confidence AS confidence
25399
+ FROM inspection_findings f
25400
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25401
+ WHERE f.audit_event_id = :auditEventId
25402
+ ORDER BY f.span_start, f.id`
25403
+ );
24862
25404
  }
24863
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24864
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25405
+ db;
25406
+ ensureRowStmt;
25407
+ sessionsStmt;
25408
+ rowsStmt;
25409
+ stampStmt;
25410
+ countsStmt;
25411
+ fingerprintStmt;
25412
+ setFingerprintStmt;
25413
+ rearmStmt;
25414
+ claimStmt;
25415
+ heartbeatStmt;
25416
+ releaseStmt;
25417
+ leaseStmt;
25418
+ inspectionsStmt;
25419
+ closeWindowStmt;
25420
+ releaseBoundaryStmt;
25421
+ freezeBoundaryStmt;
25422
+ captureRowsStmt;
25423
+ markOwedStmt;
25424
+ markCaptureBacklogOwedStmt;
25425
+ captureSkipCountStmt;
25426
+ disownCapturesStmt;
25427
+ partitionStmt;
25428
+ partitionByKindStmt;
25429
+ claimRowStmt;
25430
+ releaseRowStmt;
25431
+ releaseStaleClaimsStmt;
25432
+ /**
25433
+ * The masked detections recorded against one tool call.
25434
+ *
25435
+ * These travel with the event because a tool call's target is not
25436
+ * re-inspectable from the event alone — unlike a capture, where the text
25437
+ * itself is re-scannable. What crosses is the masked match and the rule that
25438
+ * produced it, never the value.
25439
+ */
25440
+ inspectionsFor(auditEventId) {
25441
+ return allRows(this.inspectionsStmt, { auditEventId });
24865
25442
  }
24866
- ensureSyncedAtColumn(db, "audit_events");
24867
- ensureScanLedgerTable(db);
24868
- ensureHistorySyncTable(db);
24869
- ensureBlockedDetectionsTable(db);
24870
- ensureRuleProbeCacheTable(db);
24871
- ensureWriteGateTrigger(db);
24872
- ensureTokenUsageColumns(db);
24873
- reconcileSourceProjectIds(db);
24874
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24875
- const drained = runLegacyHistoryBackfill(db);
24876
- if (drained) applyLegacyDropMigration(db, file2);
25443
+ /**
25444
+ * Sessions with structural rows still to send, oldest first.
25445
+ *
25446
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25447
+ * read. Anything recorded after the machine attached is the live forward
25448
+ * path's to deliver; this drain exists for what was recorded before it, and a
25449
+ * row both paths send is at best a duplicate request and at worst — for a
25450
+ * session root — an overwrite of the inventory ids the live path resolved.
25451
+ */
25452
+ pendingSessions(limit, before) {
25453
+ return allRows(this.sessionsStmt, { limit, before }).map(
25454
+ (r) => r.sessionId
25455
+ );
24877
25456
  }
24878
- }
24879
- function readLegacyTables(db) {
24880
- let holdsRows = false;
24881
- const marks = [];
24882
- for (const table of ["events", "findings"]) {
24883
- try {
24884
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24885
- if (row === void 0) {
24886
- holdsRows = true;
24887
- marks.push(`${table}:unreadable`);
24888
- continue;
24889
- }
24890
- if (row.n > 0) holdsRows = true;
24891
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24892
- } catch {
24893
- holdsRows = true;
24894
- marks.push(`${table}:unreadable`);
24895
- }
25457
+ /** One session's undelivered structural rows within the backlog, root first. */
25458
+ pendingRows(sessionId, limit, before) {
25459
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24896
25460
  }
24897
- return { holdsRows, mark: marks.join("|") };
24898
- }
24899
- function applyLegacyDropMigration(db, file2) {
24900
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24901
- if (!migration) return;
24902
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24903
- if (file2 !== void 0 && before?.holdsRows === true) {
24904
- try {
24905
- backupBeforeLegacyDrop(db, file2);
24906
- } catch (error61) {
24907
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24908
- return;
24909
- }
25461
+ /**
25462
+ * Captures this machine still owes the deployment, oldest first.
25463
+ *
25464
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25465
+ * by a time window — see captureRowsStmt for why a window could not express
25466
+ * this. `before` is the grace window that leaves a just-recorded capture to
25467
+ * the live path.
25468
+ */
25469
+ pendingCaptureRows(limit, before) {
25470
+ return allRows(this.captureRowsStmt, { limit, before });
24910
25471
  }
24911
- try {
25472
+ /**
25473
+ * Record that a capture is OWED to the deployment.
25474
+ *
25475
+ * Written by the attached forward path when a live send did not confirm
25476
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25477
+ * a fact rather than an inference: the machine was attached, the send did not
25478
+ * land, so the row is owed — which no time window can state, because the same
25479
+ * window that holds the rows a past attachment left owed also holds every
25480
+ * capture recorded while the machine was DETACHED, and those were never
25481
+ * offered to anyone.
25482
+ *
25483
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25484
+ * out of the drain's read.
25485
+ */
25486
+ markCaptureOwed(id) {
25487
+ this.markOwedStmt.run({ id });
25488
+ }
25489
+ /**
25490
+ * Mark every capture already on disk as owed, as of `before`.
25491
+ *
25492
+ * The consent-time backfill, called once from `aka attach` when a human
25493
+ * grants existing-history consent — never from an ongoing drain pass, and
25494
+ * never inferred from a boundary that could later move. `before` is the
25495
+ * caller's own "now" at the moment consent was granted, so what this marks
25496
+ * is exactly the backlog the consent prompt already counted, not whatever a
25497
+ * later re-attach or key rotation might widen it to.
25498
+ *
25499
+ * Returns how many rows matched, for the caller to log or test against. Not a
25500
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25501
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25502
+ */
25503
+ markCaptureBacklogOwed(before) {
25504
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25505
+ }
25506
+ /**
25507
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25508
+ *
25509
+ * CLEARS any failure reason in the same statement. A row that failed against
25510
+ * one deployment and then landed is delivered, and leaving the reason behind
25511
+ * would leave the store holding two contradictory answers about one row —
25512
+ * with the surface free to render either.
25513
+ */
25514
+ markSynced(ids, atMs) {
25515
+ this.stampAll(ids, atMs, null);
25516
+ }
25517
+ /**
25518
+ * Record that THIS MACHINE cannot express the row on the wire.
25519
+ *
25520
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25521
+ * payload, or a body the client itself refused to send. It fails identically
25522
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25523
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25524
+ * is retried; marking those would turn one outage into permanent data loss.
25525
+ */
25526
+ markSkipped(ids, atMs) {
25527
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25528
+ }
25529
+ /**
25530
+ * Record that THIS DEPLOYMENT refused the row.
25531
+ *
25532
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25533
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25534
+ * row is outstanding rather than why. What separates them is the reason, and
25535
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25536
+ * on one body, so it is terminal only for as long as this machine points at
25537
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25538
+ *
25539
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25540
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25541
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25542
+ */
25543
+ markRefused(ids, atMs) {
25544
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25545
+ }
25546
+ eachInTransaction(ids, run) {
25547
+ if (ids.length === 0) return;
24912
25548
  withTransaction(
24913
- db,
25549
+ this.db,
24914
25550
  () => {
24915
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24916
- if (alreadyDropped) return;
24917
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24918
- akaWarn(
24919
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24920
- );
24921
- return;
24922
- }
24923
- for (const statement of splitStatements(migration.sql)) {
24924
- db.exec(statement);
24925
- }
24926
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24927
- migration.tag,
24928
- Date.now()
25551
+ for (const id of ids) run(id);
25552
+ },
25553
+ "IMMEDIATE"
25554
+ );
25555
+ }
25556
+ stampAll(ids, value, failure, failedAtMs) {
25557
+ if (ids.length === 0) return;
25558
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25559
+ withTransaction(
25560
+ this.db,
25561
+ () => {
25562
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25563
+ },
25564
+ "IMMEDIATE"
25565
+ );
25566
+ }
25567
+ /**
25568
+ * Claim rows as in-flight.
25569
+ *
25570
+ * Advisory in exactly the sense the lease is: it records that a send is in
25571
+ * progress so a surface can say so, and a lost claim costs a row showing as
25572
+ * queued while it is actually being sent. It is not exclusion — the far side
25573
+ * settles a duplicate on the row id.
25574
+ */
25575
+ claimRows(ids, atMs) {
25576
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25577
+ }
25578
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25579
+ releaseRows(ids) {
25580
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25581
+ }
25582
+ /**
25583
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25584
+ *
25585
+ * A process killed between claiming and settling leaves rows claimed with
25586
+ * nothing left to settle them. Without this they read as "sending" for ever.
25587
+ */
25588
+ releaseStaleClaims(staleBefore) {
25589
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25590
+ }
25591
+ /**
25592
+ * Every tracked row in exactly one delivery state.
25593
+ *
25594
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25595
+ * pick up now", which is a different question from "what state is this row
25596
+ * in" — and a machine that has never attached has no boundary to pass, so
25597
+ * requiring one would force a caller to invent one and report the whole store
25598
+ * as queued.
25599
+ */
25600
+ /**
25601
+ * The same partition, one row per kind that a lane carries.
25602
+ *
25603
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25604
+ * scope decides which rows exist at all, so a kind that has never been
25605
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25606
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25607
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25608
+ * different things.
25609
+ */
25610
+ partitionByKind() {
25611
+ return allRows(
25612
+ this.partitionByKindStmt,
25613
+ {}
25614
+ ).map((row) => ({
25615
+ kind: row.kind,
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
+ partition() {
25626
+ const row = getRow(this.partitionStmt, {});
25627
+ return {
25628
+ queued: row?.queued ?? 0,
25629
+ inProgress: row?.inProgress ?? 0,
25630
+ synced: row?.synced ?? 0,
25631
+ failed: row?.failed ?? 0,
25632
+ refused: row?.refused ?? 0,
25633
+ detached: row?.detached ?? 0,
25634
+ total: row?.total ?? 0
25635
+ };
25636
+ }
25637
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25638
+ counts(before) {
25639
+ const row = getRow(this.countsStmt, { before });
25640
+ const captures = getRow(this.captureSkipCountStmt);
25641
+ return {
25642
+ pending: row?.pending ?? 0,
25643
+ sent: row?.sent ?? 0,
25644
+ skipped: row?.skipped ?? 0,
25645
+ refused: row?.refused ?? 0,
25646
+ detached: row?.detached ?? 0,
25647
+ capturesSkipped: captures?.skipped ?? 0
25648
+ };
25649
+ }
25650
+ /**
25651
+ * The deployment the current stamps were made against, and where its backlog
25652
+ * ends.
25653
+ *
25654
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25655
+ * machine that has never drained is — and every writer below seeds the row
25656
+ * before it needs one, so nothing depends on this creating it. Keeping the
25657
+ * write off the gate path matters because the gate runs on every pass while a
25658
+ * write has to take the database's write lock.
25659
+ */
25660
+ deployment() {
25661
+ const row = getRow(
25662
+ this.fingerprintStmt
25663
+ );
25664
+ return {
25665
+ fingerprint: row?.fingerprint ?? void 0,
25666
+ backlogBefore: row?.backlogBefore ?? void 0
25667
+ };
25668
+ }
25669
+ /**
25670
+ * Point the ledger at a different deployment, discarding what it recorded
25671
+ * about the previous one.
25672
+ *
25673
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25674
+ * machine has just left are undelivered as far as the new one is concerned.
25675
+ * All four in one transaction, so a crash between them cannot leave stamps
25676
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25677
+ * a disown with no re-mark to follow it.
25678
+ *
25679
+ * The boundary is written HERE and only here, which is what freezes it: a
25680
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25681
+ * unchanged, so this never runs and the backlog does not widen back over rows
25682
+ * the live path has since delivered.
25683
+ *
25684
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25685
+ * granted existing-history consent for the deployment this call is arming —
25686
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25687
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25688
+ * apart. Passed only when that grant is valid, since this method has no way
25689
+ * to check consent itself and must not mark a row owed for a machine that
25690
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25691
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25692
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25693
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25694
+ * on the cleared side of that bound — and the re-mark in the same
25695
+ * transaction is what puts those rows back. A crash between the two cannot
25696
+ * strand the ledger disowned with nothing re-marked — the transaction either
25697
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25698
+ * committed re-enters this method on the very next pass. Omit it (the
25699
+ * structural-only tests do) to exercise the disown in isolation.
25700
+ *
25701
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25702
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25703
+ * live path can mark a capture owed from the moment `aka attach` writes the
25704
+ * descriptor, before the drain's first pass ever reaches this method, and
25705
+ * such a row sits at or after the bound rather than below it. What keeps the
25706
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25707
+ * bound — disown runs first, re-mark second, both inside the one
25708
+ * transaction above.
25709
+ */
25710
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25711
+ this.ensureRowStmt.run();
25712
+ withTransaction(
25713
+ this.db,
25714
+ () => {
25715
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25716
+ this.rearmStmt.run();
25717
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25718
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25719
+ }
25720
+ if (backfillCapturesBefore !== void 0) {
25721
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25722
+ }
25723
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25724
+ },
25725
+ "IMMEDIATE"
25726
+ );
25727
+ }
25728
+ /**
25729
+ * End the attached period: hand its rows to the live path, and release the
25730
+ * boundary so the next attachment can freeze a new one.
25731
+ *
25732
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25733
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25734
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25735
+ * during the detached period, because the machine is not attached. Rows
25736
+ * recorded in that window sit after the boundary and before the re-attach, so
25737
+ * neither path takes them, and the pending count reports none outstanding.
25738
+ *
25739
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25740
+ * closing attachment's to deliver and are no longer outstanding — that is what
25741
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25742
+ * distinction is not academic: this used to write a delivery TIME, which every
25743
+ * read treats as delivery, so one detach turned a window of undelivered rows
25744
+ * into a window of delivered ones and no surface could tell. It writes the
25745
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25746
+ * "received" stop being the same fact.
25747
+ *
25748
+ * A change of deployment still frees them (see the re-arm), because the next
25749
+ * deployment has seen none of this machine's history — so the rows reach it
25750
+ * exactly as they did when this wrote a delivery time.
25751
+ *
25752
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25753
+ * window unstamped — that half-state would re-send the whole attached period
25754
+ * on the next attach, which is the failure the boundary exists to prevent.
25755
+ */
25756
+ closeAttachedWindow(attachedAtMs, atMs) {
25757
+ this.ensureRowStmt.run();
25758
+ withTransaction(
25759
+ this.db,
25760
+ () => {
25761
+ const row = getRow(this.fingerprintStmt);
25762
+ const from = row?.backlogBefore ?? attachedAtMs;
25763
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25764
+ this.releaseBoundaryStmt.run();
25765
+ },
25766
+ "IMMEDIATE"
25767
+ );
25768
+ }
25769
+ /**
25770
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25771
+ *
25772
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25773
+ * different deployment and therefore discards what was delivered to the old
25774
+ * one: here the recipient is the same, so everything already sent to it stays
25775
+ * sent.
25776
+ */
25777
+ freezeBoundary(backlogBefore) {
25778
+ this.ensureRowStmt.run();
25779
+ this.freezeBoundaryStmt.run({ backlogBefore });
25780
+ }
25781
+ /** Take the claim, or report that someone live already holds it. */
25782
+ claim(pid, host, nowMs, staleAfterMs) {
25783
+ this.ensureRowStmt.run();
25784
+ let taken = false;
25785
+ withTransaction(
25786
+ this.db,
25787
+ () => {
25788
+ const result = this.claimStmt.run({
25789
+ pid,
25790
+ host,
25791
+ now: nowMs,
25792
+ staleBefore: nowMs - staleAfterMs
25793
+ });
25794
+ taken = result.changes === 1;
25795
+ },
25796
+ "IMMEDIATE"
25797
+ );
25798
+ return taken;
25799
+ }
25800
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25801
+ heartbeat(pid, nowMs) {
25802
+ this.heartbeatStmt.run({ now: nowMs, pid });
25803
+ }
25804
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25805
+ release(pid) {
25806
+ this.releaseStmt.run({ pid });
25807
+ }
25808
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25809
+ lease() {
25810
+ return getRow(this.leaseStmt);
25811
+ }
25812
+ };
25813
+
25814
+ // ../../packages/persistence/src/migrations.ts
25815
+ function describeObject(object2) {
25816
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25817
+ }
25818
+ function splitStatements(sql) {
25819
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25820
+ }
25821
+ function createdIndexName(statement) {
25822
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25823
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25824
+ }
25825
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25826
+ function applyMigrations(db, file2, options = {}) {
25827
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25828
+ db.exec(
25829
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25830
+ );
25831
+ const applied = new Set(
25832
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25833
+ );
25834
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25835
+ const record2 = db.prepare(
25836
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25837
+ );
25838
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25839
+ if (applied.has(migration.tag)) continue;
25840
+ if (options.skipTags?.has(migration.tag) === true) continue;
25841
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25842
+ const evidence = evidenceObjects(migration.sql);
25843
+ const present = evidence.filter((o) => evidenceExists(db, o));
25844
+ if (present.length > 0 && present.length < evidence.length) {
25845
+ const missing = evidence.filter((o) => !present.includes(o));
25846
+ 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.`;
25847
+ akaWarn(message);
25848
+ throw new Error(`[aka] ${message}`);
25849
+ }
25850
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25851
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25852
+ const statements = splitStatements(migration.sql);
25853
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25854
+ try {
25855
+ withTransaction(
25856
+ db,
25857
+ () => {
25858
+ for (const statement of statements) {
25859
+ const indexName = createdIndexName(statement);
25860
+ if (indexName === void 0) {
25861
+ if (alreadyApplied) continue;
25862
+ } else if (indexExists(db, indexName)) {
25863
+ continue;
25864
+ }
25865
+ db.exec(statement);
25866
+ }
25867
+ if (wantsFkOff && !alreadyApplied) {
25868
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25869
+ if (violations.length > 0) {
25870
+ throw new Error(
25871
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25872
+ );
25873
+ }
25874
+ }
25875
+ record2.run(migration.tag, Date.now());
25876
+ },
25877
+ "IMMEDIATE"
25878
+ );
25879
+ } finally {
25880
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25881
+ }
25882
+ }
25883
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25884
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25885
+ }
25886
+ ensureSyncedAtColumn(db, "audit_events");
25887
+ ensureScanLedgerTable(db);
25888
+ ensureHistorySyncTable(db);
25889
+ ensureBlockedDetectionsTable(db);
25890
+ ensureRuleProbeCacheTable(db);
25891
+ ensureWriteGateTrigger(db);
25892
+ ensureTokenUsageColumns(db);
25893
+ reconcileSourceProjectIds(db);
25894
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25895
+ const drained = runLegacyHistoryBackfill(db);
25896
+ if (drained) applyLegacyDropMigration(db, file2);
25897
+ }
25898
+ }
25899
+ function readLegacyTables(db) {
25900
+ let holdsRows = false;
25901
+ const marks = [];
25902
+ for (const table of ["events", "findings"]) {
25903
+ try {
25904
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25905
+ if (row === void 0) {
25906
+ holdsRows = true;
25907
+ marks.push(`${table}:unreadable`);
25908
+ continue;
25909
+ }
25910
+ if (row.n > 0) holdsRows = true;
25911
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25912
+ } catch {
25913
+ holdsRows = true;
25914
+ marks.push(`${table}:unreadable`);
25915
+ }
25916
+ }
25917
+ return { holdsRows, mark: marks.join("|") };
25918
+ }
25919
+ function applyLegacyDropMigration(db, file2) {
25920
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25921
+ if (!migration) return;
25922
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25923
+ if (file2 !== void 0 && before?.holdsRows === true) {
25924
+ try {
25925
+ backupBeforeLegacyDrop(db, file2);
25926
+ } catch (error61) {
25927
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25928
+ return;
25929
+ }
25930
+ }
25931
+ try {
25932
+ withTransaction(
25933
+ db,
25934
+ () => {
25935
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25936
+ if (alreadyDropped) return;
25937
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25938
+ akaWarn(
25939
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25940
+ );
25941
+ return;
25942
+ }
25943
+ for (const statement of splitStatements(migration.sql)) {
25944
+ db.exec(statement);
25945
+ }
25946
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25947
+ migration.tag,
25948
+ Date.now()
24929
25949
  );
24930
25950
  },
24931
25951
  "IMMEDIATE"
@@ -25224,10 +26244,62 @@ function ensureSyncedAtColumn(db, table) {
25224
26244
  if (!columns.includes("outbox_owed")) {
25225
26245
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25226
26246
  }
26247
+ if (!columns.includes("sync_failed_at")) {
26248
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26249
+ }
26250
+ if (!columns.includes("sync_failure")) {
26251
+ withTransaction(
26252
+ db,
26253
+ () => {
26254
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26255
+ db.exec(
26256
+ `UPDATE ${table} SET synced_at = NULL
26257
+ WHERE synced_at = -1
26258
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26259
+ );
26260
+ },
26261
+ "IMMEDIATE"
26262
+ );
26263
+ }
25227
26264
  db.exec(
25228
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25229
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26265
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26266
+ BEFORE UPDATE OF sync_failure ON ${table}
26267
+ WHEN ${syncFailureRejectCondition()}
26268
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25230
26269
  );
26270
+ const syncIndexColumns = [
26271
+ "event_type",
26272
+ "synced_at",
26273
+ "sync_claimed_at",
26274
+ "started_at",
26275
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26276
+ // has to be in the index for the read to stay covered — but putting it
26277
+ // ahead of `started_at` would reorder the prefix the structural drain's
26278
+ // reads match on.
26279
+ "sync_failure"
26280
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26281
+ //
26282
+ // The delivery-state read tests it — a capture's state depends on whether a
26283
+ // live forward marked it owed — so carrying it here makes that read covering
26284
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26285
+ // But a sixth column changes what the planner charges for this index, and
26286
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26287
+ // then stops choosing the per-session index for the token rollup and walks
26288
+ // every `llm_call` in the store through the event-type index instead. That
26289
+ // read grows with the store; this one does not.
26290
+ //
26291
+ // 40 ms on the largest store measured, once per render, is a cost worth
26292
+ // paying to leave every other read's plan where it was.
26293
+ ];
26294
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26295
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26296
+ if (!syncIndexMatches) {
26297
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26298
+ db.exec(
26299
+ `CREATE INDEX idx_audit_events_sync
26300
+ ON audit_events (${syncIndexColumns.join(", ")})`
26301
+ );
26302
+ }
25231
26303
  db.exec(
25232
26304
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25233
26305
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25449,7 +26521,11 @@ function buildAuditEvent(row) {
25449
26521
  link: linkParsed?.success ? linkParsed.data : null,
25450
26522
  targetId: row.target_id,
25451
26523
  internal: intToBool(row.internal),
25452
- flagged: intToBool(row.flagged)
26524
+ flagged: intToBool(row.flagged),
26525
+ // Only meaningful when the title came out empty — a row whose body was
26526
+ // expired but whose title fell back to `tool_name` still has something to
26527
+ // render, and flagging it would make the view apologise for nothing.
26528
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25453
26529
  };
25454
26530
  }
25455
26531
  var TIMELINE_COLUMNS = `
@@ -25457,6 +26533,7 @@ var TIMELINE_COLUMNS = `
25457
26533
  event_type,
25458
26534
  started_at,
25459
26535
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26536
+ content_expired_at,
25460
26537
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25461
26538
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25462
26539
  json_extract(attributes, '$.severity') AS severity,
@@ -25583,7 +26660,8 @@ var SqliteActivityRepository = class {
25583
26660
  SELECT 1 FROM audit_events d
25584
26661
  WHERE d.root_session_id = audit_events.id
25585
26662
  AND (d.content LIKE ? ESCAPE '\\'
25586
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26663
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26664
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25587
26665
  );
25588
26666
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25589
26667
  }
@@ -26121,6 +27199,88 @@ var SqliteAuditEventsRepository = class {
26121
27199
  }
26122
27200
  };
26123
27201
 
27202
+ // ../../packages/persistence/src/repositories/body-retention.ts
27203
+ var DEFAULT_BATCH_SIZE = 500;
27204
+ var DEFAULT_MAX_ROWS = 5e4;
27205
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27206
+ var SqliteBodyRetentionRepository = class {
27207
+ constructor(db) {
27208
+ this.db = db;
27209
+ const select = (laneClause) => `
27210
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27211
+ FROM audit_events
27212
+ WHERE content IS NOT NULL
27213
+ AND started_at < :cutoff
27214
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27215
+ ${laneClause}
27216
+ ORDER BY started_at
27217
+ LIMIT :limit`;
27218
+ this.candidatesStmt = this.db.prepare(select(""));
27219
+ this.candidatesSyncSafeStmt = this.db.prepare(
27220
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27221
+ );
27222
+ this.heldBySyncStmt = this.db.prepare(`
27223
+ SELECT COUNT(*) AS n
27224
+ FROM audit_events
27225
+ WHERE content IS NOT NULL
27226
+ AND started_at < :cutoff
27227
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27228
+ AND synced_at IS NULL`);
27229
+ this.expireStmt = this.db.prepare(
27230
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27231
+ );
27232
+ }
27233
+ db;
27234
+ candidatesStmt;
27235
+ candidatesSyncSafeStmt;
27236
+ heldBySyncStmt;
27237
+ expireStmt;
27238
+ /** How many bytes a pass with these options would free, changing nothing. */
27239
+ preview(opts) {
27240
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27241
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27242
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27243
+ return {
27244
+ rowsExpired: rows.length,
27245
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27246
+ rowsHeldBySync: this.countHeldBySync(opts)
27247
+ };
27248
+ }
27249
+ /** Clear eligible bodies, in bounded batches. */
27250
+ expire(opts) {
27251
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27252
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27253
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27254
+ let rowsExpired = 0;
27255
+ let bytesFreed = 0;
27256
+ let done = true;
27257
+ while (rowsExpired < maxRows) {
27258
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27259
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27260
+ if (batch.length === 0) break;
27261
+ withTransaction(
27262
+ this.db,
27263
+ () => {
27264
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27265
+ },
27266
+ "IMMEDIATE"
27267
+ );
27268
+ rowsExpired += batch.length;
27269
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27270
+ if (batch.length < remaining) break;
27271
+ if (rowsExpired >= maxRows) {
27272
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27273
+ }
27274
+ }
27275
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27276
+ }
27277
+ countHeldBySync(opts) {
27278
+ if (opts.sweepSyncLane) return 0;
27279
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27280
+ return row.n;
27281
+ }
27282
+ };
27283
+
26124
27284
  // ../../packages/persistence/src/repositories/classified-data.ts
26125
27285
  var SqliteClassifiedDataRepository = class {
26126
27286
  constructor(db) {
@@ -26921,23 +28081,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26921
28081
  )`;
26922
28082
 
26923
28083
  // ../../packages/persistence/src/repositories/findings.ts
26924
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26925
- var DEFAULT_LOCATIONS_LIMIT = 100;
26926
- var LOCATION_RULE_IDS_CAP = 20;
26927
- function compareLocationOrder(a, b) {
26928
- return compareFindingGroupOrder(
26929
- {
26930
- severity: a.maxSeverity,
26931
- latestDetectedAt: a.latestDetectedAt,
26932
- id: ""
26933
- },
26934
- {
26935
- severity: b.maxSeverity,
26936
- latestDetectedAt: b.latestDetectedAt,
26937
- id: ""
26938
- }
26939
- );
26940
- }
26941
28084
  var CONCAT_SEP = ",";
26942
28085
  var TUPLE_SEP = "|";
26943
28086
  function splitConcat(value) {
@@ -26966,7 +28109,15 @@ function toFlatFindingRow(r) {
26966
28109
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26967
28110
  eventId: r.event_id,
26968
28111
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26969
- status: deriveInstanceStatus(r)
28112
+ status: deriveInstanceStatus(r),
28113
+ delivery: deriveFindingDelivery({
28114
+ kind: r.kind,
28115
+ syncedAt: r.synced_at,
28116
+ syncClaimedAt: r.sync_claimed_at,
28117
+ syncFailedAt: r.sync_failed_at,
28118
+ syncFailure: r.sync_failure,
28119
+ outboxOwed: r.outbox_owed
28120
+ })
26970
28121
  };
26971
28122
  }
26972
28123
  function encodeGroupCursor(group) {
@@ -26989,13 +28140,51 @@ function decodeGroupCursor(cursor) {
26989
28140
  return null;
26990
28141
  }
26991
28142
  function firstAfter(sorted, cursor) {
26992
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28143
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26993
28144
  return index === -1 ? sorted.length : index;
26994
28145
  }
26995
28146
  function findDeepLinked(sorted, page, id) {
26996
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26997
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28147
+ if (page.some((t) => t.id === id)) return void 0;
28148
+ return sorted.find((t) => t.id === id);
26998
28149
  }
28150
+ function encodeLocationCursor(location) {
28151
+ const payload = {
28152
+ sev: location.maxSeverity,
28153
+ t: location.latestDetectedAt,
28154
+ r: location.repo,
28155
+ f: location.file
28156
+ };
28157
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28158
+ }
28159
+ function decodeLocationCursor(cursor) {
28160
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28161
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28162
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28163
+ }
28164
+ return null;
28165
+ }
28166
+ function firstLocationAfter(sorted, cursor) {
28167
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28168
+ return index === -1 ? sorted.length : index;
28169
+ }
28170
+ function findDeepLinkedLocation(sorted, page, id) {
28171
+ if (page.some((l) => l.id === id)) return void 0;
28172
+ return sorted.find((l) => l.id === id);
28173
+ }
28174
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28175
+ d.severity AS severity, f.masked_match AS masked_match,
28176
+ f.action_taken AS action_taken, f.confidence AS confidence,
28177
+ e.started_at AS occurred_at,
28178
+ e.source_tool AS source_tool,
28179
+ e.repo AS repo,
28180
+ e.file_path AS file,
28181
+ e.tool_name AS tool_name,
28182
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28183
+ e.event_type AS kind, f.finding_key AS finding_key,
28184
+ ${latestResolutionStatusSql("f")} AS latest_status,
28185
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28186
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28187
+ e.outbox_owed AS outbox_owed`;
26999
28188
  var DAY_MS3 = 864e5;
27000
28189
  var SqliteFindingsRepository = class {
27001
28190
  constructor(db) {
@@ -27116,30 +28305,26 @@ var SqliteFindingsRepository = class {
27116
28305
  );
27117
28306
  }
27118
28307
  /**
27119
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27120
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27121
- * attributes bag, rule_id/category/severity from the definition), scoped to
27122
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27123
- * rows this list must never surface), groups by ruleId, computes
27124
- * per-filter-excluded facets, applies the requested filters, and sorts by
27125
- * severity then recency. Filtering
27126
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27127
- * reflect the full filtered set; `items` is the requested
27128
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27129
- * filter, `totals.findings` counts only instances whose derived status was
27130
- * requested, and each item's instance preview is narrowed the same way.
28308
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28309
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28310
+ * list must never surface), with per-filter-excluded facets, the requested
28311
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28312
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28313
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28314
+ * Under a `status` filter, `totals.findings` counts only findings whose
28315
+ * derived status was requested.
28316
+ *
28317
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28318
+ * folding EVERY finding into the numbers a type row and the filters need
28319
+ * (count, severity, category, providers, actions, statuses, latest, search
28320
+ * text). The findings OF a type come from listFindingInstances scoped to
28321
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27131
28322
  *
27132
- * Two reads, neither of which materializes a row per finding:
27133
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27134
- * the group and the filters need (count, providers, actions, statuses,
27135
- * latest, search text);
27136
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27137
- * populate `instances` for the table's expanded rows.
27138
28323
  * The aggregates carry raw DB values and are translated by the same
27139
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27140
- * rule is ever restated in SQL.
28324
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28325
+ * status rule is ever restated in SQL.
27141
28326
  */
27142
- listGroupedFindings(query) {
28327
+ listFindingTypes(query) {
27143
28328
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27144
28329
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27145
28330
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27152,12 +28337,7 @@ var SqliteFindingsRepository = class {
27152
28337
  predicate,
27153
28338
  params: sessionParams
27154
28339
  });
27155
- const rows = this.previewRows(aggregates, {
27156
- sessionId: query.sessionId,
27157
- from: query.from
27158
- });
27159
- const groupable = rows.map(toFlatFindingRow);
27160
- const allGroups = buildFindingGroups(groupable, { aggregates });
28340
+ const allTypes = buildFindingTypes(aggregates);
27161
28341
  const filterOpts = {
27162
28342
  severity: query.severity,
27163
28343
  providers: query.provider,
@@ -27166,30 +28346,25 @@ var SqliteFindingsRepository = class {
27166
28346
  subtype: query.subtype,
27167
28347
  q: query.q
27168
28348
  };
27169
- const facets = computeFindingFacets(allGroups, filterOpts);
27170
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28349
+ const facets = computeFindingFacets(allTypes, filterOpts);
28350
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27171
28351
  const statusFilter = query.status ?? [];
27172
28352
  const totals = {
27173
- findings: sorted.reduce((acc, g) => {
27174
- if (statusFilter.length === 0) return acc + g.instanceCount;
27175
- const agg = aggregates.get(g.id);
27176
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28353
+ findings: sorted.reduce((acc, t) => {
28354
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28355
+ const agg = aggregates.get(t.id);
28356
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27177
28357
  }, 0),
27178
- groups: sorted.length
28358
+ types: sorted.length
27179
28359
  };
27180
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28360
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27181
28361
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27182
28362
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27183
28363
  const page = sorted.slice(start, start + limit);
27184
28364
  const lastOnPage = page.at(-1);
27185
28365
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27186
28366
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27187
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27188
- const narrow = (g) => statusSet ? {
27189
- ...g,
27190
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27191
- } : g;
27192
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28367
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27193
28368
  return Promise.resolve({
27194
28369
  totals,
27195
28370
  facets,
@@ -27200,7 +28375,7 @@ var SqliteFindingsRepository = class {
27200
28375
  }
27201
28376
  /**
27202
28377
  * One row per rule_id, folding EVERY instance of the group into the values
27203
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28378
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27204
28379
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27205
28380
  *
27206
28381
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27254,6 +28429,7 @@ var SqliteFindingsRepository = class {
27254
28429
  providers: query.provider,
27255
28430
  actions: query.action,
27256
28431
  statuses: query.status,
28432
+ deliveries: query.deployment,
27257
28433
  tools: query.tool,
27258
28434
  repo: query.repo,
27259
28435
  file: query.file,
@@ -27294,13 +28470,25 @@ var SqliteFindingsRepository = class {
27294
28470
  });
27295
28471
  }
27296
28472
  /**
27297
- * The same findings folded by location: repository, then file within it.
28473
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27298
28474
  *
27299
28475
  * The grouping keys come from the capturing event's attributes, which is what
27300
- * the local store relates a finding to — there is no finding↔asset row to
27301
- * group by instead. A repo or file the event did not record folds into the
27302
- * empty-string bucket, which the view renders but does not link, since no
27303
- * filter can name it.
28476
+ * the local store relates a finding to; there is no finding↔asset row to group
28477
+ * by instead. A repo or file the event did not record folds into the
28478
+ * empty-string bucket, which is a real location like any other: it is listed,
28479
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28480
+ *
28481
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28482
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28483
+ * list was rebuilt to remove — and two-level pagination inside an
28484
+ * expand/collapse table is what pushed that view to master/detail in the first
28485
+ * place.
28486
+ *
28487
+ * Every filter narrows the FINDINGS and the locations fall out of what
28488
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28489
+ * reports for the same filters scoped to that pair. The view depends on it:
28490
+ * one toolbar sits over both panels precisely because a location owns none of
28491
+ * its fields.
27304
28492
  */
27305
28493
  listFindingLocations(query) {
27306
28494
  const opts = {
@@ -27309,16 +28497,20 @@ var SqliteFindingsRepository = class {
27309
28497
  providers: query.provider,
27310
28498
  actions: query.action,
27311
28499
  statuses: query.status,
28500
+ deliveries: query.deployment,
27312
28501
  tools: query.tool,
27313
28502
  q: query.q
27314
28503
  };
27315
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28504
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28505
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27316
28506
  const byRepo = /* @__PURE__ */ new Map();
28507
+ const accumulator = createInstanceFacetAccumulator(opts);
27317
28508
  let total = 0;
27318
28509
  for (const row of this.scanFindingRows({
27319
28510
  sessionId: query.sessionId,
27320
28511
  from: query.from
27321
28512
  })) {
28513
+ accumulator.add(row);
27322
28514
  if (!matchesInstanceFilters(row, opts)) continue;
27323
28515
  total += 1;
27324
28516
  let files = byRepo.get(row.repo);
@@ -27333,103 +28525,35 @@ var SqliteFindingsRepository = class {
27333
28525
  }
27334
28526
  addToLocation(acc, row);
27335
28527
  }
27336
- let fileCount = 0;
27337
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27338
- fileCount += files.size;
27339
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27340
- file: file2,
27341
- instanceCount: acc.instanceCount,
27342
- maxSeverity: acc.maxSeverity,
27343
- latestDetectedAt: acc.latestDetectedAt,
27344
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27345
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27346
- })).sort(compareLocationOrder);
27347
- const rollup = fileRows.reduce(
27348
- (a, f) => ({
27349
- instanceCount: a.instanceCount + f.instanceCount,
27350
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27351
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27352
- }),
27353
- {
27354
- instanceCount: 0,
27355
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27356
- latestDetectedAt: ""
27357
- }
27358
- );
27359
- const statuses = fileRows.map((f) => f.status);
27360
- const folded = foldGroupStatus(statuses);
27361
- return {
27362
- repo,
27363
- instanceCount: rollup.instanceCount,
27364
- maxSeverity: rollup.maxSeverity,
27365
- latestDetectedAt: rollup.latestDetectedAt,
27366
- ...folded === void 0 ? {} : { status: folded },
27367
- files: fileRows
27368
- };
27369
- });
27370
- repos.sort(compareLocationOrder);
28528
+ const sorted = [];
28529
+ for (const [repo, files] of byRepo) {
28530
+ for (const [file2, acc] of files) {
28531
+ const status = foldGroupStatus(acc.statuses);
28532
+ sorted.push({
28533
+ id: encodeLocationId(repo, file2),
28534
+ repo,
28535
+ file: file2,
28536
+ instanceCount: acc.instanceCount,
28537
+ maxSeverity: acc.maxSeverity,
28538
+ latestDetectedAt: acc.latestDetectedAt,
28539
+ ...status === void 0 ? {} : { status },
28540
+ ruleIds: [...acc.ruleIds]
28541
+ });
28542
+ }
28543
+ }
28544
+ sorted.sort(compareLocationOrder);
28545
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28546
+ const page = sorted.slice(start, start + limit);
28547
+ const lastOnPage = page.at(-1);
28548
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28549
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27371
28550
  return Promise.resolve({
27372
- totals: { findings: total, repos: repos.length, files: fileCount },
27373
- items: repos.slice(0, limit),
27374
- hasMore: repos.length > limit
28551
+ totals: { findings: total, locations: sorted.length },
28552
+ facets: accumulator.facets(),
28553
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28554
+ nextCursor
27375
28555
  });
27376
28556
  }
27377
- /**
27378
- * Each group's newest instances, for the table's expanded rows.
27379
- *
27380
- * ONE index-ordered scan with early termination, and the shape is the point.
27381
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27382
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27383
- * through a temp B-tree to keep a bounded preview of each group, and then
27384
- * sorts the survivors again for the page order. Both sorts grow with the
27385
- * store while the answer does not.
27386
- *
27387
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27388
- * (or the session or window index the scope names — see `findingScanSql`),
27389
- * which is already the order the page wants, and keeps rows per rule until
27390
- * each rule has as many as it can show. The aggregate the caller already holds
27391
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27392
- * per rule, summed, is the number of rows this scan has to find, and it stops
27393
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27394
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27395
- * store with many firing rules widens it. The bound that DOES hold
27396
- * unconditionally is the sorted form's floor: this scan visits at most as
27397
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27398
- * sorted, and stops the moment every rule has its cap, where the sorted form
27399
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27400
- * wanted instances sitting at the tail of the scope — is one pass over
27401
- * everything in scope with a block sort of the id tie-break only, never a
27402
- * sort of the scope, which is still that floor.
27403
- *
27404
- * A row whose rule the aggregate did not see is skipped: the two statements
27405
- * run without a shared snapshot, so a capture landing between them can add a
27406
- * rule here that has no counts there, and the counts are what the group is
27407
- * built from.
27408
- */
27409
- previewRows(aggregates, scope) {
27410
- const wanted = /* @__PURE__ */ new Map();
27411
- let remaining = 0;
27412
- for (const [ruleId, agg] of aggregates) {
27413
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27414
- wanted.set(ruleId, n);
27415
- remaining += n;
27416
- }
27417
- const rows = [];
27418
- if (remaining === 0) return rows;
27419
- const { sql, params } = this.findingScanSql(scope);
27420
- const taken = /* @__PURE__ */ new Map();
27421
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27422
- const want = wanted.get(r.rule_id);
27423
- if (want === void 0) continue;
27424
- const have = taken.get(r.rule_id) ?? 0;
27425
- if (have >= want) continue;
27426
- taken.set(r.rule_id, have + 1);
27427
- rows.push(r);
27428
- remaining -= 1;
27429
- if (remaining === 0) break;
27430
- }
27431
- return rows;
27432
- }
27433
28557
  /**
27434
28558
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27435
28559
  *
@@ -27456,6 +28580,33 @@ var SqliteFindingsRepository = class {
27456
28580
  yield toFlatFindingRow(r);
27457
28581
  }
27458
28582
  }
28583
+ /**
28584
+ * One finding by its own id, or null when no such row exists.
28585
+ *
28586
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28587
+ * the store — and, unlike anything derived from a list page, it resolves a
28588
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28589
+ * deep link needs: the id it carries may name a finding thousands of rows
28590
+ * older than anything a first page holds.
28591
+ *
28592
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28593
+ * RESOLVES an id; whether that row would survive the list's current filters is
28594
+ * a different question, and hiding the target because a filter excludes it is
28595
+ * worse than showing it.
28596
+ *
28597
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28598
+ * type should the list select?" and "what does the drawer show?".
28599
+ */
28600
+ findingInstance(id) {
28601
+ const row = this.db.prepare(
28602
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28603
+ FROM inspection_findings f
28604
+ JOIN audit_events e ON e.id = f.audit_event_id
28605
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28606
+ WHERE f.id = ?`
28607
+ ).get(id);
28608
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28609
+ }
27459
28610
  /**
27460
28611
  * The one statement both instance-level scans run: every finding in scope,
27461
28612
  * joined to its event and definition, newest first.
@@ -27489,17 +28640,7 @@ var SqliteFindingsRepository = class {
27489
28640
  conditions.push("e.started_at >= ?");
27490
28641
  params.push(isoToEpochMillis(scope.from));
27491
28642
  }
27492
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27493
- d.severity AS severity, f.masked_match AS masked_match,
27494
- f.action_taken AS action_taken, f.confidence AS confidence,
27495
- e.started_at AS occurred_at,
27496
- e.source_tool AS source_tool,
27497
- e.repo AS repo,
27498
- e.file_path AS file,
27499
- e.tool_name AS tool_name,
27500
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27501
- e.event_type AS kind, f.finding_key AS finding_key,
27502
- ${latestResolutionStatusSql("f")} AS latest_status
28643
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27503
28644
  FROM audit_events e
27504
28645
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27505
28646
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27513,6 +28654,26 @@ var SqliteFindingsRepository = class {
27513
28654
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27514
28655
  const rows = this.db.prepare(
27515
28656
  `SELECT rule_id,
28657
+ -- BARE columns beside max(latest_at), which is deliberate and
28658
+ -- is SQLite's documented behaviour: with a single min()/max()
28659
+ -- in an aggregate query, every bare column takes its value from
28660
+ -- the row that produced the extremum. So these are the severity
28661
+ -- and category of the definition whose finding is NEWEST, which
28662
+ -- is what the row-based build they replaced read off its first
28663
+ -- (newest-first) row.
28664
+ --
28665
+ -- min() is WRONG here and was the defect: inspection_definitions
28666
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28667
+ -- mints a new row), so a rule whose severity moved between
28668
+ -- versions has several, and min() picks the ALPHABETICALLY
28669
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28670
+ -- That is arbitrary in direction, and it feeds the badge, the
28671
+ -- filter, the facet counts and the primary sort key.
28672
+ --
28673
+ -- Adding a second min()/max() aggregate here would make these
28674
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28675
+ severity,
28676
+ category,
27516
28677
  sum(tuple_count) AS instance_count,
27517
28678
  max(latest_at) AS latest_at,
27518
28679
  group_concat(source_tools) AS source_tools,
@@ -27523,6 +28684,14 @@ var SqliteFindingsRepository = class {
27523
28684
  group_concat(tool_names) AS tool_names
27524
28685
  FROM (
27525
28686
  SELECT d.rule_id AS rule_id,
28687
+ -- Severity and category are columns of the DEFINITION, and
28688
+ -- a rule can have SEVERAL definitions (one per version), so
28689
+ -- these are grouped on below and resolved to the newest
28690
+ -- firing version by the outer query's bare-column select.
28691
+ -- They ride the aggregate because the type build has no rows
28692
+ -- to read them off \u2014 see buildFindingTypes.
28693
+ d.severity AS severity,
28694
+ d.category AS category,
27526
28695
  e.event_type || '${TUPLE_SEP}' ||
27527
28696
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27528
28697
  coalesce(latest.status, '') AS status_tuple,
@@ -27537,7 +28706,7 @@ var SqliteFindingsRepository = class {
27537
28706
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27538
28707
  ON latest.finding_key = f.finding_key
27539
28708
  ${scope.predicate}
27540
- GROUP BY d.rule_id, status_tuple
28709
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27541
28710
  )
27542
28711
  GROUP BY rule_id`
27543
28712
  ).all(scope.params);
@@ -27546,6 +28715,8 @@ var SqliteFindingsRepository = class {
27546
28715
  r.rule_id,
27547
28716
  {
27548
28717
  instanceCount: r.instance_count,
28718
+ severity: r.severity,
28719
+ category: r.category,
27549
28720
  sourceTools: splitConcat(r.source_tools),
27550
28721
  actionsTaken: splitConcat(r.actions_taken),
27551
28722
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27562,7 +28733,7 @@ var SqliteFindingsRepository = class {
27562
28733
  latestDetectedAt: epochMillisToIso(r.latest_at),
27563
28734
  // Free text only — joined and substring-matched, so group_concat's
27564
28735
  // commas need no unpicking (a repo/path containing one still matches).
27565
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28736
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27566
28737
  // tell "no q this request" from "a group with no repo/file at all"
27567
28738
  // and skip priming a haystack nothing will read.
27568
28739
  ...withSearchText ? {
@@ -27590,7 +28761,9 @@ var SqliteFindingsRepository = class {
27590
28761
  )
27591
28762
  );
27592
28763
  for (const row of grouped) {
27593
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28764
+ if (Object.hasOwn(byAction, row.action_taken)) {
28765
+ byAction[row.action_taken] = row.c;
28766
+ }
27594
28767
  }
27595
28768
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27596
28769
  const sevRows = allRows(
@@ -27607,7 +28780,9 @@ var SqliteFindingsRepository = class {
27607
28780
  )
27608
28781
  );
27609
28782
  for (const row of sevRows) {
27610
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28783
+ if (Object.hasOwn(bySeverity, row.severity)) {
28784
+ bySeverity[row.severity] = row.c;
28785
+ }
27611
28786
  }
27612
28787
  const categories = ENFORCEABLE_CATEGORIES;
27613
28788
  const enabledRows = allRows(
@@ -27656,469 +28831,6 @@ function isoDay(ms) {
27656
28831
  return new Date(ms).toISOString().slice(0, 10);
27657
28832
  }
27658
28833
 
27659
- // ../../packages/persistence/src/repositories/history-sync.ts
27660
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27661
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27662
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27663
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27664
- var SKIPPED = -1;
27665
- var ROW_COLUMNS = `id,
27666
- parent_id AS parentId,
27667
- root_session_id AS rootSessionId,
27668
- event_type AS eventType,
27669
- host_id AS hostId,
27670
- harness_id AS harnessId,
27671
- source_project_id AS sourceProjectId,
27672
- started_at AS startedAt,
27673
- ended_at AS endedAt,
27674
- severity,
27675
- priority,
27676
- content,
27677
- content_hash AS contentHash,
27678
- attributes`;
27679
- var SqliteHistorySyncRepository = class {
27680
- constructor(db) {
27681
- this.db = db;
27682
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27683
- this.sessionsStmt = db.prepare(
27684
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27685
- FROM audit_events
27686
- WHERE synced_at IS NULL
27687
- AND event_type IN (${TYPE_LIST})
27688
- AND started_at < :before
27689
- GROUP BY sessionId
27690
- ORDER BY earliest
27691
- LIMIT :limit`
27692
- );
27693
- this.rowsStmt = db.prepare(
27694
- `SELECT ${ROW_COLUMNS}
27695
- FROM audit_events
27696
- WHERE synced_at IS NULL
27697
- AND event_type IN (${TYPE_LIST})
27698
- AND started_at < :before
27699
- AND COALESCE(root_session_id, id) = :sessionId
27700
- ORDER BY (event_type = 'session') DESC, started_at
27701
- LIMIT :limit`
27702
- );
27703
- this.captureRowsStmt = db.prepare(
27704
- `SELECT ${ROW_COLUMNS}
27705
- FROM audit_events
27706
- WHERE synced_at IS NULL
27707
- AND sync_claimed_at IS NULL
27708
- AND outbox_owed = 1
27709
- AND event_type IN (${CAPTURE_TYPE_LIST})
27710
- AND started_at < :before
27711
- ORDER BY started_at
27712
- LIMIT :limit`
27713
- );
27714
- this.markOwedStmt = db.prepare(
27715
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27716
- );
27717
- this.stampStmt = db.prepare(
27718
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27719
- );
27720
- this.claimRowStmt = db.prepare(
27721
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27722
- );
27723
- this.releaseRowStmt = db.prepare(
27724
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27725
- );
27726
- this.releaseStaleClaimsStmt = db.prepare(
27727
- `UPDATE audit_events SET sync_claimed_at = NULL
27728
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27729
- );
27730
- this.partitionStmt = db.prepare(
27731
- `SELECT
27732
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27733
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27734
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27735
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27736
- COUNT(*) AS total
27737
- FROM audit_events
27738
- WHERE event_type IN (${TYPE_LIST})`
27739
- );
27740
- this.countsStmt = db.prepare(
27741
- `SELECT
27742
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27743
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27744
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27745
- FROM audit_events
27746
- WHERE event_type IN (${TYPE_LIST})`
27747
- );
27748
- this.captureSkipCountStmt = db.prepare(
27749
- `SELECT COUNT(*) AS skipped
27750
- FROM audit_events
27751
- WHERE synced_at = ${String(SKIPPED)}
27752
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27753
- );
27754
- this.fingerprintStmt = db.prepare(
27755
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27756
- FROM history_sync WHERE id = 1`
27757
- );
27758
- this.setFingerprintStmt = db.prepare(
27759
- `UPDATE history_sync
27760
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27761
- WHERE id = 1`
27762
- );
27763
- this.disownCapturesStmt = db.prepare(
27764
- `UPDATE audit_events SET outbox_owed = NULL
27765
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27766
- );
27767
- this.rearmStmt = db.prepare(
27768
- `UPDATE audit_events SET synced_at = NULL
27769
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27770
- );
27771
- this.claimStmt = db.prepare(
27772
- `UPDATE history_sync
27773
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27774
- WHERE id = 1
27775
- AND (owner_pid IS NULL
27776
- OR heartbeat_at IS NULL
27777
- OR heartbeat_at < :staleBefore
27778
- OR heartbeat_at > :now)`
27779
- );
27780
- this.heartbeatStmt = db.prepare(
27781
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27782
- );
27783
- this.releaseStmt = db.prepare(
27784
- `UPDATE history_sync
27785
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27786
- WHERE id = 1 AND owner_pid = :pid`
27787
- );
27788
- this.closeWindowStmt = db.prepare(
27789
- `UPDATE audit_events SET synced_at = :at
27790
- WHERE synced_at IS NULL
27791
- AND event_type IN (${TYPE_LIST})
27792
- AND started_at >= :attachedAt`
27793
- );
27794
- this.releaseBoundaryStmt = db.prepare(
27795
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27796
- );
27797
- this.freezeBoundaryStmt = db.prepare(
27798
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27799
- );
27800
- this.leaseStmt = db.prepare(
27801
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27802
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27803
- FROM history_sync WHERE id = 1`
27804
- );
27805
- this.inspectionsStmt = db.prepare(
27806
- `SELECT d.rule_id AS ruleId,
27807
- d.name AS ruleName,
27808
- d.version AS ruleVersion,
27809
- d.category AS category,
27810
- d.severity AS severity,
27811
- f.span_start AS spanStart,
27812
- f.span_end AS spanEnd,
27813
- f.masked_match AS maskedMatch,
27814
- f.action_taken AS actionTaken,
27815
- f.confidence AS confidence
27816
- FROM inspection_findings f
27817
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27818
- WHERE f.audit_event_id = :auditEventId
27819
- ORDER BY f.span_start, f.id`
27820
- );
27821
- }
27822
- db;
27823
- ensureRowStmt;
27824
- sessionsStmt;
27825
- rowsStmt;
27826
- stampStmt;
27827
- countsStmt;
27828
- fingerprintStmt;
27829
- setFingerprintStmt;
27830
- rearmStmt;
27831
- claimStmt;
27832
- heartbeatStmt;
27833
- releaseStmt;
27834
- leaseStmt;
27835
- inspectionsStmt;
27836
- closeWindowStmt;
27837
- releaseBoundaryStmt;
27838
- freezeBoundaryStmt;
27839
- captureRowsStmt;
27840
- markOwedStmt;
27841
- captureSkipCountStmt;
27842
- disownCapturesStmt;
27843
- partitionStmt;
27844
- claimRowStmt;
27845
- releaseRowStmt;
27846
- releaseStaleClaimsStmt;
27847
- /**
27848
- * The masked detections recorded against one tool call.
27849
- *
27850
- * These travel with the event because a tool call's target is not
27851
- * re-inspectable from the event alone — unlike a capture, where the text
27852
- * itself is re-scannable. What crosses is the masked match and the rule that
27853
- * produced it, never the value.
27854
- */
27855
- inspectionsFor(auditEventId) {
27856
- return allRows(this.inspectionsStmt, { auditEventId });
27857
- }
27858
- /**
27859
- * Sessions with structural rows still to send, oldest first.
27860
- *
27861
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27862
- * read. Anything recorded after the machine attached is the live forward
27863
- * path's to deliver; this drain exists for what was recorded before it, and a
27864
- * row both paths send is at best a duplicate request and at worst — for a
27865
- * session root — an overwrite of the inventory ids the live path resolved.
27866
- */
27867
- pendingSessions(limit, before) {
27868
- return allRows(this.sessionsStmt, { limit, before }).map(
27869
- (r) => r.sessionId
27870
- );
27871
- }
27872
- /** One session's undelivered structural rows within the backlog, root first. */
27873
- pendingRows(sessionId, limit, before) {
27874
- return allRows(this.rowsStmt, { sessionId, limit, before });
27875
- }
27876
- /**
27877
- * Captures this machine still owes the deployment, oldest first.
27878
- *
27879
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27880
- * by a time window — see captureRowsStmt for why a window could not express
27881
- * this. `before` is the grace window that leaves a just-recorded capture to
27882
- * the live path.
27883
- */
27884
- pendingCaptureRows(limit, before) {
27885
- return allRows(this.captureRowsStmt, { limit, before });
27886
- }
27887
- /**
27888
- * Record that a capture is OWED to the deployment.
27889
- *
27890
- * Written by the attached forward path when a live send did not confirm
27891
- * delivery, and read by the drain as the whole of its eligibility test. It is
27892
- * a fact rather than an inference: the machine was attached, the send did not
27893
- * land, so the row is owed — which no time window can state, because the same
27894
- * window that holds the rows a past attachment left owed also holds every
27895
- * capture recorded while the machine was DETACHED, and those were never
27896
- * offered to anyone.
27897
- *
27898
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27899
- * out of the drain's read.
27900
- */
27901
- markCaptureOwed(id) {
27902
- this.markOwedStmt.run({ id });
27903
- }
27904
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27905
- markSynced(ids, atMs) {
27906
- this.stampAll(ids, atMs);
27907
- }
27908
- /**
27909
- * Record that a row will never be sent.
27910
- *
27911
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27912
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27913
- * is retried; marking those would turn one outage into permanent data loss.
27914
- */
27915
- markSkipped(ids) {
27916
- this.stampAll(ids, SKIPPED);
27917
- }
27918
- eachInTransaction(ids, run) {
27919
- if (ids.length === 0) return;
27920
- withTransaction(
27921
- this.db,
27922
- () => {
27923
- for (const id of ids) run(id);
27924
- },
27925
- "IMMEDIATE"
27926
- );
27927
- }
27928
- stampAll(ids, value) {
27929
- if (ids.length === 0) return;
27930
- withTransaction(
27931
- this.db,
27932
- () => {
27933
- for (const id of ids) this.stampStmt.run({ at: value, id });
27934
- },
27935
- "IMMEDIATE"
27936
- );
27937
- }
27938
- /**
27939
- * Claim rows as in-flight.
27940
- *
27941
- * Advisory in exactly the sense the lease is: it records that a send is in
27942
- * progress so a surface can say so, and a lost claim costs a row showing as
27943
- * queued while it is actually being sent. It is not exclusion — the far side
27944
- * settles a duplicate on the row id.
27945
- */
27946
- claimRows(ids, atMs) {
27947
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27948
- }
27949
- /** Give back a claim without settling — the send failed, the row is queued again. */
27950
- releaseRows(ids) {
27951
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27952
- }
27953
- /**
27954
- * Clear claims older than `staleBefore`, and report how many were cleared.
27955
- *
27956
- * A process killed between claiming and settling leaves rows claimed with
27957
- * nothing left to settle them. Without this they read as "sending" for ever.
27958
- */
27959
- releaseStaleClaims(staleBefore) {
27960
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27961
- }
27962
- /**
27963
- * Every tracked row in exactly one delivery state.
27964
- *
27965
- * Takes no boundary on purpose. The boundary answers "what should the drain
27966
- * pick up now", which is a different question from "what state is this row
27967
- * in" — and a machine that has never attached has no boundary to pass, so
27968
- * requiring one would force a caller to invent one and report the whole store
27969
- * as queued.
27970
- */
27971
- partition() {
27972
- const row = getRow(this.partitionStmt, {});
27973
- return {
27974
- queued: row?.queued ?? 0,
27975
- inProgress: row?.inProgress ?? 0,
27976
- synced: row?.synced ?? 0,
27977
- failed: row?.failed ?? 0,
27978
- total: row?.total ?? 0
27979
- };
27980
- }
27981
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27982
- counts(before) {
27983
- const row = getRow(
27984
- this.countsStmt,
27985
- { before }
27986
- );
27987
- const captures = getRow(this.captureSkipCountStmt);
27988
- return {
27989
- pending: row?.pending ?? 0,
27990
- sent: row?.sent ?? 0,
27991
- skipped: row?.skipped ?? 0,
27992
- capturesSkipped: captures?.skipped ?? 0
27993
- };
27994
- }
27995
- /**
27996
- * The deployment the current stamps were made against, and where its backlog
27997
- * ends.
27998
- *
27999
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28000
- * machine that has never drained is — and every writer below seeds the row
28001
- * before it needs one, so nothing depends on this creating it. Keeping the
28002
- * write off the gate path matters because the gate runs on every pass while a
28003
- * write has to take the database's write lock.
28004
- */
28005
- deployment() {
28006
- const row = getRow(
28007
- this.fingerprintStmt
28008
- );
28009
- return {
28010
- fingerprint: row?.fingerprint ?? void 0,
28011
- backlogBefore: row?.backlogBefore ?? void 0
28012
- };
28013
- }
28014
- /**
28015
- * Point the ledger at a different deployment, discarding what it recorded
28016
- * about the previous one.
28017
- *
28018
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28019
- * machine has just left are undelivered as far as the new one is concerned.
28020
- * All three in one transaction, so a crash between them cannot leave stamps
28021
- * attributed to the wrong deployment, or a boundary that belongs to another.
28022
- *
28023
- * The boundary is written HERE and only here, which is what freezes it: a
28024
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28025
- * unchanged, so this never runs and the backlog does not widen back over rows
28026
- * the live path has since delivered.
28027
- */
28028
- rearmFor(fingerprint, backlogBefore) {
28029
- this.ensureRowStmt.run();
28030
- withTransaction(
28031
- this.db,
28032
- () => {
28033
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28034
- this.rearmStmt.run();
28035
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28036
- this.disownCapturesStmt.run();
28037
- }
28038
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28039
- },
28040
- "IMMEDIATE"
28041
- );
28042
- }
28043
- /**
28044
- * End the attached period: hand its rows to the live path, and release the
28045
- * boundary so the next attachment can freeze a new one.
28046
- *
28047
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28048
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28049
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28050
- * during the detached period, because the machine is not attached. Rows
28051
- * recorded in that window sit after the boundary and before the re-attach, so
28052
- * neither path takes them, and the pending count reports none outstanding.
28053
- *
28054
- * Stamping the attached window is not a claim that every one of those rows
28055
- * reached the deployment — the live path drops on failure and says so
28056
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28057
- * status quo: they sit outside the frozen boundary today and are equally never
28058
- * re-sent. Making it explicit is what lets the boundary move.
28059
- *
28060
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28061
- * window unstamped — that half-state would re-send the whole attached period
28062
- * on the next attach, which is the failure the boundary exists to prevent.
28063
- */
28064
- closeAttachedWindow(attachedAtMs, atMs) {
28065
- this.ensureRowStmt.run();
28066
- withTransaction(
28067
- this.db,
28068
- () => {
28069
- const row = getRow(this.fingerprintStmt);
28070
- const from = row?.backlogBefore ?? attachedAtMs;
28071
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28072
- this.releaseBoundaryStmt.run();
28073
- },
28074
- "IMMEDIATE"
28075
- );
28076
- }
28077
- /**
28078
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28079
- *
28080
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28081
- * different deployment and therefore discards what was delivered to the old
28082
- * one: here the recipient is the same, so everything already sent to it stays
28083
- * sent.
28084
- */
28085
- freezeBoundary(backlogBefore) {
28086
- this.ensureRowStmt.run();
28087
- this.freezeBoundaryStmt.run({ backlogBefore });
28088
- }
28089
- /** Take the claim, or report that someone live already holds it. */
28090
- claim(pid, host, nowMs, staleAfterMs) {
28091
- this.ensureRowStmt.run();
28092
- let taken = false;
28093
- withTransaction(
28094
- this.db,
28095
- () => {
28096
- const result = this.claimStmt.run({
28097
- pid,
28098
- host,
28099
- now: nowMs,
28100
- staleBefore: nowMs - staleAfterMs
28101
- });
28102
- taken = result.changes === 1;
28103
- },
28104
- "IMMEDIATE"
28105
- );
28106
- return taken;
28107
- }
28108
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28109
- heartbeat(pid, nowMs) {
28110
- this.heartbeatStmt.run({ now: nowMs, pid });
28111
- }
28112
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28113
- release(pid) {
28114
- this.releaseStmt.run({ pid });
28115
- }
28116
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28117
- lease() {
28118
- return getRow(this.leaseStmt);
28119
- }
28120
- };
28121
-
28122
28834
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28123
28835
  var SqliteInspectionDefinitionsRepository = class {
28124
28836
  constructor(db) {
@@ -28313,7 +29025,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28313
29025
  }
28314
29026
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28315
29027
  }
28316
- function readManagedSettings(paths = managedSettingsPaths()) {
29028
+ var testOnlyManagedPaths = null;
29029
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28317
29030
  for (const path of paths) {
28318
29031
  let text;
28319
29032
  try {
@@ -28348,6 +29061,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28348
29061
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28349
29062
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28350
29063
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29064
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28351
29065
  if (values.vaultConsent !== void 0) {
28352
29066
  merged.vaultConsent = values.vaultConsent ? (
28353
29067
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30793,7 +31507,7 @@ function toUtcDateString(ms) {
30793
31507
  return new Date(ms).toISOString().slice(0, 10);
30794
31508
  }
30795
31509
  function isTimeseriesSeverity(s) {
30796
- return s === "critical" || s === "high" || s === "medium";
31510
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30797
31511
  }
30798
31512
  var SqliteSecurityRepository = class {
30799
31513
  constructor(db, now = () => Date.now()) {
@@ -30855,7 +31569,7 @@ var SqliteSecurityRepository = class {
30855
31569
  ELSE 0
30856
31570
  END) AS open_at_rest
30857
31571
  FROM inspection_findings f
30858
- JOIN audit_events e ON e.id = f.audit_event_id
31572
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30859
31573
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30860
31574
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30861
31575
  ON latest.finding_key = f.finding_key
@@ -30922,12 +31636,16 @@ var SqliteSecurityRepository = class {
30922
31636
  const now = this.now();
30923
31637
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30924
31638
  const rows = this.findingsInRange(windowStart, now);
30925
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30926
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30927
- critical: 0,
30928
- high: 0,
30929
- medium: 0
30930
- }));
31639
+ const points = Array.from(
31640
+ { length: numBuckets },
31641
+ (_, i) => ({
31642
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31643
+ critical: 0,
31644
+ high: 0,
31645
+ medium: 0,
31646
+ low: 0
31647
+ })
31648
+ );
30931
31649
  for (const r of rows) {
30932
31650
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30933
31651
  const bucket = points[idx];
@@ -31077,7 +31795,7 @@ var SqliteSecurityRepository = class {
31077
31795
  this.db.prepare(
31078
31796
  `SELECT e.repo AS repo, count(*) AS c
31079
31797
  FROM inspection_findings f
31080
- JOIN audit_events e ON e.id = f.audit_event_id
31798
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31081
31799
  WHERE e.started_at >= :from AND e.started_at < :to
31082
31800
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31083
31801
  AND e.repo IS NOT NULL
@@ -31145,6 +31863,7 @@ var SqliteSecurityRepository = class {
31145
31863
  `SELECT f.finding_key AS finding_key,
31146
31864
  d.rule_id AS rule_id,
31147
31865
  d.severity AS severity,
31866
+ e.repo AS repo,
31148
31867
  e.file_path AS path,
31149
31868
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31150
31869
  latest.resolved_at AS latest_resolved_at
@@ -31164,6 +31883,7 @@ var SqliteSecurityRepository = class {
31164
31883
  const items = rows.map((r) => ({
31165
31884
  findingKey: r.finding_key,
31166
31885
  ruleId: r.rule_id,
31886
+ repo: r.repo ?? "",
31167
31887
  severity: r.severity,
31168
31888
  path: r.path ?? "",
31169
31889
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31173,15 +31893,68 @@ var SqliteSecurityRepository = class {
31173
31893
  }));
31174
31894
  return Promise.resolve({ items });
31175
31895
  }
31896
+ /**
31897
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31898
+ *
31899
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31900
+ * list: a secret committed three weeks ago and never rotated is still the most
31901
+ * important thing to fix, and any window hides it. It carried a "newest N
31902
+ * findings" cap and then a range; the first meant a different span on every
31903
+ * machine, and the second reported "no recommendations" over live exposure.
31904
+ *
31905
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31906
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31907
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31908
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31909
+ * The two answer different questions and only this one has to match a link.
31910
+ *
31911
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31912
+ * whole-store scope costs a grouped scan rather than a row per finding.
31913
+ */
31914
+ recommendationInputs() {
31915
+ const rows = allRows(
31916
+ this.db.prepare(
31917
+ `SELECT d.rule_id AS rule_id,
31918
+ d.category AS category,
31919
+ d.severity AS severity,
31920
+ COUNT(*) AS count
31921
+ FROM inspection_findings f
31922
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31923
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31924
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31925
+ ON latest.finding_key = f.finding_key
31926
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31927
+ AND e.event_type = 'code_change'
31928
+ AND (
31929
+ f.finding_key IS NULL
31930
+ OR latest.status IS NULL
31931
+ OR latest.status NOT IN ('resolved', 'dismissed')
31932
+ )
31933
+ GROUP BY d.rule_id, d.category, d.severity`
31934
+ )
31935
+ );
31936
+ return Promise.resolve(
31937
+ rows.map((r) => ({
31938
+ ruleId: r.rule_id,
31939
+ category: r.category,
31940
+ severity: r.severity,
31941
+ count: r.count
31942
+ }))
31943
+ );
31944
+ }
31176
31945
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31177
31946
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31178
31947
  // numeric and the JS aggregations bucket/split on ms directly.
31179
31948
  findingsInRange(fromMs, toMs) {
31180
31949
  const rows = allRows(
31181
31950
  this.db.prepare(
31182
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31951
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31952
+ // joined for `severity`, so they are two more columns off a row this read
31953
+ // already fetches. They feed the recommended-actions rollup.
31954
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31955
+ d.rule_id AS rule_id, d.category AS category
31183
31956
  FROM inspection_findings f
31184
- JOIN audit_events e ON e.id = f.audit_event_id
31957
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31185
31958
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31186
31959
  WHERE e.started_at >= :from AND e.started_at < :to
31187
31960
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31192,7 +31965,9 @@ var SqliteSecurityRepository = class {
31192
31965
  return rows.map((r) => ({
31193
31966
  occurredAt: r.occurred_at,
31194
31967
  severity: r.severity,
31195
- actionTaken: r.action_taken
31968
+ actionTaken: r.action_taken,
31969
+ ruleId: r.rule_id,
31970
+ category: r.category
31196
31971
  }));
31197
31972
  }
31198
31973
  };
@@ -32020,6 +32795,7 @@ function openWithPragmas(file2) {
32020
32795
  db.exec("PRAGMA journal_mode = WAL");
32021
32796
  db.exec("PRAGMA busy_timeout = 2000");
32022
32797
  db.exec("PRAGMA foreign_keys = ON");
32798
+ registerSqlFunctions(db);
32023
32799
  } catch (err) {
32024
32800
  closeQuietly(db);
32025
32801
  throw err;
@@ -32049,7 +32825,7 @@ function backupLegacyStore(db, file2) {
32049
32825
  discardStore(file2, backup);
32050
32826
  return backup;
32051
32827
  }
32052
- function openAndInitialize(file2, base) {
32828
+ function openAndInitialize(file2, base, skipTags) {
32053
32829
  let db = openWithPragmas(file2);
32054
32830
  try {
32055
32831
  if (isForeignSqliteLineage(db)) {
@@ -32059,7 +32835,7 @@ function openAndInitialize(file2, base) {
32059
32835
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32060
32836
  );
32061
32837
  }
32062
- applyMigrations(db, file2);
32838
+ applyMigrations(db, file2, { skipTags });
32063
32839
  tightenPerms(file2);
32064
32840
  const policies = new SqlitePoliciesRepository(db);
32065
32841
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32074,6 +32850,7 @@ function openAndInitialize(file2, base) {
32074
32850
  exceptions: new SqliteExceptionsRepository(db),
32075
32851
  resolutions: new SqliteResolutionsRepository(db),
32076
32852
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32853
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32077
32854
  security: new SqliteSecurityRepository(db),
32078
32855
  detections: new SqliteDetectionsRepository(db),
32079
32856
  shares: new SqliteSharesRepository(db),
@@ -32096,7 +32873,8 @@ function openAndInitialize(file2, base) {
32096
32873
  throw err;
32097
32874
  }
32098
32875
  }
32099
- function openLocalDatabase(dir) {
32876
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32877
+ function openLocalDatabase(dir, options = {}) {
32100
32878
  ensureDataDirSync(dir);
32101
32879
  const file2 = join7(dir, DB_FILENAME);
32102
32880
  reapStalePartials(file2);
@@ -32108,6 +32886,7 @@ function openLocalDatabase(dir) {
32108
32886
  installedPacks,
32109
32887
  scanLedger,
32110
32888
  historySync,
32889
+ bodyRetention,
32111
32890
  secretVault,
32112
32891
  exceptions,
32113
32892
  resolutions,
@@ -32131,7 +32910,8 @@ function openLocalDatabase(dir) {
32131
32910
  // `dir` is always `<base>/data` — every caller resolves it through
32132
32911
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32133
32912
  // settings/ and data/, and the pack-policy floor needs both halves.
32134
- dirname2(dir)
32913
+ dirname2(dir),
32914
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32135
32915
  );
32136
32916
  function captureRowId(event) {
32137
32917
  return captureId(
@@ -32324,6 +33104,7 @@ function openLocalDatabase(dir) {
32324
33104
  installedPacks,
32325
33105
  scanLedger,
32326
33106
  historySync,
33107
+ bodyRetention,
32327
33108
  secretVault,
32328
33109
  exceptions,
32329
33110
  resolutions,
@@ -32362,6 +33143,70 @@ function openLocalDatabase(dir) {
32362
33143
  };
32363
33144
  }
32364
33145
 
33146
+ // ../../packages/persistence/src/egress-wire.ts
33147
+ import { createHash as createHash3 } from "crypto";
33148
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33149
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33150
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33151
+ var FILE_URL = /^file:\/\//i;
33152
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33153
+ var SLASH = "/".charCodeAt(0);
33154
+ var GIT_SUFFIX = ".git";
33155
+ function trimSlashes(path) {
33156
+ let start = 0;
33157
+ let end = path.length;
33158
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33159
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33160
+ return path.slice(start, end);
33161
+ }
33162
+ function canonicalGitUrl(url2) {
33163
+ const trimmed = url2.trim();
33164
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33165
+ const scheme = SCHEME_FORM.exec(trimmed);
33166
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33167
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33168
+ if (host === void 0) return trimmed;
33169
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33170
+ const bare = trimSlashes(path);
33171
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33172
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33173
+ }
33174
+ function hashProjectKey(projectKey) {
33175
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33176
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33177
+ }
33178
+ function toIngestHit(hit) {
33179
+ return {
33180
+ host: hit.host,
33181
+ kind: hit.kind,
33182
+ name: hit.name,
33183
+ category: hit.category,
33184
+ trust: hit.trust,
33185
+ network: hit.network,
33186
+ method: hit.method,
33187
+ transport: hit.transport,
33188
+ url: hit.url,
33189
+ template: hit.template,
33190
+ dataClass: hit.dataClass,
33191
+ site: {
33192
+ file: hit.site.file,
33193
+ line: hit.site.line,
33194
+ dynamic: hit.site.dynamic,
33195
+ vendored: hit.site.vendored
33196
+ }
33197
+ };
33198
+ }
33199
+ function toEgressIngestRequest(input2) {
33200
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33201
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33202
+ return {
33203
+ projectKey: hashProjectKey(input2.projectKey),
33204
+ project: input2.project,
33205
+ reconcile,
33206
+ hits: hits.map(toIngestHit)
33207
+ };
33208
+ }
33209
+
32365
33210
  // ../../packages/persistence/src/exception-policy.ts
32366
33211
  var UserGrantPolicyProvider = class {
32367
33212
  #exceptions;
@@ -32383,13 +33228,13 @@ var UserGrantPolicyProvider = class {
32383
33228
  };
32384
33229
 
32385
33230
  // ../../packages/persistence/src/finding-key.ts
32386
- import { createHash as createHash3 } from "crypto";
33231
+ import { createHash as createHash4 } from "crypto";
32387
33232
  function normalizeFilePath(filePath) {
32388
33233
  return filePath.replaceAll("\\", "/");
32389
33234
  }
32390
33235
  function computeFindingKey(input2) {
32391
33236
  const normalizedPath = normalizeFilePath(input2.filePath);
32392
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
33237
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32393
33238
  }
32394
33239
 
32395
33240
  // ../../packages/persistence/src/fingerprint.ts
@@ -32515,14 +33360,50 @@ function fingerprintValue(key, raw) {
32515
33360
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32516
33361
  }
32517
33362
 
32518
- // ../../packages/persistence/src/history-preview.ts
32519
- import { existsSync as existsSync4 } from "fs";
33363
+ // ../../packages/persistence/src/forward-health.ts
33364
+ import { readFileSync as readFileSync7 } from "fs";
32520
33365
  import { join as join9 } from "path";
33366
+ var FAILURES = /* @__PURE__ */ new Set([
33367
+ "unauthorized",
33368
+ "forbidden",
33369
+ "unreachable"
33370
+ ]);
33371
+ var BREAKER_COOLDOWN_MS = 3e4;
33372
+ function parseForwardHealth(raw, nowMs) {
33373
+ try {
33374
+ const parsed2 = JSON.parse(raw);
33375
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33376
+ const record2 = parsed2;
33377
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33378
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33379
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33380
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33381
+ } catch {
33382
+ return null;
33383
+ }
33384
+ }
33385
+ function isForwardPaused(health, nowMs) {
33386
+ const openedAtMs = health?.openedAtMs ?? null;
33387
+ if (openedAtMs === null) return false;
33388
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33389
+ }
33390
+
33391
+ // ../../packages/persistence/src/history-backfill.ts
33392
+ import { existsSync as existsSync4 } from "fs";
33393
+ import { join as join10 } from "path";
33394
+
33395
+ // ../../packages/persistence/src/history-preview.ts
33396
+ import { existsSync as existsSync5 } from "fs";
33397
+ import { join as join11 } from "path";
32521
33398
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32522
33399
 
33400
+ // ../../packages/persistence/src/history-sync-state.ts
33401
+ import { readFileSync as readFileSync8 } from "fs";
33402
+ import { join as join12 } from "path";
33403
+
32523
33404
  // ../../packages/persistence/src/store-symlinks.ts
32524
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32525
- import { dirname as dirname3, join as join10, resolve } from "path";
33405
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33406
+ import { dirname as dirname3, join as join13, resolve } from "path";
32526
33407
  var STORE_DB = "the store database (including the prompt corpus)";
32527
33408
  var STORE_SETTINGS = "your settings file";
32528
33409
  function storeContents(home) {
@@ -32531,7 +33412,7 @@ function storeContents(home) {
32531
33412
  [settingsDir(home), STORE_SETTINGS],
32532
33413
  [dataDir(home), STORE_DB],
32533
33414
  [keysDir(home), "the vault key"],
32534
- [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
33415
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32535
33416
  [dbPath(home), STORE_DB]
32536
33417
  ]);
32537
33418
  }
@@ -32546,7 +33427,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
32546
33427
  holds,
32547
33428
  // existsSync follows the link, so a target that is gone reads as
32548
33429
  // absent here while lstat above still sees the link itself.
32549
- missing: !existsSync5(path),
33430
+ missing: !existsSync6(path),
32550
33431
  mode: targetMode(path, platform2)
32551
33432
  }
32552
33433
  ];
@@ -32682,8 +33563,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32682
33563
  // ../../packages/persistence/src/vault/key-provider.ts
32683
33564
  import { execFileSync } from "child_process";
32684
33565
  import { randomBytes as randomBytes2 } from "crypto";
32685
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32686
- import { join as join11 } from "path";
33566
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33567
+ import { join as join14 } from "path";
32687
33568
  var VAULT_OCCUPANT_REASON = {
32688
33569
  symlink: "the path is a symlink; remove it so a keyring can be created",
32689
33570
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32782,7 +33663,7 @@ function claimRotationLock(lock, owner) {
32782
33663
  throw asError(err);
32783
33664
  }
32784
33665
  try {
32785
- writeFileSync3(join11(lock, LOCK_OWNER_FILE), `${owner}
33666
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32786
33667
  `, { mode: DATA_FILE_MODE });
32787
33668
  return true;
32788
33669
  } catch (err) {
@@ -32791,7 +33672,7 @@ function claimRotationLock(lock, owner) {
32791
33672
  }
32792
33673
  }
32793
33674
  function acquireRotationLock(keysDir2) {
32794
- const lock = join11(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33675
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32795
33676
  const owner = randomBytes2(16).toString("hex");
32796
33677
  if (claimRotationLock(lock, owner)) return { lock, owner };
32797
33678
  let held;
@@ -32818,7 +33699,7 @@ function acquireRotationLock(keysDir2) {
32818
33699
  }
32819
33700
  function releaseRotationLock(lease) {
32820
33701
  try {
32821
- if (readFileSync7(join11(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33702
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
32822
33703
  } catch {
32823
33704
  return;
32824
33705
  }
@@ -32839,7 +33720,7 @@ var FileKeyProvider = class {
32839
33720
  this.#keysDir = keysDir2;
32840
33721
  }
32841
33722
  get filePath() {
32842
- return join11(this.#keysDir, VAULT_KEY_FILENAME);
33723
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
32843
33724
  }
32844
33725
  loadOrCreate() {
32845
33726
  return asAsync(() => {
@@ -32869,7 +33750,7 @@ var FileKeyProvider = class {
32869
33750
  #read() {
32870
33751
  let raw;
32871
33752
  try {
32872
- raw = readFileSync7(this.filePath, "utf8");
33753
+ raw = readFileSync9(this.filePath, "utf8");
32873
33754
  } catch (err) {
32874
33755
  if (err.code === "ENOENT") return null;
32875
33756
  throw err instanceof Error ? err : new Error(String(err));
@@ -33504,13 +34385,13 @@ var SecretVault = class {
33504
34385
  };
33505
34386
 
33506
34387
  // ../../packages/persistence/src/warn-era-cap.ts
33507
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
33508
- import { join as join12 } from "path";
34388
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
34389
+ import { join as join15 } from "path";
33509
34390
  var MARKER = "warn-era-capped";
33510
34391
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33511
34392
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33512
- const marker = join12(dataDir2, MARKER);
33513
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
34393
+ const marker = join15(dataDir2, MARKER);
34394
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33514
34395
  const capped = db.policies.capCategoryActions();
33515
34396
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
33516
34397
  `, { mode: DATA_FILE_MODE });
@@ -33569,8 +34450,8 @@ function resolveProvider() {
33569
34450
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33570
34451
  try {
33571
34452
  ensureLayoutDirSync(base);
33572
- const settingsFile = join13(settingsDir(base), "settings.json");
33573
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
34453
+ const settingsFile = join16(settingsDir(base), "settings.json");
34454
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33574
34455
  } catch {
33575
34456
  }
33576
34457
  migrateLegacyLayout(base);
@@ -33593,9 +34474,9 @@ function resolveProviderSafe(resolveProviderFn) {
33593
34474
  }
33594
34475
 
33595
34476
  // ../../packages/plugin-sdk/src/config-inventory.ts
33596
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34477
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33597
34478
  import { homedir as homedir2 } from "os";
33598
- import { basename as basename3, join as join15 } from "path";
34479
+ import { basename as basename3, join as join18 } from "path";
33599
34480
 
33600
34481
  // ../../packages/detections/src/egress/registry.ts
33601
34482
  var EXTRACTOR_VERSION = "1";
@@ -36684,8 +37565,8 @@ function bundledDetections() {
36684
37565
  }
36685
37566
 
36686
37567
  // ../../packages/plugin-sdk/src/repo.ts
36687
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36688
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
37568
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
37569
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
36689
37570
  function resolveRepo(cwd) {
36690
37571
  try {
36691
37572
  const root = findGitRoot(cwd);
@@ -36700,36 +37581,36 @@ function resolveRepo(cwd) {
36700
37581
  function findGitRoot(start) {
36701
37582
  let dir = start;
36702
37583
  for (; ; ) {
36703
- if (existsSync8(join14(dir, ".git"))) return dir;
37584
+ if (existsSync9(join17(dir, ".git"))) return dir;
36704
37585
  const parent = dirname4(dir);
36705
37586
  if (parent === dir) return void 0;
36706
37587
  dir = parent;
36707
37588
  }
36708
37589
  }
36709
37590
  function resolveGitContext(root) {
36710
- const dotGit = join14(root, ".git");
37591
+ const dotGit = join17(root, ".git");
36711
37592
  try {
36712
37593
  if (statSync6(dotGit).isDirectory()) {
36713
- return { configPath: join14(dotGit, "config"), headRoot: root };
37594
+ return { configPath: join17(dotGit, "config"), headRoot: root };
36714
37595
  }
36715
37596
  } catch {
36716
37597
  return void 0;
36717
37598
  }
36718
37599
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36719
37600
  if (!target) return void 0;
36720
- const gitdir = isAbsolute(target) ? target : join14(root, target);
36721
- if (existsSync8(join14(gitdir, "config"))) {
36722
- return { configPath: join14(gitdir, "config"), headRoot: root };
37601
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
37602
+ if (existsSync9(join17(gitdir, "config"))) {
37603
+ return { configPath: join17(gitdir, "config"), headRoot: root };
36723
37604
  }
36724
- const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
37605
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
36725
37606
  if (!commonRaw) return void 0;
36726
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
37607
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
36727
37608
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36728
- return { configPath: join14(commonGitDir, "config"), headRoot };
37609
+ return { configPath: join17(commonGitDir, "config"), headRoot };
36729
37610
  }
36730
37611
  function safeRead(path) {
36731
37612
  try {
36732
- return readFileSync8(path, "utf8");
37613
+ return readFileSync10(path, "utf8");
36733
37614
  } catch {
36734
37615
  return void 0;
36735
37616
  }
@@ -36767,9 +37648,9 @@ function slugFromUrl(url2) {
36767
37648
  }
36768
37649
 
36769
37650
  // ../../packages/plugin-sdk/src/events.ts
36770
- import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
37651
+ import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36771
37652
  function contentHashOf(text) {
36772
- return createHash4("sha256").update(text).digest("hex");
37653
+ return createHash5("sha256").update(text).digest("hex");
36773
37654
  }
36774
37655
  function buildIngestEvent(input2) {
36775
37656
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -36795,7 +37676,7 @@ function buildIngestEvent(input2) {
36795
37676
  }
36796
37677
 
36797
37678
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36798
- import { existsSync as existsSync9 } from "fs";
37679
+ import { existsSync as existsSync10 } from "fs";
36799
37680
  import { fileURLToPath } from "url";
36800
37681
  import { Worker } from "worker_threads";
36801
37682
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -36809,7 +37690,7 @@ function resolveWorkerUrl() {
36809
37690
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
36810
37691
  const candidate = new URL(name, import.meta.url);
36811
37692
  try {
36812
- if (existsSync9(fileURLToPath(candidate))) {
37693
+ if (existsSync10(fileURLToPath(candidate))) {
36813
37694
  resolvedWorkerUrl = candidate;
36814
37695
  return candidate;
36815
37696
  }
@@ -37272,13 +38153,9 @@ function createGuardedScanner(partition, gateway, opts) {
37272
38153
  };
37273
38154
  }
37274
38155
 
37275
- // ../../packages/plugin-sdk/src/ignore-layers.ts
37276
- var import_ignore = __toESM(require_ignore(), 1);
37277
- import { readFileSync as readFileSync10 } from "fs";
37278
- import { join as join16 } from "path";
37279
-
37280
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
37281
- import { arch, hostname as hostname4, platform, release } from "os";
38156
+ // ../../packages/plugin-sdk/src/host-floor.ts
38157
+ import { readFileSync as readFileSync13 } from "fs";
38158
+ import { join as join20 } from "path";
37282
38159
 
37283
38160
  // ../../packages/plugin-sdk/src/model-governance.ts
37284
38161
  import {
@@ -37286,11 +38163,11 @@ import {
37286
38163
  fstatSync,
37287
38164
  mkdirSync as mkdirSync2,
37288
38165
  openSync as openSync2,
37289
- readFileSync as readFileSync11,
38166
+ readFileSync as readFileSync12,
37290
38167
  readSync,
37291
38168
  writeFileSync as writeFileSync5
37292
38169
  } from "fs";
37293
- import { join as join17 } from "path";
38170
+ import { join as join19 } from "path";
37294
38171
  var DATE_SUFFIX = /-\d{8}$/;
37295
38172
  function normalizeModelId(model) {
37296
38173
  return model.trim().toLowerCase().replace(DATE_SUFFIX, "");
@@ -37349,9 +38226,35 @@ function buildModelRefusalEvent(input2) {
37349
38226
  };
37350
38227
  }
37351
38228
 
38229
+ // ../../packages/plugin-sdk/src/host-floor.ts
38230
+ var HOST_FEATURE = {
38231
+ ModelSwitch: "model-switch",
38232
+ VaultPointerDisplay: "vault-pointer-display"
38233
+ };
38234
+ var HOST_FLOORS = {
38235
+ [HOST_FEATURE.ModelSwitch]: {
38236
+ label: "model-switch protection",
38237
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
38238
+ since: "2.1.251"
38239
+ },
38240
+ [HOST_FEATURE.VaultPointerDisplay]: {
38241
+ label: "vault pointer display",
38242
+ hookEvents: ["MessageDisplay"],
38243
+ since: "2.1.152"
38244
+ }
38245
+ };
38246
+
38247
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
38248
+ var import_ignore = __toESM(require_ignore(), 1);
38249
+ import { readFileSync as readFileSync14 } from "fs";
38250
+ import { join as join21 } from "path";
38251
+
38252
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
38253
+ import { arch, hostname as hostname4, platform, release } from "os";
38254
+
37352
38255
  // ../../packages/plugin-sdk/src/nudge.ts
37353
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
37354
- import { join as join18 } from "path";
38256
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
38257
+ import { join as join22 } from "path";
37355
38258
 
37356
38259
  // ../../packages/plugin-sdk/src/paths.ts
37357
38260
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37393,8 +38296,8 @@ function createPolicyResolver(bundle) {
37393
38296
  }
37394
38297
 
37395
38298
  // ../../packages/plugin-sdk/src/project-files.ts
37396
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
37397
- import { basename as basename5, join as join19 } from "path";
38299
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
38300
+ import { basename as basename5, join as join23 } from "path";
37398
38301
 
37399
38302
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37400
38303
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37425,6 +38328,14 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
37425
38328
  // ../../packages/plugin-sdk/src/runtime.ts
37426
38329
  import { randomUUID as randomUUID14 } from "crypto";
37427
38330
  var ENFORCEMENT_CEILING_ENABLED = false;
38331
+ function applyEnforcementCeiling(action, policyMode, enabled) {
38332
+ if (!enabled || policyMode !== "warn") return action;
38333
+ return action === "block" || action === "redact" ? "warn" : action;
38334
+ }
38335
+ function resolveEnforcedAction(action, opts) {
38336
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
38337
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
38338
+ }
37428
38339
  function startTiming() {
37429
38340
  try {
37430
38341
  return performance.now();
@@ -37461,7 +38372,7 @@ function createPluginRuntime(gateway, settings, opts) {
37461
38372
  bundlesPacked = true;
37462
38373
  }
37463
38374
  const policyMode = settings.policy;
37464
- const redactFallback = settings.redactFallback;
38375
+ let redactFallback = settings.redactFallback;
37465
38376
  const dataDir2 = opts?.dataDir;
37466
38377
  let rules = [];
37467
38378
  let scanner;
@@ -37505,6 +38416,7 @@ function createPluginRuntime(gateway, settings, opts) {
37505
38416
  rules = [...verified, ...unverified];
37506
38417
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
37507
38418
  bundleExceptions = bundle.exceptions ?? [];
38419
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
37508
38420
  initialized = true;
37509
38421
  }
37510
38422
  let cachedKey;
@@ -37533,21 +38445,23 @@ function createPluginRuntime(gateway, settings, opts) {
37533
38445
  }
37534
38446
  function actionForFinding(finding, excepted, rewritable = true) {
37535
38447
  if (excepted?.has(finding)) return "allow";
37536
- const action = resolveAction(finding.ruleId, finding.category);
37537
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
37538
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
37539
- return "warn";
37540
- }
37541
- return action;
38448
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
38449
+ policyMode,
38450
+ redactFallback,
38451
+ rewritable,
38452
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
38453
+ });
37542
38454
  }
37543
38455
  function decide(findings, text, excepted, rewritable = true) {
37544
38456
  if (findings.length === 0) return { action: "log", text, findings: [] };
37545
38457
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38458
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38459
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
37546
38460
  let worst = "log";
37547
38461
  for (const finding of findings) {
37548
38462
  worst = strongerAction(worst, actionFor(finding));
37549
38463
  }
37550
- if (worst === "block") return { action: "block", text: null, findings };
38464
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
37551
38465
  if (worst === "redact") {
37552
38466
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
37553
38467
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -37557,9 +38471,13 @@ function createPluginRuntime(gateway, settings, opts) {
37557
38471
  findings,
37558
38472
  enforcedFindings: redactFindings,
37559
38473
  reversibleFindings
38474
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38475
+ // CAPTURE, so on an unrewritable field every redact has already become
38476
+ // the fallback and this branch is unreachable. Spreading it would read
38477
+ // as a case that can happen.
37560
38478
  };
37561
38479
  }
37562
- return { action: worst, text, findings };
38480
+ return { action: worst, text, findings, ...degraded };
37563
38481
  }
37564
38482
  function fingerprintOf(key, finding, cache) {
37565
38483
  let fp = cache.get(finding);
@@ -37688,8 +38606,8 @@ function createPluginRuntime(gateway, settings, opts) {
37688
38606
  };
37689
38607
  }
37690
38608
  }
37691
- async function processText(text, context) {
37692
- return (await evaluate(text, context, {})).decision;
38609
+ async function processText(text, context, opts2 = {}) {
38610
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
37693
38611
  }
37694
38612
  async function capture(input2, opts2 = {}) {
37695
38613
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -37712,10 +38630,12 @@ function createPluginRuntime(gateway, settings, opts) {
37712
38630
  );
37713
38631
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
37714
38632
  const inspectionMs = elapsedMs(timingStartedAt);
37715
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
38633
+ const redactDegradedTo = decision.redactDegradedTo;
38634
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
37716
38635
  ...input2.metadata,
37717
38636
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
37718
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
38637
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
38638
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
37719
38639
  } : input2.metadata;
37720
38640
  const event = buildIngestEvent({
37721
38641
  kind: input2.kind,
@@ -37787,7 +38707,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37787
38707
 
37788
38708
  // ../../packages/plugin-sdk/src/throttle.ts
37789
38709
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37790
- import { join as join20 } from "path";
38710
+ import { join as join24 } from "path";
37791
38711
 
37792
38712
  // ../../packages/plugin-sdk/src/tokenize.ts
37793
38713
  function redactedPlaceholder(category) {
@@ -38107,17 +39027,17 @@ var UNOPENABLE_VAULT = {
38107
39027
 
38108
39028
  // src/protocol/marker.ts
38109
39029
  import { randomBytes as randomBytes4 } from "crypto";
38110
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync13, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "fs";
38111
- import { join as join21 } from "path";
39030
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync16, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "fs";
39031
+ import { join as join25 } from "path";
38112
39032
  var MARKER_FILE = "protocol-marker";
38113
39033
  function mintMarker() {
38114
39034
  return randomBytes4(8).toString("hex");
38115
39035
  }
38116
39036
  function sessionProtocolMarker(dataDir2, sessionId) {
38117
39037
  if (!sessionId) return mintMarker();
38118
- const path = join21(dataDir2, MARKER_FILE);
39038
+ const path = join25(dataDir2, MARKER_FILE);
38119
39039
  try {
38120
- const stored = JSON.parse(readFileSync13(path, "utf8"));
39040
+ const stored = JSON.parse(readFileSync16(path, "utf8"));
38121
39041
  if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
38122
39042
  return stored.marker;
38123
39043
  }
@@ -38126,7 +39046,7 @@ function sessionProtocolMarker(dataDir2, sessionId) {
38126
39046
  const marker = mintMarker();
38127
39047
  try {
38128
39048
  mkdirSync5(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
38129
- const tmp = join21(dataDir2, `${MARKER_FILE}.tmp`);
39049
+ const tmp = join25(dataDir2, `${MARKER_FILE}.tmp`);
38130
39050
  writeFileSync8(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
38131
39051
  renameSync5(tmp, path);
38132
39052
  } catch {
@@ -38181,9 +39101,9 @@ function userDisclosure(opts) {
38181
39101
 
38182
39102
  // src/hooks/model-guard.ts
38183
39103
  import { randomUUID as randomUUID15 } from "crypto";
38184
- import { readFileSync as readFileSync14, statSync as statSync9 } from "fs";
39104
+ import { readFileSync as readFileSync17, statSync as statSync9 } from "fs";
38185
39105
  import { homedir as homedir3 } from "os";
38186
- import { dirname as dirname6, join as join22 } from "path";
39106
+ import { dirname as dirname6, join as join26 } from "path";
38187
39107
  var SUBAGENT_TOOLS = /* @__PURE__ */ new Set(["Task", "Agent"]);
38188
39108
  var SAFE_SUBAGENT_TYPE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
38189
39109
  function projectAgentsRoot(from) {
@@ -38193,7 +39113,7 @@ function projectAgentsRoot(from) {
38193
39113
  for (let depth = 0; depth < 24; depth += 1) {
38194
39114
  if (dir === home) return void 0;
38195
39115
  try {
38196
- if (statSync9(join22(dir, ".claude", "agents")).isDirectory()) return dir;
39116
+ if (statSync9(join26(dir, ".claude", "agents")).isDirectory()) return dir;
38197
39117
  } catch {
38198
39118
  }
38199
39119
  const parent = dirname6(dir);
@@ -38209,7 +39129,7 @@ function modelFromAgentDefinition(subagentType, cwd) {
38209
39129
  );
38210
39130
  for (const root of roots) {
38211
39131
  try {
38212
- const raw = readFileSync14(join22(root, ".claude", "agents", `${subagentType}.md`), "utf8");
39132
+ const raw = readFileSync17(join26(root, ".claude", "agents", `${subagentType}.md`), "utf8");
38213
39133
  const lines = raw.split("\n");
38214
39134
  if (lines[0]?.trim() !== "---") continue;
38215
39135
  for (const line of lines.slice(1)) {
@@ -38406,7 +39326,7 @@ function exceptionPointer(references) {
38406
39326
  }
38407
39327
 
38408
39328
  // src/hooks/pre-tool-use-decision.ts
38409
- var EXECUTABLE_REDACT_NOTE = "Masking inside an executable command would silently change what runs, so a redact policy blocks it instead.";
39329
+ var EXECUTABLE_REDACT_NOTE = "Masking inside an executable command would silently change what runs, so masking in place was not possible and this workspace\u2019s fallback for that case is to block.";
38410
39330
  var UNREDACTABLE_NOTE = "The redacted form of this input was unavailable, so the call is blocked rather than sent unmasked.";
38411
39331
  function pointerCategory(token) {
38412
39332
  const match = /^\[\[aka:([a-z_]+):/.exec(token);
@@ -38423,9 +39343,8 @@ async function decidePreToolUse(toolName, toolInput, scanned, tokenizeField) {
38423
39343
  let updatedInput = null;
38424
39344
  const realized = { pointers: [], degraded: [] };
38425
39345
  for (const { spec, text, result } of scanned) {
38426
- const escalate = result.action === "redact" && spec.executable;
38427
- if (escalate) escalated = true;
38428
- const action = escalate ? "block" : result.action;
39346
+ if (result.redactDegradedTo === "block") escalated = true;
39347
+ const action = result.action;
38429
39348
  if (action === "block") {
38430
39349
  for (const finding of result.findings) blockedRules.add(finding.ruleId);
38431
39350
  if (result.blockedReferences) blockedReferences.push(...result.blockedReferences);
@@ -38640,45 +39559,8 @@ function baseMetadata(input2) {
38640
39559
  }
38641
39560
 
38642
39561
  // src/hooks/store-health.ts
38643
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync20, writeFileSync as writeFileSync9 } from "fs";
38644
- import { dirname as dirname7, join as join29 } from "path";
38645
-
38646
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
38647
- import { createHash as createHash5 } from "crypto";
38648
- function hashProjectKey(projectKey) {
38649
- return createHash5("sha256").update(projectKey, "utf8").digest("hex");
38650
- }
38651
- function toIngestHit(hit) {
38652
- return {
38653
- host: hit.host,
38654
- kind: hit.kind,
38655
- name: hit.name,
38656
- category: hit.category,
38657
- trust: hit.trust,
38658
- network: hit.network,
38659
- method: hit.method,
38660
- transport: hit.transport,
38661
- url: hit.url,
38662
- template: hit.template,
38663
- dataClass: hit.dataClass,
38664
- site: {
38665
- file: hit.site.file,
38666
- line: hit.site.line,
38667
- dynamic: hit.site.dynamic,
38668
- vendored: hit.site.vendored
38669
- }
38670
- };
38671
- }
38672
- function toEgressIngestRequest(input2) {
38673
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
38674
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
38675
- return {
38676
- projectKey: hashProjectKey(input2.projectKey),
38677
- project: input2.project,
38678
- reconcile,
38679
- hits: hits.map(toIngestHit)
38680
- };
38681
- }
39562
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
39563
+ import { dirname as dirname7, join as join32 } from "path";
38682
39564
 
38683
39565
  // ../../packages/remote/src/http.ts
38684
39566
  import { request as httpRequest } from "http";
@@ -38863,10 +39745,10 @@ function parsed(schema, body, route) {
38863
39745
  }
38864
39746
  function withoutTrailingSlashes(endpoint) {
38865
39747
  let end = endpoint.length;
38866
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
39748
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
38867
39749
  return endpoint.slice(0, end);
38868
39750
  }
38869
- var SLASH = "/".charCodeAt(0);
39751
+ var SLASH2 = "/".charCodeAt(0);
38870
39752
  function createRemoteClient(options) {
38871
39753
  const base = withoutTrailingSlashes(options.endpoint);
38872
39754
  const url2 = (route) => `${base}${route}`;
@@ -38959,6 +39841,7 @@ function createRemoteClient(options) {
38959
39841
  url: url2(ROUTES.shares),
38960
39842
  body: JSON.stringify(validated.data)
38961
39843
  });
39844
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
38962
39845
  okBody(response);
38963
39846
  },
38964
39847
  async pollCommand() {
@@ -38981,19 +39864,51 @@ function createRemoteClient(options) {
38981
39864
  };
38982
39865
  }
38983
39866
 
38984
- // ../../packages/plugin-runtime/src/attached/failure.ts
39867
+ // ../../packages/remote/src/failure-kind.ts
38985
39868
  function statusOf(err) {
38986
39869
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
38987
39870
  const { status } = err;
38988
39871
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
38989
39872
  return status >= 100 && status <= 599 ? status : null;
38990
39873
  }
38991
- function classifyFailure(err) {
38992
- switch (statusOf(err)) {
39874
+ function nameOf(err) {
39875
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
39876
+ return typeof err.name === "string" ? err.name : null;
39877
+ }
39878
+ function classifyRemoteFailure(err) {
39879
+ switch (nameOf(err)) {
39880
+ case "RemoteRouteAbsent":
39881
+ return "route-absent";
39882
+ case "RemoteRequestInvalid":
39883
+ return "invalid-request";
39884
+ case "RemoteResponseInvalid":
39885
+ return "rejected";
39886
+ default:
39887
+ break;
39888
+ }
39889
+ const status = statusOf(err);
39890
+ if (status === null) return "unreachable";
39891
+ switch (status) {
38993
39892
  case 401:
38994
39893
  return "unauthorized";
38995
39894
  case 403:
38996
39895
  return "forbidden";
39896
+ case 429:
39897
+ return "unreachable";
39898
+ case 404:
39899
+ return "unreachable";
39900
+ default:
39901
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
39902
+ }
39903
+ }
39904
+
39905
+ // ../../packages/plugin-runtime/src/attached/failure.ts
39906
+ function classifyFailure(err) {
39907
+ switch (classifyRemoteFailure(err)) {
39908
+ case "unauthorized":
39909
+ return "unauthorized";
39910
+ case "forbidden":
39911
+ return "forbidden";
38997
39912
  default:
38998
39913
  return "unreachable";
38999
39914
  }
@@ -39015,11 +39930,11 @@ function withTimeout(promise2, ms) {
39015
39930
  }
39016
39931
 
39017
39932
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
39018
- import { readFileSync as readFileSync15 } from "fs";
39019
- import { join as join23 } from "path";
39933
+ import { readFileSync as readFileSync18 } from "fs";
39934
+ import { join as join27 } from "path";
39020
39935
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
39021
39936
  function forwardDropsPath(dataDir2) {
39022
- return join23(dataDir2, FORWARD_DROPS_FILENAME);
39937
+ return join27(dataDir2, FORWARD_DROPS_FILENAME);
39023
39938
  }
39024
39939
  function recordForwardDrops(dataDir2, count, nowMs) {
39025
39940
  if (count <= 0) return;
@@ -39037,7 +39952,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
39037
39952
  }
39038
39953
  function readForwardDrops(dataDir2) {
39039
39954
  try {
39040
- const parsed2 = JSON.parse(readFileSync15(forwardDropsPath(dataDir2), "utf8"));
39955
+ const parsed2 = JSON.parse(readFileSync18(forwardDropsPath(dataDir2), "utf8"));
39041
39956
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
39042
39957
  const record2 = parsed2;
39043
39958
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -39055,9 +39970,8 @@ function readForwardDrops(dataDir2) {
39055
39970
 
39056
39971
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
39057
39972
  import { randomUUID as randomUUID16 } from "crypto";
39058
- import { readFileSync as readFileSync16 } from "fs";
39059
39973
  import { readFile, rename, writeFile } from "fs/promises";
39060
- import { join as join24 } from "path";
39974
+ import { join as join28 } from "path";
39061
39975
  function isInvalidRequest(err) {
39062
39976
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
39063
39977
  }
@@ -39071,31 +39985,12 @@ function isServerRejection(err) {
39071
39985
  var FORWARD_BUDGET_MS = 1500;
39072
39986
  var DECISION_PATH_BUDGET_MS = 800;
39073
39987
  var BREAKER_FAILURE_THRESHOLD = 3;
39074
- var BREAKER_COOLDOWN_MS = 3e4;
39075
39988
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
39076
- var FAILURES = /* @__PURE__ */ new Set([
39077
- "unauthorized",
39078
- "forbidden",
39079
- "unreachable"
39080
- ]);
39081
39989
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
39082
39990
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
39083
- function parseBreakerState(raw, nowMs) {
39084
- try {
39085
- const parsed2 = JSON.parse(raw);
39086
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
39087
- const record2 = parsed2;
39088
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
39089
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
39090
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
39091
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
39092
- } catch {
39093
- return null;
39094
- }
39095
- }
39096
39991
  function createForwardPolicy(deps) {
39097
39992
  const now = deps.now ?? (() => Date.now());
39098
- const file2 = join24(deps.dir, STATE_FILENAME);
39993
+ const file2 = join28(deps.dir, STATE_FILENAME);
39099
39994
  let state = null;
39100
39995
  let loading = null;
39101
39996
  async function readState() {
@@ -39105,7 +40000,7 @@ function createForwardPolicy(deps) {
39105
40000
  } catch {
39106
40001
  return { ...CLOSED };
39107
40002
  }
39108
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
40003
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
39109
40004
  }
39110
40005
  async function load() {
39111
40006
  if (state !== null) return state;
@@ -39151,7 +40046,7 @@ function createForwardPolicy(deps) {
39151
40046
  };
39152
40047
  const at = now();
39153
40048
  if (current.openedAtMs !== null) {
39154
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
40049
+ if (isForwardPaused(current, at)) {
39155
40050
  return { ok: false, reason: "breaker-open" };
39156
40051
  }
39157
40052
  await persist({
@@ -39688,7 +40583,18 @@ var AttachedDataGateway = class {
39688
40583
  // and the spread above would otherwise drop the field silently — which is
39689
40584
  // exactly what it did, leaving the whole control inert on every device
39690
40585
  // while every test around it stayed green.
39691
- prohibitedModels: cached2.prohibitedModels
40586
+ prohibitedModels: cached2.prohibitedModels,
40587
+ // NAMED for the same reason as the line above, and it is the same defect
40588
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
40589
+ // only the cache carries is dropped in silence. That is what left
40590
+ // `prohibitedModels` inert on every attached device with every test
40591
+ // around it green.
40592
+ //
40593
+ // Taken from the cache rather than merged here, because merging it needs
40594
+ // the device's own SETTING — which is not a bundle field and is not in
40595
+ // scope at this seam. The runtime does that merge, raise-only, where both
40596
+ // values are in hand (createPluginRuntime's ensureInitialized).
40597
+ redactFallback: cached2.redactFallback
39692
40598
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39693
40599
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39694
40600
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39816,10 +40722,6 @@ function toolAuditEvent(input2) {
39816
40722
  };
39817
40723
  }
39818
40724
 
39819
- // ../../packages/plugin-runtime/src/attached/history-state.ts
39820
- import { readFileSync as readFileSync17 } from "fs";
39821
- import { join as join25 } from "path";
39822
-
39823
40725
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39824
40726
  import { createHash as createHash6 } from "crypto";
39825
40727
  import { hostname as hostname5 } from "os";
@@ -39828,6 +40730,10 @@ import { hostname as hostname5 } from "os";
39828
40730
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39829
40731
  var TRACE_ID = EventMetadata.shape.traceId;
39830
40732
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40733
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40734
+
40735
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
40736
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39831
40737
 
39832
40738
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39833
40739
  import { spawn } from "child_process";
@@ -39835,7 +40741,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
39835
40741
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
39836
40742
 
39837
40743
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
39838
- import { readFileSync as readFileSync18 } from "fs";
40744
+ import { readFileSync as readFileSync19 } from "fs";
39839
40745
  function createPluginBlock(build, policyStore) {
39840
40746
  return async () => {
39841
40747
  const cached2 = await policyStore.read();
@@ -39854,7 +40760,7 @@ function createPluginBlock(build, policyStore) {
39854
40760
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39855
40761
  import { randomUUID as randomUUID17 } from "crypto";
39856
40762
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39857
- import { join as join26 } from "path";
40763
+ import { join as join29 } from "path";
39858
40764
 
39859
40765
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39860
40766
  import { rename as rename2 } from "fs/promises";
@@ -39878,7 +40784,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39878
40784
 
39879
40785
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39880
40786
  function createPolicyStore(dir = dataDir()) {
39881
- const file2 = join26(dir, "policy-cache.json");
40787
+ const file2 = join29(dir, "policy-cache.json");
39882
40788
  async function read() {
39883
40789
  try {
39884
40790
  const raw = await readFile2(file2, "utf8");
@@ -40109,11 +41015,11 @@ function readStorePosture(dbPath2) {
40109
41015
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
40110
41016
  import { randomUUID as randomUUID18 } from "crypto";
40111
41017
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
40112
- import { join as join27 } from "path";
41018
+ import { join as join30 } from "path";
40113
41019
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40114
41020
  function createPostureStore(dir = settingsDir(), legacyDir) {
40115
- const file2 = join27(dir, "posture-state.json");
40116
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
41021
+ const file2 = join30(dir, "posture-state.json");
41022
+ const legacyFile = legacyDir === void 0 ? null : join30(legacyDir, "posture-state.json");
40117
41023
  async function persist(state) {
40118
41024
  await ensureDataDir(dir);
40119
41025
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -40181,8 +41087,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40181
41087
  }
40182
41088
 
40183
41089
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
40184
- import { readFileSync as readFileSync19 } from "fs";
40185
- import { join as join28 } from "path";
41090
+ import { readFileSync as readFileSync20 } from "fs";
41091
+ import { join as join31 } from "path";
40186
41092
 
40187
41093
  // ../../packages/plugin-runtime/src/attached/status.ts
40188
41094
  var REFUSAL_LINES = {
@@ -40203,6 +41109,14 @@ import { spawn as spawn2 } from "child_process";
40203
41109
  import { fileURLToPath as fileURLToPath3 } from "url";
40204
41110
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
40205
41111
 
41112
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
41113
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
41114
+
41115
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
41116
+ import { spawn as spawn3 } from "child_process";
41117
+ import { fileURLToPath as fileURLToPath4 } from "url";
41118
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
41119
+
40206
41120
  // ../../packages/plugin-runtime/src/attached/factory.ts
40207
41121
  import { hostname as hostname6 } from "os";
40208
41122
 
@@ -40678,7 +41592,7 @@ function markerDirs(dataDir2) {
40678
41592
  function alreadyClaimed(dirs, marker, sessionId) {
40679
41593
  return dirs.some((dir) => {
40680
41594
  try {
40681
- return readFileSync20(join29(dir, marker), "utf8") === sessionId;
41595
+ return readFileSync21(join32(dir, marker), "utf8") === sessionId;
40682
41596
  } catch {
40683
41597
  return false;
40684
41598
  }
@@ -40688,7 +41602,7 @@ function recordClaim(dirs, marker, sessionId) {
40688
41602
  for (const dir of dirs) {
40689
41603
  try {
40690
41604
  mkdirSync6(dir, { recursive: true, mode: DATA_DIR_MODE });
40691
- writeFileSync9(join29(dir, marker), sessionId, { mode: DATA_FILE_MODE });
41605
+ writeFileSync9(join32(dir, marker), sessionId, { mode: DATA_FILE_MODE });
40692
41606
  return;
40693
41607
  } catch {
40694
41608
  }
@@ -40836,7 +41750,14 @@ async function main() {
40836
41750
  ...kind === "tool_use" ? { persist: "with-findings" } : {},
40837
41751
  // Grants this call's pointer crossing already spent: suppression
40838
41752
  // applies without charging a second use.
40839
- ...spentGrantIds.length > 0 ? { preAuthorizedGrantIds: spentGrantIds } : {}
41753
+ ...spentGrantIds.length > 0 ? { preAuthorizedGrantIds: spentGrantIds } : {},
41754
+ // Per FIELD: a field that EXECUTES cannot be masked in place, since
41755
+ // rewriting a command changes what runs. Data fields can be, and keep
41756
+ // true redaction — including the reversible vault rewrite below. A
41757
+ // redact on an executable field degrades to the configured
41758
+ // `redactFallback` inside the runtime, the one place the emitted
41759
+ // decision, the recorded action and the ledger all read.
41760
+ rewritable: !spec.executable
40840
41761
  }
40841
41762
  );
40842
41763
  scanned.push({ spec, text, result });