@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.
package/scripts/sync.js CHANGED
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -491,9 +491,6 @@ var require_ignore = __commonJS({
491
491
  }
492
492
  });
493
493
 
494
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
495
- import { createHash as createHash4 } from "crypto";
496
-
497
494
  // ../../packages/persistence/src/attached-derived.ts
498
495
  import { rmSync } from "fs";
499
496
  import { join } from "path";
@@ -506,6 +503,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
506
503
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
504
  import { join as join2 } from "path";
508
505
 
506
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
507
+ var DEFERRED_MIGRATION_TAGS = [
508
+ "0031_audit_capture_by_time_index",
509
+ "0032_audit_capture_by_id_index",
510
+ "0033_audit_capture_location_index",
511
+ "0034_findings_read_indexes"
512
+ ];
513
+
509
514
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
515
  var SQLITE_MIGRATIONS = [
511
516
  {
@@ -623,6 +628,30 @@ var SQLITE_MIGRATIONS = [
623
628
  {
624
629
  tag: "0028_activity_session_probe_indexes",
625
630
  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"
631
+ },
632
+ {
633
+ tag: "0029_audit_capture_rollup_index",
634
+ 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');"
635
+ },
636
+ {
637
+ tag: "0030_audit_content_expiry",
638
+ 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;"
639
+ },
640
+ {
641
+ tag: "0031_audit_capture_by_time_index",
642
+ 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');"
643
+ },
644
+ {
645
+ tag: "0032_audit_capture_by_id_index",
646
+ 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');"
647
+ },
648
+ {
649
+ tag: "0033_audit_capture_location_index",
650
+ 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');"
651
+ },
652
+ {
653
+ tag: "0034_findings_read_indexes",
654
+ 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
655
  }
627
656
  ];
628
657
 
@@ -20670,6 +20699,15 @@ var FindingCategory = external_exports.enum([
20670
20699
  ]).meta({ id: "FindingCategory" });
20671
20700
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20672
20701
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20702
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20703
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20704
+ var FindingDelivery = external_exports.object({
20705
+ state: FindingDeliveryState,
20706
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20707
+ at: external_exports.iso.datetime().optional(),
20708
+ // Only on `not_sent`, and only when a known reason was recorded.
20709
+ reason: SyncFailureReason.optional()
20710
+ }).meta({ id: "FindingDelivery" });
20673
20711
  var ResolutionMethod = external_exports.enum([
20674
20712
  "enforced-in-flight",
20675
20713
  "fixed-at-source",
@@ -20726,7 +20764,10 @@ var FindingInstance = external_exports.object({
20726
20764
  // The session that event belongs to, when it has one — the seam a
20727
20765
  // per-instance "view session" link needs. Absent for events captured
20728
20766
  // outside a session.
20729
- sessionId: external_exports.string().optional()
20767
+ sessionId: external_exports.string().optional(),
20768
+ // The delivery state of the event above (see FindingDelivery). Optional so
20769
+ // readers that do not project it stay valid.
20770
+ delivery: FindingDelivery.optional()
20730
20771
  }).meta({ id: "FindingInstance" });
20731
20772
  var FindingGroup = external_exports.object({
20732
20773
  id: external_exports.string(),
@@ -20743,13 +20784,11 @@ var FindingGroup = external_exports.object({
20743
20784
  latestDetectedAt: external_exports.iso.datetime(),
20744
20785
  instances: external_exports.array(FindingInstance),
20745
20786
  // Derived from instances' statuses with open-dominates precedence (see
20746
- // buildFindingGroups). Undefined only when no instance carries a status.
20787
+ // foldGroupStatus). Undefined only when no instance carries a status.
20747
20788
  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.
20789
+ // The distinct people across the WHOLE group, not just the instances
20790
+ // carried here. Undefined when no instance carries a user, or when the
20791
+ // store supplied whole-group folds without one.
20753
20792
  users: external_exports.array(FindingUser).optional()
20754
20793
  }).meta({ id: "FindingGroup" });
20755
20794
  var FindingStats = external_exports.object({
@@ -20778,21 +20817,34 @@ var FindingFacets = external_exports.object({
20778
20817
  // counted under no value.
20779
20818
  status: external_exports.array(FindingFacetItem),
20780
20819
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
- // reads, which can filter by it; the grouped read omits the dimension
20820
+ // reads, which can filter by it; the type-level read omits the dimension
20782
20821
  // because a group spans tools.
20783
- tool: external_exports.array(FindingFacetItem).optional()
20822
+ tool: external_exports.array(FindingFacetItem).optional(),
20823
+ // Delivery states (FindingDeliveryState). Present only on the
20824
+ // instance-level reads, like `tool`.
20825
+ deployment: external_exports.array(FindingFacetItem).optional()
20784
20826
  }).meta({ id: "FindingFacets" });
20785
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20786
- var ListGroupedFindingsQuery = external_exports.object({
20827
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20828
+ id: "FindingTypeSummary"
20829
+ });
20830
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20831
+ var MAX_FINDING_TYPES_LIMIT = 100;
20832
+ var ListFindingTypesQuery = external_exports.object({
20787
20833
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20788
- // FindingAction.
20834
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20835
+ // firing version carries, and this list pages types.
20836
+ //
20837
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20838
+ // definition versions at different severities, so a type kept by this filter
20839
+ // can hold findings that individually do not match — see totals.findings on
20840
+ // ListFindingTypesResponse, which counts them all.
20789
20841
  severity: external_exports.array(Severity).optional(),
20790
20842
  subtype: external_exports.array(external_exports.string()).optional(),
20791
20843
  provider: external_exports.array(FindingProvider).optional(),
20792
20844
  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.
20845
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20846
+ // individual findings' — so a filtered row's status always reads one of the
20847
+ // requested values.
20796
20848
  status: external_exports.array(FindingStatus).optional(),
20797
20849
  q: external_exports.string().optional(),
20798
20850
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20802,23 +20854,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20802
20854
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20803
20855
  // means all time — this list has no default window.
20804
20856
  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.
20857
+ // A RULE id that must appear in the page even when the cursor has already
20858
+ // advanced past its sort position. This is what keeps the selected type
20859
+ // visible in the list once it paginates: the target is appended out of sort
20860
+ // order rather than scanned forward for. Never affects totals, facets or the
20861
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20862
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20863
+ // and so is not bounded by what any page happens to hold.
20810
20864
  includeId: external_exports.string().optional(),
20811
- groupBy: external_exports.literal("type").optional(),
20812
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20865
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20813
20866
  cursor: external_exports.string().optional()
20814
20867
  });
20815
- var ListGroupedFindingsResponse = external_exports.object({
20868
+ var ListFindingTypesResponse = external_exports.object({
20816
20869
  totals: external_exports.object({
20870
+ // Findings belonging to the matching TYPES — not findings that each match
20871
+ // the filters. The filters here select types, so a type that survives
20872
+ // contributes its whole instanceCount.
20873
+ //
20874
+ // `status` is the one exception, narrowed per finding via
20875
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20876
+ // this can exceed what the instance read reports for the same filters: a
20877
+ // rule whose severity moved between versions is kept on its newest and
20878
+ // still counts its older findings. Narrowing the other three needs
20879
+ // per-dimension counts the aggregate does not carry today.
20817
20880
  findings: external_exports.number().int().nonnegative(),
20818
- groups: external_exports.number().int().nonnegative()
20881
+ // Counts TYPES, which is the unit this read pages. The instance read's
20882
+ // own totals count findings; the two deliberately answer different
20883
+ // questions and are never summed.
20884
+ types: external_exports.number().int().nonnegative()
20819
20885
  }),
20820
20886
  facets: FindingFacets,
20821
- items: external_exports.array(FindingGroup),
20887
+ items: external_exports.array(FindingTypeSummary),
20822
20888
  nextCursor: external_exports.string().nullable(),
20823
20889
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20824
20890
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20826,7 +20892,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20826
20892
  // every firing, so the two numbers legitimately differ — this map lets a
20827
20893
  // session-scoped view show both.
20828
20894
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20829
- }).meta({ id: "ListGroupedFindingsResponse" });
20895
+ }).meta({ id: "ListFindingTypesResponse" });
20830
20896
  var ApplyFindingActionRequest = external_exports.object({
20831
20897
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20832
20898
  // it, so it is excluded from the request contract. The mapping helper
@@ -20856,16 +20922,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20856
20922
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20857
20923
  var ListFindingInstancesQuery = external_exports.object({
20858
20924
  severity: external_exports.array(Severity).optional(),
20859
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20925
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20926
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20860
20927
  subtype: external_exports.array(external_exports.string()).optional(),
20861
20928
  provider: external_exports.array(FindingProvider).optional(),
20862
20929
  action: external_exports.array(FindingAction).optional(),
20863
20930
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20864
- // the grouped query's group-level fold.
20931
+ // the types query's type-level fold.
20865
20932
  status: external_exports.array(FindingStatus).optional(),
20866
20933
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20867
20934
  // where the free-text `q` can only match the rendered "via Bash" label.
20868
20935
  tool: external_exports.array(external_exports.string()).optional(),
20936
+ // The delivery state of each finding's event (see FindingDelivery).
20937
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20869
20938
  // Exact repository / file-path matches, for the drill-down out of the
20870
20939
  // locations view. A row whose event carries no repo/file matches neither.
20871
20940
  repo: external_exports.string().optional(),
@@ -20878,37 +20947,51 @@ var ListFindingInstancesQuery = external_exports.object({
20878
20947
  });
20879
20948
  var ListFindingInstancesResponse = external_exports.object({
20880
20949
  // Instances matching the filters across the whole scope, not just this
20881
- // page — cursor-independent, like the grouped list's totals.
20950
+ // page — cursor-independent, like the types list's totals.
20882
20951
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20883
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20952
+ // Counts in INSTANCES here, where the types response counts types. Each
20884
20953
  // dimension still excludes its own filter.
20885
20954
  facets: FindingFacets,
20886
20955
  items: external_exports.array(FindingInstanceDetail),
20887
20956
  nextCursor: external_exports.string().nullable()
20888
20957
  }).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({
20958
+ var ListFindingInstancesPage = external_exports.object({
20959
+ items: external_exports.array(FindingInstanceDetail),
20960
+ nextCursor: external_exports.string().nullable()
20961
+ }).meta({ id: "ListFindingInstancesPage" });
20962
+ var FindingLocationSummary = external_exports.object({
20963
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20964
+ // because a location's identity is two values and a URL param carries one:
20965
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20966
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20967
+ // client's page dedupe — never decoded, and never a sort key.
20968
+ id: external_exports.string(),
20904
20969
  /** Empty when the instances carried no repo attribute. */
20905
20970
  repo: external_exports.string(),
20971
+ // Empty when the instances carried no file path (a prompt, or a tool call
20972
+ // with no file attribution). Both halves empty is a real location — usually
20973
+ // the largest one in a store — and is selectable like any other.
20974
+ file: external_exports.string(),
20906
20975
  instanceCount: external_exports.number().int().nonnegative(),
20976
+ // The WORST severity present, not the first row's. It is this list's primary
20977
+ // sort key, so it is also what explains why a row is where it is, and it is
20978
+ // how a reader decides what to open without opening everything.
20907
20979
  maxSeverity: Severity,
20908
20980
  latestDetectedAt: external_exports.iso.datetime(),
20981
+ // Folded from the instances' derived statuses with the same open-dominates
20982
+ // precedence a group uses, so it answers "is anything left to do here" and
20983
+ // not much more: a location holding 1 open among 40 resolved reads like one
20984
+ // holding 40 open. That loss is accepted — the panel beside this list
20985
+ // carries each finding's own status, and instanceCount sits next to the
20986
+ // badge.
20909
20987
  status: FindingStatus.optional(),
20910
- files: external_exports.array(FindingLocationFile)
20911
- }).meta({ id: "FindingLocationRepo" });
20988
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20989
+ // tally rather than a sample and a row can say how many there are. Bounded
20990
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20991
+ ruleIds: external_exports.array(external_exports.string())
20992
+ }).meta({ id: "FindingLocationSummary" });
20993
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20994
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20912
20995
  var ListFindingLocationsQuery = external_exports.object({
20913
20996
  severity: external_exports.array(Severity).optional(),
20914
20997
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20918,21 +21001,47 @@ var ListFindingLocationsQuery = external_exports.object({
20918
21001
  // instances that match, and folds its status from those.
20919
21002
  status: external_exports.array(FindingStatus).optional(),
20920
21003
  tool: external_exports.array(external_exports.string()).optional(),
21004
+ // The delivery state of each finding's event (see FindingDelivery).
21005
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20921
21006
  q: external_exports.string().optional(),
20922
21007
  sessionId: external_exports.string().optional(),
20923
21008
  from: external_exports.iso.datetime().optional(),
20924
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21009
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21010
+ // even when the cursor has already advanced past its sort position — the
21011
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21012
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21013
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21014
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21015
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21016
+ includeId: external_exports.string().optional(),
21017
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21018
+ cursor: external_exports.string().optional()
20925
21019
  });
20926
21020
  var ListFindingLocationsResponse = external_exports.object({
20927
21021
  totals: external_exports.object({
21022
+ // Findings matching the filters across the whole scope. Unlike the types
21023
+ // read's same-named field this needs no caveat: the filters here narrow
21024
+ // per finding, so this is the sum of every row's instanceCount.
20928
21025
  findings: external_exports.number().int().nonnegative(),
20929
- repos: external_exports.number().int().nonnegative(),
20930
- files: external_exports.number().int().nonnegative()
21026
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21027
+ // states. The facets beside it count FINDINGS (see below); a surface
21028
+ // showing both says which is which.
21029
+ locations: external_exports.number().int().nonnegative()
20931
21030
  }),
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()
21031
+ // Counts in FINDINGS, where the types response counts types, each dimension
21032
+ // still excluding its own filter. Deliberately not locations: counting those
21033
+ // needs a set of location keys per dimension per value — memory tracking the
21034
+ // store times the vocabulary, in a read whose scan promises flat memory —
21035
+ // and the cheap per-location version is not an approximation but WRONG. A
21036
+ // location holding {claudecode, block} and {codex, warn} would survive
21037
+ // provider=claudecode AND action=warn, under which no single finding
21038
+ // matches, so the facet would contradict the instanceCount this whole view
21039
+ // rests on. Findings also keep the toolbar in the same unit as the page
21040
+ // tally and the panel it sits above.
21041
+ facets: FindingFacets,
21042
+ /** Sorted by max severity, then most recent, then (repo, file). */
21043
+ items: external_exports.array(FindingLocationSummary),
21044
+ nextCursor: external_exports.string().nullable()
20936
21045
  }).meta({ id: "ListFindingLocationsResponse" });
20937
21046
 
20938
21047
  // ../../packages/schema/src/zod/meta.ts
@@ -21096,6 +21205,10 @@ var CaptureAttributes = external_exports.object({
21096
21205
  // to 'allow' — the enforcement audit trail's link back to the grant that
21097
21206
  // authorized the bypass.
21098
21207
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21208
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21209
+ // join back to the `llm_call` leaf for the same assistant turn.
21210
+ message_id: external_exports.string().optional(),
21211
+ conversation_id: external_exports.string().optional(),
21099
21212
  // Whole milliseconds this capture's inspection blocked its caller — the
21100
21213
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21101
21214
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21104,7 +21217,19 @@ var CaptureAttributes = external_exports.object({
21104
21217
  // inline json_extract and is not itself an optimization.
21105
21218
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21106
21219
  // before the measurement shipped — never present as a placeholder 0.
21107
- inspection_ms: external_exports.number().int().nonnegative().optional()
21220
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21221
+ // What a `redact` this capture could not carry out became instead (see
21222
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21223
+ // degrade actually happened, so absence is the ordinary case rather than a
21224
+ // reader having to distinguish it from a zero.
21225
+ //
21226
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21227
+ // so on a multi-finding row this does not say which finding degraded, and
21228
+ // its presence does not mean the fallback decided the capture's action. A
21229
+ // capture denied by another finding's own Block policy carries `block`
21230
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21231
+ // repeated rather than referenced because a store reader opens this file.
21232
+ redact_degraded_to: ActionTaken.optional()
21108
21233
  }).catchall(external_exports.unknown());
21109
21234
  var ToolCallInspection = external_exports.object({
21110
21235
  ruleId: external_exports.string().min(1),
@@ -21303,7 +21428,17 @@ var AuditEvent = external_exports.object({
21303
21428
  /** `share` to a first-party/internal destination. */
21304
21429
  internal: external_exports.boolean(),
21305
21430
  /** Event needs review (e.g. unverified egress). */
21306
- flagged: external_exports.boolean()
21431
+ flagged: external_exports.boolean(),
21432
+ /**
21433
+ * The body this event's `title` is drawn from was cleared by local body
21434
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21435
+ *
21436
+ * A separate flag rather than a sentinel written into `title`: the title is
21437
+ * rendered text, and a store-layer module that invented display copy for it
21438
+ * would be choosing words the view is supposed to choose. Additive and
21439
+ * defaulted, so an older producer still validates.
21440
+ */
21441
+ bodyExpired: external_exports.boolean().default(false)
21307
21442
  }).meta({ id: "ActivityAuditEvent" });
21308
21443
  var ActivitySessionSummary = external_exports.object({
21309
21444
  id: external_exports.string(),
@@ -22101,6 +22236,14 @@ var ControlPlaneErrorBody = external_exports.object({
22101
22236
  message: external_exports.string().optional()
22102
22237
  }).optional()
22103
22238
  });
22239
+ var RemoteFailureKind = external_exports.enum([
22240
+ "unauthorized",
22241
+ "forbidden",
22242
+ "route-absent",
22243
+ "invalid-request",
22244
+ "rejected",
22245
+ "unreachable"
22246
+ ]);
22104
22247
  var AttachDeviceRequest = external_exports.object({
22105
22248
  // This machine's own continuity id, so re-attaching ROTATES the credential
22106
22249
  // on one machine record instead of producing a second one. Client-minted
@@ -22636,6 +22779,12 @@ var EventMetadata = external_exports.object({
22636
22779
  // to 'allow' — the enforcement audit trail's link back to the grant that
22637
22780
  // authorized the bypass. Absent on captures where no exception applied.
22638
22781
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22782
+ // The assistant message this capture belongs to, and the conversation it sits
22783
+ // in — set by the browser extension's network capture so a stored `response`
22784
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22785
+ // on every other capture path, which has no such id.
22786
+ messageId: external_exports.string().optional(),
22787
+ conversationId: external_exports.string().optional(),
22639
22788
  // How long THIS capture's inspection blocked its caller, in whole
22640
22789
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22641
22790
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22648,7 +22797,37 @@ var EventMetadata = external_exports.object({
22648
22797
  // Absent is also what every pre-measurement client writes, and what a
22649
22798
  // clock failure degrades to — a reader must treat absence as "not measured"
22650
22799
  // and never as a zero, which would read as "inspection is free".
22651
- inspectionMs: external_exports.number().int().nonnegative().optional()
22800
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22801
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22802
+ // workspace's `redactFallback`, applied because the field could not be
22803
+ // masked in place (a shell command, a URL, or any argument on a host whose
22804
+ // hook contract offers no rewrite channel).
22805
+ //
22806
+ // It exists because the action alone cannot say why. A finding recorded as
22807
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22808
+ // assigned Redact on a field that could not take one — and those are
22809
+ // different facts about the same row: the first is a policy the user chose,
22810
+ // the second is a masking the host could not perform. Absent means no
22811
+ // degrade happened, which is every ordinary capture.
22812
+ //
22813
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22814
+ // is the CAPTURE while `actionTaken` is per FINDING:
22815
+ //
22816
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22817
+ // `redact` alongside a finding ASSIGNED the same action stores both
22818
+ // identically and one reason for the pair; attributing it to both
22819
+ // describes the assigned one wrongly, and to neither loses the degrade.
22820
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22821
+ // became, not the reason the capture ended as it did — a capture denied
22822
+ // by some other finding's own Block policy still carries `block` here,
22823
+ // and clearing the workspace's fallback would not have let it through.
22824
+ // Gate on the value against what a fallback can produce; never read the
22825
+ // field's presence as "this was the fallback's doing".
22826
+ //
22827
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22828
+ // Closing either means moving the reason onto the finding row, which
22829
+ // already carries its own action.
22830
+ redactDegradedTo: ActionTaken.optional()
22652
22831
  }).meta({ id: "EventMetadata" });
22653
22832
  var Event = external_exports.object({
22654
22833
  id: external_exports.guid(),
@@ -22758,7 +22937,32 @@ var RotateKeyInput = external_exports.object({
22758
22937
  confirmation: external_exports.string()
22759
22938
  });
22760
22939
 
22940
+ // ../../packages/schema/src/zod/finding-delivery.ts
22941
+ var KNOWN_REASONS = SyncFailureReason.options;
22942
+ function knownReason(value) {
22943
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22944
+ }
22945
+ function deriveFindingDelivery(row) {
22946
+ if (row.kind === "code_change") return { state: "local_scan" };
22947
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22948
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22949
+ }
22950
+ if (row.syncedAt !== null) {
22951
+ const reason = knownReason(row.syncFailure);
22952
+ return {
22953
+ state: "not_sent",
22954
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22955
+ ...reason === void 0 ? {} : { reason }
22956
+ };
22957
+ }
22958
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22959
+ return { state: "never_offered" };
22960
+ }
22961
+
22761
22962
  // ../../packages/schema/src/zod/findings-group-build.ts
22963
+ function lookupOwn(map2, key) {
22964
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22965
+ }
22762
22966
  function toApiAction(dbVal) {
22763
22967
  const map2 = {
22764
22968
  log: "monitored",
@@ -22767,7 +22971,7 @@ function toApiAction(dbVal) {
22767
22971
  warn: "warned",
22768
22972
  allow: "allowed"
22769
22973
  };
22770
- return map2[dbVal] ?? "allowed";
22974
+ return lookupOwn(map2, dbVal) ?? "allowed";
22771
22975
  }
22772
22976
  function toApiCategory(dbVal) {
22773
22977
  if (dbVal === "code_context") return "source_code";
@@ -22775,13 +22979,18 @@ function toApiCategory(dbVal) {
22775
22979
  return parsed2.success ? parsed2.data : "custom";
22776
22980
  }
22777
22981
  function toApiProvider(sourceTool) {
22778
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22982
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22779
22983
  }
22780
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22984
+ var FINDING_STATUS_PRECEDENCE = [
22985
+ "open",
22986
+ "handled",
22987
+ "dismissed",
22988
+ "resolved"
22989
+ ];
22781
22990
  function foldGroupStatus(instanceStatuses) {
22782
22991
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22783
22992
  if (statuses.size === 0) return void 0;
22784
- for (const candidate of STATUS_PRECEDENCE) {
22993
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22785
22994
  if (statuses.has(candidate)) return candidate;
22786
22995
  }
22787
22996
  return void 0;
@@ -22794,139 +23003,62 @@ function deriveFindingStatus(row) {
22794
23003
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22795
23004
  return "open";
22796
23005
  }
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
23006
  function sortUsers(users) {
22808
23007
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22809
23008
  }
22810
- function buildFindingGroups(rows, opts = {}) {
22811
- const overrides = opts.overrides;
23009
+ function buildFindingTypes(aggregates, opts = {}) {
22812
23010
  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
- );
23011
+ const types = [];
23012
+ for (const [ruleId, agg] of aggregates) {
23013
+ const users = sortUsers(agg.users ?? []);
23014
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23015
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22854
23016
  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 = {
23017
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23018
+ const type = {
22871
23019
  id: ruleId,
22872
23020
  category: apiCategory,
22873
23021
  subtype: ruleId,
22874
23022
  // human label comes with pack metadata later
22875
- severity,
22876
- match,
22877
- detection,
22878
- policy,
22879
- instanceCount: agg?.instanceCount ?? instances.length,
23023
+ severity: agg.severity ?? "low",
23024
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23025
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23026
+ instanceCount: agg.instanceCount,
22880
23027
  providers,
22881
23028
  aggregateAction,
22882
- latestDetectedAt,
22883
- instances,
22884
- status,
23029
+ latestDetectedAt: agg.latestDetectedAt,
23030
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22885
23031
  ...users.length > 0 ? { users } : {}
22886
23032
  };
22887
- if (agg) {
22888
- actionsCache.set(group, [...actionSet]);
22889
- if (agg.searchText !== void 0) {
22890
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22891
- }
23033
+ actionsCache.set(type, [...actionSet]);
23034
+ if (agg.searchText !== void 0) {
23035
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22892
23036
  }
22893
- groups.push(group);
23037
+ types.push(type);
22894
23038
  }
22895
- return groups;
23039
+ return types;
22896
23040
  }
22897
23041
  var haystackCache = /* @__PURE__ */ new WeakMap();
22898
- function buildHaystack(g, extra) {
23042
+ function buildHaystack(t, extra) {
22899
23043
  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 ?? ""),
23044
+ t.subtype,
23045
+ t.category,
23046
+ t.policy.name,
23047
+ t.id,
23048
+ ...(t.users ?? []).map((u) => u.name),
22913
23049
  ...extra === void 0 ? [] : [extra]
22914
23050
  ].join(" ").toLowerCase();
22915
23051
  }
22916
- function groupHaystack(g) {
22917
- const cached2 = haystackCache.get(g);
23052
+ function typeHaystack(t) {
23053
+ const cached2 = haystackCache.get(t);
22918
23054
  if (cached2 !== void 0) return cached2;
22919
- const haystack = buildHaystack(g);
22920
- haystackCache.set(g, haystack);
23055
+ const haystack = buildHaystack(t);
23056
+ haystackCache.set(t, haystack);
22921
23057
  return haystack;
22922
23058
  }
22923
23059
  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;
23060
+ function typeActions(t) {
23061
+ return actionsCache.get(t) ?? [];
22930
23062
  }
22931
23063
  function countInstancesByStatus(statusInputs, statuses) {
22932
23064
  const statusSet = new Set(statuses);
@@ -22937,8 +23069,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22937
23069
  }
22938
23070
  return sum;
22939
23071
  }
22940
- function applyFindingFilters(groups, opts) {
22941
- let filtered = groups;
23072
+ function applyFindingFilters(types, opts) {
23073
+ let filtered = types;
22942
23074
  if (opts.severity && opts.severity.length > 0) {
22943
23075
  const sevSet = new Set(opts.severity);
22944
23076
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22949,7 +23081,7 @@ function applyFindingFilters(groups, opts) {
22949
23081
  }
22950
23082
  if (opts.actions && opts.actions.length > 0) {
22951
23083
  const actionSet = new Set(opts.actions);
22952
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23084
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22953
23085
  }
22954
23086
  if (opts.subtype && opts.subtype.length > 0) {
22955
23087
  const subtypeSet = new Set(opts.subtype);
@@ -22961,26 +23093,31 @@ function applyFindingFilters(groups, opts) {
22961
23093
  }
22962
23094
  if (opts.q) {
22963
23095
  const q = opts.q.toLowerCase();
22964
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23096
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22965
23097
  }
22966
23098
  return filtered;
22967
23099
  }
22968
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22969
- var SEVERITY_RANK = SEVERITY_ORDER;
23100
+ function rankByOrder(members2) {
23101
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23102
+ }
23103
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23104
+ function severityRank(severity) {
23105
+ return lookupOwn(SEVERITY_RANK, severity);
23106
+ }
22970
23107
  function compareFindingGroupOrder(a, b) {
22971
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22972
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23108
+ const rankA = severityRank(a.severity) ?? -1;
23109
+ const rankB = severityRank(b.severity) ?? -1;
22973
23110
  const severityDiff = rankA - rankB;
22974
23111
  if (severityDiff !== 0) return severityDiff;
22975
23112
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22976
23113
  if (recencyDiff !== 0) return recencyDiff;
22977
23114
  return a.id.localeCompare(b.id);
22978
23115
  }
22979
- function sortFindingGroups(groups) {
22980
- return [...groups].sort(compareFindingGroupOrder);
23116
+ function sortFindingTypes(types) {
23117
+ return [...types].sort(compareFindingGroupOrder);
22981
23118
  }
22982
- function computeFindingFacets(allGroups, opts) {
22983
- const forSeverity = applyFindingFilters(allGroups, {
23119
+ function computeFindingFacets(allTypes, opts) {
23120
+ const forSeverity = applyFindingFilters(allTypes, {
22984
23121
  providers: opts.providers,
22985
23122
  actions: opts.actions,
22986
23123
  statuses: opts.statuses,
@@ -22991,7 +23128,7 @@ function computeFindingFacets(allGroups, opts) {
22991
23128
  for (const g of forSeverity) {
22992
23129
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22993
23130
  }
22994
- const forProvider = applyFindingFilters(allGroups, {
23131
+ const forProvider = applyFindingFilters(allTypes, {
22995
23132
  actions: opts.actions,
22996
23133
  statuses: opts.statuses,
22997
23134
  q: opts.q,
@@ -23002,7 +23139,7 @@ function computeFindingFacets(allGroups, opts) {
23002
23139
  for (const g of forProvider) {
23003
23140
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23004
23141
  }
23005
- const forAction = applyFindingFilters(allGroups, {
23142
+ const forAction = applyFindingFilters(allTypes, {
23006
23143
  providers: opts.providers,
23007
23144
  statuses: opts.statuses,
23008
23145
  q: opts.q,
@@ -23011,9 +23148,9 @@ function computeFindingFacets(allGroups, opts) {
23011
23148
  });
23012
23149
  const actionMap = /* @__PURE__ */ new Map();
23013
23150
  for (const g of forAction) {
23014
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23151
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23015
23152
  }
23016
- const forSubtype = applyFindingFilters(allGroups, {
23153
+ const forSubtype = applyFindingFilters(allTypes, {
23017
23154
  providers: opts.providers,
23018
23155
  actions: opts.actions,
23019
23156
  statuses: opts.statuses,
@@ -23022,7 +23159,7 @@ function computeFindingFacets(allGroups, opts) {
23022
23159
  });
23023
23160
  const subtypeMap = /* @__PURE__ */ new Map();
23024
23161
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23025
- const forStatus = applyFindingFilters(allGroups, {
23162
+ const forStatus = applyFindingFilters(allTypes, {
23026
23163
  providers: opts.providers,
23027
23164
  actions: opts.actions,
23028
23165
  q: opts.q,
@@ -23044,6 +23181,20 @@ function computeFindingFacets(allGroups, opts) {
23044
23181
  }
23045
23182
 
23046
23183
  // ../../packages/schema/src/zod/findings-flat-build.ts
23184
+ function compareCodePoints(a, b) {
23185
+ const aIter = a[Symbol.iterator]();
23186
+ const bIter = b[Symbol.iterator]();
23187
+ for (; ; ) {
23188
+ const aNext = aIter.next();
23189
+ const bNext = bIter.next();
23190
+ if (aNext.done && bNext.done) return 0;
23191
+ if (aNext.done) return -1;
23192
+ if (bNext.done) return 1;
23193
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23194
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23195
+ if (aPoint !== bPoint) return aPoint - bPoint;
23196
+ }
23197
+ }
23047
23198
  function rowHaystack(row) {
23048
23199
  return [
23049
23200
  row.ruleId,
@@ -23068,12 +23219,24 @@ function matchesDimension(row, opts, dimension) {
23068
23219
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23069
23220
  case "statuses":
23070
23221
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23222
+ case "deliveries":
23223
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23071
23224
  case "tools":
23072
23225
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23226
+ // An EMPTY value is a real filter here, not an absent one. The location
23227
+ // list buckets a finding whose event recorded no repo — or no file — under
23228
+ // the empty string, and selecting that bucket has to narrow the panel to
23229
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23230
+ // row omits the key, which every call site already does.
23231
+ //
23232
+ // Reading '' as unset is what this replaced, and it failed in the one place
23233
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23234
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23235
+ // — a row reading 3 findings beside a panel listing every finding there is.
23073
23236
  case "repo":
23074
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23237
+ return opts.repo === void 0 || row.repo === opts.repo;
23075
23238
  case "file":
23076
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23239
+ return opts.file === void 0 || row.file === opts.file;
23077
23240
  case "q":
23078
23241
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23079
23242
  }
@@ -23084,6 +23247,7 @@ var DIMENSIONS = [
23084
23247
  "providers",
23085
23248
  "actions",
23086
23249
  "statuses",
23250
+ "deliveries",
23087
23251
  "tools",
23088
23252
  "repo",
23089
23253
  "file",
@@ -23097,10 +23261,19 @@ function matchesInstanceFilters(row, opts, except) {
23097
23261
  return true;
23098
23262
  }
23099
23263
  function toItems(counts) {
23100
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23264
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23265
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23266
+ // NFD spelling of the same text) as equal, so a count tie between
23267
+ // them would otherwise be ordered by whichever the Map iteration
23268
+ // produced. compareCodePoints breaks that tie deterministically, which
23269
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23270
+ // which it need not: foldFacetTuples runs this same sort over grouped
23271
+ // tuples, so both paths order facets identically by construction.
23272
+ compareCodePoints(a.value, b.value)
23273
+ );
23101
23274
  }
23102
- function bump(counts, value) {
23103
- counts.set(value, (counts.get(value) ?? 0) + 1);
23275
+ function bump(counts, value, by = 1) {
23276
+ counts.set(value, (counts.get(value) ?? 0) + by);
23104
23277
  }
23105
23278
  function createInstanceFacetAccumulator(opts) {
23106
23279
  const severity = /* @__PURE__ */ new Map();
@@ -23109,6 +23282,7 @@ function createInstanceFacetAccumulator(opts) {
23109
23282
  const action = /* @__PURE__ */ new Map();
23110
23283
  const status = /* @__PURE__ */ new Map();
23111
23284
  const tool = /* @__PURE__ */ new Map();
23285
+ const deployment = /* @__PURE__ */ new Map();
23112
23286
  return {
23113
23287
  add(row) {
23114
23288
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23123,6 +23297,9 @@ function createInstanceFacetAccumulator(opts) {
23123
23297
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23124
23298
  bump(tool, row.toolName);
23125
23299
  }
23300
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23301
+ bump(deployment, row.delivery.state);
23302
+ }
23126
23303
  },
23127
23304
  facets: () => ({
23128
23305
  severity: toItems(severity),
@@ -23130,7 +23307,8 @@ function createInstanceFacetAccumulator(opts) {
23130
23307
  provider: toItems(provider),
23131
23308
  action: toItems(action),
23132
23309
  status: toItems(status),
23133
- tool: toItems(tool)
23310
+ tool: toItems(tool),
23311
+ deployment: toItems(deployment)
23134
23312
  })
23135
23313
  };
23136
23314
  }
@@ -23144,6 +23322,7 @@ function toInstanceDetail(row) {
23144
23322
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23145
23323
  eventId: row.eventId,
23146
23324
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23325
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23147
23326
  ...row.user === void 0 ? {} : { user: row.user },
23148
23327
  action: toApiAction(row.actionTaken),
23149
23328
  detectedAt: row.occurredAt,
@@ -23158,12 +23337,6 @@ function toInstanceDetail(row) {
23158
23337
  policy: { id: `category:${category}`, name: category }
23159
23338
  };
23160
23339
  }
23161
- var SEVERITY_ORDER2 = {
23162
- critical: 0,
23163
- high: 1,
23164
- medium: 2,
23165
- low: 3
23166
- };
23167
23340
  function newLocationAccumulator() {
23168
23341
  return {
23169
23342
  instanceCount: 0,
@@ -23178,7 +23351,7 @@ function newLocationAccumulator() {
23178
23351
  }
23179
23352
  function addToLocation(acc, row) {
23180
23353
  acc.instanceCount += 1;
23181
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23354
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23182
23355
  if (rank < acc.maxSeverityRank) {
23183
23356
  acc.maxSeverityRank = rank;
23184
23357
  acc.maxSeverity = row.severity;
@@ -23187,6 +23360,23 @@ function addToLocation(acc, row) {
23187
23360
  acc.statuses.push(row.status);
23188
23361
  acc.ruleIds.add(row.ruleId);
23189
23362
  }
23363
+ function compareLocationOrder(a, b) {
23364
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23365
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23366
+ if (rankA !== rankB) return rankA - rankB;
23367
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23368
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23369
+ }
23370
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23371
+ if (repoDiff !== 0) return repoDiff;
23372
+ return compareCodePoints(a.file, b.file);
23373
+ }
23374
+ function encodeLocationId(repo, file2) {
23375
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23376
+ }
23377
+ function encodePart(value) {
23378
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23379
+ }
23190
23380
 
23191
23381
  // ../../packages/schema/src/zod/installed-pack.ts
23192
23382
  var InstalledPack = external_exports.object({
@@ -23254,6 +23444,11 @@ var Policy = external_exports.object({
23254
23444
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23255
23445
  provenance: PolicyProvenance.optional()
23256
23446
  }).meta({ id: "Policy" });
23447
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23448
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23449
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23450
+ id: "RedactFallback"
23451
+ });
23257
23452
  var PolicyBundle = external_exports.object({
23258
23453
  version: external_exports.string(),
23259
23454
  policies: external_exports.array(Policy),
@@ -23301,6 +23496,16 @@ var PolicyBundle = external_exports.object({
23301
23496
  // control plane), so no name resolution stands between the decision and the
23302
23497
  // comparison.
23303
23498
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23499
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23500
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23501
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23502
+ // a control plane can tighten a machine and never loosen one — the same
23503
+ // direction `mergeRaiseOnly` enforces for policies.
23504
+ //
23505
+ // Optional so an older backend, and an older on-disk cache, still parses;
23506
+ // absent leaves the device's own setting in force, which is the behaviour
23507
+ // that predates the field and the safe direction to default.
23508
+ redactFallback: RedactFallback.optional(),
23304
23509
  customKeywords: external_exports.array(external_exports.string()),
23305
23510
  fetchedAt: external_exports.iso.datetime()
23306
23511
  }).meta({ id: "PolicyBundle" });
@@ -23330,11 +23535,6 @@ function severityFloorPolicy(category) {
23330
23535
  const peak = CATEGORY_PEAK_SEVERITY[category];
23331
23536
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23332
23537
  }
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
23538
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23339
23539
  var BUILTIN_POLICY_SPECS = {
23340
23540
  monitor: {
@@ -23390,6 +23590,11 @@ function isActionAtLeast(action, floor) {
23390
23590
  function strongerAction(a, b) {
23391
23591
  return actionRank(a) >= actionRank(b) ? a : b;
23392
23592
  }
23593
+ function strongerRedactFallback(local, remote) {
23594
+ if (remote === void 0) return local;
23595
+ const localAction = builtinPolicyToAction(local);
23596
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23597
+ }
23393
23598
  function weakestBuiltinAtLeast(floor) {
23394
23599
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23395
23600
  }
@@ -23630,7 +23835,7 @@ var VaultConsent = external_exports.object({
23630
23835
  });
23631
23836
 
23632
23837
  // ../../packages/schema/src/zod/local.ts
23633
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23838
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23634
23839
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23635
23840
  var RunMode = external_exports.enum(["standalone", "attached"]);
23636
23841
  var ControlPlaneConnection = external_exports.object({
@@ -23650,6 +23855,15 @@ var HistorySyncConsent = external_exports.object({
23650
23855
  payloadVersion: external_exports.number().int().positive(),
23651
23856
  endpoint: external_exports.string()
23652
23857
  });
23858
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23859
+ var BodyRetention = external_exports.object({
23860
+ enabled: external_exports.boolean().default(false),
23861
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23862
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23863
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23864
+ // candidate set that is already bounded by "delivered, or never owed".
23865
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23866
+ }).meta({ id: "BodyRetention" });
23653
23867
  var WorkspaceSettings = external_exports.object({
23654
23868
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23655
23869
  runMode: RunMode.default("standalone"),
@@ -23693,12 +23907,18 @@ var WorkspaceSettings = external_exports.object({
23693
23907
  // covers the current payload and must be re-granted.
23694
23908
  modelJudgeConsent: ModelJudgeConsent.optional(),
23695
23909
  // Records that the user consented to the DEFERRED send — the outbox — along
23696
- // with the payload shape and the endpoint they agreed to. Since payload v2
23697
- // that covers both the pre-attach backlog and undelivered captures (which
23698
- // carry prompt/reply text in `content`); the key name predates the widening.
23699
- // Absent until granted, and a grant for a different endpoint or an older
23700
- // payload no longer counts.
23701
- historySyncConsent: HistorySyncConsent.optional()
23910
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23911
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23912
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23913
+ // both widenings. Absent until granted, and a grant for a different endpoint
23914
+ // or an older payload no longer counts.
23915
+ historySyncConsent: HistorySyncConsent.optional(),
23916
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23917
+ // body never removes the row or its findings.
23918
+ bodyRetention: BodyRetention.default({
23919
+ enabled: false,
23920
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23921
+ })
23702
23922
  });
23703
23923
  function defaultWorkspaceSettings() {
23704
23924
  return WorkspaceSettings.parse({});
@@ -23793,12 +24013,15 @@ function toCaptureAttributes(event) {
23793
24013
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23794
24014
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23795
24015
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24016
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23796
24017
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23797
24018
  // has ever populated either), but every legacy metadata key still rides
23798
24019
  // the bag rather than being silently dropped — CaptureAttributes'
23799
24020
  // `.catchall(z.unknown())` carries the long tail.
23800
24021
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23801
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24022
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24023
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24024
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23802
24025
  };
23803
24026
  }
23804
24027
  function captureDefinitionVersion(finding) {
@@ -23826,10 +24049,22 @@ var ManagedSettingKey = external_exports.enum([
23826
24049
  "vaultInlineReveal",
23827
24050
  "modelJudgeConsent",
23828
24051
  "dataSharesInPlace",
23829
- "redactFallback"
24052
+ "redactFallback",
24053
+ // Pins the toggle and the day count together — see BodyRetention on why the
24054
+ // two are one unit. An administrator mandating a window wants the count
24055
+ // enforced with it, not one a user can widen while the toggle stays on.
24056
+ "bodyRetention"
23830
24057
  ]).meta({ id: "ManagedSettingKey" });
24058
+ function isManagedSettingKey(value) {
24059
+ return ManagedSettingKey.safeParse(value).success;
24060
+ }
23831
24061
  var ManagedSettingsValues = external_exports.object({
23832
24062
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24063
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24064
+ // plain, non-strict objects: a key under either that this build does not know
24065
+ // is stripped and nothing reports it. The unknown-value split in
24066
+ // ManagedSettings below classifies top-level names only, so it stops at
24067
+ // these boundaries.
23833
24068
  controlPlane: external_exports.object({
23834
24069
  endpoint: external_exports.string().min(1),
23835
24070
  label: external_exports.string().min(1).optional()
@@ -23840,7 +24075,8 @@ var ManagedSettingsValues = external_exports.object({
23840
24075
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23841
24076
  modelJudgeConsent: external_exports.boolean().optional(),
23842
24077
  dataSharesInPlace: external_exports.boolean().optional(),
23843
- redactFallback: RedactFallback.optional()
24078
+ redactFallback: RedactFallback.optional(),
24079
+ bodyRetention: BodyRetention.optional()
23844
24080
  }).meta({ id: "ManagedSettingsValues" });
23845
24081
  var ManagedSettings = external_exports.object({
23846
24082
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23848,11 +24084,59 @@ var ManagedSettings = external_exports.object({
23848
24084
  // decision from a bug. Absent renders as a generic "your organization".
23849
24085
  organization: external_exports.string().min(1).optional(),
23850
24086
  // What the administrator pinned.
23851
- values: ManagedSettingsValues.default({}),
24087
+ //
24088
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24089
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24090
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24091
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24092
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24093
+ // exactly the file an administrator is most likely to write while a fleet
24094
+ // is mid-upgrade.
24095
+ //
24096
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24097
+ // file, which is the outcome the lock half already rejected — an older
24098
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24099
+ // value still fails, because the nested schema is re-run over the known
24100
+ // subset and its issues are re-raised on this parse.
24101
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23852
24102
  // Which of those the user may not change. A key here with no matching value
23853
24103
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23854
24104
  // the user may still override. The two are separable on purpose.
23855
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24105
+ //
24106
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24107
+ // build does not know is dropped from the locked set and reported, never a
24108
+ // reason to refuse the file. The same shape reaches an older build whenever
24109
+ // an administrator locks a key a newer build added, and refusing it there
24110
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24111
+ // the fleets most likely to carry a version skew. A name outside the enum
24112
+ // is still never HONOURED: the lockable set stays explicit above.
24113
+ lockedFields: external_exports.array(external_exports.string()).default([])
24114
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24115
+ const known = [];
24116
+ const unknown2 = [];
24117
+ for (const name of lockedFields) {
24118
+ if (isManagedSettingKey(name)) known.push(name);
24119
+ else unknown2.push(name);
24120
+ }
24121
+ const knownValues = /* @__PURE__ */ Object.create(null);
24122
+ const unknownValues = [];
24123
+ for (const [name, value] of Object.entries(values)) {
24124
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24125
+ else unknownValues.push(name);
24126
+ }
24127
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24128
+ if (!pinned.success) {
24129
+ for (const issue2 of pinned.error.issues)
24130
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24131
+ return external_exports.NEVER;
24132
+ }
24133
+ return {
24134
+ ...rest,
24135
+ values: pinned.data,
24136
+ lockedFields: known,
24137
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24138
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24139
+ };
23856
24140
  }).meta({ id: "ManagedSettings" });
23857
24141
 
23858
24142
  // ../../packages/schema/src/zod/project-files.ts
@@ -23976,7 +24260,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23976
24260
  timestamp: external_exports.iso.date(),
23977
24261
  critical: external_exports.number().int().nonnegative(),
23978
24262
  high: external_exports.number().int().nonnegative(),
23979
- medium: external_exports.number().int().nonnegative()
24263
+ medium: external_exports.number().int().nonnegative(),
24264
+ // Optional and additive, so a producer written against the earlier
24265
+ // three-series contract keeps validating. A consumer plotting it resolves the
24266
+ // absent case itself — the chart point requires a number.
24267
+ low: external_exports.number().int().nonnegative().optional()
23980
24268
  }).meta({ id: "FindingsTimeseriesPoint" });
23981
24269
  var FindingsTimeseriesResponse = external_exports.object({
23982
24270
  range: TimeRange,
@@ -24002,6 +24290,10 @@ var ResolvedFeedItem = external_exports.object({
24002
24290
  findingKey: external_exports.string(),
24003
24291
  ruleId: external_exports.string(),
24004
24292
  severity: Severity,
24293
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24294
+ // identifies the file: a bare path matches the same name in every repo.
24295
+ // Optional and additive; empty when the event carried no repo.
24296
+ repo: external_exports.string().optional(),
24005
24297
  path: external_exports.string(),
24006
24298
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24007
24299
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24107,7 +24399,23 @@ var SaveSettingsInput = external_exports.object({
24107
24399
  modelJudgeConsent: ModelJudgeConsentChoice,
24108
24400
  historySyncConsent: HistorySyncConsentChoice,
24109
24401
  vaultConsent: external_exports.string(),
24110
- vaultInlineReveal: external_exports.string()
24402
+ vaultInlineReveal: external_exports.string(),
24403
+ // Widened to `string` like its neighbours rather than typed as
24404
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24405
+ // the call site, so the domain check receives the type it was written for.
24406
+ //
24407
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24408
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24409
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24410
+ // trade against. The real cost runs the other way and is the part worth
24411
+ // knowing: a value this schema admits and the domain enum then rejects lands
24412
+ // on the action's shared refusal, which names NO field, where a shape
24413
+ // rejection reaches `malformedInput` and names the schema key.
24414
+ redactFallback: external_exports.string(),
24415
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24416
+ // `BodyRetention`'s and the action checks it there, so there is one place
24417
+ // that decides what a legal horizon is rather than two that can drift.
24418
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24111
24419
  });
24112
24420
  var AttachInput = external_exports.object({
24113
24421
  endpoint: external_exports.string(),
@@ -24279,6 +24587,52 @@ function reviewSeverityRank(reasons) {
24279
24587
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24280
24588
  }
24281
24589
 
24590
+ // ../../packages/schema/src/zod/web-capture.ts
24591
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24592
+ var WebUsage = external_exports.object({
24593
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24594
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24595
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24596
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24597
+ });
24598
+ var WebToolCall = external_exports.object({
24599
+ toolUseId: external_exports.string().min(1),
24600
+ toolName: external_exports.string().min(1),
24601
+ target: external_exports.string().optional(),
24602
+ isError: external_exports.boolean().optional(),
24603
+ inputSize: external_exports.number().int().nonnegative().optional(),
24604
+ outputSize: external_exports.number().int().nonnegative().optional()
24605
+ });
24606
+ var WebExchange = external_exports.object({
24607
+ messageId: external_exports.string().min(1),
24608
+ startedAt: external_exports.iso.datetime(),
24609
+ model: external_exports.string().optional(),
24610
+ usage: WebUsage.optional(),
24611
+ usageSource: WebUsageSource,
24612
+ stopReason: external_exports.string().optional(),
24613
+ conversationId: external_exports.string().optional(),
24614
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24615
+ toolCalls: external_exports.array(WebToolCall).default([]),
24616
+ // Absent when the adapter recovered no text. Capped by the caller at
24617
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24618
+ // short capture is never mistaken for a short reply.
24619
+ responseText: external_exports.string().optional(),
24620
+ truncated: external_exports.boolean().default(false)
24621
+ });
24622
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24623
+ var WebCaptureStatus = external_exports.object({
24624
+ patched: external_exports.boolean(),
24625
+ live: external_exports.boolean(),
24626
+ blind: external_exports.boolean(),
24627
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24628
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24629
+ parseFailures: external_exports.number().int().nonnegative(),
24630
+ unparsedBodies: external_exports.number().int().nonnegative(),
24631
+ // The adapter-declared JSON key paths that were absent from a real payload —
24632
+ // the earliest signal that a site's contract moved.
24633
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24634
+ });
24635
+
24282
24636
  // ../../packages/persistence/src/paths.ts
24283
24637
  import {
24284
24638
  chmodSync,
@@ -24639,6 +24993,22 @@ function discardStore(file2, backup) {
24639
24993
  }
24640
24994
  }
24641
24995
 
24996
+ // ../../packages/persistence/src/internal/sql-functions.ts
24997
+ var utf8 = new TextDecoder();
24998
+ function akaLower(value) {
24999
+ if (value === null) return null;
25000
+ if (typeof value === "string") return value.toLowerCase();
25001
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25002
+ return utf8.decode(value).toLowerCase();
25003
+ }
25004
+ function registerSqlFunctions(db) {
25005
+ db.function(
25006
+ "aka_lower",
25007
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25008
+ akaLower
25009
+ );
25010
+ }
25011
+
24642
25012
  // ../../packages/persistence/src/internal/sql-text.ts
24643
25013
  function escapeLikePattern(s) {
24644
25014
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24723,6 +25093,11 @@ function schemaObjectExists(db, kind, name) {
24723
25093
  function indexExists(db, name) {
24724
25094
  return schemaObjectExists(db, "index", name);
24725
25095
  }
25096
+ function indexColumns(db, name) {
25097
+ if (!indexExists(db, name)) return [];
25098
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25099
+ return columns.map((c) => c.name).filter((c) => c !== null);
25100
+ }
24726
25101
  function columnNames(db, table, opts) {
24727
25102
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24728
25103
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24784,6 +25159,647 @@ function mapRowsTolerant(rows, map2) {
24784
25159
  return out;
24785
25160
  }
24786
25161
 
25162
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25163
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25164
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25165
+
25166
+ // ../../packages/persistence/src/sync-failure.ts
25167
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25168
+ function syncFailureRejectCondition(column = "sync_failure") {
25169
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25170
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
25171
+ }
25172
+
25173
+ // ../../packages/persistence/src/repositories/history-sync.ts
25174
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25175
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25176
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25177
+ var COUNTED_EVENT_TYPES = [
25178
+ ...STRUCTURAL_EVENT_TYPES,
25179
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25180
+ ];
25181
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25182
+ var PARTITION_BUCKETS = `
25183
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25184
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25185
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25186
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25187
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25188
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25189
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25190
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25191
+ -- added later lands in no bucket and fails the sum assertion, instead
25192
+ -- of silently joining this one.
25193
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25194
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25195
+ THEN 1 ELSE 0 END) AS failed,
25196
+ COUNT(*) AS total`;
25197
+ var COUNTED_SCOPE = `
25198
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25199
+ AND (
25200
+ event_type IN (${TYPE_LIST})
25201
+ OR synced_at IS NOT NULL
25202
+ OR outbox_owed = 1
25203
+ )`;
25204
+ var SKIPPED = -1;
25205
+ var ROW_COLUMNS = `id,
25206
+ parent_id AS parentId,
25207
+ root_session_id AS rootSessionId,
25208
+ event_type AS eventType,
25209
+ host_id AS hostId,
25210
+ harness_id AS harnessId,
25211
+ source_project_id AS sourceProjectId,
25212
+ started_at AS startedAt,
25213
+ ended_at AS endedAt,
25214
+ severity,
25215
+ priority,
25216
+ content,
25217
+ content_hash AS contentHash,
25218
+ attributes`;
25219
+ var SqliteHistorySyncRepository = class {
25220
+ constructor(db) {
25221
+ this.db = db;
25222
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25223
+ this.sessionsStmt = db.prepare(
25224
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25225
+ FROM audit_events
25226
+ WHERE synced_at IS NULL
25227
+ AND event_type IN (${TYPE_LIST})
25228
+ AND started_at < :before
25229
+ GROUP BY sessionId
25230
+ ORDER BY earliest
25231
+ LIMIT :limit`
25232
+ );
25233
+ this.rowsStmt = db.prepare(
25234
+ `SELECT ${ROW_COLUMNS}
25235
+ FROM audit_events
25236
+ WHERE synced_at IS NULL
25237
+ AND event_type IN (${TYPE_LIST})
25238
+ AND started_at < :before
25239
+ AND COALESCE(root_session_id, id) = :sessionId
25240
+ ORDER BY (event_type = 'session') DESC, started_at
25241
+ LIMIT :limit`
25242
+ );
25243
+ this.captureRowsStmt = db.prepare(
25244
+ `SELECT ${ROW_COLUMNS}
25245
+ FROM audit_events
25246
+ WHERE synced_at IS NULL
25247
+ AND sync_claimed_at IS NULL
25248
+ AND outbox_owed = 1
25249
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25250
+ AND started_at < :before
25251
+ ORDER BY started_at
25252
+ LIMIT :limit`
25253
+ );
25254
+ this.markOwedStmt = db.prepare(
25255
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25256
+ );
25257
+ this.markCaptureBacklogOwedStmt = db.prepare(
25258
+ `UPDATE audit_events SET outbox_owed = 1
25259
+ WHERE synced_at IS NULL
25260
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25261
+ AND started_at < :before`
25262
+ );
25263
+ this.stampStmt = db.prepare(
25264
+ `UPDATE audit_events
25265
+ SET synced_at = :at,
25266
+ sync_claimed_at = NULL,
25267
+ sync_failed_at = :failedAt,
25268
+ sync_failure = :failure
25269
+ WHERE id = :id`
25270
+ );
25271
+ this.claimRowStmt = db.prepare(
25272
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25273
+ );
25274
+ this.releaseRowStmt = db.prepare(
25275
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25276
+ );
25277
+ this.releaseStaleClaimsStmt = db.prepare(
25278
+ `UPDATE audit_events SET sync_claimed_at = NULL
25279
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25280
+ );
25281
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25282
+ FROM audit_events${COUNTED_SCOPE}`);
25283
+ this.partitionByKindStmt = db.prepare(
25284
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25285
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25286
+ GROUP BY event_type`
25287
+ );
25288
+ this.countsStmt = db.prepare(
25289
+ `SELECT
25290
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25291
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25292
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25293
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25294
+ THEN 1 ELSE 0 END) AS skipped,
25295
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25296
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25297
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25298
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25299
+ FROM audit_events
25300
+ WHERE event_type IN (${TYPE_LIST})`
25301
+ );
25302
+ this.captureSkipCountStmt = db.prepare(
25303
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25304
+ // way the structural totals are. The split exists because a refusal is
25305
+ // terminal only against the deployment that gave it, and the structural
25306
+ // re-arm frees it on a change of deployment. The capture lane has no such
25307
+ // escape: re-arming a capture would offer one deployment's undelivered
25308
+ // prompts, with their text, to a deployment that never saw them, which is
25309
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25310
+ // reasons mean the same thing — this row will not be sent — and splitting
25311
+ // them would put refused captures in a bucket nothing reads and nothing
25312
+ // frees.
25313
+ `SELECT COUNT(*) AS skipped
25314
+ FROM audit_events
25315
+ WHERE synced_at = ${String(SKIPPED)}
25316
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25317
+ );
25318
+ this.fingerprintStmt = db.prepare(
25319
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25320
+ FROM history_sync WHERE id = 1`
25321
+ );
25322
+ this.setFingerprintStmt = db.prepare(
25323
+ `UPDATE history_sync
25324
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25325
+ WHERE id = 1`
25326
+ );
25327
+ this.disownCapturesStmt = db.prepare(
25328
+ `UPDATE audit_events SET outbox_owed = NULL
25329
+ WHERE outbox_owed IS NOT NULL
25330
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25331
+ AND started_at < :attachedAt`
25332
+ );
25333
+ this.rearmStmt = db.prepare(
25334
+ `UPDATE audit_events
25335
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25336
+ WHERE (synced_at > 0
25337
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25338
+ AND event_type IN (${TYPE_LIST})`
25339
+ );
25340
+ this.claimStmt = db.prepare(
25341
+ `UPDATE history_sync
25342
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25343
+ WHERE id = 1
25344
+ AND (owner_pid IS NULL
25345
+ OR heartbeat_at IS NULL
25346
+ OR heartbeat_at < :staleBefore
25347
+ OR heartbeat_at > :now)`
25348
+ );
25349
+ this.heartbeatStmt = db.prepare(
25350
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25351
+ );
25352
+ this.releaseStmt = db.prepare(
25353
+ `UPDATE history_sync
25354
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25355
+ WHERE id = 1 AND owner_pid = :pid`
25356
+ );
25357
+ this.closeWindowStmt = db.prepare(
25358
+ `UPDATE audit_events
25359
+ SET synced_at = ${String(SKIPPED)},
25360
+ sync_failed_at = :at,
25361
+ sync_failure = 'detached_undelivered'
25362
+ WHERE synced_at IS NULL
25363
+ AND event_type IN (${TYPE_LIST})
25364
+ AND started_at >= :attachedAt`
25365
+ );
25366
+ this.releaseBoundaryStmt = db.prepare(
25367
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25368
+ );
25369
+ this.freezeBoundaryStmt = db.prepare(
25370
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25371
+ );
25372
+ this.leaseStmt = db.prepare(
25373
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25374
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25375
+ FROM history_sync WHERE id = 1`
25376
+ );
25377
+ this.inspectionsStmt = db.prepare(
25378
+ `SELECT d.rule_id AS ruleId,
25379
+ d.name AS ruleName,
25380
+ d.version AS ruleVersion,
25381
+ d.category AS category,
25382
+ d.severity AS severity,
25383
+ f.span_start AS spanStart,
25384
+ f.span_end AS spanEnd,
25385
+ f.masked_match AS maskedMatch,
25386
+ f.action_taken AS actionTaken,
25387
+ f.confidence AS confidence
25388
+ FROM inspection_findings f
25389
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25390
+ WHERE f.audit_event_id = :auditEventId
25391
+ ORDER BY f.span_start, f.id`
25392
+ );
25393
+ }
25394
+ db;
25395
+ ensureRowStmt;
25396
+ sessionsStmt;
25397
+ rowsStmt;
25398
+ stampStmt;
25399
+ countsStmt;
25400
+ fingerprintStmt;
25401
+ setFingerprintStmt;
25402
+ rearmStmt;
25403
+ claimStmt;
25404
+ heartbeatStmt;
25405
+ releaseStmt;
25406
+ leaseStmt;
25407
+ inspectionsStmt;
25408
+ closeWindowStmt;
25409
+ releaseBoundaryStmt;
25410
+ freezeBoundaryStmt;
25411
+ captureRowsStmt;
25412
+ markOwedStmt;
25413
+ markCaptureBacklogOwedStmt;
25414
+ captureSkipCountStmt;
25415
+ disownCapturesStmt;
25416
+ partitionStmt;
25417
+ partitionByKindStmt;
25418
+ claimRowStmt;
25419
+ releaseRowStmt;
25420
+ releaseStaleClaimsStmt;
25421
+ /**
25422
+ * The masked detections recorded against one tool call.
25423
+ *
25424
+ * These travel with the event because a tool call's target is not
25425
+ * re-inspectable from the event alone — unlike a capture, where the text
25426
+ * itself is re-scannable. What crosses is the masked match and the rule that
25427
+ * produced it, never the value.
25428
+ */
25429
+ inspectionsFor(auditEventId) {
25430
+ return allRows(this.inspectionsStmt, { auditEventId });
25431
+ }
25432
+ /**
25433
+ * Sessions with structural rows still to send, oldest first.
25434
+ *
25435
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25436
+ * read. Anything recorded after the machine attached is the live forward
25437
+ * path's to deliver; this drain exists for what was recorded before it, and a
25438
+ * row both paths send is at best a duplicate request and at worst — for a
25439
+ * session root — an overwrite of the inventory ids the live path resolved.
25440
+ */
25441
+ pendingSessions(limit, before) {
25442
+ return allRows(this.sessionsStmt, { limit, before }).map(
25443
+ (r) => r.sessionId
25444
+ );
25445
+ }
25446
+ /** One session's undelivered structural rows within the backlog, root first. */
25447
+ pendingRows(sessionId, limit, before) {
25448
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25449
+ }
25450
+ /**
25451
+ * Captures this machine still owes the deployment, oldest first.
25452
+ *
25453
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25454
+ * by a time window — see captureRowsStmt for why a window could not express
25455
+ * this. `before` is the grace window that leaves a just-recorded capture to
25456
+ * the live path.
25457
+ */
25458
+ pendingCaptureRows(limit, before) {
25459
+ return allRows(this.captureRowsStmt, { limit, before });
25460
+ }
25461
+ /**
25462
+ * Record that a capture is OWED to the deployment.
25463
+ *
25464
+ * Written by the attached forward path when a live send did not confirm
25465
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25466
+ * a fact rather than an inference: the machine was attached, the send did not
25467
+ * land, so the row is owed — which no time window can state, because the same
25468
+ * window that holds the rows a past attachment left owed also holds every
25469
+ * capture recorded while the machine was DETACHED, and those were never
25470
+ * offered to anyone.
25471
+ *
25472
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25473
+ * out of the drain's read.
25474
+ */
25475
+ markCaptureOwed(id) {
25476
+ this.markOwedStmt.run({ id });
25477
+ }
25478
+ /**
25479
+ * Mark every capture already on disk as owed, as of `before`.
25480
+ *
25481
+ * The consent-time backfill, called once from `aka attach` when a human
25482
+ * grants existing-history consent — never from an ongoing drain pass, and
25483
+ * never inferred from a boundary that could later move. `before` is the
25484
+ * caller's own "now" at the moment consent was granted, so what this marks
25485
+ * is exactly the backlog the consent prompt already counted, not whatever a
25486
+ * later re-attach or key rotation might widen it to.
25487
+ *
25488
+ * Returns how many rows matched, for the caller to log or test against. Not a
25489
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25490
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25491
+ */
25492
+ markCaptureBacklogOwed(before) {
25493
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25494
+ }
25495
+ /**
25496
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25497
+ *
25498
+ * CLEARS any failure reason in the same statement. A row that failed against
25499
+ * one deployment and then landed is delivered, and leaving the reason behind
25500
+ * would leave the store holding two contradictory answers about one row —
25501
+ * with the surface free to render either.
25502
+ */
25503
+ markSynced(ids, atMs) {
25504
+ this.stampAll(ids, atMs, null);
25505
+ }
25506
+ /**
25507
+ * Record that THIS MACHINE cannot express the row on the wire.
25508
+ *
25509
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25510
+ * payload, or a body the client itself refused to send. It fails identically
25511
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25512
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25513
+ * is retried; marking those would turn one outage into permanent data loss.
25514
+ */
25515
+ markSkipped(ids, atMs) {
25516
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25517
+ }
25518
+ /**
25519
+ * Record that THIS DEPLOYMENT refused the row.
25520
+ *
25521
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25522
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25523
+ * row is outstanding rather than why. What separates them is the reason, and
25524
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25525
+ * on one body, so it is terminal only for as long as this machine points at
25526
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25527
+ *
25528
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25529
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25530
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25531
+ */
25532
+ markRefused(ids, atMs) {
25533
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25534
+ }
25535
+ eachInTransaction(ids, run) {
25536
+ if (ids.length === 0) return;
25537
+ withTransaction(
25538
+ this.db,
25539
+ () => {
25540
+ for (const id of ids) run(id);
25541
+ },
25542
+ "IMMEDIATE"
25543
+ );
25544
+ }
25545
+ stampAll(ids, value, failure, failedAtMs) {
25546
+ if (ids.length === 0) return;
25547
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25548
+ withTransaction(
25549
+ this.db,
25550
+ () => {
25551
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25552
+ },
25553
+ "IMMEDIATE"
25554
+ );
25555
+ }
25556
+ /**
25557
+ * Claim rows as in-flight.
25558
+ *
25559
+ * Advisory in exactly the sense the lease is: it records that a send is in
25560
+ * progress so a surface can say so, and a lost claim costs a row showing as
25561
+ * queued while it is actually being sent. It is not exclusion — the far side
25562
+ * settles a duplicate on the row id.
25563
+ */
25564
+ claimRows(ids, atMs) {
25565
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25566
+ }
25567
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25568
+ releaseRows(ids) {
25569
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25570
+ }
25571
+ /**
25572
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25573
+ *
25574
+ * A process killed between claiming and settling leaves rows claimed with
25575
+ * nothing left to settle them. Without this they read as "sending" for ever.
25576
+ */
25577
+ releaseStaleClaims(staleBefore) {
25578
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25579
+ }
25580
+ /**
25581
+ * Every tracked row in exactly one delivery state.
25582
+ *
25583
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25584
+ * pick up now", which is a different question from "what state is this row
25585
+ * in" — and a machine that has never attached has no boundary to pass, so
25586
+ * requiring one would force a caller to invent one and report the whole store
25587
+ * as queued.
25588
+ */
25589
+ /**
25590
+ * The same partition, one row per kind that a lane carries.
25591
+ *
25592
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25593
+ * scope decides which rows exist at all, so a kind that has never been
25594
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25595
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25596
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25597
+ * different things.
25598
+ */
25599
+ partitionByKind() {
25600
+ return allRows(
25601
+ this.partitionByKindStmt,
25602
+ {}
25603
+ ).map((row) => ({
25604
+ kind: row.kind,
25605
+ queued: row.queued ?? 0,
25606
+ inProgress: row.inProgress ?? 0,
25607
+ synced: row.synced ?? 0,
25608
+ failed: row.failed ?? 0,
25609
+ refused: row.refused ?? 0,
25610
+ detached: row.detached ?? 0,
25611
+ total: row.total ?? 0
25612
+ }));
25613
+ }
25614
+ partition() {
25615
+ const row = getRow(this.partitionStmt, {});
25616
+ return {
25617
+ queued: row?.queued ?? 0,
25618
+ inProgress: row?.inProgress ?? 0,
25619
+ synced: row?.synced ?? 0,
25620
+ failed: row?.failed ?? 0,
25621
+ refused: row?.refused ?? 0,
25622
+ detached: row?.detached ?? 0,
25623
+ total: row?.total ?? 0
25624
+ };
25625
+ }
25626
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25627
+ counts(before) {
25628
+ const row = getRow(this.countsStmt, { before });
25629
+ const captures = getRow(this.captureSkipCountStmt);
25630
+ return {
25631
+ pending: row?.pending ?? 0,
25632
+ sent: row?.sent ?? 0,
25633
+ skipped: row?.skipped ?? 0,
25634
+ refused: row?.refused ?? 0,
25635
+ detached: row?.detached ?? 0,
25636
+ capturesSkipped: captures?.skipped ?? 0
25637
+ };
25638
+ }
25639
+ /**
25640
+ * The deployment the current stamps were made against, and where its backlog
25641
+ * ends.
25642
+ *
25643
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25644
+ * machine that has never drained is — and every writer below seeds the row
25645
+ * before it needs one, so nothing depends on this creating it. Keeping the
25646
+ * write off the gate path matters because the gate runs on every pass while a
25647
+ * write has to take the database's write lock.
25648
+ */
25649
+ deployment() {
25650
+ const row = getRow(
25651
+ this.fingerprintStmt
25652
+ );
25653
+ return {
25654
+ fingerprint: row?.fingerprint ?? void 0,
25655
+ backlogBefore: row?.backlogBefore ?? void 0
25656
+ };
25657
+ }
25658
+ /**
25659
+ * Point the ledger at a different deployment, discarding what it recorded
25660
+ * about the previous one.
25661
+ *
25662
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25663
+ * machine has just left are undelivered as far as the new one is concerned.
25664
+ * All four in one transaction, so a crash between them cannot leave stamps
25665
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25666
+ * a disown with no re-mark to follow it.
25667
+ *
25668
+ * The boundary is written HERE and only here, which is what freezes it: a
25669
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25670
+ * unchanged, so this never runs and the backlog does not widen back over rows
25671
+ * the live path has since delivered.
25672
+ *
25673
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25674
+ * granted existing-history consent for the deployment this call is arming —
25675
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25676
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25677
+ * apart. Passed only when that grant is valid, since this method has no way
25678
+ * to check consent itself and must not mark a row owed for a machine that
25679
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25680
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25681
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25682
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25683
+ * on the cleared side of that bound — and the re-mark in the same
25684
+ * transaction is what puts those rows back. A crash between the two cannot
25685
+ * strand the ledger disowned with nothing re-marked — the transaction either
25686
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25687
+ * committed re-enters this method on the very next pass. Omit it (the
25688
+ * structural-only tests do) to exercise the disown in isolation.
25689
+ *
25690
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25691
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25692
+ * live path can mark a capture owed from the moment `aka attach` writes the
25693
+ * descriptor, before the drain's first pass ever reaches this method, and
25694
+ * such a row sits at or after the bound rather than below it. What keeps the
25695
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25696
+ * bound — disown runs first, re-mark second, both inside the one
25697
+ * transaction above.
25698
+ */
25699
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25700
+ this.ensureRowStmt.run();
25701
+ withTransaction(
25702
+ this.db,
25703
+ () => {
25704
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25705
+ this.rearmStmt.run();
25706
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25707
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25708
+ }
25709
+ if (backfillCapturesBefore !== void 0) {
25710
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25711
+ }
25712
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25713
+ },
25714
+ "IMMEDIATE"
25715
+ );
25716
+ }
25717
+ /**
25718
+ * End the attached period: hand its rows to the live path, and release the
25719
+ * boundary so the next attachment can freeze a new one.
25720
+ *
25721
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25722
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25723
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25724
+ * during the detached period, because the machine is not attached. Rows
25725
+ * recorded in that window sit after the boundary and before the re-attach, so
25726
+ * neither path takes them, and the pending count reports none outstanding.
25727
+ *
25728
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25729
+ * closing attachment's to deliver and are no longer outstanding — that is what
25730
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25731
+ * distinction is not academic: this used to write a delivery TIME, which every
25732
+ * read treats as delivery, so one detach turned a window of undelivered rows
25733
+ * into a window of delivered ones and no surface could tell. It writes the
25734
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25735
+ * "received" stop being the same fact.
25736
+ *
25737
+ * A change of deployment still frees them (see the re-arm), because the next
25738
+ * deployment has seen none of this machine's history — so the rows reach it
25739
+ * exactly as they did when this wrote a delivery time.
25740
+ *
25741
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25742
+ * window unstamped — that half-state would re-send the whole attached period
25743
+ * on the next attach, which is the failure the boundary exists to prevent.
25744
+ */
25745
+ closeAttachedWindow(attachedAtMs, atMs) {
25746
+ this.ensureRowStmt.run();
25747
+ withTransaction(
25748
+ this.db,
25749
+ () => {
25750
+ const row = getRow(this.fingerprintStmt);
25751
+ const from = row?.backlogBefore ?? attachedAtMs;
25752
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25753
+ this.releaseBoundaryStmt.run();
25754
+ },
25755
+ "IMMEDIATE"
25756
+ );
25757
+ }
25758
+ /**
25759
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25760
+ *
25761
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25762
+ * different deployment and therefore discards what was delivered to the old
25763
+ * one: here the recipient is the same, so everything already sent to it stays
25764
+ * sent.
25765
+ */
25766
+ freezeBoundary(backlogBefore) {
25767
+ this.ensureRowStmt.run();
25768
+ this.freezeBoundaryStmt.run({ backlogBefore });
25769
+ }
25770
+ /** Take the claim, or report that someone live already holds it. */
25771
+ claim(pid, host, nowMs, staleAfterMs) {
25772
+ this.ensureRowStmt.run();
25773
+ let taken = false;
25774
+ withTransaction(
25775
+ this.db,
25776
+ () => {
25777
+ const result = this.claimStmt.run({
25778
+ pid,
25779
+ host,
25780
+ now: nowMs,
25781
+ staleBefore: nowMs - staleAfterMs
25782
+ });
25783
+ taken = result.changes === 1;
25784
+ },
25785
+ "IMMEDIATE"
25786
+ );
25787
+ return taken;
25788
+ }
25789
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25790
+ heartbeat(pid, nowMs) {
25791
+ this.heartbeatStmt.run({ now: nowMs, pid });
25792
+ }
25793
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25794
+ release(pid) {
25795
+ this.releaseStmt.run({ pid });
25796
+ }
25797
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25798
+ lease() {
25799
+ return getRow(this.leaseStmt);
25800
+ }
25801
+ };
25802
+
24787
25803
  // ../../packages/persistence/src/migrations.ts
24788
25804
  function describeObject(object2) {
24789
25805
  return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
@@ -24796,7 +25812,7 @@ function createdIndexName(statement) {
24796
25812
  return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
24797
25813
  }
24798
25814
  var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24799
- function applyMigrations(db, file2) {
25815
+ function applyMigrations(db, file2, options = {}) {
24800
25816
  const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24801
25817
  db.exec(
24802
25818
  "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
@@ -24810,6 +25826,7 @@ function applyMigrations(db, file2) {
24810
25826
  );
24811
25827
  for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24812
25828
  if (applied.has(migration.tag)) continue;
25829
+ if (options.skipTags?.has(migration.tag) === true) continue;
24813
25830
  if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24814
25831
  const evidence = evidenceObjects(migration.sql);
24815
25832
  const present = evidence.filter((o) => evidenceExists(db, o));
@@ -25216,10 +26233,62 @@ function ensureSyncedAtColumn(db, table) {
25216
26233
  if (!columns.includes("outbox_owed")) {
25217
26234
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25218
26235
  }
26236
+ if (!columns.includes("sync_failed_at")) {
26237
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26238
+ }
26239
+ if (!columns.includes("sync_failure")) {
26240
+ withTransaction(
26241
+ db,
26242
+ () => {
26243
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26244
+ db.exec(
26245
+ `UPDATE ${table} SET synced_at = NULL
26246
+ WHERE synced_at = -1
26247
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26248
+ );
26249
+ },
26250
+ "IMMEDIATE"
26251
+ );
26252
+ }
25219
26253
  db.exec(
25220
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25221
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26254
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26255
+ BEFORE UPDATE OF sync_failure ON ${table}
26256
+ WHEN ${syncFailureRejectCondition()}
26257
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25222
26258
  );
26259
+ const syncIndexColumns = [
26260
+ "event_type",
26261
+ "synced_at",
26262
+ "sync_claimed_at",
26263
+ "started_at",
26264
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26265
+ // has to be in the index for the read to stay covered — but putting it
26266
+ // ahead of `started_at` would reorder the prefix the structural drain's
26267
+ // reads match on.
26268
+ "sync_failure"
26269
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26270
+ //
26271
+ // The delivery-state read tests it — a capture's state depends on whether a
26272
+ // live forward marked it owed — so carrying it here makes that read covering
26273
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26274
+ // But a sixth column changes what the planner charges for this index, and
26275
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26276
+ // then stops choosing the per-session index for the token rollup and walks
26277
+ // every `llm_call` in the store through the event-type index instead. That
26278
+ // read grows with the store; this one does not.
26279
+ //
26280
+ // 40 ms on the largest store measured, once per render, is a cost worth
26281
+ // paying to leave every other read's plan where it was.
26282
+ ];
26283
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26284
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26285
+ if (!syncIndexMatches) {
26286
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26287
+ db.exec(
26288
+ `CREATE INDEX idx_audit_events_sync
26289
+ ON audit_events (${syncIndexColumns.join(", ")})`
26290
+ );
26291
+ }
25223
26292
  db.exec(
25224
26293
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25225
26294
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25441,7 +26510,11 @@ function buildAuditEvent(row) {
25441
26510
  link: linkParsed?.success ? linkParsed.data : null,
25442
26511
  targetId: row.target_id,
25443
26512
  internal: intToBool(row.internal),
25444
- flagged: intToBool(row.flagged)
26513
+ flagged: intToBool(row.flagged),
26514
+ // Only meaningful when the title came out empty — a row whose body was
26515
+ // expired but whose title fell back to `tool_name` still has something to
26516
+ // render, and flagging it would make the view apologise for nothing.
26517
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25445
26518
  };
25446
26519
  }
25447
26520
  var TIMELINE_COLUMNS = `
@@ -25449,6 +26522,7 @@ var TIMELINE_COLUMNS = `
25449
26522
  event_type,
25450
26523
  started_at,
25451
26524
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26525
+ content_expired_at,
25452
26526
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25453
26527
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25454
26528
  json_extract(attributes, '$.severity') AS severity,
@@ -25575,7 +26649,8 @@ var SqliteActivityRepository = class {
25575
26649
  SELECT 1 FROM audit_events d
25576
26650
  WHERE d.root_session_id = audit_events.id
25577
26651
  AND (d.content LIKE ? ESCAPE '\\'
25578
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26652
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26653
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25579
26654
  );
25580
26655
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25581
26656
  }
@@ -26113,6 +27188,88 @@ var SqliteAuditEventsRepository = class {
26113
27188
  }
26114
27189
  };
26115
27190
 
27191
+ // ../../packages/persistence/src/repositories/body-retention.ts
27192
+ var DEFAULT_BATCH_SIZE = 500;
27193
+ var DEFAULT_MAX_ROWS = 5e4;
27194
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27195
+ var SqliteBodyRetentionRepository = class {
27196
+ constructor(db) {
27197
+ this.db = db;
27198
+ const select = (laneClause) => `
27199
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27200
+ FROM audit_events
27201
+ WHERE content IS NOT NULL
27202
+ AND started_at < :cutoff
27203
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27204
+ ${laneClause}
27205
+ ORDER BY started_at
27206
+ LIMIT :limit`;
27207
+ this.candidatesStmt = this.db.prepare(select(""));
27208
+ this.candidatesSyncSafeStmt = this.db.prepare(
27209
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27210
+ );
27211
+ this.heldBySyncStmt = this.db.prepare(`
27212
+ SELECT COUNT(*) AS n
27213
+ FROM audit_events
27214
+ WHERE content IS NOT NULL
27215
+ AND started_at < :cutoff
27216
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27217
+ AND synced_at IS NULL`);
27218
+ this.expireStmt = this.db.prepare(
27219
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27220
+ );
27221
+ }
27222
+ db;
27223
+ candidatesStmt;
27224
+ candidatesSyncSafeStmt;
27225
+ heldBySyncStmt;
27226
+ expireStmt;
27227
+ /** How many bytes a pass with these options would free, changing nothing. */
27228
+ preview(opts) {
27229
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27230
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27231
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27232
+ return {
27233
+ rowsExpired: rows.length,
27234
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27235
+ rowsHeldBySync: this.countHeldBySync(opts)
27236
+ };
27237
+ }
27238
+ /** Clear eligible bodies, in bounded batches. */
27239
+ expire(opts) {
27240
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27241
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27242
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27243
+ let rowsExpired = 0;
27244
+ let bytesFreed = 0;
27245
+ let done = true;
27246
+ while (rowsExpired < maxRows) {
27247
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27248
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27249
+ if (batch.length === 0) break;
27250
+ withTransaction(
27251
+ this.db,
27252
+ () => {
27253
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27254
+ },
27255
+ "IMMEDIATE"
27256
+ );
27257
+ rowsExpired += batch.length;
27258
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27259
+ if (batch.length < remaining) break;
27260
+ if (rowsExpired >= maxRows) {
27261
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27262
+ }
27263
+ }
27264
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27265
+ }
27266
+ countHeldBySync(opts) {
27267
+ if (opts.sweepSyncLane) return 0;
27268
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27269
+ return row.n;
27270
+ }
27271
+ };
27272
+
26116
27273
  // ../../packages/persistence/src/repositories/classified-data.ts
26117
27274
  var SqliteClassifiedDataRepository = class {
26118
27275
  constructor(db) {
@@ -26913,23 +28070,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26913
28070
  )`;
26914
28071
 
26915
28072
  // ../../packages/persistence/src/repositories/findings.ts
26916
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26917
- var DEFAULT_LOCATIONS_LIMIT = 100;
26918
- var LOCATION_RULE_IDS_CAP = 20;
26919
- function compareLocationOrder(a, b) {
26920
- return compareFindingGroupOrder(
26921
- {
26922
- severity: a.maxSeverity,
26923
- latestDetectedAt: a.latestDetectedAt,
26924
- id: ""
26925
- },
26926
- {
26927
- severity: b.maxSeverity,
26928
- latestDetectedAt: b.latestDetectedAt,
26929
- id: ""
26930
- }
26931
- );
26932
- }
26933
28073
  var CONCAT_SEP = ",";
26934
28074
  var TUPLE_SEP = "|";
26935
28075
  function splitConcat(value) {
@@ -26958,7 +28098,15 @@ function toFlatFindingRow(r) {
26958
28098
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26959
28099
  eventId: r.event_id,
26960
28100
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26961
- status: deriveInstanceStatus(r)
28101
+ status: deriveInstanceStatus(r),
28102
+ delivery: deriveFindingDelivery({
28103
+ kind: r.kind,
28104
+ syncedAt: r.synced_at,
28105
+ syncClaimedAt: r.sync_claimed_at,
28106
+ syncFailedAt: r.sync_failed_at,
28107
+ syncFailure: r.sync_failure,
28108
+ outboxOwed: r.outbox_owed
28109
+ })
26962
28110
  };
26963
28111
  }
26964
28112
  function encodeGroupCursor(group) {
@@ -26981,13 +28129,51 @@ function decodeGroupCursor(cursor) {
26981
28129
  return null;
26982
28130
  }
26983
28131
  function firstAfter(sorted, cursor) {
26984
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28132
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26985
28133
  return index === -1 ? sorted.length : index;
26986
28134
  }
26987
28135
  function findDeepLinked(sorted, page, id) {
26988
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26989
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28136
+ if (page.some((t) => t.id === id)) return void 0;
28137
+ return sorted.find((t) => t.id === id);
28138
+ }
28139
+ function encodeLocationCursor(location) {
28140
+ const payload = {
28141
+ sev: location.maxSeverity,
28142
+ t: location.latestDetectedAt,
28143
+ r: location.repo,
28144
+ f: location.file
28145
+ };
28146
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28147
+ }
28148
+ function decodeLocationCursor(cursor) {
28149
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28150
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28151
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28152
+ }
28153
+ return null;
28154
+ }
28155
+ function firstLocationAfter(sorted, cursor) {
28156
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28157
+ return index === -1 ? sorted.length : index;
26990
28158
  }
28159
+ function findDeepLinkedLocation(sorted, page, id) {
28160
+ if (page.some((l) => l.id === id)) return void 0;
28161
+ return sorted.find((l) => l.id === id);
28162
+ }
28163
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28164
+ d.severity AS severity, f.masked_match AS masked_match,
28165
+ f.action_taken AS action_taken, f.confidence AS confidence,
28166
+ e.started_at AS occurred_at,
28167
+ e.source_tool AS source_tool,
28168
+ e.repo AS repo,
28169
+ e.file_path AS file,
28170
+ e.tool_name AS tool_name,
28171
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28172
+ e.event_type AS kind, f.finding_key AS finding_key,
28173
+ ${latestResolutionStatusSql("f")} AS latest_status,
28174
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28175
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28176
+ e.outbox_owed AS outbox_owed`;
26991
28177
  var DAY_MS3 = 864e5;
26992
28178
  var SqliteFindingsRepository = class {
26993
28179
  constructor(db) {
@@ -27108,30 +28294,26 @@ var SqliteFindingsRepository = class {
27108
28294
  );
27109
28295
  }
27110
28296
  /**
27111
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27112
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27113
- * attributes bag, rule_id/category/severity from the definition), scoped to
27114
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27115
- * rows this list must never surface), groups by ruleId, computes
27116
- * per-filter-excluded facets, applies the requested filters, and sorts by
27117
- * severity then recency. Filtering
27118
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27119
- * reflect the full filtered set; `items` is the requested
27120
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27121
- * filter, `totals.findings` counts only instances whose derived status was
27122
- * requested, and each item's instance preview is narrowed the same way.
28297
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28298
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28299
+ * list must never surface), with per-filter-excluded facets, the requested
28300
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28301
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28302
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28303
+ * Under a `status` filter, `totals.findings` counts only findings whose
28304
+ * derived status was requested.
28305
+ *
28306
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28307
+ * folding EVERY finding into the numbers a type row and the filters need
28308
+ * (count, severity, category, providers, actions, statuses, latest, search
28309
+ * text). The findings OF a type come from listFindingInstances scoped to
28310
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27123
28311
  *
27124
- * Two reads, neither of which materializes a row per finding:
27125
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27126
- * the group and the filters need (count, providers, actions, statuses,
27127
- * latest, search text);
27128
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27129
- * populate `instances` for the table's expanded rows.
27130
28312
  * The aggregates carry raw DB values and are translated by the same
27131
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27132
- * rule is ever restated in SQL.
28313
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28314
+ * status rule is ever restated in SQL.
27133
28315
  */
27134
- listGroupedFindings(query) {
28316
+ listFindingTypes(query) {
27135
28317
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27136
28318
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27137
28319
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27144,12 +28326,7 @@ var SqliteFindingsRepository = class {
27144
28326
  predicate,
27145
28327
  params: sessionParams
27146
28328
  });
27147
- const rows = this.previewRows(aggregates, {
27148
- sessionId: query.sessionId,
27149
- from: query.from
27150
- });
27151
- const groupable = rows.map(toFlatFindingRow);
27152
- const allGroups = buildFindingGroups(groupable, { aggregates });
28329
+ const allTypes = buildFindingTypes(aggregates);
27153
28330
  const filterOpts = {
27154
28331
  severity: query.severity,
27155
28332
  providers: query.provider,
@@ -27158,30 +28335,25 @@ var SqliteFindingsRepository = class {
27158
28335
  subtype: query.subtype,
27159
28336
  q: query.q
27160
28337
  };
27161
- const facets = computeFindingFacets(allGroups, filterOpts);
27162
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28338
+ const facets = computeFindingFacets(allTypes, filterOpts);
28339
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27163
28340
  const statusFilter = query.status ?? [];
27164
28341
  const totals = {
27165
- findings: sorted.reduce((acc, g) => {
27166
- if (statusFilter.length === 0) return acc + g.instanceCount;
27167
- const agg = aggregates.get(g.id);
27168
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28342
+ findings: sorted.reduce((acc, t) => {
28343
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28344
+ const agg = aggregates.get(t.id);
28345
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27169
28346
  }, 0),
27170
- groups: sorted.length
28347
+ types: sorted.length
27171
28348
  };
27172
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28349
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27173
28350
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27174
28351
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27175
28352
  const page = sorted.slice(start, start + limit);
27176
28353
  const lastOnPage = page.at(-1);
27177
28354
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27178
28355
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27179
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27180
- const narrow = (g) => statusSet ? {
27181
- ...g,
27182
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27183
- } : g;
27184
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28356
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27185
28357
  return Promise.resolve({
27186
28358
  totals,
27187
28359
  facets,
@@ -27192,7 +28364,7 @@ var SqliteFindingsRepository = class {
27192
28364
  }
27193
28365
  /**
27194
28366
  * One row per rule_id, folding EVERY instance of the group into the values
27195
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28367
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27196
28368
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27197
28369
  *
27198
28370
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27246,6 +28418,7 @@ var SqliteFindingsRepository = class {
27246
28418
  providers: query.provider,
27247
28419
  actions: query.action,
27248
28420
  statuses: query.status,
28421
+ deliveries: query.deployment,
27249
28422
  tools: query.tool,
27250
28423
  repo: query.repo,
27251
28424
  file: query.file,
@@ -27286,13 +28459,25 @@ var SqliteFindingsRepository = class {
27286
28459
  });
27287
28460
  }
27288
28461
  /**
27289
- * The same findings folded by location: repository, then file within it.
28462
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27290
28463
  *
27291
28464
  * The grouping keys come from the capturing event's attributes, which is what
27292
- * the local store relates a finding to — there is no finding↔asset row to
27293
- * group by instead. A repo or file the event did not record folds into the
27294
- * empty-string bucket, which the view renders but does not link, since no
27295
- * filter can name it.
28465
+ * the local store relates a finding to; there is no finding↔asset row to group
28466
+ * by instead. A repo or file the event did not record folds into the
28467
+ * empty-string bucket, which is a real location like any other: it is listed,
28468
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28469
+ *
28470
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28471
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28472
+ * list was rebuilt to remove — and two-level pagination inside an
28473
+ * expand/collapse table is what pushed that view to master/detail in the first
28474
+ * place.
28475
+ *
28476
+ * Every filter narrows the FINDINGS and the locations fall out of what
28477
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28478
+ * reports for the same filters scoped to that pair. The view depends on it:
28479
+ * one toolbar sits over both panels precisely because a location owns none of
28480
+ * its fields.
27296
28481
  */
27297
28482
  listFindingLocations(query) {
27298
28483
  const opts = {
@@ -27301,16 +28486,20 @@ var SqliteFindingsRepository = class {
27301
28486
  providers: query.provider,
27302
28487
  actions: query.action,
27303
28488
  statuses: query.status,
28489
+ deliveries: query.deployment,
27304
28490
  tools: query.tool,
27305
28491
  q: query.q
27306
28492
  };
27307
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28493
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28494
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27308
28495
  const byRepo = /* @__PURE__ */ new Map();
28496
+ const accumulator = createInstanceFacetAccumulator(opts);
27309
28497
  let total = 0;
27310
28498
  for (const row of this.scanFindingRows({
27311
28499
  sessionId: query.sessionId,
27312
28500
  from: query.from
27313
28501
  })) {
28502
+ accumulator.add(row);
27314
28503
  if (!matchesInstanceFilters(row, opts)) continue;
27315
28504
  total += 1;
27316
28505
  let files = byRepo.get(row.repo);
@@ -27325,103 +28514,35 @@ var SqliteFindingsRepository = class {
27325
28514
  }
27326
28515
  addToLocation(acc, row);
27327
28516
  }
27328
- let fileCount = 0;
27329
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27330
- fileCount += files.size;
27331
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27332
- file: file2,
27333
- instanceCount: acc.instanceCount,
27334
- maxSeverity: acc.maxSeverity,
27335
- latestDetectedAt: acc.latestDetectedAt,
27336
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27337
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27338
- })).sort(compareLocationOrder);
27339
- const rollup = fileRows.reduce(
27340
- (a, f) => ({
27341
- instanceCount: a.instanceCount + f.instanceCount,
27342
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27343
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27344
- }),
27345
- {
27346
- instanceCount: 0,
27347
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27348
- latestDetectedAt: ""
27349
- }
27350
- );
27351
- const statuses = fileRows.map((f) => f.status);
27352
- const folded = foldGroupStatus(statuses);
27353
- return {
27354
- repo,
27355
- instanceCount: rollup.instanceCount,
27356
- maxSeverity: rollup.maxSeverity,
27357
- latestDetectedAt: rollup.latestDetectedAt,
27358
- ...folded === void 0 ? {} : { status: folded },
27359
- files: fileRows
27360
- };
27361
- });
27362
- repos.sort(compareLocationOrder);
28517
+ const sorted = [];
28518
+ for (const [repo, files] of byRepo) {
28519
+ for (const [file2, acc] of files) {
28520
+ const status = foldGroupStatus(acc.statuses);
28521
+ sorted.push({
28522
+ id: encodeLocationId(repo, file2),
28523
+ repo,
28524
+ file: file2,
28525
+ instanceCount: acc.instanceCount,
28526
+ maxSeverity: acc.maxSeverity,
28527
+ latestDetectedAt: acc.latestDetectedAt,
28528
+ ...status === void 0 ? {} : { status },
28529
+ ruleIds: [...acc.ruleIds]
28530
+ });
28531
+ }
28532
+ }
28533
+ sorted.sort(compareLocationOrder);
28534
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28535
+ const page = sorted.slice(start, start + limit);
28536
+ const lastOnPage = page.at(-1);
28537
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28538
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27363
28539
  return Promise.resolve({
27364
- totals: { findings: total, repos: repos.length, files: fileCount },
27365
- items: repos.slice(0, limit),
27366
- hasMore: repos.length > limit
28540
+ totals: { findings: total, locations: sorted.length },
28541
+ facets: accumulator.facets(),
28542
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28543
+ nextCursor
27367
28544
  });
27368
28545
  }
27369
- /**
27370
- * Each group's newest instances, for the table's expanded rows.
27371
- *
27372
- * ONE index-ordered scan with early termination, and the shape is the point.
27373
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27374
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27375
- * through a temp B-tree to keep a bounded preview of each group, and then
27376
- * sorts the survivors again for the page order. Both sorts grow with the
27377
- * store while the answer does not.
27378
- *
27379
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27380
- * (or the session or window index the scope names — see `findingScanSql`),
27381
- * which is already the order the page wants, and keeps rows per rule until
27382
- * each rule has as many as it can show. The aggregate the caller already holds
27383
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27384
- * per rule, summed, is the number of rows this scan has to find, and it stops
27385
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27386
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27387
- * store with many firing rules widens it. The bound that DOES hold
27388
- * unconditionally is the sorted form's floor: this scan visits at most as
27389
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27390
- * sorted, and stops the moment every rule has its cap, where the sorted form
27391
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27392
- * wanted instances sitting at the tail of the scope — is one pass over
27393
- * everything in scope with a block sort of the id tie-break only, never a
27394
- * sort of the scope, which is still that floor.
27395
- *
27396
- * A row whose rule the aggregate did not see is skipped: the two statements
27397
- * run without a shared snapshot, so a capture landing between them can add a
27398
- * rule here that has no counts there, and the counts are what the group is
27399
- * built from.
27400
- */
27401
- previewRows(aggregates, scope) {
27402
- const wanted = /* @__PURE__ */ new Map();
27403
- let remaining = 0;
27404
- for (const [ruleId, agg] of aggregates) {
27405
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27406
- wanted.set(ruleId, n);
27407
- remaining += n;
27408
- }
27409
- const rows = [];
27410
- if (remaining === 0) return rows;
27411
- const { sql, params } = this.findingScanSql(scope);
27412
- const taken = /* @__PURE__ */ new Map();
27413
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27414
- const want = wanted.get(r.rule_id);
27415
- if (want === void 0) continue;
27416
- const have = taken.get(r.rule_id) ?? 0;
27417
- if (have >= want) continue;
27418
- taken.set(r.rule_id, have + 1);
27419
- rows.push(r);
27420
- remaining -= 1;
27421
- if (remaining === 0) break;
27422
- }
27423
- return rows;
27424
- }
27425
28546
  /**
27426
28547
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27427
28548
  *
@@ -27448,6 +28569,33 @@ var SqliteFindingsRepository = class {
27448
28569
  yield toFlatFindingRow(r);
27449
28570
  }
27450
28571
  }
28572
+ /**
28573
+ * One finding by its own id, or null when no such row exists.
28574
+ *
28575
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28576
+ * the store — and, unlike anything derived from a list page, it resolves a
28577
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28578
+ * deep link needs: the id it carries may name a finding thousands of rows
28579
+ * older than anything a first page holds.
28580
+ *
28581
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28582
+ * RESOLVES an id; whether that row would survive the list's current filters is
28583
+ * a different question, and hiding the target because a filter excludes it is
28584
+ * worse than showing it.
28585
+ *
28586
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28587
+ * type should the list select?" and "what does the drawer show?".
28588
+ */
28589
+ findingInstance(id) {
28590
+ const row = this.db.prepare(
28591
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28592
+ FROM inspection_findings f
28593
+ JOIN audit_events e ON e.id = f.audit_event_id
28594
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28595
+ WHERE f.id = ?`
28596
+ ).get(id);
28597
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28598
+ }
27451
28599
  /**
27452
28600
  * The one statement both instance-level scans run: every finding in scope,
27453
28601
  * joined to its event and definition, newest first.
@@ -27481,17 +28629,7 @@ var SqliteFindingsRepository = class {
27481
28629
  conditions.push("e.started_at >= ?");
27482
28630
  params.push(isoToEpochMillis(scope.from));
27483
28631
  }
27484
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27485
- d.severity AS severity, f.masked_match AS masked_match,
27486
- f.action_taken AS action_taken, f.confidence AS confidence,
27487
- e.started_at AS occurred_at,
27488
- e.source_tool AS source_tool,
27489
- e.repo AS repo,
27490
- e.file_path AS file,
27491
- e.tool_name AS tool_name,
27492
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27493
- e.event_type AS kind, f.finding_key AS finding_key,
27494
- ${latestResolutionStatusSql("f")} AS latest_status
28632
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27495
28633
  FROM audit_events e
27496
28634
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27497
28635
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27505,6 +28643,26 @@ var SqliteFindingsRepository = class {
27505
28643
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27506
28644
  const rows = this.db.prepare(
27507
28645
  `SELECT rule_id,
28646
+ -- BARE columns beside max(latest_at), which is deliberate and
28647
+ -- is SQLite's documented behaviour: with a single min()/max()
28648
+ -- in an aggregate query, every bare column takes its value from
28649
+ -- the row that produced the extremum. So these are the severity
28650
+ -- and category of the definition whose finding is NEWEST, which
28651
+ -- is what the row-based build they replaced read off its first
28652
+ -- (newest-first) row.
28653
+ --
28654
+ -- min() is WRONG here and was the defect: inspection_definitions
28655
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28656
+ -- mints a new row), so a rule whose severity moved between
28657
+ -- versions has several, and min() picks the ALPHABETICALLY
28658
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28659
+ -- That is arbitrary in direction, and it feeds the badge, the
28660
+ -- filter, the facet counts and the primary sort key.
28661
+ --
28662
+ -- Adding a second min()/max() aggregate here would make these
28663
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28664
+ severity,
28665
+ category,
27508
28666
  sum(tuple_count) AS instance_count,
27509
28667
  max(latest_at) AS latest_at,
27510
28668
  group_concat(source_tools) AS source_tools,
@@ -27515,6 +28673,14 @@ var SqliteFindingsRepository = class {
27515
28673
  group_concat(tool_names) AS tool_names
27516
28674
  FROM (
27517
28675
  SELECT d.rule_id AS rule_id,
28676
+ -- Severity and category are columns of the DEFINITION, and
28677
+ -- a rule can have SEVERAL definitions (one per version), so
28678
+ -- these are grouped on below and resolved to the newest
28679
+ -- firing version by the outer query's bare-column select.
28680
+ -- They ride the aggregate because the type build has no rows
28681
+ -- to read them off \u2014 see buildFindingTypes.
28682
+ d.severity AS severity,
28683
+ d.category AS category,
27518
28684
  e.event_type || '${TUPLE_SEP}' ||
27519
28685
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27520
28686
  coalesce(latest.status, '') AS status_tuple,
@@ -27529,7 +28695,7 @@ var SqliteFindingsRepository = class {
27529
28695
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27530
28696
  ON latest.finding_key = f.finding_key
27531
28697
  ${scope.predicate}
27532
- GROUP BY d.rule_id, status_tuple
28698
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27533
28699
  )
27534
28700
  GROUP BY rule_id`
27535
28701
  ).all(scope.params);
@@ -27538,6 +28704,8 @@ var SqliteFindingsRepository = class {
27538
28704
  r.rule_id,
27539
28705
  {
27540
28706
  instanceCount: r.instance_count,
28707
+ severity: r.severity,
28708
+ category: r.category,
27541
28709
  sourceTools: splitConcat(r.source_tools),
27542
28710
  actionsTaken: splitConcat(r.actions_taken),
27543
28711
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27554,7 +28722,7 @@ var SqliteFindingsRepository = class {
27554
28722
  latestDetectedAt: epochMillisToIso(r.latest_at),
27555
28723
  // Free text only — joined and substring-matched, so group_concat's
27556
28724
  // commas need no unpicking (a repo/path containing one still matches).
27557
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28725
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27558
28726
  // tell "no q this request" from "a group with no repo/file at all"
27559
28727
  // and skip priming a haystack nothing will read.
27560
28728
  ...withSearchText ? {
@@ -27582,7 +28750,9 @@ var SqliteFindingsRepository = class {
27582
28750
  )
27583
28751
  );
27584
28752
  for (const row of grouped) {
27585
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28753
+ if (Object.hasOwn(byAction, row.action_taken)) {
28754
+ byAction[row.action_taken] = row.c;
28755
+ }
27586
28756
  }
27587
28757
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27588
28758
  const sevRows = allRows(
@@ -27599,7 +28769,9 @@ var SqliteFindingsRepository = class {
27599
28769
  )
27600
28770
  );
27601
28771
  for (const row of sevRows) {
27602
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28772
+ if (Object.hasOwn(bySeverity, row.severity)) {
28773
+ bySeverity[row.severity] = row.c;
28774
+ }
27603
28775
  }
27604
28776
  const categories = ENFORCEABLE_CATEGORIES;
27605
28777
  const enabledRows = allRows(
@@ -27648,469 +28820,6 @@ function isoDay(ms) {
27648
28820
  return new Date(ms).toISOString().slice(0, 10);
27649
28821
  }
27650
28822
 
27651
- // ../../packages/persistence/src/repositories/history-sync.ts
27652
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27653
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27654
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27655
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27656
- var SKIPPED = -1;
27657
- var ROW_COLUMNS = `id,
27658
- parent_id AS parentId,
27659
- root_session_id AS rootSessionId,
27660
- event_type AS eventType,
27661
- host_id AS hostId,
27662
- harness_id AS harnessId,
27663
- source_project_id AS sourceProjectId,
27664
- started_at AS startedAt,
27665
- ended_at AS endedAt,
27666
- severity,
27667
- priority,
27668
- content,
27669
- content_hash AS contentHash,
27670
- attributes`;
27671
- var SqliteHistorySyncRepository = class {
27672
- constructor(db) {
27673
- this.db = db;
27674
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27675
- this.sessionsStmt = db.prepare(
27676
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27677
- FROM audit_events
27678
- WHERE synced_at IS NULL
27679
- AND event_type IN (${TYPE_LIST})
27680
- AND started_at < :before
27681
- GROUP BY sessionId
27682
- ORDER BY earliest
27683
- LIMIT :limit`
27684
- );
27685
- this.rowsStmt = db.prepare(
27686
- `SELECT ${ROW_COLUMNS}
27687
- FROM audit_events
27688
- WHERE synced_at IS NULL
27689
- AND event_type IN (${TYPE_LIST})
27690
- AND started_at < :before
27691
- AND COALESCE(root_session_id, id) = :sessionId
27692
- ORDER BY (event_type = 'session') DESC, started_at
27693
- LIMIT :limit`
27694
- );
27695
- this.captureRowsStmt = db.prepare(
27696
- `SELECT ${ROW_COLUMNS}
27697
- FROM audit_events
27698
- WHERE synced_at IS NULL
27699
- AND sync_claimed_at IS NULL
27700
- AND outbox_owed = 1
27701
- AND event_type IN (${CAPTURE_TYPE_LIST})
27702
- AND started_at < :before
27703
- ORDER BY started_at
27704
- LIMIT :limit`
27705
- );
27706
- this.markOwedStmt = db.prepare(
27707
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27708
- );
27709
- this.stampStmt = db.prepare(
27710
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27711
- );
27712
- this.claimRowStmt = db.prepare(
27713
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27714
- );
27715
- this.releaseRowStmt = db.prepare(
27716
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27717
- );
27718
- this.releaseStaleClaimsStmt = db.prepare(
27719
- `UPDATE audit_events SET sync_claimed_at = NULL
27720
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27721
- );
27722
- this.partitionStmt = db.prepare(
27723
- `SELECT
27724
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27725
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27726
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27727
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27728
- COUNT(*) AS total
27729
- FROM audit_events
27730
- WHERE event_type IN (${TYPE_LIST})`
27731
- );
27732
- this.countsStmt = db.prepare(
27733
- `SELECT
27734
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27735
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27736
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27737
- FROM audit_events
27738
- WHERE event_type IN (${TYPE_LIST})`
27739
- );
27740
- this.captureSkipCountStmt = db.prepare(
27741
- `SELECT COUNT(*) AS skipped
27742
- FROM audit_events
27743
- WHERE synced_at = ${String(SKIPPED)}
27744
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27745
- );
27746
- this.fingerprintStmt = db.prepare(
27747
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27748
- FROM history_sync WHERE id = 1`
27749
- );
27750
- this.setFingerprintStmt = db.prepare(
27751
- `UPDATE history_sync
27752
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27753
- WHERE id = 1`
27754
- );
27755
- this.disownCapturesStmt = db.prepare(
27756
- `UPDATE audit_events SET outbox_owed = NULL
27757
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27758
- );
27759
- this.rearmStmt = db.prepare(
27760
- `UPDATE audit_events SET synced_at = NULL
27761
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27762
- );
27763
- this.claimStmt = db.prepare(
27764
- `UPDATE history_sync
27765
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27766
- WHERE id = 1
27767
- AND (owner_pid IS NULL
27768
- OR heartbeat_at IS NULL
27769
- OR heartbeat_at < :staleBefore
27770
- OR heartbeat_at > :now)`
27771
- );
27772
- this.heartbeatStmt = db.prepare(
27773
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27774
- );
27775
- this.releaseStmt = db.prepare(
27776
- `UPDATE history_sync
27777
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27778
- WHERE id = 1 AND owner_pid = :pid`
27779
- );
27780
- this.closeWindowStmt = db.prepare(
27781
- `UPDATE audit_events SET synced_at = :at
27782
- WHERE synced_at IS NULL
27783
- AND event_type IN (${TYPE_LIST})
27784
- AND started_at >= :attachedAt`
27785
- );
27786
- this.releaseBoundaryStmt = db.prepare(
27787
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27788
- );
27789
- this.freezeBoundaryStmt = db.prepare(
27790
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27791
- );
27792
- this.leaseStmt = db.prepare(
27793
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27794
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27795
- FROM history_sync WHERE id = 1`
27796
- );
27797
- this.inspectionsStmt = db.prepare(
27798
- `SELECT d.rule_id AS ruleId,
27799
- d.name AS ruleName,
27800
- d.version AS ruleVersion,
27801
- d.category AS category,
27802
- d.severity AS severity,
27803
- f.span_start AS spanStart,
27804
- f.span_end AS spanEnd,
27805
- f.masked_match AS maskedMatch,
27806
- f.action_taken AS actionTaken,
27807
- f.confidence AS confidence
27808
- FROM inspection_findings f
27809
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27810
- WHERE f.audit_event_id = :auditEventId
27811
- ORDER BY f.span_start, f.id`
27812
- );
27813
- }
27814
- db;
27815
- ensureRowStmt;
27816
- sessionsStmt;
27817
- rowsStmt;
27818
- stampStmt;
27819
- countsStmt;
27820
- fingerprintStmt;
27821
- setFingerprintStmt;
27822
- rearmStmt;
27823
- claimStmt;
27824
- heartbeatStmt;
27825
- releaseStmt;
27826
- leaseStmt;
27827
- inspectionsStmt;
27828
- closeWindowStmt;
27829
- releaseBoundaryStmt;
27830
- freezeBoundaryStmt;
27831
- captureRowsStmt;
27832
- markOwedStmt;
27833
- captureSkipCountStmt;
27834
- disownCapturesStmt;
27835
- partitionStmt;
27836
- claimRowStmt;
27837
- releaseRowStmt;
27838
- releaseStaleClaimsStmt;
27839
- /**
27840
- * The masked detections recorded against one tool call.
27841
- *
27842
- * These travel with the event because a tool call's target is not
27843
- * re-inspectable from the event alone — unlike a capture, where the text
27844
- * itself is re-scannable. What crosses is the masked match and the rule that
27845
- * produced it, never the value.
27846
- */
27847
- inspectionsFor(auditEventId) {
27848
- return allRows(this.inspectionsStmt, { auditEventId });
27849
- }
27850
- /**
27851
- * Sessions with structural rows still to send, oldest first.
27852
- *
27853
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27854
- * read. Anything recorded after the machine attached is the live forward
27855
- * path's to deliver; this drain exists for what was recorded before it, and a
27856
- * row both paths send is at best a duplicate request and at worst — for a
27857
- * session root — an overwrite of the inventory ids the live path resolved.
27858
- */
27859
- pendingSessions(limit, before) {
27860
- return allRows(this.sessionsStmt, { limit, before }).map(
27861
- (r) => r.sessionId
27862
- );
27863
- }
27864
- /** One session's undelivered structural rows within the backlog, root first. */
27865
- pendingRows(sessionId, limit, before) {
27866
- return allRows(this.rowsStmt, { sessionId, limit, before });
27867
- }
27868
- /**
27869
- * Captures this machine still owes the deployment, oldest first.
27870
- *
27871
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27872
- * by a time window — see captureRowsStmt for why a window could not express
27873
- * this. `before` is the grace window that leaves a just-recorded capture to
27874
- * the live path.
27875
- */
27876
- pendingCaptureRows(limit, before) {
27877
- return allRows(this.captureRowsStmt, { limit, before });
27878
- }
27879
- /**
27880
- * Record that a capture is OWED to the deployment.
27881
- *
27882
- * Written by the attached forward path when a live send did not confirm
27883
- * delivery, and read by the drain as the whole of its eligibility test. It is
27884
- * a fact rather than an inference: the machine was attached, the send did not
27885
- * land, so the row is owed — which no time window can state, because the same
27886
- * window that holds the rows a past attachment left owed also holds every
27887
- * capture recorded while the machine was DETACHED, and those were never
27888
- * offered to anyone.
27889
- *
27890
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27891
- * out of the drain's read.
27892
- */
27893
- markCaptureOwed(id) {
27894
- this.markOwedStmt.run({ id });
27895
- }
27896
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27897
- markSynced(ids, atMs) {
27898
- this.stampAll(ids, atMs);
27899
- }
27900
- /**
27901
- * Record that a row will never be sent.
27902
- *
27903
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27904
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27905
- * is retried; marking those would turn one outage into permanent data loss.
27906
- */
27907
- markSkipped(ids) {
27908
- this.stampAll(ids, SKIPPED);
27909
- }
27910
- eachInTransaction(ids, run) {
27911
- if (ids.length === 0) return;
27912
- withTransaction(
27913
- this.db,
27914
- () => {
27915
- for (const id of ids) run(id);
27916
- },
27917
- "IMMEDIATE"
27918
- );
27919
- }
27920
- stampAll(ids, value) {
27921
- if (ids.length === 0) return;
27922
- withTransaction(
27923
- this.db,
27924
- () => {
27925
- for (const id of ids) this.stampStmt.run({ at: value, id });
27926
- },
27927
- "IMMEDIATE"
27928
- );
27929
- }
27930
- /**
27931
- * Claim rows as in-flight.
27932
- *
27933
- * Advisory in exactly the sense the lease is: it records that a send is in
27934
- * progress so a surface can say so, and a lost claim costs a row showing as
27935
- * queued while it is actually being sent. It is not exclusion — the far side
27936
- * settles a duplicate on the row id.
27937
- */
27938
- claimRows(ids, atMs) {
27939
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27940
- }
27941
- /** Give back a claim without settling — the send failed, the row is queued again. */
27942
- releaseRows(ids) {
27943
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27944
- }
27945
- /**
27946
- * Clear claims older than `staleBefore`, and report how many were cleared.
27947
- *
27948
- * A process killed between claiming and settling leaves rows claimed with
27949
- * nothing left to settle them. Without this they read as "sending" for ever.
27950
- */
27951
- releaseStaleClaims(staleBefore) {
27952
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27953
- }
27954
- /**
27955
- * Every tracked row in exactly one delivery state.
27956
- *
27957
- * Takes no boundary on purpose. The boundary answers "what should the drain
27958
- * pick up now", which is a different question from "what state is this row
27959
- * in" — and a machine that has never attached has no boundary to pass, so
27960
- * requiring one would force a caller to invent one and report the whole store
27961
- * as queued.
27962
- */
27963
- partition() {
27964
- const row = getRow(this.partitionStmt, {});
27965
- return {
27966
- queued: row?.queued ?? 0,
27967
- inProgress: row?.inProgress ?? 0,
27968
- synced: row?.synced ?? 0,
27969
- failed: row?.failed ?? 0,
27970
- total: row?.total ?? 0
27971
- };
27972
- }
27973
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27974
- counts(before) {
27975
- const row = getRow(
27976
- this.countsStmt,
27977
- { before }
27978
- );
27979
- const captures = getRow(this.captureSkipCountStmt);
27980
- return {
27981
- pending: row?.pending ?? 0,
27982
- sent: row?.sent ?? 0,
27983
- skipped: row?.skipped ?? 0,
27984
- capturesSkipped: captures?.skipped ?? 0
27985
- };
27986
- }
27987
- /**
27988
- * The deployment the current stamps were made against, and where its backlog
27989
- * ends.
27990
- *
27991
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27992
- * machine that has never drained is — and every writer below seeds the row
27993
- * before it needs one, so nothing depends on this creating it. Keeping the
27994
- * write off the gate path matters because the gate runs on every pass while a
27995
- * write has to take the database's write lock.
27996
- */
27997
- deployment() {
27998
- const row = getRow(
27999
- this.fingerprintStmt
28000
- );
28001
- return {
28002
- fingerprint: row?.fingerprint ?? void 0,
28003
- backlogBefore: row?.backlogBefore ?? void 0
28004
- };
28005
- }
28006
- /**
28007
- * Point the ledger at a different deployment, discarding what it recorded
28008
- * about the previous one.
28009
- *
28010
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28011
- * machine has just left are undelivered as far as the new one is concerned.
28012
- * All three in one transaction, so a crash between them cannot leave stamps
28013
- * attributed to the wrong deployment, or a boundary that belongs to another.
28014
- *
28015
- * The boundary is written HERE and only here, which is what freezes it: a
28016
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28017
- * unchanged, so this never runs and the backlog does not widen back over rows
28018
- * the live path has since delivered.
28019
- */
28020
- rearmFor(fingerprint, backlogBefore) {
28021
- this.ensureRowStmt.run();
28022
- withTransaction(
28023
- this.db,
28024
- () => {
28025
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28026
- this.rearmStmt.run();
28027
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28028
- this.disownCapturesStmt.run();
28029
- }
28030
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28031
- },
28032
- "IMMEDIATE"
28033
- );
28034
- }
28035
- /**
28036
- * End the attached period: hand its rows to the live path, and release the
28037
- * boundary so the next attachment can freeze a new one.
28038
- *
28039
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28040
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28041
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28042
- * during the detached period, because the machine is not attached. Rows
28043
- * recorded in that window sit after the boundary and before the re-attach, so
28044
- * neither path takes them, and the pending count reports none outstanding.
28045
- *
28046
- * Stamping the attached window is not a claim that every one of those rows
28047
- * reached the deployment — the live path drops on failure and says so
28048
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28049
- * status quo: they sit outside the frozen boundary today and are equally never
28050
- * re-sent. Making it explicit is what lets the boundary move.
28051
- *
28052
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28053
- * window unstamped — that half-state would re-send the whole attached period
28054
- * on the next attach, which is the failure the boundary exists to prevent.
28055
- */
28056
- closeAttachedWindow(attachedAtMs, atMs) {
28057
- this.ensureRowStmt.run();
28058
- withTransaction(
28059
- this.db,
28060
- () => {
28061
- const row = getRow(this.fingerprintStmt);
28062
- const from = row?.backlogBefore ?? attachedAtMs;
28063
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28064
- this.releaseBoundaryStmt.run();
28065
- },
28066
- "IMMEDIATE"
28067
- );
28068
- }
28069
- /**
28070
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28071
- *
28072
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28073
- * different deployment and therefore discards what was delivered to the old
28074
- * one: here the recipient is the same, so everything already sent to it stays
28075
- * sent.
28076
- */
28077
- freezeBoundary(backlogBefore) {
28078
- this.ensureRowStmt.run();
28079
- this.freezeBoundaryStmt.run({ backlogBefore });
28080
- }
28081
- /** Take the claim, or report that someone live already holds it. */
28082
- claim(pid, host, nowMs, staleAfterMs) {
28083
- this.ensureRowStmt.run();
28084
- let taken = false;
28085
- withTransaction(
28086
- this.db,
28087
- () => {
28088
- const result = this.claimStmt.run({
28089
- pid,
28090
- host,
28091
- now: nowMs,
28092
- staleBefore: nowMs - staleAfterMs
28093
- });
28094
- taken = result.changes === 1;
28095
- },
28096
- "IMMEDIATE"
28097
- );
28098
- return taken;
28099
- }
28100
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28101
- heartbeat(pid, nowMs) {
28102
- this.heartbeatStmt.run({ now: nowMs, pid });
28103
- }
28104
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28105
- release(pid) {
28106
- this.releaseStmt.run({ pid });
28107
- }
28108
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28109
- lease() {
28110
- return getRow(this.leaseStmt);
28111
- }
28112
- };
28113
-
28114
28823
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28115
28824
  var SqliteInspectionDefinitionsRepository = class {
28116
28825
  constructor(db) {
@@ -28302,7 +29011,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28302
29011
  }
28303
29012
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28304
29013
  }
28305
- function readManagedSettings(paths = managedSettingsPaths()) {
29014
+ var testOnlyManagedPaths = null;
29015
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28306
29016
  for (const path of paths) {
28307
29017
  let text;
28308
29018
  try {
@@ -28337,6 +29047,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28337
29047
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28338
29048
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28339
29049
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29050
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28340
29051
  if (values.vaultConsent !== void 0) {
28341
29052
  merged.vaultConsent = values.vaultConsent ? (
28342
29053
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30782,7 +31493,7 @@ function toUtcDateString(ms) {
30782
31493
  return new Date(ms).toISOString().slice(0, 10);
30783
31494
  }
30784
31495
  function isTimeseriesSeverity(s) {
30785
- return s === "critical" || s === "high" || s === "medium";
31496
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30786
31497
  }
30787
31498
  var SqliteSecurityRepository = class {
30788
31499
  constructor(db, now = () => Date.now()) {
@@ -30844,7 +31555,7 @@ var SqliteSecurityRepository = class {
30844
31555
  ELSE 0
30845
31556
  END) AS open_at_rest
30846
31557
  FROM inspection_findings f
30847
- JOIN audit_events e ON e.id = f.audit_event_id
31558
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30848
31559
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30849
31560
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30850
31561
  ON latest.finding_key = f.finding_key
@@ -30911,12 +31622,16 @@ var SqliteSecurityRepository = class {
30911
31622
  const now = this.now();
30912
31623
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30913
31624
  const rows = this.findingsInRange(windowStart, now);
30914
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30915
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30916
- critical: 0,
30917
- high: 0,
30918
- medium: 0
30919
- }));
31625
+ const points = Array.from(
31626
+ { length: numBuckets },
31627
+ (_, i) => ({
31628
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31629
+ critical: 0,
31630
+ high: 0,
31631
+ medium: 0,
31632
+ low: 0
31633
+ })
31634
+ );
30920
31635
  for (const r of rows) {
30921
31636
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30922
31637
  const bucket = points[idx];
@@ -31066,7 +31781,7 @@ var SqliteSecurityRepository = class {
31066
31781
  this.db.prepare(
31067
31782
  `SELECT e.repo AS repo, count(*) AS c
31068
31783
  FROM inspection_findings f
31069
- JOIN audit_events e ON e.id = f.audit_event_id
31784
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31070
31785
  WHERE e.started_at >= :from AND e.started_at < :to
31071
31786
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31072
31787
  AND e.repo IS NOT NULL
@@ -31134,6 +31849,7 @@ var SqliteSecurityRepository = class {
31134
31849
  `SELECT f.finding_key AS finding_key,
31135
31850
  d.rule_id AS rule_id,
31136
31851
  d.severity AS severity,
31852
+ e.repo AS repo,
31137
31853
  e.file_path AS path,
31138
31854
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31139
31855
  latest.resolved_at AS latest_resolved_at
@@ -31153,6 +31869,7 @@ var SqliteSecurityRepository = class {
31153
31869
  const items = rows.map((r) => ({
31154
31870
  findingKey: r.finding_key,
31155
31871
  ruleId: r.rule_id,
31872
+ repo: r.repo ?? "",
31156
31873
  severity: r.severity,
31157
31874
  path: r.path ?? "",
31158
31875
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31162,15 +31879,68 @@ var SqliteSecurityRepository = class {
31162
31879
  }));
31163
31880
  return Promise.resolve({ items });
31164
31881
  }
31882
+ /**
31883
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31884
+ *
31885
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31886
+ * list: a secret committed three weeks ago and never rotated is still the most
31887
+ * important thing to fix, and any window hides it. It carried a "newest N
31888
+ * findings" cap and then a range; the first meant a different span on every
31889
+ * machine, and the second reported "no recommendations" over live exposure.
31890
+ *
31891
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31892
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31893
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31894
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31895
+ * The two answer different questions and only this one has to match a link.
31896
+ *
31897
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31898
+ * whole-store scope costs a grouped scan rather than a row per finding.
31899
+ */
31900
+ recommendationInputs() {
31901
+ const rows = allRows(
31902
+ this.db.prepare(
31903
+ `SELECT d.rule_id AS rule_id,
31904
+ d.category AS category,
31905
+ d.severity AS severity,
31906
+ COUNT(*) AS count
31907
+ FROM inspection_findings f
31908
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31909
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31910
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31911
+ ON latest.finding_key = f.finding_key
31912
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31913
+ AND e.event_type = 'code_change'
31914
+ AND (
31915
+ f.finding_key IS NULL
31916
+ OR latest.status IS NULL
31917
+ OR latest.status NOT IN ('resolved', 'dismissed')
31918
+ )
31919
+ GROUP BY d.rule_id, d.category, d.severity`
31920
+ )
31921
+ );
31922
+ return Promise.resolve(
31923
+ rows.map((r) => ({
31924
+ ruleId: r.rule_id,
31925
+ category: r.category,
31926
+ severity: r.severity,
31927
+ count: r.count
31928
+ }))
31929
+ );
31930
+ }
31165
31931
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31166
31932
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31167
31933
  // numeric and the JS aggregations bucket/split on ms directly.
31168
31934
  findingsInRange(fromMs, toMs) {
31169
31935
  const rows = allRows(
31170
31936
  this.db.prepare(
31171
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31937
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31938
+ // joined for `severity`, so they are two more columns off a row this read
31939
+ // already fetches. They feed the recommended-actions rollup.
31940
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31941
+ d.rule_id AS rule_id, d.category AS category
31172
31942
  FROM inspection_findings f
31173
- JOIN audit_events e ON e.id = f.audit_event_id
31943
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31174
31944
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31175
31945
  WHERE e.started_at >= :from AND e.started_at < :to
31176
31946
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31181,7 +31951,9 @@ var SqliteSecurityRepository = class {
31181
31951
  return rows.map((r) => ({
31182
31952
  occurredAt: r.occurred_at,
31183
31953
  severity: r.severity,
31184
- actionTaken: r.action_taken
31954
+ actionTaken: r.action_taken,
31955
+ ruleId: r.rule_id,
31956
+ category: r.category
31185
31957
  }));
31186
31958
  }
31187
31959
  };
@@ -32009,6 +32781,7 @@ function openWithPragmas(file2) {
32009
32781
  db.exec("PRAGMA journal_mode = WAL");
32010
32782
  db.exec("PRAGMA busy_timeout = 2000");
32011
32783
  db.exec("PRAGMA foreign_keys = ON");
32784
+ registerSqlFunctions(db);
32012
32785
  } catch (err) {
32013
32786
  closeQuietly(db);
32014
32787
  throw err;
@@ -32038,7 +32811,7 @@ function backupLegacyStore(db, file2) {
32038
32811
  discardStore(file2, backup);
32039
32812
  return backup;
32040
32813
  }
32041
- function openAndInitialize(file2, base) {
32814
+ function openAndInitialize(file2, base, skipTags) {
32042
32815
  let db = openWithPragmas(file2);
32043
32816
  try {
32044
32817
  if (isForeignSqliteLineage(db)) {
@@ -32048,7 +32821,7 @@ function openAndInitialize(file2, base) {
32048
32821
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32049
32822
  );
32050
32823
  }
32051
- applyMigrations(db, file2);
32824
+ applyMigrations(db, file2, { skipTags });
32052
32825
  tightenPerms(file2);
32053
32826
  const policies = new SqlitePoliciesRepository(db);
32054
32827
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32063,6 +32836,7 @@ function openAndInitialize(file2, base) {
32063
32836
  exceptions: new SqliteExceptionsRepository(db),
32064
32837
  resolutions: new SqliteResolutionsRepository(db),
32065
32838
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32839
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32066
32840
  security: new SqliteSecurityRepository(db),
32067
32841
  detections: new SqliteDetectionsRepository(db),
32068
32842
  shares: new SqliteSharesRepository(db),
@@ -32085,7 +32859,8 @@ function openAndInitialize(file2, base) {
32085
32859
  throw err;
32086
32860
  }
32087
32861
  }
32088
- function openLocalDatabase(dir) {
32862
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32863
+ function openLocalDatabase(dir, options = {}) {
32089
32864
  ensureDataDirSync(dir);
32090
32865
  const file2 = join7(dir, DB_FILENAME);
32091
32866
  reapStalePartials(file2);
@@ -32097,6 +32872,7 @@ function openLocalDatabase(dir) {
32097
32872
  installedPacks,
32098
32873
  scanLedger,
32099
32874
  historySync,
32875
+ bodyRetention,
32100
32876
  secretVault,
32101
32877
  exceptions,
32102
32878
  resolutions,
@@ -32120,7 +32896,8 @@ function openLocalDatabase(dir) {
32120
32896
  // `dir` is always `<base>/data` — every caller resolves it through
32121
32897
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32122
32898
  // settings/ and data/, and the pack-policy floor needs both halves.
32123
- dirname2(dir)
32899
+ dirname2(dir),
32900
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32124
32901
  );
32125
32902
  function captureRowId(event) {
32126
32903
  return captureId(
@@ -32313,6 +33090,7 @@ function openLocalDatabase(dir) {
32313
33090
  installedPacks,
32314
33091
  scanLedger,
32315
33092
  historySync,
33093
+ bodyRetention,
32316
33094
  secretVault,
32317
33095
  exceptions,
32318
33096
  resolutions,
@@ -32351,14 +33129,78 @@ function openLocalDatabase(dir) {
32351
33129
  };
32352
33130
  }
32353
33131
 
32354
- // ../../packages/persistence/src/finding-key.ts
33132
+ // ../../packages/persistence/src/egress-wire.ts
32355
33133
  import { createHash as createHash3 } from "crypto";
33134
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33135
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33136
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33137
+ var FILE_URL = /^file:\/\//i;
33138
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33139
+ var SLASH = "/".charCodeAt(0);
33140
+ var GIT_SUFFIX = ".git";
33141
+ function trimSlashes(path) {
33142
+ let start = 0;
33143
+ let end = path.length;
33144
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33145
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33146
+ return path.slice(start, end);
33147
+ }
33148
+ function canonicalGitUrl(url2) {
33149
+ const trimmed = url2.trim();
33150
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33151
+ const scheme = SCHEME_FORM.exec(trimmed);
33152
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33153
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33154
+ if (host === void 0) return trimmed;
33155
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33156
+ const bare = trimSlashes(path);
33157
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33158
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33159
+ }
33160
+ function hashProjectKey(projectKey) {
33161
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33162
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33163
+ }
33164
+ function toIngestHit(hit) {
33165
+ return {
33166
+ host: hit.host,
33167
+ kind: hit.kind,
33168
+ name: hit.name,
33169
+ category: hit.category,
33170
+ trust: hit.trust,
33171
+ network: hit.network,
33172
+ method: hit.method,
33173
+ transport: hit.transport,
33174
+ url: hit.url,
33175
+ template: hit.template,
33176
+ dataClass: hit.dataClass,
33177
+ site: {
33178
+ file: hit.site.file,
33179
+ line: hit.site.line,
33180
+ dynamic: hit.site.dynamic,
33181
+ vendored: hit.site.vendored
33182
+ }
33183
+ };
33184
+ }
33185
+ function toEgressIngestRequest(input2) {
33186
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33187
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33188
+ return {
33189
+ projectKey: hashProjectKey(input2.projectKey),
33190
+ project: input2.project,
33191
+ reconcile,
33192
+ hits: hits.map(toIngestHit)
33193
+ };
33194
+ }
33195
+
33196
+ // ../../packages/persistence/src/finding-key.ts
33197
+ import { createHash as createHash4 } from "crypto";
32356
33198
  function normalizeFilePath(filePath) {
32357
33199
  return filePath.replaceAll("\\", "/");
32358
33200
  }
32359
33201
  function computeFindingKey(input2) {
32360
33202
  const normalizedPath = normalizeFilePath(input2.filePath);
32361
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
33203
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32362
33204
  }
32363
33205
 
32364
33206
  // ../../packages/persistence/src/fingerprint.ts
@@ -32484,14 +33326,50 @@ function fingerprintValue(key, raw) {
32484
33326
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32485
33327
  }
32486
33328
 
32487
- // ../../packages/persistence/src/history-preview.ts
32488
- import { existsSync as existsSync4 } from "fs";
33329
+ // ../../packages/persistence/src/forward-health.ts
33330
+ import { readFileSync as readFileSync7 } from "fs";
32489
33331
  import { join as join9 } from "path";
33332
+ var FAILURES = /* @__PURE__ */ new Set([
33333
+ "unauthorized",
33334
+ "forbidden",
33335
+ "unreachable"
33336
+ ]);
33337
+ var BREAKER_COOLDOWN_MS = 3e4;
33338
+ function parseForwardHealth(raw, nowMs) {
33339
+ try {
33340
+ const parsed2 = JSON.parse(raw);
33341
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33342
+ const record2 = parsed2;
33343
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33344
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33345
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33346
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33347
+ } catch {
33348
+ return null;
33349
+ }
33350
+ }
33351
+ function isForwardPaused(health, nowMs) {
33352
+ const openedAtMs = health?.openedAtMs ?? null;
33353
+ if (openedAtMs === null) return false;
33354
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33355
+ }
33356
+
33357
+ // ../../packages/persistence/src/history-backfill.ts
33358
+ import { existsSync as existsSync4 } from "fs";
33359
+ import { join as join10 } from "path";
33360
+
33361
+ // ../../packages/persistence/src/history-preview.ts
33362
+ import { existsSync as existsSync5 } from "fs";
33363
+ import { join as join11 } from "path";
32490
33364
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32491
33365
 
33366
+ // ../../packages/persistence/src/history-sync-state.ts
33367
+ import { readFileSync as readFileSync8 } from "fs";
33368
+ import { join as join12 } from "path";
33369
+
32492
33370
  // ../../packages/persistence/src/store-symlinks.ts
32493
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32494
- import { dirname as dirname3, join as join10, resolve } from "path";
33371
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33372
+ import { dirname as dirname3, join as join13, resolve } from "path";
32495
33373
 
32496
33374
  // ../../packages/persistence/src/vault/crypto.ts
32497
33375
  import {
@@ -32505,62 +33383,26 @@ import {
32505
33383
  // ../../packages/persistence/src/vault/key-provider.ts
32506
33384
  import { execFileSync } from "child_process";
32507
33385
  import { randomBytes as randomBytes2 } from "crypto";
32508
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32509
- import { join as join11 } from "path";
33386
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33387
+ import { join as join14 } from "path";
32510
33388
 
32511
33389
  // ../../packages/persistence/src/vault/vault.ts
32512
33390
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32513
33391
 
32514
33392
  // ../../packages/persistence/src/warn-era-cap.ts
32515
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32516
- import { join as join12 } from "path";
33393
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33394
+ import { join as join15 } from "path";
32517
33395
  var MARKER = "warn-era-capped";
32518
33396
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32519
33397
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32520
- const marker = join12(dataDir2, MARKER);
32521
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33398
+ const marker = join15(dataDir2, MARKER);
33399
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32522
33400
  const capped = db.policies.capCategoryActions();
32523
33401
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32524
33402
  `, { mode: DATA_FILE_MODE });
32525
33403
  return { capped };
32526
33404
  }
32527
33405
 
32528
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32529
- function hashProjectKey(projectKey) {
32530
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32531
- }
32532
- function toIngestHit(hit) {
32533
- return {
32534
- host: hit.host,
32535
- kind: hit.kind,
32536
- name: hit.name,
32537
- category: hit.category,
32538
- trust: hit.trust,
32539
- network: hit.network,
32540
- method: hit.method,
32541
- transport: hit.transport,
32542
- url: hit.url,
32543
- template: hit.template,
32544
- dataClass: hit.dataClass,
32545
- site: {
32546
- file: hit.site.file,
32547
- line: hit.site.line,
32548
- dynamic: hit.site.dynamic,
32549
- vendored: hit.site.vendored
32550
- }
32551
- };
32552
- }
32553
- function toEgressIngestRequest(input2) {
32554
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32555
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32556
- return {
32557
- projectKey: hashProjectKey(input2.projectKey),
32558
- project: input2.project,
32559
- reconcile,
32560
- hits: hits.map(toIngestHit)
32561
- };
32562
- }
32563
-
32564
33406
  // ../../packages/remote/src/http.ts
32565
33407
  import { request as httpRequest } from "http";
32566
33408
  import { request as httpsRequest } from "https";
@@ -32744,10 +33586,10 @@ function parsed(schema, body, route) {
32744
33586
  }
32745
33587
  function withoutTrailingSlashes(endpoint) {
32746
33588
  let end = endpoint.length;
32747
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33589
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32748
33590
  return endpoint.slice(0, end);
32749
33591
  }
32750
- var SLASH = "/".charCodeAt(0);
33592
+ var SLASH2 = "/".charCodeAt(0);
32751
33593
  function createRemoteClient(options) {
32752
33594
  const base = withoutTrailingSlashes(options.endpoint);
32753
33595
  const url2 = (route) => `${base}${route}`;
@@ -32840,6 +33682,7 @@ function createRemoteClient(options) {
32840
33682
  url: url2(ROUTES.shares),
32841
33683
  body: JSON.stringify(validated.data)
32842
33684
  });
33685
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32843
33686
  okBody(response);
32844
33687
  },
32845
33688
  async pollCommand() {
@@ -32862,19 +33705,51 @@ function createRemoteClient(options) {
32862
33705
  };
32863
33706
  }
32864
33707
 
32865
- // ../../packages/plugin-runtime/src/attached/failure.ts
33708
+ // ../../packages/remote/src/failure-kind.ts
32866
33709
  function statusOf(err) {
32867
33710
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32868
33711
  const { status } = err;
32869
33712
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32870
33713
  return status >= 100 && status <= 599 ? status : null;
32871
33714
  }
32872
- function classifyFailure(err) {
32873
- switch (statusOf(err)) {
33715
+ function nameOf(err) {
33716
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33717
+ return typeof err.name === "string" ? err.name : null;
33718
+ }
33719
+ function classifyRemoteFailure(err) {
33720
+ switch (nameOf(err)) {
33721
+ case "RemoteRouteAbsent":
33722
+ return "route-absent";
33723
+ case "RemoteRequestInvalid":
33724
+ return "invalid-request";
33725
+ case "RemoteResponseInvalid":
33726
+ return "rejected";
33727
+ default:
33728
+ break;
33729
+ }
33730
+ const status = statusOf(err);
33731
+ if (status === null) return "unreachable";
33732
+ switch (status) {
32874
33733
  case 401:
32875
33734
  return "unauthorized";
32876
33735
  case 403:
32877
33736
  return "forbidden";
33737
+ case 429:
33738
+ return "unreachable";
33739
+ case 404:
33740
+ return "unreachable";
33741
+ default:
33742
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33743
+ }
33744
+ }
33745
+
33746
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33747
+ function classifyFailure(err) {
33748
+ switch (classifyRemoteFailure(err)) {
33749
+ case "unauthorized":
33750
+ return "unauthorized";
33751
+ case "forbidden":
33752
+ return "forbidden";
32878
33753
  default:
32879
33754
  return "unreachable";
32880
33755
  }
@@ -32965,11 +33840,11 @@ function commandScanFor(config2, scanWorktree2, sourceTool) {
32965
33840
  }
32966
33841
 
32967
33842
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32968
- import { readFileSync as readFileSync8 } from "fs";
32969
- import { join as join13 } from "path";
33843
+ import { readFileSync as readFileSync10 } from "fs";
33844
+ import { join as join16 } from "path";
32970
33845
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32971
33846
  function forwardDropsPath(dataDir2) {
32972
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33847
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
32973
33848
  }
32974
33849
  function recordForwardDrops(dataDir2, count, nowMs) {
32975
33850
  if (count <= 0) return;
@@ -32987,7 +33862,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
32987
33862
  }
32988
33863
  function readForwardDrops(dataDir2) {
32989
33864
  try {
32990
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33865
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
32991
33866
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
32992
33867
  const record2 = parsed2;
32993
33868
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -33005,13 +33880,12 @@ function readForwardDrops(dataDir2) {
33005
33880
 
33006
33881
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33007
33882
  import { randomUUID as randomUUID15 } from "crypto";
33008
- import { readFileSync as readFileSync14 } from "fs";
33009
33883
  import { readFile, rename, writeFile } from "fs/promises";
33010
- import { join as join22 } from "path";
33884
+ import { join as join26 } from "path";
33011
33885
 
33012
33886
  // ../../packages/plugin-sdk/src/config.ts
33013
- import { existsSync as existsSync7 } from "fs";
33014
- import { join as join14 } from "path";
33887
+ import { existsSync as existsSync8 } from "fs";
33888
+ import { join as join17 } from "path";
33015
33889
 
33016
33890
  // ../../packages/plugin-sdk/src/provider-env.ts
33017
33891
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33065,8 +33939,8 @@ function resolveProvider() {
33065
33939
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33066
33940
  try {
33067
33941
  ensureLayoutDirSync(base);
33068
- const settingsFile = join14(settingsDir(base), "settings.json");
33069
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33942
+ const settingsFile = join17(settingsDir(base), "settings.json");
33943
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33070
33944
  } catch {
33071
33945
  }
33072
33946
  migrateLegacyLayout(base);
@@ -33089,9 +33963,9 @@ function resolveProviderSafe(resolveProviderFn) {
33089
33963
  }
33090
33964
 
33091
33965
  // ../../packages/plugin-sdk/src/config-inventory.ts
33092
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33966
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33093
33967
  import { homedir as homedir2 } from "os";
33094
- import { basename as basename3, join as join16 } from "path";
33968
+ import { basename as basename3, join as join19 } from "path";
33095
33969
 
33096
33970
  // ../../packages/detections/src/egress/registry.ts
33097
33971
  var EXTRACTOR_VERSION = "1";
@@ -33784,12 +34658,18 @@ var EGRESS_CODE_EXTENSIONS = /* @__PURE__ */ new Set([
33784
34658
  ".rs"
33785
34659
  ]);
33786
34660
  var SNIPPET_MAX = 200;
34661
+ var WHITESPACE = /\s/;
33787
34662
  var MASK = "\u2022\u2022\u2022\u2022";
33788
34663
  var URL_CANDIDATE = /(https?|wss?|sftp|grpcs?|smtp):\/\/(?:[^\s'"`<>()[\]{},;]|\$\{[^}\s]{1,64}\}|\{[A-Za-z_]\w{0,63}\}|%[sd])+/gi;
33789
34664
  var PLACEHOLDER = /\$\{[^}\s]{1,64}\}|\{[A-Za-z_]\w{0,63}\}|%[sd]/g;
33790
34665
  var VAR_TOKEN = "${var}";
33791
34666
  var VAR_SENTINEL = "akaegressvar0";
33792
- var TRAILING_PUNCTUATION = /[.,;:'"]+$/;
34667
+ var TRAILING_PUNCTUATION = `.,;:'"`;
34668
+ function stripTrailingPunctuation(value) {
34669
+ let end = value.length;
34670
+ while (end > 0 && TRAILING_PUNCTUATION.includes(value.charAt(end - 1))) end -= 1;
34671
+ return end === value.length ? value : value.slice(0, end);
34672
+ }
33793
34673
  var TRANSPORT_BY_SCHEME = {
33794
34674
  http: "http",
33795
34675
  https: "https",
@@ -33854,35 +34734,100 @@ var VENDORED_PATH = /(^|\/)(vendor|third_party|external)\//;
33854
34734
  function isVendoredPath(file2) {
33855
34735
  return VENDORED_PATH.test(file2);
33856
34736
  }
33857
- function redactLine(line) {
33858
- return line.trim().replace(USERINFO, "://").replace(WEBHOOK_URL, `$1${MASK}`).replace(SECRET_VALUE, `$1${MASK}`).replace(AUTH_SCHEME_VALUE, `$1$2 ${MASK}`).replace(BEARER_TOKEN, `Bearer ${MASK}`);
34737
+ var REDACTION_PASSES = [
34738
+ { pattern: USERINFO, replace: () => "://" },
34739
+ { pattern: WEBHOOK_URL, replace: (m) => `${m[1] ?? ""}${MASK}` },
34740
+ { pattern: SECRET_VALUE, replace: (m) => `${m[1] ?? ""}${MASK}` },
34741
+ { pattern: AUTH_SCHEME_VALUE, replace: (m) => `${m[1] ?? ""}${m[2] ?? ""} ${MASK}` },
34742
+ { pattern: BEARER_TOKEN, replace: () => `Bearer ${MASK}` }
34743
+ ];
34744
+ function runPass(input2, pass) {
34745
+ const at = [];
34746
+ const end = [];
34747
+ const before = [];
34748
+ const after = [];
34749
+ let output2 = "";
34750
+ let copied = 0;
34751
+ let shift = 0;
34752
+ for (const match of input2.matchAll(pass.pattern)) {
34753
+ const start = match.index;
34754
+ const matched = match[0];
34755
+ const replacement = pass.replace(match);
34756
+ output2 += input2.slice(copied, start) + replacement;
34757
+ at.push(start);
34758
+ end.push(start + matched.length);
34759
+ before.push(shift);
34760
+ shift += replacement.length - matched.length;
34761
+ after.push(shift);
34762
+ copied = start + matched.length;
34763
+ }
34764
+ if (at.length === 0) return { output: input2, edits: { at, end, before, after } };
34765
+ return { output: output2 + input2.slice(copied), edits: { at, end, before, after } };
34766
+ }
34767
+ function throughPass(edits, offset) {
34768
+ let low = 0;
34769
+ let high = edits.at.length - 1;
34770
+ let found = -1;
34771
+ while (low <= high) {
34772
+ const mid = low + high >> 1;
34773
+ if ((edits.at[mid] ?? 0) <= offset) {
34774
+ found = mid;
34775
+ low = mid + 1;
34776
+ } else {
34777
+ high = mid - 1;
34778
+ }
34779
+ }
34780
+ if (found === -1) return offset;
34781
+ if (offset < (edits.end[found] ?? 0)) return (edits.at[found] ?? 0) + (edits.before[found] ?? 0);
34782
+ return offset + (edits.after[found] ?? 0);
33859
34783
  }
33860
- function redactSnippet(line, anchor2 = 0) {
33861
- const redacted = redactLine(line);
33862
- if (redacted.length <= SNIPPET_MAX) return redacted;
33863
- const lead = line.length - line.trimStart().length;
34784
+ function redactedLineOf(line) {
33864
34785
  const trimmed = line.trim();
33865
- const mapped = redacted.length === trimmed.length ? anchor2 - lead : redactLine(trimmed.slice(0, Math.max(0, anchor2 - lead))).length;
34786
+ const edits = [];
34787
+ let text = trimmed;
34788
+ for (const pass of REDACTION_PASSES) {
34789
+ const result = runPass(text, pass);
34790
+ text = result.output;
34791
+ edits.push(result.edits);
34792
+ }
34793
+ if (text.length <= SNIPPET_MAX) return { redacted: text };
34794
+ return {
34795
+ redacted: text,
34796
+ window: { trimmed, edits, lead: line.length - line.trimStart().length }
34797
+ };
34798
+ }
34799
+ function snippetWindow({ redacted, window }, anchor2) {
34800
+ if (window === void 0) return redacted;
34801
+ const { trimmed, edits, lead } = window;
34802
+ let mapped = Math.max(0, anchor2 - lead);
34803
+ if (redacted.length !== trimmed.length) {
34804
+ while (mapped > 0 && WHITESPACE.test(trimmed.charAt(mapped - 1))) mapped -= 1;
34805
+ for (const pass of edits) mapped = throughPass(pass, mapped);
34806
+ }
33866
34807
  const start = Math.min(
33867
34808
  Math.max(0, mapped - Math.floor(SNIPPET_MAX / 2)),
33868
34809
  redacted.length - SNIPPET_MAX
33869
34810
  );
33870
34811
  return redacted.slice(start, start + SNIPPET_MAX);
33871
34812
  }
34813
+ function redactSnippet(line, anchor2 = 0) {
34814
+ return snippetWindow(redactedLineOf(line), anchor2);
34815
+ }
33872
34816
  function extractEgress(text) {
33873
34817
  const lineStarts = lineStartOffsets(text);
33874
34818
  const urlSpans = [];
33875
34819
  const hits = [];
33876
34820
  const lineTextOf = memoizeByLine((index) => lineTextAt(text, lineStarts, index));
33877
34821
  const ipContextOf = memoizeByLine((index) => ipLineContext(lineTextOf(index)));
33878
- const snippetAt = (index, offset) => redactSnippet(lineTextOf(index), offset - (lineStarts[index] ?? 0));
34822
+ const redactedOf = memoizeByLine((index) => redactedLineOf(lineTextOf(index)));
34823
+ const snippetAt = (index, offset) => snippetWindow(redactedOf(index), offset - (lineStarts[index] ?? 0));
33879
34824
  for (const match of text.matchAll(URL_CANDIDATE)) {
33880
34825
  const start = match.index;
33881
34826
  const matched = match[0];
33882
34827
  urlSpans.push([start, start + matched.length]);
33883
34828
  const scheme = match[1];
33884
34829
  if (scheme === void 0) continue;
33885
- const candidate = matched.replace(TRAILING_PUNCTUATION, "");
34830
+ const candidate = stripTrailingPunctuation(matched);
33886
34831
  if (candidate === "") continue;
33887
34832
  const parsed2 = parseCandidate(candidate, scheme);
33888
34833
  if (parsed2 === null) continue;
@@ -34116,33 +35061,37 @@ function extractManifestSdks(text, kind) {
34116
35061
  return [];
34117
35062
  }
34118
35063
  }
34119
- function makeHit(ecosystem, pkg, line, rawLine) {
34120
- return { ecosystem, pkg, line, snippet: redactSnippet(rawLine) };
35064
+ function makeHit(ecosystem, pkg, line, snippet) {
35065
+ return { ecosystem, pkg, line, snippet };
34121
35066
  }
34122
35067
  function extractPackageJson(text) {
34123
35068
  const parsed2 = parseJson(text);
34124
35069
  if (parsed2 === null) return [];
34125
35070
  const seen = /* @__PURE__ */ new Set();
34126
35071
  const hits = [];
35072
+ const lines = manifestLines(text);
35073
+ const tokens = quotedTokenOffsets(text);
35074
+ const dependenciesAt = sectionOffset(text, "dependencies");
35075
+ const optionalAt = sectionOffset(text, "optionalDependencies");
34127
35076
  for (const pkg of objectKeys(parsed2.dependencies)) {
34128
35077
  seen.add(pkg);
34129
- hits.push(hitAtQuotedKey("npm", pkg, text, "dependencies"));
35078
+ hits.push(hitAtQuotedKey("npm", pkg, text, dependenciesAt, lines, tokens));
34130
35079
  }
34131
35080
  for (const pkg of objectKeys(parsed2.optionalDependencies)) {
34132
35081
  if (seen.has(pkg)) continue;
34133
35082
  seen.add(pkg);
34134
- hits.push(hitAtQuotedKey("npm", pkg, text, "optionalDependencies"));
35083
+ hits.push(hitAtQuotedKey("npm", pkg, text, optionalAt, lines, tokens));
34135
35084
  }
34136
35085
  return hits;
34137
35086
  }
34138
35087
  var REQUIREMENTS_NAME = /^\s*([A-Za-z0-9][\w.-]*)/;
34139
35088
  function extractRequirementsTxt(text) {
34140
35089
  const hits = [];
34141
- eachLine(text, (rawLine, lineNumber) => {
35090
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34142
35091
  const match = REQUIREMENTS_NAME.exec(rawLine);
34143
35092
  const name = match?.[1];
34144
35093
  if (name === void 0) return;
34145
- hits.push(makeHit("pypi", normalizePypi(name), lineNumber, rawLine));
35094
+ hits.push(makeHit("pypi", normalizePypi(name), lineNumber, snippet()));
34146
35095
  });
34147
35096
  return hits;
34148
35097
  }
@@ -34154,7 +35103,7 @@ function extractPyprojectToml(text) {
34154
35103
  const hits = [];
34155
35104
  let section = "";
34156
35105
  let inDependenciesArray = false;
34157
- eachLine(text, (rawLine, lineNumber) => {
35106
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34158
35107
  const sectionMatch = TOML_SECTION.exec(rawLine);
34159
35108
  if (sectionMatch) {
34160
35109
  section = sectionMatch[1]?.trim() ?? "";
@@ -34168,7 +35117,7 @@ function extractPyprojectToml(text) {
34168
35117
  for (const spec of quotedStrings(rawLine)) {
34169
35118
  const name = PEP508_NAME.exec(spec)?.[1];
34170
35119
  if (name !== void 0)
34171
- hits.push(makeHit("pypi", normalizePypi(name), lineNumber, rawLine));
35120
+ hits.push(makeHit("pypi", normalizePypi(name), lineNumber, snippet()));
34172
35121
  }
34173
35122
  if (rawLine.includes("]")) inDependenciesArray = false;
34174
35123
  return;
@@ -34176,7 +35125,7 @@ function extractPyprojectToml(text) {
34176
35125
  if (section === "tool.poetry.dependencies") {
34177
35126
  const key = POETRY_KEY.exec(rawLine)?.[1];
34178
35127
  if (key !== void 0 && key !== "python") {
34179
- hits.push(makeHit("pypi", normalizePypi(key), lineNumber, rawLine));
35128
+ hits.push(makeHit("pypi", normalizePypi(key), lineNumber, snippet()));
34180
35129
  }
34181
35130
  }
34182
35131
  });
@@ -34192,7 +35141,7 @@ var GO_MODULE_VERSION_LINE = /^\s*([\w./-]+)\s+v\d/;
34192
35141
  function extractGoMod(text) {
34193
35142
  const hits = [];
34194
35143
  let blockKeyword = null;
34195
- eachLine(text, (rawLine, lineNumber) => {
35144
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34196
35145
  if (blockKeyword === null) {
34197
35146
  const open3 = GO_BLOCK_OPEN.exec(rawLine)?.[1];
34198
35147
  if (open3 !== void 0) {
@@ -34200,7 +35149,7 @@ function extractGoMod(text) {
34200
35149
  return;
34201
35150
  }
34202
35151
  const path = GO_REQUIRE_SINGLE_LINE.exec(rawLine)?.[1];
34203
- if (path !== void 0) hits.push(makeHit("go", path, lineNumber, rawLine));
35152
+ if (path !== void 0) hits.push(makeHit("go", path, lineNumber, snippet()));
34204
35153
  return;
34205
35154
  }
34206
35155
  if (GO_BLOCK_CLOSE.test(rawLine)) {
@@ -34209,7 +35158,7 @@ function extractGoMod(text) {
34209
35158
  }
34210
35159
  if (blockKeyword === "require") {
34211
35160
  const path = GO_MODULE_VERSION_LINE.exec(rawLine)?.[1];
34212
- if (path !== void 0) hits.push(makeHit("go", path, lineNumber, rawLine));
35161
+ if (path !== void 0) hits.push(makeHit("go", path, lineNumber, snippet()));
34213
35162
  }
34214
35163
  });
34215
35164
  return hits;
@@ -34226,13 +35175,13 @@ var POM_CONTEXT_TAGS = /* @__PURE__ */ new Set([
34226
35175
  "exclusions",
34227
35176
  "exclusion"
34228
35177
  ]);
34229
- var XML_TAG = /<(\/?)([A-Za-z][\w.-]*)([^<>]*)>/g;
35178
+ var XML_TAG = /<(\/?)([A-Za-z][\w.-]*)((?:[^<>\w.-][^<>]*)?)>/g;
34230
35179
  var LEADING_TEXT = /^([^<]*)/;
34231
35180
  function extractPomXml(text) {
34232
35181
  const hits = [];
34233
35182
  const stack = [];
34234
35183
  let inComment = false;
34235
- eachLine(text, (rawLine, lineNumber) => {
35184
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34236
35185
  const stripped = stripXmlComments(rawLine, inComment);
34237
35186
  inComment = stripped.inComment;
34238
35187
  const visible = stripped.visible;
@@ -34251,7 +35200,7 @@ function extractPomXml(text) {
34251
35200
  const after = visible.slice(match.index + match[0].length);
34252
35201
  const value = LEADING_TEXT.exec(after)?.[1]?.trim() ?? "";
34253
35202
  if (value !== "" && isProjectDependencyGroupId(stack)) {
34254
- hits.push(makeHit("maven", value, lineNumber, rawLine));
35203
+ hits.push(makeHit("maven", value, lineNumber, snippet()));
34255
35204
  }
34256
35205
  continue;
34257
35206
  }
@@ -34267,11 +35216,11 @@ var GRADLE_DEPENDENCY = /\b(?:implementation|api|compile)\b\s*[('"]*(?:platform\
34267
35216
  var LINE_COMMENT = /^\s*\/\//;
34268
35217
  function extractBuildGradle(text) {
34269
35218
  const hits = [];
34270
- eachLine(text, (rawLine, lineNumber) => {
35219
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34271
35220
  if (LINE_COMMENT.test(rawLine)) return;
34272
35221
  for (const match of rawLine.matchAll(GRADLE_DEPENDENCY)) {
34273
35222
  const groupId = match[1];
34274
- if (groupId !== void 0) hits.push(makeHit("maven", groupId, lineNumber, rawLine));
35223
+ if (groupId !== void 0) hits.push(makeHit("maven", groupId, lineNumber, snippet()));
34275
35224
  }
34276
35225
  });
34277
35226
  return hits;
@@ -34279,9 +35228,9 @@ function extractBuildGradle(text) {
34279
35228
  var GEMFILE_DEPENDENCY = /^\s*gem\s+['"]([\w-]+)['"]/;
34280
35229
  function extractGemfile(text) {
34281
35230
  const hits = [];
34282
- eachLine(text, (rawLine, lineNumber) => {
35231
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34283
35232
  const name = GEMFILE_DEPENDENCY.exec(rawLine)?.[1];
34284
- if (name !== void 0) hits.push(makeHit("rubygems", name, lineNumber, rawLine));
35233
+ if (name !== void 0) hits.push(makeHit("rubygems", name, lineNumber, snippet()));
34285
35234
  });
34286
35235
  return hits;
34287
35236
  }
@@ -34289,7 +35238,7 @@ var CARGO_KEY = /^([A-Za-z0-9_-]+)\s*=/;
34289
35238
  function extractCargoToml(text) {
34290
35239
  const hits = [];
34291
35240
  let mode = "none";
34292
- eachLine(text, (rawLine, lineNumber) => {
35241
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34293
35242
  const sectionMatch = TOML_SECTION.exec(rawLine);
34294
35243
  if (sectionMatch) {
34295
35244
  const name = sectionMatch[1]?.trim() ?? "";
@@ -34298,7 +35247,7 @@ function extractCargoToml(text) {
34298
35247
  } else if (name.startsWith("dependencies.")) {
34299
35248
  mode = "dotted";
34300
35249
  const crate = name.slice("dependencies.".length);
34301
- if (crate !== "") hits.push(makeHit("cargo", crate, lineNumber, rawLine));
35250
+ if (crate !== "") hits.push(makeHit("cargo", crate, lineNumber, snippet()));
34302
35251
  } else {
34303
35252
  mode = "none";
34304
35253
  }
@@ -34306,7 +35255,7 @@ function extractCargoToml(text) {
34306
35255
  }
34307
35256
  if (mode === "plain") {
34308
35257
  const crate = CARGO_KEY.exec(rawLine)?.[1];
34309
- if (crate !== void 0) hits.push(makeHit("cargo", crate, lineNumber, rawLine));
35258
+ if (crate !== void 0) hits.push(makeHit("cargo", crate, lineNumber, snippet()));
34310
35259
  }
34311
35260
  });
34312
35261
  return hits;
@@ -34315,17 +35264,20 @@ function extractComposerJson(text) {
34315
35264
  const parsed2 = parseJson(text);
34316
35265
  if (parsed2 === null) return [];
34317
35266
  const pkgs = objectKeys(parsed2.require).filter((pkg) => pkg !== "php" && !pkg.startsWith("ext-"));
34318
- return pkgs.map((pkg) => hitAtQuotedKey("composer", pkg, text, "require"));
35267
+ const lines = manifestLines(text);
35268
+ const tokens = quotedTokenOffsets(text);
35269
+ const requireAt = sectionOffset(text, "require");
35270
+ return pkgs.map((pkg) => hitAtQuotedKey("composer", pkg, text, requireAt, lines, tokens));
34319
35271
  }
34320
35272
  var CSPROJ_PACKAGE_REFERENCE = /<PackageReference\s+Include="([^"]+)"/;
34321
35273
  function extractCsproj(text) {
34322
35274
  const hits = [];
34323
35275
  let inComment = false;
34324
- eachLine(text, (rawLine, lineNumber) => {
35276
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34325
35277
  const stripped = stripXmlComments(rawLine, inComment);
34326
35278
  inComment = stripped.inComment;
34327
35279
  const name = CSPROJ_PACKAGE_REFERENCE.exec(stripped.visible)?.[1];
34328
- if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, rawLine));
35280
+ if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, snippet()));
34329
35281
  });
34330
35282
  return hits;
34331
35283
  }
@@ -34333,11 +35285,11 @@ var PACKAGES_CONFIG_PACKAGE = /<package\s+id="([^"]+)"/;
34333
35285
  function extractPackagesConfig(text) {
34334
35286
  const hits = [];
34335
35287
  let inComment = false;
34336
- eachLine(text, (rawLine, lineNumber) => {
35288
+ eachLine(text, (rawLine, lineNumber, snippet) => {
34337
35289
  const stripped = stripXmlComments(rawLine, inComment);
34338
35290
  inComment = stripped.inComment;
34339
35291
  const name = PACKAGES_CONFIG_PACKAGE.exec(stripped.visible)?.[1];
34340
- if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, rawLine));
35292
+ if (name !== void 0) hits.push(makeHit("nuget", name, lineNumber, snippet()));
34341
35293
  });
34342
35294
  return hits;
34343
35295
  }
@@ -34363,7 +35315,9 @@ function stripXmlComments(line, inComment) {
34363
35315
  function eachLine(text, fn) {
34364
35316
  const lines = text.split("\n");
34365
35317
  for (let i = 0; i < lines.length; i += 1) {
34366
- fn(lines[i] ?? "", i + 1);
35318
+ const rawLine = lines[i] ?? "";
35319
+ let cached2;
35320
+ fn(rawLine, i + 1, () => cached2 ??= redactSnippet(rawLine));
34367
35321
  }
34368
35322
  }
34369
35323
  function parseJson(text) {
@@ -34385,24 +35339,76 @@ function objectKeys(value) {
34385
35339
  if (typeof value !== "object" || value === null) return [];
34386
35340
  return Object.keys(value);
34387
35341
  }
34388
- function hitAtQuotedKey(ecosystem, pkg, text, sectionKey) {
34389
- const sectionStart = text.indexOf(`"${sectionKey}"`);
34390
- const searchFrom = sectionStart === -1 ? 0 : sectionStart;
34391
- const index = text.indexOf(`"${pkg}"`, searchFrom);
34392
- if (index === -1) return makeHit(ecosystem, pkg, 1, pkg);
34393
- return makeHit(ecosystem, pkg, lineNumberAt(text, index), lineContaining(text, index));
35342
+ function manifestLines(text) {
35343
+ const starts = lineStartOffsets(text);
35344
+ const snippets = /* @__PURE__ */ new Map();
35345
+ return {
35346
+ numberAt: (index) => lineIndexAt(starts, index) + 1,
35347
+ snippetAt: (index) => {
35348
+ const line = lineIndexAt(starts, index);
35349
+ const cached2 = snippets.get(line);
35350
+ if (cached2 !== void 0) return cached2;
35351
+ const value = redactSnippet(lineTextAt(text, starts, line));
35352
+ snippets.set(line, value);
35353
+ return value;
35354
+ }
35355
+ };
35356
+ }
35357
+ function sectionOffset(text, sectionKey) {
35358
+ const at = text.indexOf(`"${sectionKey}"`);
35359
+ return at === -1 ? 0 : at;
34394
35360
  }
34395
- function lineNumberAt(text, index) {
34396
- let line = 1;
34397
- for (let i = 0; i < index; i += 1) {
34398
- if (text[i] === "\n") line += 1;
35361
+ var QUOTE = 34;
35362
+ var BACKSLASH = 92;
35363
+ function quotedTokenOffsets(text) {
35364
+ const at = /* @__PURE__ */ new Map();
35365
+ for (let i = 0; i < text.length; i += 1) {
35366
+ if (text.charCodeAt(i) !== QUOTE) continue;
35367
+ let end = i + 1;
35368
+ while (end < text.length && text.charCodeAt(end) !== QUOTE) {
35369
+ end += text.charCodeAt(end) === BACKSLASH ? 2 : 1;
35370
+ }
35371
+ if (end >= text.length) break;
35372
+ const inner = text.slice(i + 1, end);
35373
+ const name = inner.includes("\\") ? decodeJsonString(text.slice(i, end + 1)) : inner;
35374
+ if (name !== void 0) {
35375
+ const seen = at.get(name);
35376
+ if (seen === void 0) at.set(name, [i]);
35377
+ else seen.push(i);
35378
+ }
35379
+ i = end;
34399
35380
  }
34400
- return line;
35381
+ return at;
34401
35382
  }
34402
- function lineContaining(text, index) {
34403
- const start = text.lastIndexOf("\n", index) + 1;
34404
- const end = text.indexOf("\n", index);
34405
- return text.slice(start, end === -1 ? text.length : end);
35383
+ function decodeJsonString(quoted) {
35384
+ try {
35385
+ return JSON.parse(quoted);
35386
+ } catch {
35387
+ return void 0;
35388
+ }
35389
+ }
35390
+ function firstAtOrAfter(offsets, from) {
35391
+ let low = 0;
35392
+ let high = offsets.length - 1;
35393
+ let found;
35394
+ while (low <= high) {
35395
+ const mid = low + high >> 1;
35396
+ const at = offsets[mid] ?? 0;
35397
+ if (at >= from) {
35398
+ found = at;
35399
+ high = mid - 1;
35400
+ } else {
35401
+ low = mid + 1;
35402
+ }
35403
+ }
35404
+ return found;
35405
+ }
35406
+ function hitAtQuotedKey(ecosystem, pkg, text, searchFrom, lines, tokens) {
35407
+ const offsets = tokens.get(pkg);
35408
+ const known = offsets === void 0 ? void 0 : firstAtOrAfter(offsets, searchFrom);
35409
+ const index = known ?? text.indexOf(`"${pkg}"`, searchFrom);
35410
+ if (index === -1) return makeHit(ecosystem, pkg, 1, redactSnippet(pkg));
35411
+ return { ecosystem, pkg, line: lines.numberAt(index), snippet: lines.snippetAt(index) };
34406
35412
  }
34407
35413
 
34408
35414
  // ../../packages/detections/src/egress/resolve.ts
@@ -37015,8 +38021,8 @@ function bundledDetections() {
37015
38021
  }
37016
38022
 
37017
38023
  // ../../packages/plugin-sdk/src/repo.ts
37018
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
37019
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
38024
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
38025
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
37020
38026
  function resolveRepoIdentity(cwd) {
37021
38027
  try {
37022
38028
  const root = findGitRoot(cwd);
@@ -37045,36 +38051,36 @@ function resolveWorktreeRoot(cwd) {
37045
38051
  function findGitRoot(start) {
37046
38052
  let dir = start;
37047
38053
  for (; ; ) {
37048
- if (existsSync8(join15(dir, ".git"))) return dir;
38054
+ if (existsSync9(join18(dir, ".git"))) return dir;
37049
38055
  const parent = dirname4(dir);
37050
38056
  if (parent === dir) return void 0;
37051
38057
  dir = parent;
37052
38058
  }
37053
38059
  }
37054
38060
  function resolveGitContext(root) {
37055
- const dotGit = join15(root, ".git");
38061
+ const dotGit = join18(root, ".git");
37056
38062
  try {
37057
38063
  if (statSync6(dotGit).isDirectory()) {
37058
- return { configPath: join15(dotGit, "config"), headRoot: root };
38064
+ return { configPath: join18(dotGit, "config"), headRoot: root };
37059
38065
  }
37060
38066
  } catch {
37061
38067
  return void 0;
37062
38068
  }
37063
38069
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
37064
38070
  if (!target) return void 0;
37065
- const gitdir = isAbsolute(target) ? target : join15(root, target);
37066
- if (existsSync8(join15(gitdir, "config"))) {
37067
- return { configPath: join15(gitdir, "config"), headRoot: root };
38071
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
38072
+ if (existsSync9(join18(gitdir, "config"))) {
38073
+ return { configPath: join18(gitdir, "config"), headRoot: root };
37068
38074
  }
37069
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
38075
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
37070
38076
  if (!commonRaw) return void 0;
37071
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
38077
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
37072
38078
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
37073
- return { configPath: join15(commonGitDir, "config"), headRoot };
38079
+ return { configPath: join18(commonGitDir, "config"), headRoot };
37074
38080
  }
37075
38081
  function safeRead(path) {
37076
38082
  try {
37077
- return readFileSync9(path, "utf8");
38083
+ return readFileSync11(path, "utf8");
37078
38084
  } catch {
37079
38085
  return void 0;
37080
38086
  }
@@ -37140,7 +38146,7 @@ function buildIngestEvent(input2) {
37140
38146
  }
37141
38147
 
37142
38148
  // ../../packages/plugin-sdk/src/isolated-scan.ts
37143
- import { existsSync as existsSync9 } from "fs";
38149
+ import { existsSync as existsSync10 } from "fs";
37144
38150
  import { fileURLToPath } from "url";
37145
38151
  import { Worker } from "worker_threads";
37146
38152
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -37154,7 +38160,7 @@ function resolveWorkerUrl() {
37154
38160
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
37155
38161
  const candidate = new URL(name, import.meta.url);
37156
38162
  try {
37157
- if (existsSync9(fileURLToPath(candidate))) {
38163
+ if (existsSync10(fileURLToPath(candidate))) {
37158
38164
  resolvedWorkerUrl = candidate;
37159
38165
  return candidate;
37160
38166
  }
@@ -37617,13 +38623,48 @@ function createGuardedScanner(partition, gateway, opts) {
37617
38623
  };
37618
38624
  }
37619
38625
 
38626
+ // ../../packages/plugin-sdk/src/host-floor.ts
38627
+ import { readFileSync as readFileSync14 } from "fs";
38628
+ import { join as join21 } from "path";
38629
+
38630
+ // ../../packages/plugin-sdk/src/model-governance.ts
38631
+ import {
38632
+ closeSync as closeSync2,
38633
+ fstatSync,
38634
+ mkdirSync as mkdirSync2,
38635
+ openSync as openSync2,
38636
+ readFileSync as readFileSync13,
38637
+ readSync,
38638
+ writeFileSync as writeFileSync5
38639
+ } from "fs";
38640
+ import { join as join20 } from "path";
38641
+ var TAIL_BYTES = 256 * 1024;
38642
+
38643
+ // ../../packages/plugin-sdk/src/host-floor.ts
38644
+ var HOST_FEATURE = {
38645
+ ModelSwitch: "model-switch",
38646
+ VaultPointerDisplay: "vault-pointer-display"
38647
+ };
38648
+ var HOST_FLOORS = {
38649
+ [HOST_FEATURE.ModelSwitch]: {
38650
+ label: "model-switch protection",
38651
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
38652
+ since: "2.1.251"
38653
+ },
38654
+ [HOST_FEATURE.VaultPointerDisplay]: {
38655
+ label: "vault pointer display",
38656
+ hookEvents: ["MessageDisplay"],
38657
+ since: "2.1.152"
38658
+ }
38659
+ };
38660
+
37620
38661
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37621
38662
  var import_ignore = __toESM(require_ignore(), 1);
37622
- import { readFileSync as readFileSync11 } from "fs";
37623
- import { join as join17 } from "path";
38663
+ import { readFileSync as readFileSync15 } from "fs";
38664
+ import { join as join22 } from "path";
37624
38665
  function readIgnoreLayer(dir, filename, anchorLen) {
37625
38666
  try {
37626
- return { matcher: (0, import_ignore.default)().add(readFileSync11(join17(dir, filename), "utf8")), anchorLen };
38667
+ return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
37627
38668
  } catch {
37628
38669
  return void 0;
37629
38670
  }
@@ -37653,22 +38694,9 @@ function withLayer(layers, layer) {
37653
38694
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
37654
38695
  import { arch, hostname as hostname4, platform, release } from "os";
37655
38696
 
37656
- // ../../packages/plugin-sdk/src/model-governance.ts
37657
- import {
37658
- closeSync as closeSync2,
37659
- fstatSync,
37660
- mkdirSync as mkdirSync2,
37661
- openSync as openSync2,
37662
- readFileSync as readFileSync12,
37663
- readSync,
37664
- writeFileSync as writeFileSync5
37665
- } from "fs";
37666
- import { join as join18 } from "path";
37667
- var TAIL_BYTES = 256 * 1024;
37668
-
37669
38697
  // ../../packages/plugin-sdk/src/nudge.ts
37670
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
37671
- import { join as join19 } from "path";
38698
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
38699
+ import { join as join23 } from "path";
37672
38700
 
37673
38701
  // ../../packages/plugin-sdk/src/paths.ts
37674
38702
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37740,8 +38768,8 @@ function createPolicyResolver(bundle) {
37740
38768
  }
37741
38769
 
37742
38770
  // ../../packages/plugin-sdk/src/project-files.ts
37743
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
37744
- import { basename as basename5, join as join20 } from "path";
38771
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
38772
+ import { basename as basename5, join as join24 } from "path";
37745
38773
 
37746
38774
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37747
38775
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37772,6 +38800,14 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
37772
38800
  // ../../packages/plugin-sdk/src/runtime.ts
37773
38801
  import { randomUUID as randomUUID14 } from "crypto";
37774
38802
  var ENFORCEMENT_CEILING_ENABLED = false;
38803
+ function applyEnforcementCeiling(action, policyMode, enabled) {
38804
+ if (!enabled || policyMode !== "warn") return action;
38805
+ return action === "block" || action === "redact" ? "warn" : action;
38806
+ }
38807
+ function resolveEnforcedAction(action, opts) {
38808
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
38809
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
38810
+ }
37775
38811
  function startTiming() {
37776
38812
  try {
37777
38813
  return performance.now();
@@ -37808,7 +38844,7 @@ function createPluginRuntime(gateway, settings, opts) {
37808
38844
  bundlesPacked = true;
37809
38845
  }
37810
38846
  const policyMode = settings.policy;
37811
- const redactFallback = settings.redactFallback;
38847
+ let redactFallback = settings.redactFallback;
37812
38848
  const dataDir2 = opts?.dataDir;
37813
38849
  let rules = [];
37814
38850
  let scanner;
@@ -37852,6 +38888,7 @@ function createPluginRuntime(gateway, settings, opts) {
37852
38888
  rules = [...verified, ...unverified];
37853
38889
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
37854
38890
  bundleExceptions = bundle.exceptions ?? [];
38891
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
37855
38892
  initialized = true;
37856
38893
  }
37857
38894
  let cachedKey;
@@ -37880,21 +38917,23 @@ function createPluginRuntime(gateway, settings, opts) {
37880
38917
  }
37881
38918
  function actionForFinding(finding, excepted, rewritable = true) {
37882
38919
  if (excepted?.has(finding)) return "allow";
37883
- const action = resolveAction(finding.ruleId, finding.category);
37884
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
37885
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
37886
- return "warn";
37887
- }
37888
- return action;
38920
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
38921
+ policyMode,
38922
+ redactFallback,
38923
+ rewritable,
38924
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
38925
+ });
37889
38926
  }
37890
38927
  function decide(findings, text, excepted, rewritable = true) {
37891
38928
  if (findings.length === 0) return { action: "log", text, findings: [] };
37892
38929
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38930
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38931
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
37893
38932
  let worst = "log";
37894
38933
  for (const finding of findings) {
37895
38934
  worst = strongerAction(worst, actionFor(finding));
37896
38935
  }
37897
- if (worst === "block") return { action: "block", text: null, findings };
38936
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
37898
38937
  if (worst === "redact") {
37899
38938
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
37900
38939
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -37904,9 +38943,13 @@ function createPluginRuntime(gateway, settings, opts) {
37904
38943
  findings,
37905
38944
  enforcedFindings: redactFindings,
37906
38945
  reversibleFindings
38946
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38947
+ // CAPTURE, so on an unrewritable field every redact has already become
38948
+ // the fallback and this branch is unreachable. Spreading it would read
38949
+ // as a case that can happen.
37907
38950
  };
37908
38951
  }
37909
- return { action: worst, text, findings };
38952
+ return { action: worst, text, findings, ...degraded };
37910
38953
  }
37911
38954
  function fingerprintOf(key, finding, cache) {
37912
38955
  let fp = cache.get(finding);
@@ -38035,8 +39078,8 @@ function createPluginRuntime(gateway, settings, opts) {
38035
39078
  };
38036
39079
  }
38037
39080
  }
38038
- async function processText(text, context) {
38039
- return (await evaluate(text, context, {})).decision;
39081
+ async function processText(text, context, opts2 = {}) {
39082
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
38040
39083
  }
38041
39084
  async function capture(input2, opts2 = {}) {
38042
39085
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -38059,10 +39102,12 @@ function createPluginRuntime(gateway, settings, opts) {
38059
39102
  );
38060
39103
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
38061
39104
  const inspectionMs = elapsedMs(timingStartedAt);
38062
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
39105
+ const redactDegradedTo = decision.redactDegradedTo;
39106
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
38063
39107
  ...input2.metadata,
38064
39108
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
38065
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
39109
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
39110
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
38066
39111
  } : input2.metadata;
38067
39112
  const event = buildIngestEvent({
38068
39113
  kind: input2.kind,
@@ -38134,7 +39179,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38134
39179
 
38135
39180
  // ../../packages/plugin-sdk/src/throttle.ts
38136
39181
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38137
- import { join as join21 } from "path";
39182
+ import { join as join25 } from "path";
38138
39183
 
38139
39184
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
38140
39185
  function isInvalidRequest(err) {
@@ -38150,31 +39195,12 @@ function isServerRejection(err) {
38150
39195
  var FORWARD_BUDGET_MS = 1500;
38151
39196
  var DECISION_PATH_BUDGET_MS = 800;
38152
39197
  var BREAKER_FAILURE_THRESHOLD = 3;
38153
- var BREAKER_COOLDOWN_MS = 3e4;
38154
39198
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
38155
- var FAILURES = /* @__PURE__ */ new Set([
38156
- "unauthorized",
38157
- "forbidden",
38158
- "unreachable"
38159
- ]);
38160
39199
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
38161
39200
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
38162
- function parseBreakerState(raw, nowMs) {
38163
- try {
38164
- const parsed2 = JSON.parse(raw);
38165
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
38166
- const record2 = parsed2;
38167
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
38168
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
38169
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
38170
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
38171
- } catch {
38172
- return null;
38173
- }
38174
- }
38175
39201
  function createForwardPolicy(deps) {
38176
39202
  const now = deps.now ?? (() => Date.now());
38177
- const file2 = join22(deps.dir, STATE_FILENAME);
39203
+ const file2 = join26(deps.dir, STATE_FILENAME);
38178
39204
  let state = null;
38179
39205
  let loading = null;
38180
39206
  async function readState() {
@@ -38184,7 +39210,7 @@ function createForwardPolicy(deps) {
38184
39210
  } catch {
38185
39211
  return { ...CLOSED };
38186
39212
  }
38187
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39213
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
38188
39214
  }
38189
39215
  async function load() {
38190
39216
  if (state !== null) return state;
@@ -38230,7 +39256,7 @@ function createForwardPolicy(deps) {
38230
39256
  };
38231
39257
  const at = now();
38232
39258
  if (current.openedAtMs !== null) {
38233
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39259
+ if (isForwardPaused(current, at)) {
38234
39260
  return { ok: false, reason: "breaker-open" };
38235
39261
  }
38236
39262
  await persist({
@@ -38767,7 +39793,18 @@ var AttachedDataGateway = class {
38767
39793
  // and the spread above would otherwise drop the field silently — which is
38768
39794
  // exactly what it did, leaving the whole control inert on every device
38769
39795
  // while every test around it stayed green.
38770
- prohibitedModels: cached2.prohibitedModels
39796
+ prohibitedModels: cached2.prohibitedModels,
39797
+ // NAMED for the same reason as the line above, and it is the same defect
39798
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
39799
+ // only the cache carries is dropped in silence. That is what left
39800
+ // `prohibitedModels` inert on every attached device with every test
39801
+ // around it green.
39802
+ //
39803
+ // Taken from the cache rather than merged here, because merging it needs
39804
+ // the device's own SETTING — which is not a bundle field and is not in
39805
+ // scope at this seam. The runtime does that merge, raise-only, where both
39806
+ // values are in hand (createPluginRuntime's ensureInitialized).
39807
+ redactFallback: cached2.redactFallback
38771
39808
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
38772
39809
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
38773
39810
  // it emits, so an 'authored' policy arriving from the control plane
@@ -38895,10 +39932,6 @@ function toolAuditEvent(input2) {
38895
39932
  };
38896
39933
  }
38897
39934
 
38898
- // ../../packages/plugin-runtime/src/attached/history-state.ts
38899
- import { readFileSync as readFileSync15 } from "fs";
38900
- import { join as join23 } from "path";
38901
-
38902
39935
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
38903
39936
  import { createHash as createHash6 } from "crypto";
38904
39937
  import { hostname as hostname5 } from "os";
@@ -38907,6 +39940,10 @@ import { hostname as hostname5 } from "os";
38907
39940
  var CORRELATION_ID = EventMetadata.shape.correlationId;
38908
39941
  var TRACE_ID = EventMetadata.shape.traceId;
38909
39942
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
39943
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
39944
+
39945
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
39946
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
38910
39947
 
38911
39948
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
38912
39949
  import { spawn } from "child_process";
@@ -38914,7 +39951,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
38914
39951
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
38915
39952
 
38916
39953
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
38917
- import { readFileSync as readFileSync16 } from "fs";
39954
+ import { readFileSync as readFileSync17 } from "fs";
38918
39955
  function createPluginBlock(build, policyStore) {
38919
39956
  return async () => {
38920
39957
  const cached2 = await policyStore.read();
@@ -38933,7 +39970,7 @@ function createPluginBlock(build, policyStore) {
38933
39970
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38934
39971
  import { randomUUID as randomUUID16 } from "crypto";
38935
39972
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38936
- import { join as join24 } from "path";
39973
+ import { join as join27 } from "path";
38937
39974
 
38938
39975
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38939
39976
  import { rename as rename2 } from "fs/promises";
@@ -38957,7 +39994,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38957
39994
 
38958
39995
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38959
39996
  function createPolicyStore(dir = dataDir()) {
38960
- const file2 = join24(dir, "policy-cache.json");
39997
+ const file2 = join27(dir, "policy-cache.json");
38961
39998
  async function read() {
38962
39999
  try {
38963
40000
  const raw = await readFile2(file2, "utf8");
@@ -39237,11 +40274,11 @@ function readStorePosture(dbPath2) {
39237
40274
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39238
40275
  import { randomUUID as randomUUID17 } from "crypto";
39239
40276
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39240
- import { join as join25 } from "path";
40277
+ import { join as join28 } from "path";
39241
40278
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39242
40279
  function createPostureStore(dir = settingsDir(), legacyDir) {
39243
- const file2 = join25(dir, "posture-state.json");
39244
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
40280
+ const file2 = join28(dir, "posture-state.json");
40281
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
39245
40282
  async function persist(state) {
39246
40283
  await ensureDataDir(dir);
39247
40284
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39309,11 +40346,11 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39309
40346
  }
39310
40347
 
39311
40348
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39312
- import { readFileSync as readFileSync17 } from "fs";
39313
- import { join as join26 } from "path";
40349
+ import { readFileSync as readFileSync18 } from "fs";
40350
+ import { join as join29 } from "path";
39314
40351
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
39315
40352
  function syncStatePath(dataDir2) {
39316
- return join26(dataDir2, SYNC_STATE_FILENAME);
40353
+ return join29(dataDir2, SYNC_STATE_FILENAME);
39317
40354
  }
39318
40355
  function writeSyncState(dataDir2, result) {
39319
40356
  try {
@@ -39366,6 +40403,14 @@ import { spawn as spawn2 } from "child_process";
39366
40403
  import { fileURLToPath as fileURLToPath3 } from "url";
39367
40404
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
39368
40405
 
40406
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40407
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40408
+
40409
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40410
+ import { spawn as spawn3 } from "child_process";
40411
+ import { fileURLToPath as fileURLToPath4 } from "url";
40412
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40413
+
39369
40414
  // ../../packages/plugin-runtime/src/attached/factory.ts
39370
40415
  import { hostname as hostname6 } from "os";
39371
40416
 
@@ -39817,7 +40862,7 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
39817
40862
 
39818
40863
  // ../../packages/scanner/src/discover.ts
39819
40864
  import { readdirSync as readdirSync5 } from "fs";
39820
- import { join as join27 } from "path";
40865
+ import { join as join30 } from "path";
39821
40866
 
39822
40867
  // ../../packages/scanner/src/constants.ts
39823
40868
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -39841,15 +40886,15 @@ var DISCOVER_SKIP = /* @__PURE__ */ new Set([
39841
40886
  import { basename as basename6, relative } from "path";
39842
40887
 
39843
40888
  // ../../packages/scanner/src/scan.ts
39844
- import { existsSync as existsSync11, readFileSync as readFileSync19 } from "fs";
40889
+ import { existsSync as existsSync12, readFileSync as readFileSync20 } from "fs";
39845
40890
  import { extname as extname2, isAbsolute as isAbsolute2, relative as relative3 } from "path";
39846
40891
 
39847
40892
  // ../../packages/scanner/src/manifests.ts
39848
40893
  import { statSync as statSync11 } from "fs";
39849
40894
 
39850
40895
  // ../../packages/scanner/src/walk.ts
39851
- import { readdirSync as readdirSync6, readFileSync as readFileSync18, statSync as statSync10 } from "fs";
39852
- import { extname, join as join28, relative as relative2, sep as sep4 } from "path";
40896
+ import { readdirSync as readdirSync6, readFileSync as readFileSync19, statSync as statSync10 } from "fs";
40897
+ import { extname, join as join31, relative as relative2, sep as sep4 } from "path";
39853
40898
  var import_ignore2 = __toESM(require_ignore(), 1);
39854
40899
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
39855
40900
  ".ts",
@@ -39900,7 +40945,7 @@ function* walkTree(rootDir, opts = {}) {
39900
40945
  );
39901
40946
  for (const entry of dirents) {
39902
40947
  const name = entry.name;
39903
- const fullPath = join28(dir, name);
40948
+ const fullPath = join31(dir, name);
39904
40949
  if (entry.isDirectory()) {
39905
40950
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
39906
40951
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {
@@ -39954,7 +40999,7 @@ function* walkSourceFiles(opts = {}) {
39954
40999
  if (opts.shouldRead && !opts.shouldRead(meta4)) continue;
39955
41000
  let content;
39956
41001
  try {
39957
- content = readFileSync18(file2.path, "utf8");
41002
+ content = readFileSync19(file2.path, "utf8");
39958
41003
  } catch {
39959
41004
  continue;
39960
41005
  }
@@ -40074,7 +41119,7 @@ function isUnderRoot(path, rootDir) {
40074
41119
  async function sweepDeletedFiles(gateway, rootDir, previous) {
40075
41120
  const deleted = [];
40076
41121
  for (const path of previous.keys()) {
40077
- if (!isUnderRoot(path, rootDir) || existsSync11(path)) continue;
41122
+ if (!isUnderRoot(path, rootDir) || existsSync12(path)) continue;
40078
41123
  deleted.push(path);
40079
41124
  await resolveRemovedFindings(gateway, path, [], { deleted: true });
40080
41125
  }
@@ -40181,7 +41226,7 @@ function scanManifests(egress, ledger, updates, rootDir) {
40181
41226
  if (prev?.mtime === manifest.mtime) continue;
40182
41227
  let content;
40183
41228
  try {
40184
- content = readFileSync19(manifest.path, "utf8");
41229
+ content = readFileSync20(manifest.path, "utf8");
40185
41230
  } catch {
40186
41231
  continue;
40187
41232
  }