@akasecurity/ai-tc-codex 0.9.10 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,10 +492,7 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/hooks/session-start.ts
495
- import { readFileSync as readFileSync21 } from "fs";
496
-
497
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
498
- import { createHash as createHash4 } from "crypto";
495
+ import { readFileSync as readFileSync22 } from "fs";
499
496
 
500
497
  // ../../packages/persistence/src/attached-derived.ts
501
498
  import { rmSync } from "fs";
@@ -508,6 +505,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
508
505
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
509
506
  import { join as join2 } from "path";
510
507
 
508
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
509
+ var DEFERRED_MIGRATION_TAGS = [
510
+ "0031_audit_capture_by_time_index",
511
+ "0032_audit_capture_by_id_index",
512
+ "0033_audit_capture_location_index",
513
+ "0034_findings_read_indexes"
514
+ ];
515
+
511
516
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
512
517
  var SQLITE_MIGRATIONS = [
513
518
  {
@@ -625,6 +630,30 @@ var SQLITE_MIGRATIONS = [
625
630
  {
626
631
  tag: "0028_activity_session_probe_indexes",
627
632
  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"
633
+ },
634
+ {
635
+ tag: "0029_audit_capture_rollup_index",
636
+ 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');"
637
+ },
638
+ {
639
+ tag: "0030_audit_content_expiry",
640
+ 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;"
641
+ },
642
+ {
643
+ tag: "0031_audit_capture_by_time_index",
644
+ 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');"
645
+ },
646
+ {
647
+ tag: "0032_audit_capture_by_id_index",
648
+ 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');"
649
+ },
650
+ {
651
+ tag: "0033_audit_capture_location_index",
652
+ 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');"
653
+ },
654
+ {
655
+ tag: "0034_findings_read_indexes",
656
+ 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`);"
628
657
  }
629
658
  ];
630
659
 
@@ -20625,7 +20654,7 @@ var TOOL_TO_HARNESS = {
20625
20654
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20626
20655
  };
20627
20656
  function harnessFromTool(tool) {
20628
- return TOOL_TO_HARNESS[tool] ?? tool;
20657
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20629
20658
  }
20630
20659
 
20631
20660
  // ../../packages/schema/src/zod/finding.ts
@@ -20675,6 +20704,15 @@ var FindingCategory = external_exports.enum([
20675
20704
  ]).meta({ id: "FindingCategory" });
20676
20705
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20677
20706
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20707
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20708
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20709
+ var FindingDelivery = external_exports.object({
20710
+ state: FindingDeliveryState,
20711
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20712
+ at: external_exports.iso.datetime().optional(),
20713
+ // Only on `not_sent`, and only when a known reason was recorded.
20714
+ reason: SyncFailureReason.optional()
20715
+ }).meta({ id: "FindingDelivery" });
20678
20716
  var ResolutionMethod = external_exports.enum([
20679
20717
  "enforced-in-flight",
20680
20718
  "fixed-at-source",
@@ -20731,7 +20769,10 @@ var FindingInstance = external_exports.object({
20731
20769
  // The session that event belongs to, when it has one — the seam a
20732
20770
  // per-instance "view session" link needs. Absent for events captured
20733
20771
  // outside a session.
20734
- sessionId: external_exports.string().optional()
20772
+ sessionId: external_exports.string().optional(),
20773
+ // The delivery state of the event above (see FindingDelivery). Optional so
20774
+ // readers that do not project it stay valid.
20775
+ delivery: FindingDelivery.optional()
20735
20776
  }).meta({ id: "FindingInstance" });
20736
20777
  var FindingGroup = external_exports.object({
20737
20778
  id: external_exports.string(),
@@ -20748,13 +20789,11 @@ var FindingGroup = external_exports.object({
20748
20789
  latestDetectedAt: external_exports.iso.datetime(),
20749
20790
  instances: external_exports.array(FindingInstance),
20750
20791
  // Derived from instances' statuses with open-dominates precedence (see
20751
- // buildFindingGroups). Undefined only when no instance carries a status.
20792
+ // foldGroupStatus). Undefined only when no instance carries a status.
20752
20793
  status: FindingStatus.optional(),
20753
- // The distinct people across the WHOLE group, not just the `instances`
20754
- // preview — from the store's whole-group aggregate when it supplies one,
20755
- // else folded from the rows (see buildFindingGroups). Undefined when no
20756
- // instance carries a user, or when the store supplied whole-group folds
20757
- // without one.
20794
+ // The distinct people across the WHOLE group, not just the instances
20795
+ // carried here. Undefined when no instance carries a user, or when the
20796
+ // store supplied whole-group folds without one.
20758
20797
  users: external_exports.array(FindingUser).optional()
20759
20798
  }).meta({ id: "FindingGroup" });
20760
20799
  var FindingStats = external_exports.object({
@@ -20783,21 +20822,34 @@ var FindingFacets = external_exports.object({
20783
20822
  // counted under no value.
20784
20823
  status: external_exports.array(FindingFacetItem),
20785
20824
  // Host tool (attributes.tool_name). Present only on the instance-level
20786
- // reads, which can filter by it; the grouped read omits the dimension
20825
+ // reads, which can filter by it; the type-level read omits the dimension
20787
20826
  // because a group spans tools.
20788
- tool: external_exports.array(FindingFacetItem).optional()
20827
+ tool: external_exports.array(FindingFacetItem).optional(),
20828
+ // Delivery states (FindingDeliveryState). Present only on the
20829
+ // instance-level reads, like `tool`.
20830
+ deployment: external_exports.array(FindingFacetItem).optional()
20789
20831
  }).meta({ id: "FindingFacets" });
20790
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20791
- var ListGroupedFindingsQuery = external_exports.object({
20832
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20833
+ id: "FindingTypeSummary"
20834
+ });
20835
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20836
+ var MAX_FINDING_TYPES_LIMIT = 100;
20837
+ var ListFindingTypesQuery = external_exports.object({
20792
20838
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20793
- // FindingAction.
20839
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20840
+ // firing version carries, and this list pages types.
20841
+ //
20842
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20843
+ // definition versions at different severities, so a type kept by this filter
20844
+ // can hold findings that individually do not match — see totals.findings on
20845
+ // ListFindingTypesResponse, which counts them all.
20794
20846
  severity: external_exports.array(Severity).optional(),
20795
20847
  subtype: external_exports.array(external_exports.string()).optional(),
20796
20848
  provider: external_exports.array(FindingProvider).optional(),
20797
20849
  action: external_exports.array(FindingAction).optional(),
20798
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20799
- // individual instances' — so a filtered group's Status column always reads
20800
- // one of the requested values.
20850
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20851
+ // individual findings' — so a filtered row's status always reads one of the
20852
+ // requested values.
20801
20853
  status: external_exports.array(FindingStatus).optional(),
20802
20854
  q: external_exports.string().optional(),
20803
20855
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20807,23 +20859,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20807
20859
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20808
20860
  // means all time — this list has no default window.
20809
20861
  from: external_exports.iso.datetime().optional(),
20810
- // A group or instance id that must appear in the page even when the cursor
20811
- // has already advanced past its sort position. This is what keeps the
20812
- // Findings page's one-shot ?finding= deep link resolving once the list
20813
- // paginates: the target group is appended out of sort order rather than
20814
- // scanning forward for it. Never affects totals, facets or the cursor.
20862
+ // A RULE id that must appear in the page even when the cursor has already
20863
+ // advanced past its sort position. This is what keeps the selected type
20864
+ // visible in the list once it paginates: the target is appended out of sort
20865
+ // order rather than scanned forward for. Never affects totals, facets or the
20866
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20867
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20868
+ // and so is not bounded by what any page happens to hold.
20815
20869
  includeId: external_exports.string().optional(),
20816
- groupBy: external_exports.literal("type").optional(),
20817
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20870
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20818
20871
  cursor: external_exports.string().optional()
20819
20872
  });
20820
- var ListGroupedFindingsResponse = external_exports.object({
20873
+ var ListFindingTypesResponse = external_exports.object({
20821
20874
  totals: external_exports.object({
20875
+ // Findings belonging to the matching TYPES — not findings that each match
20876
+ // the filters. The filters here select types, so a type that survives
20877
+ // contributes its whole instanceCount.
20878
+ //
20879
+ // `status` is the one exception, narrowed per finding via
20880
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20881
+ // this can exceed what the instance read reports for the same filters: a
20882
+ // rule whose severity moved between versions is kept on its newest and
20883
+ // still counts its older findings. Narrowing the other three needs
20884
+ // per-dimension counts the aggregate does not carry today.
20822
20885
  findings: external_exports.number().int().nonnegative(),
20823
- groups: external_exports.number().int().nonnegative()
20886
+ // Counts TYPES, which is the unit this read pages. The instance read's
20887
+ // own totals count findings; the two deliberately answer different
20888
+ // questions and are never summed.
20889
+ types: external_exports.number().int().nonnegative()
20824
20890
  }),
20825
20891
  facets: FindingFacets,
20826
- items: external_exports.array(FindingGroup),
20892
+ items: external_exports.array(FindingTypeSummary),
20827
20893
  nextCursor: external_exports.string().nullable(),
20828
20894
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20829
20895
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20831,7 +20897,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20831
20897
  // every firing, so the two numbers legitimately differ — this map lets a
20832
20898
  // session-scoped view show both.
20833
20899
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20834
- }).meta({ id: "ListGroupedFindingsResponse" });
20900
+ }).meta({ id: "ListFindingTypesResponse" });
20835
20901
  var ApplyFindingActionRequest = external_exports.object({
20836
20902
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20837
20903
  // it, so it is excluded from the request contract. The mapping helper
@@ -20861,16 +20927,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20861
20927
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20862
20928
  var ListFindingInstancesQuery = external_exports.object({
20863
20929
  severity: external_exports.array(Severity).optional(),
20864
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20930
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20931
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20865
20932
  subtype: external_exports.array(external_exports.string()).optional(),
20866
20933
  provider: external_exports.array(FindingProvider).optional(),
20867
20934
  action: external_exports.array(FindingAction).optional(),
20868
20935
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20869
- // the grouped query's group-level fold.
20936
+ // the types query's type-level fold.
20870
20937
  status: external_exports.array(FindingStatus).optional(),
20871
20938
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20872
20939
  // where the free-text `q` can only match the rendered "via Bash" label.
20873
20940
  tool: external_exports.array(external_exports.string()).optional(),
20941
+ // The delivery state of each finding's event (see FindingDelivery).
20942
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20874
20943
  // Exact repository / file-path matches, for the drill-down out of the
20875
20944
  // locations view. A row whose event carries no repo/file matches neither.
20876
20945
  repo: external_exports.string().optional(),
@@ -20883,37 +20952,51 @@ var ListFindingInstancesQuery = external_exports.object({
20883
20952
  });
20884
20953
  var ListFindingInstancesResponse = external_exports.object({
20885
20954
  // Instances matching the filters across the whole scope, not just this
20886
- // page — cursor-independent, like the grouped list's totals.
20955
+ // page — cursor-independent, like the types list's totals.
20887
20956
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20888
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20957
+ // Counts in INSTANCES here, where the types response counts types. Each
20889
20958
  // dimension still excludes its own filter.
20890
20959
  facets: FindingFacets,
20891
20960
  items: external_exports.array(FindingInstanceDetail),
20892
20961
  nextCursor: external_exports.string().nullable()
20893
20962
  }).meta({ id: "ListFindingInstancesResponse" });
20894
- var FindingLocationFile = external_exports.object({
20895
- // Empty when the instances carried no file path (a prompt or a tool call
20896
- // with no file attribution).
20897
- file: external_exports.string(),
20898
- instanceCount: external_exports.number().int().nonnegative(),
20899
- maxSeverity: Severity,
20900
- latestDetectedAt: external_exports.iso.datetime(),
20901
- // Folded from the instances' derived statuses with the same
20902
- // open-dominates precedence a group uses.
20903
- status: FindingStatus.optional(),
20904
- // Distinct rules seen at this location, capped — the row shows them as
20905
- // chips, and the count is what conveys scale.
20906
- ruleIds: external_exports.array(external_exports.string())
20907
- }).meta({ id: "FindingLocationFile" });
20908
- var FindingLocationRepo = external_exports.object({
20963
+ var ListFindingInstancesPage = external_exports.object({
20964
+ items: external_exports.array(FindingInstanceDetail),
20965
+ nextCursor: external_exports.string().nullable()
20966
+ }).meta({ id: "ListFindingInstancesPage" });
20967
+ var FindingLocationSummary = external_exports.object({
20968
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20969
+ // because a location's identity is two values and a URL param carries one:
20970
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20971
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20972
+ // client's page dedupe — never decoded, and never a sort key.
20973
+ id: external_exports.string(),
20909
20974
  /** Empty when the instances carried no repo attribute. */
20910
20975
  repo: external_exports.string(),
20976
+ // Empty when the instances carried no file path (a prompt, or a tool call
20977
+ // with no file attribution). Both halves empty is a real location — usually
20978
+ // the largest one in a store — and is selectable like any other.
20979
+ file: external_exports.string(),
20911
20980
  instanceCount: external_exports.number().int().nonnegative(),
20981
+ // The WORST severity present, not the first row's. It is this list's primary
20982
+ // sort key, so it is also what explains why a row is where it is, and it is
20983
+ // how a reader decides what to open without opening everything.
20912
20984
  maxSeverity: Severity,
20913
20985
  latestDetectedAt: external_exports.iso.datetime(),
20986
+ // Folded from the instances' derived statuses with the same open-dominates
20987
+ // precedence a group uses, so it answers "is anything left to do here" and
20988
+ // not much more: a location holding 1 open among 40 resolved reads like one
20989
+ // holding 40 open. That loss is accepted — the panel beside this list
20990
+ // carries each finding's own status, and instanceCount sits next to the
20991
+ // badge.
20914
20992
  status: FindingStatus.optional(),
20915
- files: external_exports.array(FindingLocationFile)
20916
- }).meta({ id: "FindingLocationRepo" });
20993
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20994
+ // tally rather than a sample and a row can say how many there are. Bounded
20995
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20996
+ ruleIds: external_exports.array(external_exports.string())
20997
+ }).meta({ id: "FindingLocationSummary" });
20998
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20999
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20917
21000
  var ListFindingLocationsQuery = external_exports.object({
20918
21001
  severity: external_exports.array(Severity).optional(),
20919
21002
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20923,21 +21006,47 @@ var ListFindingLocationsQuery = external_exports.object({
20923
21006
  // instances that match, and folds its status from those.
20924
21007
  status: external_exports.array(FindingStatus).optional(),
20925
21008
  tool: external_exports.array(external_exports.string()).optional(),
21009
+ // The delivery state of each finding's event (see FindingDelivery).
21010
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20926
21011
  q: external_exports.string().optional(),
20927
21012
  sessionId: external_exports.string().optional(),
20928
21013
  from: external_exports.iso.datetime().optional(),
20929
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21014
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21015
+ // even when the cursor has already advanced past its sort position — the
21016
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21017
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21018
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21019
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21020
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21021
+ includeId: external_exports.string().optional(),
21022
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21023
+ cursor: external_exports.string().optional()
20930
21024
  });
20931
21025
  var ListFindingLocationsResponse = external_exports.object({
20932
21026
  totals: external_exports.object({
21027
+ // Findings matching the filters across the whole scope. Unlike the types
21028
+ // read's same-named field this needs no caveat: the filters here narrow
21029
+ // per finding, so this is the sum of every row's instanceCount.
20933
21030
  findings: external_exports.number().int().nonnegative(),
20934
- repos: external_exports.number().int().nonnegative(),
20935
- files: external_exports.number().int().nonnegative()
21031
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21032
+ // states. The facets beside it count FINDINGS (see below); a surface
21033
+ // showing both says which is which.
21034
+ locations: external_exports.number().int().nonnegative()
20936
21035
  }),
20937
- /** Sorted by max severity, then most recent. */
20938
- items: external_exports.array(FindingLocationRepo),
20939
- /** Whether `limit` truncated the repo list. */
20940
- hasMore: external_exports.boolean()
21036
+ // Counts in FINDINGS, where the types response counts types, each dimension
21037
+ // still excluding its own filter. Deliberately not locations: counting those
21038
+ // needs a set of location keys per dimension per value — memory tracking the
21039
+ // store times the vocabulary, in a read whose scan promises flat memory —
21040
+ // and the cheap per-location version is not an approximation but WRONG. A
21041
+ // location holding {claudecode, block} and {codex, warn} would survive
21042
+ // provider=claudecode AND action=warn, under which no single finding
21043
+ // matches, so the facet would contradict the instanceCount this whole view
21044
+ // rests on. Findings also keep the toolbar in the same unit as the page
21045
+ // tally and the panel it sits above.
21046
+ facets: FindingFacets,
21047
+ /** Sorted by max severity, then most recent, then (repo, file). */
21048
+ items: external_exports.array(FindingLocationSummary),
21049
+ nextCursor: external_exports.string().nullable()
20941
21050
  }).meta({ id: "ListFindingLocationsResponse" });
20942
21051
 
20943
21052
  // ../../packages/schema/src/zod/meta.ts
@@ -21101,6 +21210,10 @@ var CaptureAttributes = external_exports.object({
21101
21210
  // to 'allow' — the enforcement audit trail's link back to the grant that
21102
21211
  // authorized the bypass.
21103
21212
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21213
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21214
+ // join back to the `llm_call` leaf for the same assistant turn.
21215
+ message_id: external_exports.string().optional(),
21216
+ conversation_id: external_exports.string().optional(),
21104
21217
  // Whole milliseconds this capture's inspection blocked its caller — the
21105
21218
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21106
21219
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21109,7 +21222,19 @@ var CaptureAttributes = external_exports.object({
21109
21222
  // inline json_extract and is not itself an optimization.
21110
21223
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21111
21224
  // before the measurement shipped — never present as a placeholder 0.
21112
- inspection_ms: external_exports.number().int().nonnegative().optional()
21225
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21226
+ // What a `redact` this capture could not carry out became instead (see
21227
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21228
+ // degrade actually happened, so absence is the ordinary case rather than a
21229
+ // reader having to distinguish it from a zero.
21230
+ //
21231
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21232
+ // so on a multi-finding row this does not say which finding degraded, and
21233
+ // its presence does not mean the fallback decided the capture's action. A
21234
+ // capture denied by another finding's own Block policy carries `block`
21235
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21236
+ // repeated rather than referenced because a store reader opens this file.
21237
+ redact_degraded_to: ActionTaken.optional()
21113
21238
  }).catchall(external_exports.unknown());
21114
21239
  var ToolCallInspection = external_exports.object({
21115
21240
  ruleId: external_exports.string().min(1),
@@ -21308,7 +21433,17 @@ var AuditEvent = external_exports.object({
21308
21433
  /** `share` to a first-party/internal destination. */
21309
21434
  internal: external_exports.boolean(),
21310
21435
  /** Event needs review (e.g. unverified egress). */
21311
- flagged: external_exports.boolean()
21436
+ flagged: external_exports.boolean(),
21437
+ /**
21438
+ * The body this event's `title` is drawn from was cleared by local body
21439
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21440
+ *
21441
+ * A separate flag rather than a sentinel written into `title`: the title is
21442
+ * rendered text, and a store-layer module that invented display copy for it
21443
+ * would be choosing words the view is supposed to choose. Additive and
21444
+ * defaulted, so an older producer still validates.
21445
+ */
21446
+ bodyExpired: external_exports.boolean().default(false)
21312
21447
  }).meta({ id: "ActivityAuditEvent" });
21313
21448
  var ActivitySessionSummary = external_exports.object({
21314
21449
  id: external_exports.string(),
@@ -22220,6 +22355,14 @@ var ControlPlaneErrorBody = external_exports.object({
22220
22355
  message: external_exports.string().optional()
22221
22356
  }).optional()
22222
22357
  });
22358
+ var RemoteFailureKind = external_exports.enum([
22359
+ "unauthorized",
22360
+ "forbidden",
22361
+ "route-absent",
22362
+ "invalid-request",
22363
+ "rejected",
22364
+ "unreachable"
22365
+ ]);
22223
22366
  var AttachDeviceRequest = external_exports.object({
22224
22367
  // This machine's own continuity id, so re-attaching ROTATES the credential
22225
22368
  // on one machine record instead of producing a second one. Client-minted
@@ -22755,6 +22898,12 @@ var EventMetadata = external_exports.object({
22755
22898
  // to 'allow' — the enforcement audit trail's link back to the grant that
22756
22899
  // authorized the bypass. Absent on captures where no exception applied.
22757
22900
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22901
+ // The assistant message this capture belongs to, and the conversation it sits
22902
+ // in — set by the browser extension's network capture so a stored `response`
22903
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22904
+ // on every other capture path, which has no such id.
22905
+ messageId: external_exports.string().optional(),
22906
+ conversationId: external_exports.string().optional(),
22758
22907
  // How long THIS capture's inspection blocked its caller, in whole
22759
22908
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22760
22909
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22767,7 +22916,37 @@ var EventMetadata = external_exports.object({
22767
22916
  // Absent is also what every pre-measurement client writes, and what a
22768
22917
  // clock failure degrades to — a reader must treat absence as "not measured"
22769
22918
  // and never as a zero, which would read as "inspection is free".
22770
- inspectionMs: external_exports.number().int().nonnegative().optional()
22919
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22920
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22921
+ // workspace's `redactFallback`, applied because the field could not be
22922
+ // masked in place (a shell command, a URL, or any argument on a host whose
22923
+ // hook contract offers no rewrite channel).
22924
+ //
22925
+ // It exists because the action alone cannot say why. A finding recorded as
22926
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22927
+ // assigned Redact on a field that could not take one — and those are
22928
+ // different facts about the same row: the first is a policy the user chose,
22929
+ // the second is a masking the host could not perform. Absent means no
22930
+ // degrade happened, which is every ordinary capture.
22931
+ //
22932
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22933
+ // is the CAPTURE while `actionTaken` is per FINDING:
22934
+ //
22935
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22936
+ // `redact` alongside a finding ASSIGNED the same action stores both
22937
+ // identically and one reason for the pair; attributing it to both
22938
+ // describes the assigned one wrongly, and to neither loses the degrade.
22939
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22940
+ // became, not the reason the capture ended as it did — a capture denied
22941
+ // by some other finding's own Block policy still carries `block` here,
22942
+ // and clearing the workspace's fallback would not have let it through.
22943
+ // Gate on the value against what a fallback can produce; never read the
22944
+ // field's presence as "this was the fallback's doing".
22945
+ //
22946
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22947
+ // Closing either means moving the reason onto the finding row, which
22948
+ // already carries its own action.
22949
+ redactDegradedTo: ActionTaken.optional()
22771
22950
  }).meta({ id: "EventMetadata" });
22772
22951
  var Event = external_exports.object({
22773
22952
  id: external_exports.guid(),
@@ -22877,7 +23056,32 @@ var RotateKeyInput = external_exports.object({
22877
23056
  confirmation: external_exports.string()
22878
23057
  });
22879
23058
 
23059
+ // ../../packages/schema/src/zod/finding-delivery.ts
23060
+ var KNOWN_REASONS = SyncFailureReason.options;
23061
+ function knownReason(value) {
23062
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23063
+ }
23064
+ function deriveFindingDelivery(row) {
23065
+ if (row.kind === "code_change") return { state: "local_scan" };
23066
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23067
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23068
+ }
23069
+ if (row.syncedAt !== null) {
23070
+ const reason = knownReason(row.syncFailure);
23071
+ return {
23072
+ state: "not_sent",
23073
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23074
+ ...reason === void 0 ? {} : { reason }
23075
+ };
23076
+ }
23077
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23078
+ return { state: "never_offered" };
23079
+ }
23080
+
22880
23081
  // ../../packages/schema/src/zod/findings-group-build.ts
23082
+ function lookupOwn(map2, key) {
23083
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23084
+ }
22881
23085
  function toApiAction(dbVal) {
22882
23086
  const map2 = {
22883
23087
  log: "monitored",
@@ -22886,7 +23090,7 @@ function toApiAction(dbVal) {
22886
23090
  warn: "warned",
22887
23091
  allow: "allowed"
22888
23092
  };
22889
- return map2[dbVal] ?? "allowed";
23093
+ return lookupOwn(map2, dbVal) ?? "allowed";
22890
23094
  }
22891
23095
  function toApiCategory(dbVal) {
22892
23096
  if (dbVal === "code_context") return "source_code";
@@ -22894,13 +23098,18 @@ function toApiCategory(dbVal) {
22894
23098
  return parsed2.success ? parsed2.data : "custom";
22895
23099
  }
22896
23100
  function toApiProvider(sourceTool) {
22897
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23101
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22898
23102
  }
22899
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23103
+ var FINDING_STATUS_PRECEDENCE = [
23104
+ "open",
23105
+ "handled",
23106
+ "dismissed",
23107
+ "resolved"
23108
+ ];
22900
23109
  function foldGroupStatus(instanceStatuses) {
22901
23110
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22902
23111
  if (statuses.size === 0) return void 0;
22903
- for (const candidate of STATUS_PRECEDENCE) {
23112
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22904
23113
  if (statuses.has(candidate)) return candidate;
22905
23114
  }
22906
23115
  return void 0;
@@ -22913,139 +23122,62 @@ function deriveFindingStatus(row) {
22913
23122
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22914
23123
  return "open";
22915
23124
  }
22916
- function distinctUsers(instances) {
22917
- const seen = /* @__PURE__ */ new Set();
22918
- const users = [];
22919
- for (const i of instances) {
22920
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22921
- seen.add(i.user.id);
22922
- users.push(i.user);
22923
- }
22924
- return users;
22925
- }
22926
23125
  function sortUsers(users) {
22927
23126
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22928
23127
  }
22929
- function buildFindingGroups(rows, opts = {}) {
22930
- const overrides = opts.overrides;
23128
+ function buildFindingTypes(aggregates, opts = {}) {
22931
23129
  const packNames = opts.packNames;
22932
- const aggregates = opts.aggregates;
22933
- const byRuleId = /* @__PURE__ */ new Map();
22934
- for (const row of rows) {
22935
- const existing = byRuleId.get(row.ruleId);
22936
- if (existing) existing.push(row);
22937
- else byRuleId.set(row.ruleId, [row]);
22938
- }
22939
- const groups = [];
22940
- for (const [ruleId, ruleRows] of byRuleId) {
22941
- const instances = ruleRows.map((r) => {
22942
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22943
- return {
22944
- id: r.id,
22945
- provider: toApiProvider(r.sourceTool),
22946
- repo: r.repo,
22947
- file: r.file,
22948
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22949
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22950
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22951
- ...r.user === void 0 ? {} : { user: r.user },
22952
- action: toApiAction(effectiveDbAction),
22953
- detectedAt: r.occurredAt,
22954
- confidence: r.confidence,
22955
- status: r.status
22956
- };
22957
- });
22958
- const agg = aggregates?.get(ruleId);
22959
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22960
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22961
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22962
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22963
- );
22964
- const seenProviders = /* @__PURE__ */ new Set();
22965
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22966
- if (seenProviders.has(p)) return false;
22967
- seenProviders.add(p);
22968
- return true;
22969
- });
22970
- const actionSet = new Set(
22971
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22972
- );
23130
+ const types = [];
23131
+ for (const [ruleId, agg] of aggregates) {
23132
+ const users = sortUsers(agg.users ?? []);
23133
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23134
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22973
23135
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22974
- const severity = ruleRows[0]?.severity ?? "low";
22975
- const detection = {
22976
- id: ruleId,
22977
- name: packNames?.get(ruleId) ?? null
22978
- };
22979
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22980
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22981
- const match = {
22982
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22983
- contextPrefix: ""
22984
- // empty (pending privacy review)
22985
- };
22986
- const status = foldGroupStatus(
22987
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22988
- );
22989
- const group = {
23136
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23137
+ const type = {
22990
23138
  id: ruleId,
22991
23139
  category: apiCategory,
22992
23140
  subtype: ruleId,
22993
23141
  // human label comes with pack metadata later
22994
- severity,
22995
- match,
22996
- detection,
22997
- policy,
22998
- instanceCount: agg?.instanceCount ?? instances.length,
23142
+ severity: agg.severity ?? "low",
23143
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23144
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23145
+ instanceCount: agg.instanceCount,
22999
23146
  providers,
23000
23147
  aggregateAction,
23001
- latestDetectedAt,
23002
- instances,
23003
- status,
23148
+ latestDetectedAt: agg.latestDetectedAt,
23149
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
23004
23150
  ...users.length > 0 ? { users } : {}
23005
23151
  };
23006
- if (agg) {
23007
- actionsCache.set(group, [...actionSet]);
23008
- if (agg.searchText !== void 0) {
23009
- haystackCache.set(group, buildHaystack(group, agg.searchText));
23010
- }
23152
+ actionsCache.set(type, [...actionSet]);
23153
+ if (agg.searchText !== void 0) {
23154
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
23011
23155
  }
23012
- groups.push(group);
23156
+ types.push(type);
23013
23157
  }
23014
- return groups;
23158
+ return types;
23015
23159
  }
23016
23160
  var haystackCache = /* @__PURE__ */ new WeakMap();
23017
- function buildHaystack(g, extra) {
23161
+ function buildHaystack(t, extra) {
23018
23162
  return [
23019
- g.subtype,
23020
- g.category,
23021
- g.match.maskedValue,
23022
- g.policy.name,
23023
- g.id,
23024
- ...g.instances.map((i) => i.repo),
23025
- ...g.instances.map((i) => i.file),
23026
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
23027
- ...g.instances.map((i) => i.id),
23028
- // The people: the whole group's list when the store folded one, plus the
23029
- // preview's own — the two overlap, and a haystack does not mind.
23030
- ...(g.users ?? []).map((u) => u.name),
23031
- ...g.instances.map((i) => i.user?.name ?? ""),
23163
+ t.subtype,
23164
+ t.category,
23165
+ t.policy.name,
23166
+ t.id,
23167
+ ...(t.users ?? []).map((u) => u.name),
23032
23168
  ...extra === void 0 ? [] : [extra]
23033
23169
  ].join(" ").toLowerCase();
23034
23170
  }
23035
- function groupHaystack(g) {
23036
- const cached2 = haystackCache.get(g);
23171
+ function typeHaystack(t) {
23172
+ const cached2 = haystackCache.get(t);
23037
23173
  if (cached2 !== void 0) return cached2;
23038
- const haystack = buildHaystack(g);
23039
- haystackCache.set(g, haystack);
23174
+ const haystack = buildHaystack(t);
23175
+ haystackCache.set(t, haystack);
23040
23176
  return haystack;
23041
23177
  }
23042
23178
  var actionsCache = /* @__PURE__ */ new WeakMap();
23043
- function groupActions(g) {
23044
- const cached2 = actionsCache.get(g);
23045
- if (cached2 !== void 0) return cached2;
23046
- const actions = [...new Set(g.instances.map((i) => i.action))];
23047
- actionsCache.set(g, actions);
23048
- return actions;
23179
+ function typeActions(t) {
23180
+ return actionsCache.get(t) ?? [];
23049
23181
  }
23050
23182
  function countInstancesByStatus(statusInputs, statuses) {
23051
23183
  const statusSet = new Set(statuses);
@@ -23056,8 +23188,8 @@ function countInstancesByStatus(statusInputs, statuses) {
23056
23188
  }
23057
23189
  return sum;
23058
23190
  }
23059
- function applyFindingFilters(groups, opts) {
23060
- let filtered = groups;
23191
+ function applyFindingFilters(types, opts) {
23192
+ let filtered = types;
23061
23193
  if (opts.severity && opts.severity.length > 0) {
23062
23194
  const sevSet = new Set(opts.severity);
23063
23195
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -23068,7 +23200,7 @@ function applyFindingFilters(groups, opts) {
23068
23200
  }
23069
23201
  if (opts.actions && opts.actions.length > 0) {
23070
23202
  const actionSet = new Set(opts.actions);
23071
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23203
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
23072
23204
  }
23073
23205
  if (opts.subtype && opts.subtype.length > 0) {
23074
23206
  const subtypeSet = new Set(opts.subtype);
@@ -23080,26 +23212,31 @@ function applyFindingFilters(groups, opts) {
23080
23212
  }
23081
23213
  if (opts.q) {
23082
23214
  const q = opts.q.toLowerCase();
23083
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23215
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
23084
23216
  }
23085
23217
  return filtered;
23086
23218
  }
23087
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
23088
- var SEVERITY_RANK = SEVERITY_ORDER;
23219
+ function rankByOrder(members2) {
23220
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23221
+ }
23222
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23223
+ function severityRank(severity) {
23224
+ return lookupOwn(SEVERITY_RANK, severity);
23225
+ }
23089
23226
  function compareFindingGroupOrder(a, b) {
23090
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
23091
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23227
+ const rankA = severityRank(a.severity) ?? -1;
23228
+ const rankB = severityRank(b.severity) ?? -1;
23092
23229
  const severityDiff = rankA - rankB;
23093
23230
  if (severityDiff !== 0) return severityDiff;
23094
23231
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
23095
23232
  if (recencyDiff !== 0) return recencyDiff;
23096
23233
  return a.id.localeCompare(b.id);
23097
23234
  }
23098
- function sortFindingGroups(groups) {
23099
- return [...groups].sort(compareFindingGroupOrder);
23235
+ function sortFindingTypes(types) {
23236
+ return [...types].sort(compareFindingGroupOrder);
23100
23237
  }
23101
- function computeFindingFacets(allGroups, opts) {
23102
- const forSeverity = applyFindingFilters(allGroups, {
23238
+ function computeFindingFacets(allTypes, opts) {
23239
+ const forSeverity = applyFindingFilters(allTypes, {
23103
23240
  providers: opts.providers,
23104
23241
  actions: opts.actions,
23105
23242
  statuses: opts.statuses,
@@ -23110,7 +23247,7 @@ function computeFindingFacets(allGroups, opts) {
23110
23247
  for (const g of forSeverity) {
23111
23248
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
23112
23249
  }
23113
- const forProvider = applyFindingFilters(allGroups, {
23250
+ const forProvider = applyFindingFilters(allTypes, {
23114
23251
  actions: opts.actions,
23115
23252
  statuses: opts.statuses,
23116
23253
  q: opts.q,
@@ -23121,7 +23258,7 @@ function computeFindingFacets(allGroups, opts) {
23121
23258
  for (const g of forProvider) {
23122
23259
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23123
23260
  }
23124
- const forAction = applyFindingFilters(allGroups, {
23261
+ const forAction = applyFindingFilters(allTypes, {
23125
23262
  providers: opts.providers,
23126
23263
  statuses: opts.statuses,
23127
23264
  q: opts.q,
@@ -23130,9 +23267,9 @@ function computeFindingFacets(allGroups, opts) {
23130
23267
  });
23131
23268
  const actionMap = /* @__PURE__ */ new Map();
23132
23269
  for (const g of forAction) {
23133
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23270
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23134
23271
  }
23135
- const forSubtype = applyFindingFilters(allGroups, {
23272
+ const forSubtype = applyFindingFilters(allTypes, {
23136
23273
  providers: opts.providers,
23137
23274
  actions: opts.actions,
23138
23275
  statuses: opts.statuses,
@@ -23141,7 +23278,7 @@ function computeFindingFacets(allGroups, opts) {
23141
23278
  });
23142
23279
  const subtypeMap = /* @__PURE__ */ new Map();
23143
23280
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23144
- const forStatus = applyFindingFilters(allGroups, {
23281
+ const forStatus = applyFindingFilters(allTypes, {
23145
23282
  providers: opts.providers,
23146
23283
  actions: opts.actions,
23147
23284
  q: opts.q,
@@ -23163,6 +23300,20 @@ function computeFindingFacets(allGroups, opts) {
23163
23300
  }
23164
23301
 
23165
23302
  // ../../packages/schema/src/zod/findings-flat-build.ts
23303
+ function compareCodePoints(a, b) {
23304
+ const aIter = a[Symbol.iterator]();
23305
+ const bIter = b[Symbol.iterator]();
23306
+ for (; ; ) {
23307
+ const aNext = aIter.next();
23308
+ const bNext = bIter.next();
23309
+ if (aNext.done && bNext.done) return 0;
23310
+ if (aNext.done) return -1;
23311
+ if (bNext.done) return 1;
23312
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23313
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23314
+ if (aPoint !== bPoint) return aPoint - bPoint;
23315
+ }
23316
+ }
23166
23317
  function rowHaystack(row) {
23167
23318
  return [
23168
23319
  row.ruleId,
@@ -23187,12 +23338,24 @@ function matchesDimension(row, opts, dimension) {
23187
23338
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23188
23339
  case "statuses":
23189
23340
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23341
+ case "deliveries":
23342
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23190
23343
  case "tools":
23191
23344
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23345
+ // An EMPTY value is a real filter here, not an absent one. The location
23346
+ // list buckets a finding whose event recorded no repo — or no file — under
23347
+ // the empty string, and selecting that bucket has to narrow the panel to
23348
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23349
+ // row omits the key, which every call site already does.
23350
+ //
23351
+ // Reading '' as unset is what this replaced, and it failed in the one place
23352
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23353
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23354
+ // — a row reading 3 findings beside a panel listing every finding there is.
23192
23355
  case "repo":
23193
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23356
+ return opts.repo === void 0 || row.repo === opts.repo;
23194
23357
  case "file":
23195
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23358
+ return opts.file === void 0 || row.file === opts.file;
23196
23359
  case "q":
23197
23360
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23198
23361
  }
@@ -23203,6 +23366,7 @@ var DIMENSIONS = [
23203
23366
  "providers",
23204
23367
  "actions",
23205
23368
  "statuses",
23369
+ "deliveries",
23206
23370
  "tools",
23207
23371
  "repo",
23208
23372
  "file",
@@ -23216,10 +23380,19 @@ function matchesInstanceFilters(row, opts, except) {
23216
23380
  return true;
23217
23381
  }
23218
23382
  function toItems(counts) {
23219
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23383
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23384
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23385
+ // NFD spelling of the same text) as equal, so a count tie between
23386
+ // them would otherwise be ordered by whichever the Map iteration
23387
+ // produced. compareCodePoints breaks that tie deterministically, which
23388
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23389
+ // which it need not: foldFacetTuples runs this same sort over grouped
23390
+ // tuples, so both paths order facets identically by construction.
23391
+ compareCodePoints(a.value, b.value)
23392
+ );
23220
23393
  }
23221
- function bump(counts, value) {
23222
- counts.set(value, (counts.get(value) ?? 0) + 1);
23394
+ function bump(counts, value, by = 1) {
23395
+ counts.set(value, (counts.get(value) ?? 0) + by);
23223
23396
  }
23224
23397
  function createInstanceFacetAccumulator(opts) {
23225
23398
  const severity = /* @__PURE__ */ new Map();
@@ -23228,6 +23401,7 @@ function createInstanceFacetAccumulator(opts) {
23228
23401
  const action = /* @__PURE__ */ new Map();
23229
23402
  const status = /* @__PURE__ */ new Map();
23230
23403
  const tool = /* @__PURE__ */ new Map();
23404
+ const deployment = /* @__PURE__ */ new Map();
23231
23405
  return {
23232
23406
  add(row) {
23233
23407
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23242,6 +23416,9 @@ function createInstanceFacetAccumulator(opts) {
23242
23416
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23243
23417
  bump(tool, row.toolName);
23244
23418
  }
23419
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23420
+ bump(deployment, row.delivery.state);
23421
+ }
23245
23422
  },
23246
23423
  facets: () => ({
23247
23424
  severity: toItems(severity),
@@ -23249,7 +23426,8 @@ function createInstanceFacetAccumulator(opts) {
23249
23426
  provider: toItems(provider),
23250
23427
  action: toItems(action),
23251
23428
  status: toItems(status),
23252
- tool: toItems(tool)
23429
+ tool: toItems(tool),
23430
+ deployment: toItems(deployment)
23253
23431
  })
23254
23432
  };
23255
23433
  }
@@ -23263,6 +23441,7 @@ function toInstanceDetail(row) {
23263
23441
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23264
23442
  eventId: row.eventId,
23265
23443
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23444
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23266
23445
  ...row.user === void 0 ? {} : { user: row.user },
23267
23446
  action: toApiAction(row.actionTaken),
23268
23447
  detectedAt: row.occurredAt,
@@ -23277,12 +23456,6 @@ function toInstanceDetail(row) {
23277
23456
  policy: { id: `category:${category}`, name: category }
23278
23457
  };
23279
23458
  }
23280
- var SEVERITY_ORDER2 = {
23281
- critical: 0,
23282
- high: 1,
23283
- medium: 2,
23284
- low: 3
23285
- };
23286
23459
  function newLocationAccumulator() {
23287
23460
  return {
23288
23461
  instanceCount: 0,
@@ -23297,7 +23470,7 @@ function newLocationAccumulator() {
23297
23470
  }
23298
23471
  function addToLocation(acc, row) {
23299
23472
  acc.instanceCount += 1;
23300
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23473
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23301
23474
  if (rank < acc.maxSeverityRank) {
23302
23475
  acc.maxSeverityRank = rank;
23303
23476
  acc.maxSeverity = row.severity;
@@ -23306,6 +23479,23 @@ function addToLocation(acc, row) {
23306
23479
  acc.statuses.push(row.status);
23307
23480
  acc.ruleIds.add(row.ruleId);
23308
23481
  }
23482
+ function compareLocationOrder(a, b) {
23483
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23484
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23485
+ if (rankA !== rankB) return rankA - rankB;
23486
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23487
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23488
+ }
23489
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23490
+ if (repoDiff !== 0) return repoDiff;
23491
+ return compareCodePoints(a.file, b.file);
23492
+ }
23493
+ function encodeLocationId(repo, file2) {
23494
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23495
+ }
23496
+ function encodePart(value) {
23497
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23498
+ }
23309
23499
 
23310
23500
  // ../../packages/schema/src/zod/installed-pack.ts
23311
23501
  var InstalledPack = external_exports.object({
@@ -23373,6 +23563,11 @@ var Policy = external_exports.object({
23373
23563
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23374
23564
  provenance: PolicyProvenance.optional()
23375
23565
  }).meta({ id: "Policy" });
23566
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23567
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23568
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23569
+ id: "RedactFallback"
23570
+ });
23376
23571
  var PolicyBundle = external_exports.object({
23377
23572
  version: external_exports.string(),
23378
23573
  policies: external_exports.array(Policy),
@@ -23420,6 +23615,16 @@ var PolicyBundle = external_exports.object({
23420
23615
  // control plane), so no name resolution stands between the decision and the
23421
23616
  // comparison.
23422
23617
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23618
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23619
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23620
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23621
+ // a control plane can tighten a machine and never loosen one — the same
23622
+ // direction `mergeRaiseOnly` enforces for policies.
23623
+ //
23624
+ // Optional so an older backend, and an older on-disk cache, still parses;
23625
+ // absent leaves the device's own setting in force, which is the behaviour
23626
+ // that predates the field and the safe direction to default.
23627
+ redactFallback: RedactFallback.optional(),
23423
23628
  customKeywords: external_exports.array(external_exports.string()),
23424
23629
  fetchedAt: external_exports.iso.datetime()
23425
23630
  }).meta({ id: "PolicyBundle" });
@@ -23449,11 +23654,6 @@ function severityFloorPolicy(category) {
23449
23654
  const peak = CATEGORY_PEAK_SEVERITY[category];
23450
23655
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23451
23656
  }
23452
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23453
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23454
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23455
- id: "RedactFallback"
23456
- });
23457
23657
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23458
23658
  var BUILTIN_POLICY_SPECS = {
23459
23659
  monitor: {
@@ -23749,9 +23949,9 @@ var VaultConsent = external_exports.object({
23749
23949
  });
23750
23950
 
23751
23951
  // ../../packages/schema/src/zod/local.ts
23752
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23952
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23753
23953
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23754
- var HISTORY_SYNC_PAYLOAD_VERSION = 2;
23954
+ var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23755
23955
  var RunMode = external_exports.enum(["standalone", "attached"]);
23756
23956
  var ControlPlaneConnection = external_exports.object({
23757
23957
  endpoint: external_exports.string().min(1),
@@ -23774,6 +23974,15 @@ function isHistorySyncConsentValid(consent, endpoint) {
23774
23974
  if (consent === void 0 || endpoint === void 0) return false;
23775
23975
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23776
23976
  }
23977
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23978
+ var BodyRetention = external_exports.object({
23979
+ enabled: external_exports.boolean().default(false),
23980
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23981
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23982
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23983
+ // candidate set that is already bounded by "delivered, or never owed".
23984
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23985
+ }).meta({ id: "BodyRetention" });
23777
23986
  var WorkspaceSettings = external_exports.object({
23778
23987
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23779
23988
  runMode: RunMode.default("standalone"),
@@ -23817,12 +24026,18 @@ var WorkspaceSettings = external_exports.object({
23817
24026
  // covers the current payload and must be re-granted.
23818
24027
  modelJudgeConsent: ModelJudgeConsent.optional(),
23819
24028
  // Records that the user consented to the DEFERRED send — the outbox — along
23820
- // with the payload shape and the endpoint they agreed to. Since payload v2
23821
- // that covers both the pre-attach backlog and undelivered captures (which
23822
- // carry prompt/reply text in `content`); the key name predates the widening.
23823
- // Absent until granted, and a grant for a different endpoint or an older
23824
- // payload no longer counts.
23825
- historySyncConsent: HistorySyncConsent.optional()
24029
+ // with the payload shape and the endpoint they agreed to. Since payload v3
24030
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
24031
+ // carry prompt/reply/tool-output text in `content`; the key name predates
24032
+ // both widenings. Absent until granted, and a grant for a different endpoint
24033
+ // or an older payload no longer counts.
24034
+ historySyncConsent: HistorySyncConsent.optional(),
24035
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24036
+ // body never removes the row or its findings.
24037
+ bodyRetention: BodyRetention.default({
24038
+ enabled: false,
24039
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24040
+ })
23826
24041
  });
23827
24042
  function defaultWorkspaceSettings() {
23828
24043
  return WorkspaceSettings.parse({});
@@ -23917,12 +24132,15 @@ function toCaptureAttributes(event) {
23917
24132
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23918
24133
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23919
24134
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24135
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23920
24136
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23921
24137
  // has ever populated either), but every legacy metadata key still rides
23922
24138
  // the bag rather than being silently dropped — CaptureAttributes'
23923
24139
  // `.catchall(z.unknown())` carries the long tail.
23924
24140
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23925
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24141
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24142
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24143
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23926
24144
  };
23927
24145
  }
23928
24146
  function captureDefinitionVersion(finding2) {
@@ -23950,10 +24168,22 @@ var ManagedSettingKey = external_exports.enum([
23950
24168
  "vaultInlineReveal",
23951
24169
  "modelJudgeConsent",
23952
24170
  "dataSharesInPlace",
23953
- "redactFallback"
24171
+ "redactFallback",
24172
+ // Pins the toggle and the day count together — see BodyRetention on why the
24173
+ // two are one unit. An administrator mandating a window wants the count
24174
+ // enforced with it, not one a user can widen while the toggle stays on.
24175
+ "bodyRetention"
23954
24176
  ]).meta({ id: "ManagedSettingKey" });
24177
+ function isManagedSettingKey(value) {
24178
+ return ManagedSettingKey.safeParse(value).success;
24179
+ }
23955
24180
  var ManagedSettingsValues = external_exports.object({
23956
24181
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24182
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24183
+ // plain, non-strict objects: a key under either that this build does not know
24184
+ // is stripped and nothing reports it. The unknown-value split in
24185
+ // ManagedSettings below classifies top-level names only, so it stops at
24186
+ // these boundaries.
23957
24187
  controlPlane: external_exports.object({
23958
24188
  endpoint: external_exports.string().min(1),
23959
24189
  label: external_exports.string().min(1).optional()
@@ -23964,7 +24194,8 @@ var ManagedSettingsValues = external_exports.object({
23964
24194
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23965
24195
  modelJudgeConsent: external_exports.boolean().optional(),
23966
24196
  dataSharesInPlace: external_exports.boolean().optional(),
23967
- redactFallback: RedactFallback.optional()
24197
+ redactFallback: RedactFallback.optional(),
24198
+ bodyRetention: BodyRetention.optional()
23968
24199
  }).meta({ id: "ManagedSettingsValues" });
23969
24200
  var ManagedSettings = external_exports.object({
23970
24201
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23972,11 +24203,59 @@ var ManagedSettings = external_exports.object({
23972
24203
  // decision from a bug. Absent renders as a generic "your organization".
23973
24204
  organization: external_exports.string().min(1).optional(),
23974
24205
  // What the administrator pinned.
23975
- values: ManagedSettingsValues.default({}),
24206
+ //
24207
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24208
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24209
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24210
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24211
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24212
+ // exactly the file an administrator is most likely to write while a fleet
24213
+ // is mid-upgrade.
24214
+ //
24215
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24216
+ // file, which is the outcome the lock half already rejected — an older
24217
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24218
+ // value still fails, because the nested schema is re-run over the known
24219
+ // subset and its issues are re-raised on this parse.
24220
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23976
24221
  // Which of those the user may not change. A key here with no matching value
23977
24222
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23978
24223
  // the user may still override. The two are separable on purpose.
23979
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24224
+ //
24225
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24226
+ // build does not know is dropped from the locked set and reported, never a
24227
+ // reason to refuse the file. The same shape reaches an older build whenever
24228
+ // an administrator locks a key a newer build added, and refusing it there
24229
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24230
+ // the fleets most likely to carry a version skew. A name outside the enum
24231
+ // is still never HONOURED: the lockable set stays explicit above.
24232
+ lockedFields: external_exports.array(external_exports.string()).default([])
24233
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24234
+ const known = [];
24235
+ const unknown2 = [];
24236
+ for (const name of lockedFields) {
24237
+ if (isManagedSettingKey(name)) known.push(name);
24238
+ else unknown2.push(name);
24239
+ }
24240
+ const knownValues = /* @__PURE__ */ Object.create(null);
24241
+ const unknownValues = [];
24242
+ for (const [name, value] of Object.entries(values)) {
24243
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24244
+ else unknownValues.push(name);
24245
+ }
24246
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24247
+ if (!pinned.success) {
24248
+ for (const issue2 of pinned.error.issues)
24249
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24250
+ return external_exports.NEVER;
24251
+ }
24252
+ return {
24253
+ ...rest,
24254
+ values: pinned.data,
24255
+ lockedFields: known,
24256
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24257
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24258
+ };
23980
24259
  }).meta({ id: "ManagedSettings" });
23981
24260
 
23982
24261
  // ../../packages/schema/src/zod/project-files.ts
@@ -24100,7 +24379,11 @@ var FindingsTimeseriesPoint = external_exports.object({
24100
24379
  timestamp: external_exports.iso.date(),
24101
24380
  critical: external_exports.number().int().nonnegative(),
24102
24381
  high: external_exports.number().int().nonnegative(),
24103
- medium: external_exports.number().int().nonnegative()
24382
+ medium: external_exports.number().int().nonnegative(),
24383
+ // Optional and additive, so a producer written against the earlier
24384
+ // three-series contract keeps validating. A consumer plotting it resolves the
24385
+ // absent case itself — the chart point requires a number.
24386
+ low: external_exports.number().int().nonnegative().optional()
24104
24387
  }).meta({ id: "FindingsTimeseriesPoint" });
24105
24388
  var FindingsTimeseriesResponse = external_exports.object({
24106
24389
  range: TimeRange,
@@ -24126,6 +24409,10 @@ var ResolvedFeedItem = external_exports.object({
24126
24409
  findingKey: external_exports.string(),
24127
24410
  ruleId: external_exports.string(),
24128
24411
  severity: Severity,
24412
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24413
+ // identifies the file: a bare path matches the same name in every repo.
24414
+ // Optional and additive; empty when the event carried no repo.
24415
+ repo: external_exports.string().optional(),
24129
24416
  path: external_exports.string(),
24130
24417
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24131
24418
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24231,7 +24518,23 @@ var SaveSettingsInput = external_exports.object({
24231
24518
  modelJudgeConsent: ModelJudgeConsentChoice,
24232
24519
  historySyncConsent: HistorySyncConsentChoice,
24233
24520
  vaultConsent: external_exports.string(),
24234
- vaultInlineReveal: external_exports.string()
24521
+ vaultInlineReveal: external_exports.string(),
24522
+ // Widened to `string` like its neighbours rather than typed as
24523
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24524
+ // the call site, so the domain check receives the type it was written for.
24525
+ //
24526
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24527
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24528
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24529
+ // trade against. The real cost runs the other way and is the part worth
24530
+ // knowing: a value this schema admits and the domain enum then rejects lands
24531
+ // on the action's shared refusal, which names NO field, where a shape
24532
+ // rejection reaches `malformedInput` and names the schema key.
24533
+ redactFallback: external_exports.string(),
24534
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24535
+ // `BodyRetention`'s and the action checks it there, so there is one place
24536
+ // that decides what a legal horizon is rather than two that can drift.
24537
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24235
24538
  });
24236
24539
  var AttachInput = external_exports.object({
24237
24540
  endpoint: external_exports.string(),
@@ -24403,6 +24706,52 @@ function reviewSeverityRank(reasons) {
24403
24706
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24404
24707
  }
24405
24708
 
24709
+ // ../../packages/schema/src/zod/web-capture.ts
24710
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24711
+ var WebUsage = external_exports.object({
24712
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24713
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24714
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24715
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24716
+ });
24717
+ var WebToolCall = external_exports.object({
24718
+ toolUseId: external_exports.string().min(1),
24719
+ toolName: external_exports.string().min(1),
24720
+ target: external_exports.string().optional(),
24721
+ isError: external_exports.boolean().optional(),
24722
+ inputSize: external_exports.number().int().nonnegative().optional(),
24723
+ outputSize: external_exports.number().int().nonnegative().optional()
24724
+ });
24725
+ var WebExchange = external_exports.object({
24726
+ messageId: external_exports.string().min(1),
24727
+ startedAt: external_exports.iso.datetime(),
24728
+ model: external_exports.string().optional(),
24729
+ usage: WebUsage.optional(),
24730
+ usageSource: WebUsageSource,
24731
+ stopReason: external_exports.string().optional(),
24732
+ conversationId: external_exports.string().optional(),
24733
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24734
+ toolCalls: external_exports.array(WebToolCall).default([]),
24735
+ // Absent when the adapter recovered no text. Capped by the caller at
24736
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24737
+ // short capture is never mistaken for a short reply.
24738
+ responseText: external_exports.string().optional(),
24739
+ truncated: external_exports.boolean().default(false)
24740
+ });
24741
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24742
+ var WebCaptureStatus = external_exports.object({
24743
+ patched: external_exports.boolean(),
24744
+ live: external_exports.boolean(),
24745
+ blind: external_exports.boolean(),
24746
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24747
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24748
+ parseFailures: external_exports.number().int().nonnegative(),
24749
+ unparsedBodies: external_exports.number().int().nonnegative(),
24750
+ // The adapter-declared JSON key paths that were absent from a real payload —
24751
+ // the earliest signal that a site's contract moved.
24752
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24753
+ });
24754
+
24406
24755
  // ../../packages/persistence/src/paths.ts
24407
24756
  import {
24408
24757
  chmodSync,
@@ -24737,6 +25086,22 @@ function discardStore(file2, backup) {
24737
25086
  }
24738
25087
  }
24739
25088
 
25089
+ // ../../packages/persistence/src/internal/sql-functions.ts
25090
+ var utf8 = new TextDecoder();
25091
+ function akaLower(value) {
25092
+ if (value === null) return null;
25093
+ if (typeof value === "string") return value.toLowerCase();
25094
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25095
+ return utf8.decode(value).toLowerCase();
25096
+ }
25097
+ function registerSqlFunctions(db) {
25098
+ db.function(
25099
+ "aka_lower",
25100
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25101
+ akaLower
25102
+ );
25103
+ }
25104
+
24740
25105
  // ../../packages/persistence/src/internal/sql-text.ts
24741
25106
  function escapeLikePattern(s) {
24742
25107
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24821,6 +25186,11 @@ function schemaObjectExists(db, kind, name) {
24821
25186
  function indexExists(db, name) {
24822
25187
  return schemaObjectExists(db, "index", name);
24823
25188
  }
25189
+ function indexColumns(db, name) {
25190
+ if (!indexExists(db, name)) return [];
25191
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25192
+ return columns.map((c) => c.name).filter((c) => c !== null);
25193
+ }
24824
25194
  function columnNames(db, table, opts) {
24825
25195
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24826
25196
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24882,141 +25252,783 @@ function mapRowsTolerant(rows, map2) {
24882
25252
  return out;
24883
25253
  }
24884
25254
 
24885
- // ../../packages/persistence/src/migrations.ts
24886
- function describeObject(object2) {
24887
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24888
- }
24889
- function splitStatements(sql) {
24890
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24891
- }
24892
- function createdIndexName(statement) {
24893
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24894
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25255
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25256
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25257
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25258
+
25259
+ // ../../packages/persistence/src/sync-failure.ts
25260
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25261
+ function syncFailureRejectCondition(column = "sync_failure") {
25262
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25263
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24895
25264
  }
24896
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24897
- function applyMigrations(db, file2) {
24898
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24899
- db.exec(
24900
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24901
- );
24902
- const applied = new Set(
24903
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24904
- );
24905
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24906
- const record2 = db.prepare(
24907
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24908
- );
24909
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24910
- if (applied.has(migration.tag)) continue;
24911
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24912
- const evidence = evidenceObjects(migration.sql);
24913
- const present = evidence.filter((o) => evidenceExists(db, o));
24914
- if (present.length > 0 && present.length < evidence.length) {
24915
- const missing = evidence.filter((o) => !present.includes(o));
24916
- const message2 = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24917
- akaWarn(message2);
24918
- throw new Error(`[aka] ${message2}`);
24919
- }
24920
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24921
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24922
- const statements = splitStatements(migration.sql);
24923
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24924
- try {
24925
- withTransaction(
24926
- db,
24927
- () => {
24928
- for (const statement of statements) {
24929
- const indexName = createdIndexName(statement);
24930
- if (indexName === void 0) {
24931
- if (alreadyApplied) continue;
24932
- } else if (indexExists(db, indexName)) {
24933
- continue;
24934
- }
24935
- db.exec(statement);
24936
- }
24937
- if (wantsFkOff && !alreadyApplied) {
24938
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24939
- if (violations.length > 0) {
24940
- throw new Error(
24941
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24942
- );
24943
- }
24944
- }
24945
- record2.run(migration.tag, Date.now());
24946
- },
24947
- "IMMEDIATE"
24948
- );
24949
- } finally {
24950
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24951
- }
25265
+
25266
+ // ../../packages/persistence/src/repositories/history-sync.ts
25267
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25268
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25269
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25270
+ var COUNTED_EVENT_TYPES = [
25271
+ ...STRUCTURAL_EVENT_TYPES,
25272
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25273
+ ];
25274
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25275
+ var PARTITION_BUCKETS = `
25276
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25277
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25278
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25279
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25280
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25281
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25282
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25283
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25284
+ -- added later lands in no bucket and fails the sum assertion, instead
25285
+ -- of silently joining this one.
25286
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25287
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25288
+ THEN 1 ELSE 0 END) AS failed,
25289
+ COUNT(*) AS total`;
25290
+ var COUNTED_SCOPE = `
25291
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25292
+ AND (
25293
+ event_type IN (${TYPE_LIST})
25294
+ OR synced_at IS NOT NULL
25295
+ OR outbox_owed = 1
25296
+ )`;
25297
+ var SKIPPED = -1;
25298
+ var ROW_COLUMNS = `id,
25299
+ parent_id AS parentId,
25300
+ root_session_id AS rootSessionId,
25301
+ event_type AS eventType,
25302
+ host_id AS hostId,
25303
+ harness_id AS harnessId,
25304
+ source_project_id AS sourceProjectId,
25305
+ started_at AS startedAt,
25306
+ ended_at AS endedAt,
25307
+ severity,
25308
+ priority,
25309
+ content,
25310
+ content_hash AS contentHash,
25311
+ attributes`;
25312
+ var SqliteHistorySyncRepository = class {
25313
+ constructor(db) {
25314
+ this.db = db;
25315
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25316
+ this.sessionsStmt = db.prepare(
25317
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25318
+ FROM audit_events
25319
+ WHERE synced_at IS NULL
25320
+ AND event_type IN (${TYPE_LIST})
25321
+ AND started_at < :before
25322
+ GROUP BY sessionId
25323
+ ORDER BY earliest
25324
+ LIMIT :limit`
25325
+ );
25326
+ this.rowsStmt = db.prepare(
25327
+ `SELECT ${ROW_COLUMNS}
25328
+ FROM audit_events
25329
+ WHERE synced_at IS NULL
25330
+ AND event_type IN (${TYPE_LIST})
25331
+ AND started_at < :before
25332
+ AND COALESCE(root_session_id, id) = :sessionId
25333
+ ORDER BY (event_type = 'session') DESC, started_at
25334
+ LIMIT :limit`
25335
+ );
25336
+ this.captureRowsStmt = db.prepare(
25337
+ `SELECT ${ROW_COLUMNS}
25338
+ FROM audit_events
25339
+ WHERE synced_at IS NULL
25340
+ AND sync_claimed_at IS NULL
25341
+ AND outbox_owed = 1
25342
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25343
+ AND started_at < :before
25344
+ ORDER BY started_at
25345
+ LIMIT :limit`
25346
+ );
25347
+ this.markOwedStmt = db.prepare(
25348
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25349
+ );
25350
+ this.markCaptureBacklogOwedStmt = db.prepare(
25351
+ `UPDATE audit_events SET outbox_owed = 1
25352
+ WHERE synced_at IS NULL
25353
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25354
+ AND started_at < :before`
25355
+ );
25356
+ this.stampStmt = db.prepare(
25357
+ `UPDATE audit_events
25358
+ SET synced_at = :at,
25359
+ sync_claimed_at = NULL,
25360
+ sync_failed_at = :failedAt,
25361
+ sync_failure = :failure
25362
+ WHERE id = :id`
25363
+ );
25364
+ this.claimRowStmt = db.prepare(
25365
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25366
+ );
25367
+ this.releaseRowStmt = db.prepare(
25368
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25369
+ );
25370
+ this.releaseStaleClaimsStmt = db.prepare(
25371
+ `UPDATE audit_events SET sync_claimed_at = NULL
25372
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25373
+ );
25374
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25375
+ FROM audit_events${COUNTED_SCOPE}`);
25376
+ this.partitionByKindStmt = db.prepare(
25377
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25378
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25379
+ GROUP BY event_type`
25380
+ );
25381
+ this.countsStmt = db.prepare(
25382
+ `SELECT
25383
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25384
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25385
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25386
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25387
+ THEN 1 ELSE 0 END) AS skipped,
25388
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25389
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25390
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25391
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25392
+ FROM audit_events
25393
+ WHERE event_type IN (${TYPE_LIST})`
25394
+ );
25395
+ this.captureSkipCountStmt = db.prepare(
25396
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25397
+ // way the structural totals are. The split exists because a refusal is
25398
+ // terminal only against the deployment that gave it, and the structural
25399
+ // re-arm frees it on a change of deployment. The capture lane has no such
25400
+ // escape: re-arming a capture would offer one deployment's undelivered
25401
+ // prompts, with their text, to a deployment that never saw them, which is
25402
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25403
+ // reasons mean the same thing — this row will not be sent — and splitting
25404
+ // them would put refused captures in a bucket nothing reads and nothing
25405
+ // frees.
25406
+ `SELECT COUNT(*) AS skipped
25407
+ FROM audit_events
25408
+ WHERE synced_at = ${String(SKIPPED)}
25409
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25410
+ );
25411
+ this.fingerprintStmt = db.prepare(
25412
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25413
+ FROM history_sync WHERE id = 1`
25414
+ );
25415
+ this.setFingerprintStmt = db.prepare(
25416
+ `UPDATE history_sync
25417
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25418
+ WHERE id = 1`
25419
+ );
25420
+ this.disownCapturesStmt = db.prepare(
25421
+ `UPDATE audit_events SET outbox_owed = NULL
25422
+ WHERE outbox_owed IS NOT NULL
25423
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25424
+ AND started_at < :attachedAt`
25425
+ );
25426
+ this.rearmStmt = db.prepare(
25427
+ `UPDATE audit_events
25428
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25429
+ WHERE (synced_at > 0
25430
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25431
+ AND event_type IN (${TYPE_LIST})`
25432
+ );
25433
+ this.claimStmt = db.prepare(
25434
+ `UPDATE history_sync
25435
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25436
+ WHERE id = 1
25437
+ AND (owner_pid IS NULL
25438
+ OR heartbeat_at IS NULL
25439
+ OR heartbeat_at < :staleBefore
25440
+ OR heartbeat_at > :now)`
25441
+ );
25442
+ this.heartbeatStmt = db.prepare(
25443
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25444
+ );
25445
+ this.releaseStmt = db.prepare(
25446
+ `UPDATE history_sync
25447
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25448
+ WHERE id = 1 AND owner_pid = :pid`
25449
+ );
25450
+ this.closeWindowStmt = db.prepare(
25451
+ `UPDATE audit_events
25452
+ SET synced_at = ${String(SKIPPED)},
25453
+ sync_failed_at = :at,
25454
+ sync_failure = 'detached_undelivered'
25455
+ WHERE synced_at IS NULL
25456
+ AND event_type IN (${TYPE_LIST})
25457
+ AND started_at >= :attachedAt`
25458
+ );
25459
+ this.releaseBoundaryStmt = db.prepare(
25460
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25461
+ );
25462
+ this.freezeBoundaryStmt = db.prepare(
25463
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25464
+ );
25465
+ this.leaseStmt = db.prepare(
25466
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25467
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25468
+ FROM history_sync WHERE id = 1`
25469
+ );
25470
+ this.inspectionsStmt = db.prepare(
25471
+ `SELECT d.rule_id AS ruleId,
25472
+ d.name AS ruleName,
25473
+ d.version AS ruleVersion,
25474
+ d.category AS category,
25475
+ d.severity AS severity,
25476
+ f.span_start AS spanStart,
25477
+ f.span_end AS spanEnd,
25478
+ f.masked_match AS maskedMatch,
25479
+ f.action_taken AS actionTaken,
25480
+ f.confidence AS confidence
25481
+ FROM inspection_findings f
25482
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25483
+ WHERE f.audit_event_id = :auditEventId
25484
+ ORDER BY f.span_start, f.id`
25485
+ );
24952
25486
  }
24953
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24954
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25487
+ db;
25488
+ ensureRowStmt;
25489
+ sessionsStmt;
25490
+ rowsStmt;
25491
+ stampStmt;
25492
+ countsStmt;
25493
+ fingerprintStmt;
25494
+ setFingerprintStmt;
25495
+ rearmStmt;
25496
+ claimStmt;
25497
+ heartbeatStmt;
25498
+ releaseStmt;
25499
+ leaseStmt;
25500
+ inspectionsStmt;
25501
+ closeWindowStmt;
25502
+ releaseBoundaryStmt;
25503
+ freezeBoundaryStmt;
25504
+ captureRowsStmt;
25505
+ markOwedStmt;
25506
+ markCaptureBacklogOwedStmt;
25507
+ captureSkipCountStmt;
25508
+ disownCapturesStmt;
25509
+ partitionStmt;
25510
+ partitionByKindStmt;
25511
+ claimRowStmt;
25512
+ releaseRowStmt;
25513
+ releaseStaleClaimsStmt;
25514
+ /**
25515
+ * The masked detections recorded against one tool call.
25516
+ *
25517
+ * These travel with the event because a tool call's target is not
25518
+ * re-inspectable from the event alone — unlike a capture, where the text
25519
+ * itself is re-scannable. What crosses is the masked match and the rule that
25520
+ * produced it, never the value.
25521
+ */
25522
+ inspectionsFor(auditEventId) {
25523
+ return allRows(this.inspectionsStmt, { auditEventId });
24955
25524
  }
24956
- ensureSyncedAtColumn(db, "audit_events");
24957
- ensureScanLedgerTable(db);
24958
- ensureHistorySyncTable(db);
24959
- ensureBlockedDetectionsTable(db);
24960
- ensureRuleProbeCacheTable(db);
24961
- ensureWriteGateTrigger(db);
24962
- ensureTokenUsageColumns(db);
24963
- reconcileSourceProjectIds(db);
24964
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24965
- const drained = runLegacyHistoryBackfill(db);
24966
- if (drained) applyLegacyDropMigration(db, file2);
25525
+ /**
25526
+ * Sessions with structural rows still to send, oldest first.
25527
+ *
25528
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25529
+ * read. Anything recorded after the machine attached is the live forward
25530
+ * path's to deliver; this drain exists for what was recorded before it, and a
25531
+ * row both paths send is at best a duplicate request and at worst — for a
25532
+ * session root — an overwrite of the inventory ids the live path resolved.
25533
+ */
25534
+ pendingSessions(limit, before) {
25535
+ return allRows(this.sessionsStmt, { limit, before }).map(
25536
+ (r) => r.sessionId
25537
+ );
24967
25538
  }
24968
- }
24969
- function readLegacyTables(db) {
24970
- let holdsRows = false;
24971
- const marks = [];
24972
- for (const table of ["events", "findings"]) {
24973
- try {
24974
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24975
- if (row === void 0) {
24976
- holdsRows = true;
24977
- marks.push(`${table}:unreadable`);
24978
- continue;
24979
- }
24980
- if (row.n > 0) holdsRows = true;
24981
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24982
- } catch {
24983
- holdsRows = true;
24984
- marks.push(`${table}:unreadable`);
24985
- }
25539
+ /** One session's undelivered structural rows within the backlog, root first. */
25540
+ pendingRows(sessionId, limit, before) {
25541
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24986
25542
  }
24987
- return { holdsRows, mark: marks.join("|") };
24988
- }
24989
- function applyLegacyDropMigration(db, file2) {
24990
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24991
- if (!migration) return;
24992
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24993
- if (file2 !== void 0 && before?.holdsRows === true) {
24994
- try {
24995
- backupBeforeLegacyDrop(db, file2);
24996
- } catch (error61) {
24997
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24998
- return;
24999
- }
25543
+ /**
25544
+ * Captures this machine still owes the deployment, oldest first.
25545
+ *
25546
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25547
+ * by a time window — see captureRowsStmt for why a window could not express
25548
+ * this. `before` is the grace window that leaves a just-recorded capture to
25549
+ * the live path.
25550
+ */
25551
+ pendingCaptureRows(limit, before) {
25552
+ return allRows(this.captureRowsStmt, { limit, before });
25000
25553
  }
25001
- try {
25554
+ /**
25555
+ * Record that a capture is OWED to the deployment.
25556
+ *
25557
+ * Written by the attached forward path when a live send did not confirm
25558
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25559
+ * a fact rather than an inference: the machine was attached, the send did not
25560
+ * land, so the row is owed — which no time window can state, because the same
25561
+ * window that holds the rows a past attachment left owed also holds every
25562
+ * capture recorded while the machine was DETACHED, and those were never
25563
+ * offered to anyone.
25564
+ *
25565
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25566
+ * out of the drain's read.
25567
+ */
25568
+ markCaptureOwed(id) {
25569
+ this.markOwedStmt.run({ id });
25570
+ }
25571
+ /**
25572
+ * Mark every capture already on disk as owed, as of `before`.
25573
+ *
25574
+ * The consent-time backfill, called once from `aka attach` when a human
25575
+ * grants existing-history consent — never from an ongoing drain pass, and
25576
+ * never inferred from a boundary that could later move. `before` is the
25577
+ * caller's own "now" at the moment consent was granted, so what this marks
25578
+ * is exactly the backlog the consent prompt already counted, not whatever a
25579
+ * later re-attach or key rotation might widen it to.
25580
+ *
25581
+ * Returns how many rows matched, for the caller to log or test against. Not a
25582
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25583
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25584
+ */
25585
+ markCaptureBacklogOwed(before) {
25586
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25587
+ }
25588
+ /**
25589
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25590
+ *
25591
+ * CLEARS any failure reason in the same statement. A row that failed against
25592
+ * one deployment and then landed is delivered, and leaving the reason behind
25593
+ * would leave the store holding two contradictory answers about one row —
25594
+ * with the surface free to render either.
25595
+ */
25596
+ markSynced(ids, atMs) {
25597
+ this.stampAll(ids, atMs, null);
25598
+ }
25599
+ /**
25600
+ * Record that THIS MACHINE cannot express the row on the wire.
25601
+ *
25602
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25603
+ * payload, or a body the client itself refused to send. It fails identically
25604
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25605
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25606
+ * is retried; marking those would turn one outage into permanent data loss.
25607
+ */
25608
+ markSkipped(ids, atMs) {
25609
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25610
+ }
25611
+ /**
25612
+ * Record that THIS DEPLOYMENT refused the row.
25613
+ *
25614
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25615
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25616
+ * row is outstanding rather than why. What separates them is the reason, and
25617
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25618
+ * on one body, so it is terminal only for as long as this machine points at
25619
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25620
+ *
25621
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25622
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25623
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25624
+ */
25625
+ markRefused(ids, atMs) {
25626
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25627
+ }
25628
+ eachInTransaction(ids, run) {
25629
+ if (ids.length === 0) return;
25002
25630
  withTransaction(
25003
- db,
25631
+ this.db,
25004
25632
  () => {
25005
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25006
- if (alreadyDropped) return;
25007
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25008
- akaWarn(
25009
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25010
- );
25011
- return;
25012
- }
25013
- for (const statement of splitStatements(migration.sql)) {
25014
- db.exec(statement);
25015
- }
25016
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25017
- migration.tag,
25018
- Date.now()
25019
- );
25633
+ for (const id of ids) run(id);
25634
+ },
25635
+ "IMMEDIATE"
25636
+ );
25637
+ }
25638
+ stampAll(ids, value, failure, failedAtMs) {
25639
+ if (ids.length === 0) return;
25640
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25641
+ withTransaction(
25642
+ this.db,
25643
+ () => {
25644
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25645
+ },
25646
+ "IMMEDIATE"
25647
+ );
25648
+ }
25649
+ /**
25650
+ * Claim rows as in-flight.
25651
+ *
25652
+ * Advisory in exactly the sense the lease is: it records that a send is in
25653
+ * progress so a surface can say so, and a lost claim costs a row showing as
25654
+ * queued while it is actually being sent. It is not exclusion — the far side
25655
+ * settles a duplicate on the row id.
25656
+ */
25657
+ claimRows(ids, atMs) {
25658
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25659
+ }
25660
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25661
+ releaseRows(ids) {
25662
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25663
+ }
25664
+ /**
25665
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25666
+ *
25667
+ * A process killed between claiming and settling leaves rows claimed with
25668
+ * nothing left to settle them. Without this they read as "sending" for ever.
25669
+ */
25670
+ releaseStaleClaims(staleBefore) {
25671
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25672
+ }
25673
+ /**
25674
+ * Every tracked row in exactly one delivery state.
25675
+ *
25676
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25677
+ * pick up now", which is a different question from "what state is this row
25678
+ * in" — and a machine that has never attached has no boundary to pass, so
25679
+ * requiring one would force a caller to invent one and report the whole store
25680
+ * as queued.
25681
+ */
25682
+ /**
25683
+ * The same partition, one row per kind that a lane carries.
25684
+ *
25685
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25686
+ * scope decides which rows exist at all, so a kind that has never been
25687
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25688
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25689
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25690
+ * different things.
25691
+ */
25692
+ partitionByKind() {
25693
+ return allRows(
25694
+ this.partitionByKindStmt,
25695
+ {}
25696
+ ).map((row) => ({
25697
+ kind: row.kind,
25698
+ queued: row.queued ?? 0,
25699
+ inProgress: row.inProgress ?? 0,
25700
+ synced: row.synced ?? 0,
25701
+ failed: row.failed ?? 0,
25702
+ refused: row.refused ?? 0,
25703
+ detached: row.detached ?? 0,
25704
+ total: row.total ?? 0
25705
+ }));
25706
+ }
25707
+ partition() {
25708
+ const row = getRow(this.partitionStmt, {});
25709
+ return {
25710
+ queued: row?.queued ?? 0,
25711
+ inProgress: row?.inProgress ?? 0,
25712
+ synced: row?.synced ?? 0,
25713
+ failed: row?.failed ?? 0,
25714
+ refused: row?.refused ?? 0,
25715
+ detached: row?.detached ?? 0,
25716
+ total: row?.total ?? 0
25717
+ };
25718
+ }
25719
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25720
+ counts(before) {
25721
+ const row = getRow(this.countsStmt, { before });
25722
+ const captures = getRow(this.captureSkipCountStmt);
25723
+ return {
25724
+ pending: row?.pending ?? 0,
25725
+ sent: row?.sent ?? 0,
25726
+ skipped: row?.skipped ?? 0,
25727
+ refused: row?.refused ?? 0,
25728
+ detached: row?.detached ?? 0,
25729
+ capturesSkipped: captures?.skipped ?? 0
25730
+ };
25731
+ }
25732
+ /**
25733
+ * The deployment the current stamps were made against, and where its backlog
25734
+ * ends.
25735
+ *
25736
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25737
+ * machine that has never drained is — and every writer below seeds the row
25738
+ * before it needs one, so nothing depends on this creating it. Keeping the
25739
+ * write off the gate path matters because the gate runs on every pass while a
25740
+ * write has to take the database's write lock.
25741
+ */
25742
+ deployment() {
25743
+ const row = getRow(
25744
+ this.fingerprintStmt
25745
+ );
25746
+ return {
25747
+ fingerprint: row?.fingerprint ?? void 0,
25748
+ backlogBefore: row?.backlogBefore ?? void 0
25749
+ };
25750
+ }
25751
+ /**
25752
+ * Point the ledger at a different deployment, discarding what it recorded
25753
+ * about the previous one.
25754
+ *
25755
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25756
+ * machine has just left are undelivered as far as the new one is concerned.
25757
+ * All four in one transaction, so a crash between them cannot leave stamps
25758
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25759
+ * a disown with no re-mark to follow it.
25760
+ *
25761
+ * The boundary is written HERE and only here, which is what freezes it: a
25762
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25763
+ * unchanged, so this never runs and the backlog does not widen back over rows
25764
+ * the live path has since delivered.
25765
+ *
25766
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25767
+ * granted existing-history consent for the deployment this call is arming —
25768
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25769
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25770
+ * apart. Passed only when that grant is valid, since this method has no way
25771
+ * to check consent itself and must not mark a row owed for a machine that
25772
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25773
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25774
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25775
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25776
+ * on the cleared side of that bound — and the re-mark in the same
25777
+ * transaction is what puts those rows back. A crash between the two cannot
25778
+ * strand the ledger disowned with nothing re-marked — the transaction either
25779
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25780
+ * committed re-enters this method on the very next pass. Omit it (the
25781
+ * structural-only tests do) to exercise the disown in isolation.
25782
+ *
25783
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25784
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25785
+ * live path can mark a capture owed from the moment `aka attach` writes the
25786
+ * descriptor, before the drain's first pass ever reaches this method, and
25787
+ * such a row sits at or after the bound rather than below it. What keeps the
25788
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25789
+ * bound — disown runs first, re-mark second, both inside the one
25790
+ * transaction above.
25791
+ */
25792
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25793
+ this.ensureRowStmt.run();
25794
+ withTransaction(
25795
+ this.db,
25796
+ () => {
25797
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25798
+ this.rearmStmt.run();
25799
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25800
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25801
+ }
25802
+ if (backfillCapturesBefore !== void 0) {
25803
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25804
+ }
25805
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25806
+ },
25807
+ "IMMEDIATE"
25808
+ );
25809
+ }
25810
+ /**
25811
+ * End the attached period: hand its rows to the live path, and release the
25812
+ * boundary so the next attachment can freeze a new one.
25813
+ *
25814
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25815
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25816
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25817
+ * during the detached period, because the machine is not attached. Rows
25818
+ * recorded in that window sit after the boundary and before the re-attach, so
25819
+ * neither path takes them, and the pending count reports none outstanding.
25820
+ *
25821
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25822
+ * closing attachment's to deliver and are no longer outstanding — that is what
25823
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25824
+ * distinction is not academic: this used to write a delivery TIME, which every
25825
+ * read treats as delivery, so one detach turned a window of undelivered rows
25826
+ * into a window of delivered ones and no surface could tell. It writes the
25827
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25828
+ * "received" stop being the same fact.
25829
+ *
25830
+ * A change of deployment still frees them (see the re-arm), because the next
25831
+ * deployment has seen none of this machine's history — so the rows reach it
25832
+ * exactly as they did when this wrote a delivery time.
25833
+ *
25834
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25835
+ * window unstamped — that half-state would re-send the whole attached period
25836
+ * on the next attach, which is the failure the boundary exists to prevent.
25837
+ */
25838
+ closeAttachedWindow(attachedAtMs, atMs) {
25839
+ this.ensureRowStmt.run();
25840
+ withTransaction(
25841
+ this.db,
25842
+ () => {
25843
+ const row = getRow(this.fingerprintStmt);
25844
+ const from = row?.backlogBefore ?? attachedAtMs;
25845
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25846
+ this.releaseBoundaryStmt.run();
25847
+ },
25848
+ "IMMEDIATE"
25849
+ );
25850
+ }
25851
+ /**
25852
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25853
+ *
25854
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25855
+ * different deployment and therefore discards what was delivered to the old
25856
+ * one: here the recipient is the same, so everything already sent to it stays
25857
+ * sent.
25858
+ */
25859
+ freezeBoundary(backlogBefore) {
25860
+ this.ensureRowStmt.run();
25861
+ this.freezeBoundaryStmt.run({ backlogBefore });
25862
+ }
25863
+ /** Take the claim, or report that someone live already holds it. */
25864
+ claim(pid, host, nowMs, staleAfterMs) {
25865
+ this.ensureRowStmt.run();
25866
+ let taken = false;
25867
+ withTransaction(
25868
+ this.db,
25869
+ () => {
25870
+ const result = this.claimStmt.run({
25871
+ pid,
25872
+ host,
25873
+ now: nowMs,
25874
+ staleBefore: nowMs - staleAfterMs
25875
+ });
25876
+ taken = result.changes === 1;
25877
+ },
25878
+ "IMMEDIATE"
25879
+ );
25880
+ return taken;
25881
+ }
25882
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25883
+ heartbeat(pid, nowMs) {
25884
+ this.heartbeatStmt.run({ now: nowMs, pid });
25885
+ }
25886
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25887
+ release(pid) {
25888
+ this.releaseStmt.run({ pid });
25889
+ }
25890
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25891
+ lease() {
25892
+ return getRow(this.leaseStmt);
25893
+ }
25894
+ };
25895
+
25896
+ // ../../packages/persistence/src/migrations.ts
25897
+ function describeObject(object2) {
25898
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25899
+ }
25900
+ function splitStatements(sql) {
25901
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25902
+ }
25903
+ function createdIndexName(statement) {
25904
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25905
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25906
+ }
25907
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25908
+ function applyMigrations(db, file2, options = {}) {
25909
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25910
+ db.exec(
25911
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25912
+ );
25913
+ const applied = new Set(
25914
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25915
+ );
25916
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25917
+ const record2 = db.prepare(
25918
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25919
+ );
25920
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25921
+ if (applied.has(migration.tag)) continue;
25922
+ if (options.skipTags?.has(migration.tag) === true) continue;
25923
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25924
+ const evidence = evidenceObjects(migration.sql);
25925
+ const present = evidence.filter((o) => evidenceExists(db, o));
25926
+ if (present.length > 0 && present.length < evidence.length) {
25927
+ const missing = evidence.filter((o) => !present.includes(o));
25928
+ const message2 = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25929
+ akaWarn(message2);
25930
+ throw new Error(`[aka] ${message2}`);
25931
+ }
25932
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25933
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25934
+ const statements = splitStatements(migration.sql);
25935
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25936
+ try {
25937
+ withTransaction(
25938
+ db,
25939
+ () => {
25940
+ for (const statement of statements) {
25941
+ const indexName = createdIndexName(statement);
25942
+ if (indexName === void 0) {
25943
+ if (alreadyApplied) continue;
25944
+ } else if (indexExists(db, indexName)) {
25945
+ continue;
25946
+ }
25947
+ db.exec(statement);
25948
+ }
25949
+ if (wantsFkOff && !alreadyApplied) {
25950
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25951
+ if (violations.length > 0) {
25952
+ throw new Error(
25953
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25954
+ );
25955
+ }
25956
+ }
25957
+ record2.run(migration.tag, Date.now());
25958
+ },
25959
+ "IMMEDIATE"
25960
+ );
25961
+ } finally {
25962
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25963
+ }
25964
+ }
25965
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25966
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25967
+ }
25968
+ ensureSyncedAtColumn(db, "audit_events");
25969
+ ensureScanLedgerTable(db);
25970
+ ensureHistorySyncTable(db);
25971
+ ensureBlockedDetectionsTable(db);
25972
+ ensureRuleProbeCacheTable(db);
25973
+ ensureWriteGateTrigger(db);
25974
+ ensureTokenUsageColumns(db);
25975
+ reconcileSourceProjectIds(db);
25976
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25977
+ const drained = runLegacyHistoryBackfill(db);
25978
+ if (drained) applyLegacyDropMigration(db, file2);
25979
+ }
25980
+ }
25981
+ function readLegacyTables(db) {
25982
+ let holdsRows = false;
25983
+ const marks = [];
25984
+ for (const table of ["events", "findings"]) {
25985
+ try {
25986
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25987
+ if (row === void 0) {
25988
+ holdsRows = true;
25989
+ marks.push(`${table}:unreadable`);
25990
+ continue;
25991
+ }
25992
+ if (row.n > 0) holdsRows = true;
25993
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25994
+ } catch {
25995
+ holdsRows = true;
25996
+ marks.push(`${table}:unreadable`);
25997
+ }
25998
+ }
25999
+ return { holdsRows, mark: marks.join("|") };
26000
+ }
26001
+ function applyLegacyDropMigration(db, file2) {
26002
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
26003
+ if (!migration) return;
26004
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
26005
+ if (file2 !== void 0 && before?.holdsRows === true) {
26006
+ try {
26007
+ backupBeforeLegacyDrop(db, file2);
26008
+ } catch (error61) {
26009
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
26010
+ return;
26011
+ }
26012
+ }
26013
+ try {
26014
+ withTransaction(
26015
+ db,
26016
+ () => {
26017
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
26018
+ if (alreadyDropped) return;
26019
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
26020
+ akaWarn(
26021
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
26022
+ );
26023
+ return;
26024
+ }
26025
+ for (const statement of splitStatements(migration.sql)) {
26026
+ db.exec(statement);
26027
+ }
26028
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
26029
+ migration.tag,
26030
+ Date.now()
26031
+ );
25020
26032
  },
25021
26033
  "IMMEDIATE"
25022
26034
  );
@@ -25314,10 +26326,62 @@ function ensureSyncedAtColumn(db, table) {
25314
26326
  if (!columns.includes("outbox_owed")) {
25315
26327
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25316
26328
  }
26329
+ if (!columns.includes("sync_failed_at")) {
26330
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26331
+ }
26332
+ if (!columns.includes("sync_failure")) {
26333
+ withTransaction(
26334
+ db,
26335
+ () => {
26336
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26337
+ db.exec(
26338
+ `UPDATE ${table} SET synced_at = NULL
26339
+ WHERE synced_at = -1
26340
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26341
+ );
26342
+ },
26343
+ "IMMEDIATE"
26344
+ );
26345
+ }
25317
26346
  db.exec(
25318
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25319
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26347
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26348
+ BEFORE UPDATE OF sync_failure ON ${table}
26349
+ WHEN ${syncFailureRejectCondition()}
26350
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25320
26351
  );
26352
+ const syncIndexColumns = [
26353
+ "event_type",
26354
+ "synced_at",
26355
+ "sync_claimed_at",
26356
+ "started_at",
26357
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26358
+ // has to be in the index for the read to stay covered — but putting it
26359
+ // ahead of `started_at` would reorder the prefix the structural drain's
26360
+ // reads match on.
26361
+ "sync_failure"
26362
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26363
+ //
26364
+ // The delivery-state read tests it — a capture's state depends on whether a
26365
+ // live forward marked it owed — so carrying it here makes that read covering
26366
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26367
+ // But a sixth column changes what the planner charges for this index, and
26368
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26369
+ // then stops choosing the per-session index for the token rollup and walks
26370
+ // every `llm_call` in the store through the event-type index instead. That
26371
+ // read grows with the store; this one does not.
26372
+ //
26373
+ // 40 ms on the largest store measured, once per render, is a cost worth
26374
+ // paying to leave every other read's plan where it was.
26375
+ ];
26376
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26377
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26378
+ if (!syncIndexMatches) {
26379
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26380
+ db.exec(
26381
+ `CREATE INDEX idx_audit_events_sync
26382
+ ON audit_events (${syncIndexColumns.join(", ")})`
26383
+ );
26384
+ }
25321
26385
  db.exec(
25322
26386
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25323
26387
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25539,7 +26603,11 @@ function buildAuditEvent(row) {
25539
26603
  link: linkParsed?.success ? linkParsed.data : null,
25540
26604
  targetId: row.target_id,
25541
26605
  internal: intToBool(row.internal),
25542
- flagged: intToBool(row.flagged)
26606
+ flagged: intToBool(row.flagged),
26607
+ // Only meaningful when the title came out empty — a row whose body was
26608
+ // expired but whose title fell back to `tool_name` still has something to
26609
+ // render, and flagging it would make the view apologise for nothing.
26610
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25543
26611
  };
25544
26612
  }
25545
26613
  var TIMELINE_COLUMNS = `
@@ -25547,6 +26615,7 @@ var TIMELINE_COLUMNS = `
25547
26615
  event_type,
25548
26616
  started_at,
25549
26617
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26618
+ content_expired_at,
25550
26619
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25551
26620
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25552
26621
  json_extract(attributes, '$.severity') AS severity,
@@ -25673,7 +26742,8 @@ var SqliteActivityRepository = class {
25673
26742
  SELECT 1 FROM audit_events d
25674
26743
  WHERE d.root_session_id = audit_events.id
25675
26744
  AND (d.content LIKE ? ESCAPE '\\'
25676
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26745
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26746
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25677
26747
  );
25678
26748
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25679
26749
  }
@@ -26211,6 +27281,88 @@ var SqliteAuditEventsRepository = class {
26211
27281
  }
26212
27282
  };
26213
27283
 
27284
+ // ../../packages/persistence/src/repositories/body-retention.ts
27285
+ var DEFAULT_BATCH_SIZE = 500;
27286
+ var DEFAULT_MAX_ROWS = 5e4;
27287
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27288
+ var SqliteBodyRetentionRepository = class {
27289
+ constructor(db) {
27290
+ this.db = db;
27291
+ const select = (laneClause) => `
27292
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27293
+ FROM audit_events
27294
+ WHERE content IS NOT NULL
27295
+ AND started_at < :cutoff
27296
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27297
+ ${laneClause}
27298
+ ORDER BY started_at
27299
+ LIMIT :limit`;
27300
+ this.candidatesStmt = this.db.prepare(select(""));
27301
+ this.candidatesSyncSafeStmt = this.db.prepare(
27302
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27303
+ );
27304
+ this.heldBySyncStmt = this.db.prepare(`
27305
+ SELECT COUNT(*) AS n
27306
+ FROM audit_events
27307
+ WHERE content IS NOT NULL
27308
+ AND started_at < :cutoff
27309
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27310
+ AND synced_at IS NULL`);
27311
+ this.expireStmt = this.db.prepare(
27312
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27313
+ );
27314
+ }
27315
+ db;
27316
+ candidatesStmt;
27317
+ candidatesSyncSafeStmt;
27318
+ heldBySyncStmt;
27319
+ expireStmt;
27320
+ /** How many bytes a pass with these options would free, changing nothing. */
27321
+ preview(opts) {
27322
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27323
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27324
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27325
+ return {
27326
+ rowsExpired: rows.length,
27327
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27328
+ rowsHeldBySync: this.countHeldBySync(opts)
27329
+ };
27330
+ }
27331
+ /** Clear eligible bodies, in bounded batches. */
27332
+ expire(opts) {
27333
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27334
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27335
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27336
+ let rowsExpired = 0;
27337
+ let bytesFreed = 0;
27338
+ let done = true;
27339
+ while (rowsExpired < maxRows) {
27340
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27341
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27342
+ if (batch.length === 0) break;
27343
+ withTransaction(
27344
+ this.db,
27345
+ () => {
27346
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27347
+ },
27348
+ "IMMEDIATE"
27349
+ );
27350
+ rowsExpired += batch.length;
27351
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27352
+ if (batch.length < remaining) break;
27353
+ if (rowsExpired >= maxRows) {
27354
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27355
+ }
27356
+ }
27357
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27358
+ }
27359
+ countHeldBySync(opts) {
27360
+ if (opts.sweepSyncLane) return 0;
27361
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27362
+ return row.n;
27363
+ }
27364
+ };
27365
+
26214
27366
  // ../../packages/persistence/src/repositories/classified-data.ts
26215
27367
  var SqliteClassifiedDataRepository = class {
26216
27368
  constructor(db) {
@@ -27011,23 +28163,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
27011
28163
  )`;
27012
28164
 
27013
28165
  // ../../packages/persistence/src/repositories/findings.ts
27014
- var PREVIEW_INSTANCES_PER_GROUP = 200;
27015
- var DEFAULT_LOCATIONS_LIMIT = 100;
27016
- var LOCATION_RULE_IDS_CAP = 20;
27017
- function compareLocationOrder(a, b) {
27018
- return compareFindingGroupOrder(
27019
- {
27020
- severity: a.maxSeverity,
27021
- latestDetectedAt: a.latestDetectedAt,
27022
- id: ""
27023
- },
27024
- {
27025
- severity: b.maxSeverity,
27026
- latestDetectedAt: b.latestDetectedAt,
27027
- id: ""
27028
- }
27029
- );
27030
- }
27031
28166
  var CONCAT_SEP = ",";
27032
28167
  var TUPLE_SEP = "|";
27033
28168
  function splitConcat(value) {
@@ -27056,7 +28191,15 @@ function toFlatFindingRow(r) {
27056
28191
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
27057
28192
  eventId: r.event_id,
27058
28193
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27059
- status: deriveInstanceStatus(r)
28194
+ status: deriveInstanceStatus(r),
28195
+ delivery: deriveFindingDelivery({
28196
+ kind: r.kind,
28197
+ syncedAt: r.synced_at,
28198
+ syncClaimedAt: r.sync_claimed_at,
28199
+ syncFailedAt: r.sync_failed_at,
28200
+ syncFailure: r.sync_failure,
28201
+ outboxOwed: r.outbox_owed
28202
+ })
27060
28203
  };
27061
28204
  }
27062
28205
  function encodeGroupCursor(group) {
@@ -27079,13 +28222,51 @@ function decodeGroupCursor(cursor) {
27079
28222
  return null;
27080
28223
  }
27081
28224
  function firstAfter(sorted, cursor) {
27082
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28225
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
27083
28226
  return index === -1 ? sorted.length : index;
27084
28227
  }
27085
28228
  function findDeepLinked(sorted, page, id) {
27086
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
27087
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28229
+ if (page.some((t) => t.id === id)) return void 0;
28230
+ return sorted.find((t) => t.id === id);
28231
+ }
28232
+ function encodeLocationCursor(location) {
28233
+ const payload = {
28234
+ sev: location.maxSeverity,
28235
+ t: location.latestDetectedAt,
28236
+ r: location.repo,
28237
+ f: location.file
28238
+ };
28239
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28240
+ }
28241
+ function decodeLocationCursor(cursor) {
28242
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28243
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28244
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28245
+ }
28246
+ return null;
28247
+ }
28248
+ function firstLocationAfter(sorted, cursor) {
28249
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28250
+ return index === -1 ? sorted.length : index;
27088
28251
  }
28252
+ function findDeepLinkedLocation(sorted, page, id) {
28253
+ if (page.some((l) => l.id === id)) return void 0;
28254
+ return sorted.find((l) => l.id === id);
28255
+ }
28256
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28257
+ d.severity AS severity, f.masked_match AS masked_match,
28258
+ f.action_taken AS action_taken, f.confidence AS confidence,
28259
+ e.started_at AS occurred_at,
28260
+ e.source_tool AS source_tool,
28261
+ e.repo AS repo,
28262
+ e.file_path AS file,
28263
+ e.tool_name AS tool_name,
28264
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28265
+ e.event_type AS kind, f.finding_key AS finding_key,
28266
+ ${latestResolutionStatusSql("f")} AS latest_status,
28267
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28268
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28269
+ e.outbox_owed AS outbox_owed`;
27089
28270
  var DAY_MS3 = 864e5;
27090
28271
  var SqliteFindingsRepository = class {
27091
28272
  constructor(db) {
@@ -27206,30 +28387,26 @@ var SqliteFindingsRepository = class {
27206
28387
  );
27207
28388
  }
27208
28389
  /**
27209
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27210
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27211
- * attributes bag, rule_id/category/severity from the definition), scoped to
27212
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27213
- * rows this list must never surface), groups by ruleId, computes
27214
- * per-filter-excluded facets, applies the requested filters, and sorts by
27215
- * severity then recency. Filtering
27216
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27217
- * reflect the full filtered set; `items` is the requested
27218
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27219
- * filter, `totals.findings` counts only instances whose derived status was
27220
- * requested, and each item's instance preview is narrowed the same way.
28390
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28391
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28392
+ * list must never surface), with per-filter-excluded facets, the requested
28393
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28394
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28395
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28396
+ * Under a `status` filter, `totals.findings` counts only findings whose
28397
+ * derived status was requested.
28398
+ *
28399
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28400
+ * folding EVERY finding into the numbers a type row and the filters need
28401
+ * (count, severity, category, providers, actions, statuses, latest, search
28402
+ * text). The findings OF a type come from listFindingInstances scoped to
28403
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27221
28404
  *
27222
- * Two reads, neither of which materializes a row per finding:
27223
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27224
- * the group and the filters need (count, providers, actions, statuses,
27225
- * latest, search text);
27226
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27227
- * populate `instances` for the table's expanded rows.
27228
28405
  * The aggregates carry raw DB values and are translated by the same
27229
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27230
- * rule is ever restated in SQL.
28406
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28407
+ * status rule is ever restated in SQL.
27231
28408
  */
27232
- listGroupedFindings(query) {
28409
+ listFindingTypes(query) {
27233
28410
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27234
28411
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27235
28412
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27242,12 +28419,7 @@ var SqliteFindingsRepository = class {
27242
28419
  predicate,
27243
28420
  params: sessionParams
27244
28421
  });
27245
- const rows = this.previewRows(aggregates, {
27246
- sessionId: query.sessionId,
27247
- from: query.from
27248
- });
27249
- const groupable = rows.map(toFlatFindingRow);
27250
- const allGroups = buildFindingGroups(groupable, { aggregates });
28422
+ const allTypes = buildFindingTypes(aggregates);
27251
28423
  const filterOpts = {
27252
28424
  severity: query.severity,
27253
28425
  providers: query.provider,
@@ -27256,30 +28428,25 @@ var SqliteFindingsRepository = class {
27256
28428
  subtype: query.subtype,
27257
28429
  q: query.q
27258
28430
  };
27259
- const facets = computeFindingFacets(allGroups, filterOpts);
27260
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28431
+ const facets = computeFindingFacets(allTypes, filterOpts);
28432
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27261
28433
  const statusFilter = query.status ?? [];
27262
28434
  const totals = {
27263
- findings: sorted.reduce((acc, g) => {
27264
- if (statusFilter.length === 0) return acc + g.instanceCount;
27265
- const agg = aggregates.get(g.id);
27266
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28435
+ findings: sorted.reduce((acc, t) => {
28436
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28437
+ const agg = aggregates.get(t.id);
28438
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27267
28439
  }, 0),
27268
- groups: sorted.length
28440
+ types: sorted.length
27269
28441
  };
27270
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28442
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27271
28443
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27272
28444
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27273
28445
  const page = sorted.slice(start, start + limit);
27274
28446
  const lastOnPage = page.at(-1);
27275
28447
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27276
28448
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27277
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27278
- const narrow = (g) => statusSet ? {
27279
- ...g,
27280
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27281
- } : g;
27282
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28449
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27283
28450
  return Promise.resolve({
27284
28451
  totals,
27285
28452
  facets,
@@ -27290,7 +28457,7 @@ var SqliteFindingsRepository = class {
27290
28457
  }
27291
28458
  /**
27292
28459
  * One row per rule_id, folding EVERY instance of the group into the values
27293
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28460
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27294
28461
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27295
28462
  *
27296
28463
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27344,6 +28511,7 @@ var SqliteFindingsRepository = class {
27344
28511
  providers: query.provider,
27345
28512
  actions: query.action,
27346
28513
  statuses: query.status,
28514
+ deliveries: query.deployment,
27347
28515
  tools: query.tool,
27348
28516
  repo: query.repo,
27349
28517
  file: query.file,
@@ -27384,13 +28552,25 @@ var SqliteFindingsRepository = class {
27384
28552
  });
27385
28553
  }
27386
28554
  /**
27387
- * The same findings folded by location: repository, then file within it.
28555
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27388
28556
  *
27389
28557
  * The grouping keys come from the capturing event's attributes, which is what
27390
- * the local store relates a finding to — there is no finding↔asset row to
27391
- * group by instead. A repo or file the event did not record folds into the
27392
- * empty-string bucket, which the view renders but does not link, since no
27393
- * filter can name it.
28558
+ * the local store relates a finding to; there is no finding↔asset row to group
28559
+ * by instead. A repo or file the event did not record folds into the
28560
+ * empty-string bucket, which is a real location like any other: it is listed,
28561
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28562
+ *
28563
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28564
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28565
+ * list was rebuilt to remove — and two-level pagination inside an
28566
+ * expand/collapse table is what pushed that view to master/detail in the first
28567
+ * place.
28568
+ *
28569
+ * Every filter narrows the FINDINGS and the locations fall out of what
28570
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28571
+ * reports for the same filters scoped to that pair. The view depends on it:
28572
+ * one toolbar sits over both panels precisely because a location owns none of
28573
+ * its fields.
27394
28574
  */
27395
28575
  listFindingLocations(query) {
27396
28576
  const opts = {
@@ -27399,16 +28579,20 @@ var SqliteFindingsRepository = class {
27399
28579
  providers: query.provider,
27400
28580
  actions: query.action,
27401
28581
  statuses: query.status,
28582
+ deliveries: query.deployment,
27402
28583
  tools: query.tool,
27403
28584
  q: query.q
27404
28585
  };
27405
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28586
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28587
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27406
28588
  const byRepo = /* @__PURE__ */ new Map();
28589
+ const accumulator = createInstanceFacetAccumulator(opts);
27407
28590
  let total = 0;
27408
28591
  for (const row of this.scanFindingRows({
27409
28592
  sessionId: query.sessionId,
27410
28593
  from: query.from
27411
28594
  })) {
28595
+ accumulator.add(row);
27412
28596
  if (!matchesInstanceFilters(row, opts)) continue;
27413
28597
  total += 1;
27414
28598
  let files = byRepo.get(row.repo);
@@ -27423,103 +28607,35 @@ var SqliteFindingsRepository = class {
27423
28607
  }
27424
28608
  addToLocation(acc, row);
27425
28609
  }
27426
- let fileCount = 0;
27427
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27428
- fileCount += files.size;
27429
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27430
- file: file2,
27431
- instanceCount: acc.instanceCount,
27432
- maxSeverity: acc.maxSeverity,
27433
- latestDetectedAt: acc.latestDetectedAt,
27434
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27435
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27436
- })).sort(compareLocationOrder);
27437
- const rollup = fileRows.reduce(
27438
- (a, f) => ({
27439
- instanceCount: a.instanceCount + f.instanceCount,
27440
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27441
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27442
- }),
27443
- {
27444
- instanceCount: 0,
27445
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27446
- latestDetectedAt: ""
27447
- }
27448
- );
27449
- const statuses = fileRows.map((f) => f.status);
27450
- const folded = foldGroupStatus(statuses);
27451
- return {
27452
- repo,
27453
- instanceCount: rollup.instanceCount,
27454
- maxSeverity: rollup.maxSeverity,
27455
- latestDetectedAt: rollup.latestDetectedAt,
27456
- ...folded === void 0 ? {} : { status: folded },
27457
- files: fileRows
27458
- };
27459
- });
27460
- repos.sort(compareLocationOrder);
28610
+ const sorted = [];
28611
+ for (const [repo, files] of byRepo) {
28612
+ for (const [file2, acc] of files) {
28613
+ const status = foldGroupStatus(acc.statuses);
28614
+ sorted.push({
28615
+ id: encodeLocationId(repo, file2),
28616
+ repo,
28617
+ file: file2,
28618
+ instanceCount: acc.instanceCount,
28619
+ maxSeverity: acc.maxSeverity,
28620
+ latestDetectedAt: acc.latestDetectedAt,
28621
+ ...status === void 0 ? {} : { status },
28622
+ ruleIds: [...acc.ruleIds]
28623
+ });
28624
+ }
28625
+ }
28626
+ sorted.sort(compareLocationOrder);
28627
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28628
+ const page = sorted.slice(start, start + limit);
28629
+ const lastOnPage = page.at(-1);
28630
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28631
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27461
28632
  return Promise.resolve({
27462
- totals: { findings: total, repos: repos.length, files: fileCount },
27463
- items: repos.slice(0, limit),
27464
- hasMore: repos.length > limit
28633
+ totals: { findings: total, locations: sorted.length },
28634
+ facets: accumulator.facets(),
28635
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28636
+ nextCursor
27465
28637
  });
27466
28638
  }
27467
- /**
27468
- * Each group's newest instances, for the table's expanded rows.
27469
- *
27470
- * ONE index-ordered scan with early termination, and the shape is the point.
27471
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27472
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27473
- * through a temp B-tree to keep a bounded preview of each group, and then
27474
- * sorts the survivors again for the page order. Both sorts grow with the
27475
- * store while the answer does not.
27476
- *
27477
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27478
- * (or the session or window index the scope names — see `findingScanSql`),
27479
- * which is already the order the page wants, and keeps rows per rule until
27480
- * each rule has as many as it can show. The aggregate the caller already holds
27481
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27482
- * per rule, summed, is the number of rows this scan has to find, and it stops
27483
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27484
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27485
- * store with many firing rules widens it. The bound that DOES hold
27486
- * unconditionally is the sorted form's floor: this scan visits at most as
27487
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27488
- * sorted, and stops the moment every rule has its cap, where the sorted form
27489
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27490
- * wanted instances sitting at the tail of the scope — is one pass over
27491
- * everything in scope with a block sort of the id tie-break only, never a
27492
- * sort of the scope, which is still that floor.
27493
- *
27494
- * A row whose rule the aggregate did not see is skipped: the two statements
27495
- * run without a shared snapshot, so a capture landing between them can add a
27496
- * rule here that has no counts there, and the counts are what the group is
27497
- * built from.
27498
- */
27499
- previewRows(aggregates, scope) {
27500
- const wanted = /* @__PURE__ */ new Map();
27501
- let remaining = 0;
27502
- for (const [ruleId, agg] of aggregates) {
27503
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27504
- wanted.set(ruleId, n);
27505
- remaining += n;
27506
- }
27507
- const rows = [];
27508
- if (remaining === 0) return rows;
27509
- const { sql, params } = this.findingScanSql(scope);
27510
- const taken = /* @__PURE__ */ new Map();
27511
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27512
- const want = wanted.get(r.rule_id);
27513
- if (want === void 0) continue;
27514
- const have = taken.get(r.rule_id) ?? 0;
27515
- if (have >= want) continue;
27516
- taken.set(r.rule_id, have + 1);
27517
- rows.push(r);
27518
- remaining -= 1;
27519
- if (remaining === 0) break;
27520
- }
27521
- return rows;
27522
- }
27523
28639
  /**
27524
28640
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27525
28641
  *
@@ -27546,6 +28662,33 @@ var SqliteFindingsRepository = class {
27546
28662
  yield toFlatFindingRow(r);
27547
28663
  }
27548
28664
  }
28665
+ /**
28666
+ * One finding by its own id, or null when no such row exists.
28667
+ *
28668
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28669
+ * the store — and, unlike anything derived from a list page, it resolves a
28670
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28671
+ * deep link needs: the id it carries may name a finding thousands of rows
28672
+ * older than anything a first page holds.
28673
+ *
28674
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28675
+ * RESOLVES an id; whether that row would survive the list's current filters is
28676
+ * a different question, and hiding the target because a filter excludes it is
28677
+ * worse than showing it.
28678
+ *
28679
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28680
+ * type should the list select?" and "what does the drawer show?".
28681
+ */
28682
+ findingInstance(id) {
28683
+ const row = this.db.prepare(
28684
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28685
+ FROM inspection_findings f
28686
+ JOIN audit_events e ON e.id = f.audit_event_id
28687
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28688
+ WHERE f.id = ?`
28689
+ ).get(id);
28690
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28691
+ }
27549
28692
  /**
27550
28693
  * The one statement both instance-level scans run: every finding in scope,
27551
28694
  * joined to its event and definition, newest first.
@@ -27579,17 +28722,7 @@ var SqliteFindingsRepository = class {
27579
28722
  conditions.push("e.started_at >= ?");
27580
28723
  params.push(isoToEpochMillis(scope.from));
27581
28724
  }
27582
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27583
- d.severity AS severity, f.masked_match AS masked_match,
27584
- f.action_taken AS action_taken, f.confidence AS confidence,
27585
- e.started_at AS occurred_at,
27586
- e.source_tool AS source_tool,
27587
- e.repo AS repo,
27588
- e.file_path AS file,
27589
- e.tool_name AS tool_name,
27590
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27591
- e.event_type AS kind, f.finding_key AS finding_key,
27592
- ${latestResolutionStatusSql("f")} AS latest_status
28725
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27593
28726
  FROM audit_events e
27594
28727
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27595
28728
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27603,6 +28736,26 @@ var SqliteFindingsRepository = class {
27603
28736
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27604
28737
  const rows = this.db.prepare(
27605
28738
  `SELECT rule_id,
28739
+ -- BARE columns beside max(latest_at), which is deliberate and
28740
+ -- is SQLite's documented behaviour: with a single min()/max()
28741
+ -- in an aggregate query, every bare column takes its value from
28742
+ -- the row that produced the extremum. So these are the severity
28743
+ -- and category of the definition whose finding is NEWEST, which
28744
+ -- is what the row-based build they replaced read off its first
28745
+ -- (newest-first) row.
28746
+ --
28747
+ -- min() is WRONG here and was the defect: inspection_definitions
28748
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28749
+ -- mints a new row), so a rule whose severity moved between
28750
+ -- versions has several, and min() picks the ALPHABETICALLY
28751
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28752
+ -- That is arbitrary in direction, and it feeds the badge, the
28753
+ -- filter, the facet counts and the primary sort key.
28754
+ --
28755
+ -- Adding a second min()/max() aggregate here would make these
28756
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28757
+ severity,
28758
+ category,
27606
28759
  sum(tuple_count) AS instance_count,
27607
28760
  max(latest_at) AS latest_at,
27608
28761
  group_concat(source_tools) AS source_tools,
@@ -27613,6 +28766,14 @@ var SqliteFindingsRepository = class {
27613
28766
  group_concat(tool_names) AS tool_names
27614
28767
  FROM (
27615
28768
  SELECT d.rule_id AS rule_id,
28769
+ -- Severity and category are columns of the DEFINITION, and
28770
+ -- a rule can have SEVERAL definitions (one per version), so
28771
+ -- these are grouped on below and resolved to the newest
28772
+ -- firing version by the outer query's bare-column select.
28773
+ -- They ride the aggregate because the type build has no rows
28774
+ -- to read them off \u2014 see buildFindingTypes.
28775
+ d.severity AS severity,
28776
+ d.category AS category,
27616
28777
  e.event_type || '${TUPLE_SEP}' ||
27617
28778
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27618
28779
  coalesce(latest.status, '') AS status_tuple,
@@ -27627,7 +28788,7 @@ var SqliteFindingsRepository = class {
27627
28788
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27628
28789
  ON latest.finding_key = f.finding_key
27629
28790
  ${scope.predicate}
27630
- GROUP BY d.rule_id, status_tuple
28791
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27631
28792
  )
27632
28793
  GROUP BY rule_id`
27633
28794
  ).all(scope.params);
@@ -27636,6 +28797,8 @@ var SqliteFindingsRepository = class {
27636
28797
  r.rule_id,
27637
28798
  {
27638
28799
  instanceCount: r.instance_count,
28800
+ severity: r.severity,
28801
+ category: r.category,
27639
28802
  sourceTools: splitConcat(r.source_tools),
27640
28803
  actionsTaken: splitConcat(r.actions_taken),
27641
28804
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27652,7 +28815,7 @@ var SqliteFindingsRepository = class {
27652
28815
  latestDetectedAt: epochMillisToIso(r.latest_at),
27653
28816
  // Free text only — joined and substring-matched, so group_concat's
27654
28817
  // commas need no unpicking (a repo/path containing one still matches).
27655
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28818
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27656
28819
  // tell "no q this request" from "a group with no repo/file at all"
27657
28820
  // and skip priming a haystack nothing will read.
27658
28821
  ...withSearchText ? {
@@ -27680,7 +28843,9 @@ var SqliteFindingsRepository = class {
27680
28843
  )
27681
28844
  );
27682
28845
  for (const row of grouped) {
27683
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28846
+ if (Object.hasOwn(byAction, row.action_taken)) {
28847
+ byAction[row.action_taken] = row.c;
28848
+ }
27684
28849
  }
27685
28850
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27686
28851
  const sevRows = allRows(
@@ -27697,7 +28862,9 @@ var SqliteFindingsRepository = class {
27697
28862
  )
27698
28863
  );
27699
28864
  for (const row of sevRows) {
27700
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28865
+ if (Object.hasOwn(bySeverity, row.severity)) {
28866
+ bySeverity[row.severity] = row.c;
28867
+ }
27701
28868
  }
27702
28869
  const categories = ENFORCEABLE_CATEGORIES;
27703
28870
  const enabledRows = allRows(
@@ -27746,469 +28913,6 @@ function isoDay(ms) {
27746
28913
  return new Date(ms).toISOString().slice(0, 10);
27747
28914
  }
27748
28915
 
27749
- // ../../packages/persistence/src/repositories/history-sync.ts
27750
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27751
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27752
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27753
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27754
- var SKIPPED = -1;
27755
- var ROW_COLUMNS = `id,
27756
- parent_id AS parentId,
27757
- root_session_id AS rootSessionId,
27758
- event_type AS eventType,
27759
- host_id AS hostId,
27760
- harness_id AS harnessId,
27761
- source_project_id AS sourceProjectId,
27762
- started_at AS startedAt,
27763
- ended_at AS endedAt,
27764
- severity,
27765
- priority,
27766
- content,
27767
- content_hash AS contentHash,
27768
- attributes`;
27769
- var SqliteHistorySyncRepository = class {
27770
- constructor(db) {
27771
- this.db = db;
27772
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27773
- this.sessionsStmt = db.prepare(
27774
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27775
- FROM audit_events
27776
- WHERE synced_at IS NULL
27777
- AND event_type IN (${TYPE_LIST})
27778
- AND started_at < :before
27779
- GROUP BY sessionId
27780
- ORDER BY earliest
27781
- LIMIT :limit`
27782
- );
27783
- this.rowsStmt = db.prepare(
27784
- `SELECT ${ROW_COLUMNS}
27785
- FROM audit_events
27786
- WHERE synced_at IS NULL
27787
- AND event_type IN (${TYPE_LIST})
27788
- AND started_at < :before
27789
- AND COALESCE(root_session_id, id) = :sessionId
27790
- ORDER BY (event_type = 'session') DESC, started_at
27791
- LIMIT :limit`
27792
- );
27793
- this.captureRowsStmt = db.prepare(
27794
- `SELECT ${ROW_COLUMNS}
27795
- FROM audit_events
27796
- WHERE synced_at IS NULL
27797
- AND sync_claimed_at IS NULL
27798
- AND outbox_owed = 1
27799
- AND event_type IN (${CAPTURE_TYPE_LIST})
27800
- AND started_at < :before
27801
- ORDER BY started_at
27802
- LIMIT :limit`
27803
- );
27804
- this.markOwedStmt = db.prepare(
27805
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27806
- );
27807
- this.stampStmt = db.prepare(
27808
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27809
- );
27810
- this.claimRowStmt = db.prepare(
27811
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27812
- );
27813
- this.releaseRowStmt = db.prepare(
27814
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27815
- );
27816
- this.releaseStaleClaimsStmt = db.prepare(
27817
- `UPDATE audit_events SET sync_claimed_at = NULL
27818
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27819
- );
27820
- this.partitionStmt = db.prepare(
27821
- `SELECT
27822
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27823
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27824
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27825
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27826
- COUNT(*) AS total
27827
- FROM audit_events
27828
- WHERE event_type IN (${TYPE_LIST})`
27829
- );
27830
- this.countsStmt = db.prepare(
27831
- `SELECT
27832
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27833
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27834
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27835
- FROM audit_events
27836
- WHERE event_type IN (${TYPE_LIST})`
27837
- );
27838
- this.captureSkipCountStmt = db.prepare(
27839
- `SELECT COUNT(*) AS skipped
27840
- FROM audit_events
27841
- WHERE synced_at = ${String(SKIPPED)}
27842
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27843
- );
27844
- this.fingerprintStmt = db.prepare(
27845
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27846
- FROM history_sync WHERE id = 1`
27847
- );
27848
- this.setFingerprintStmt = db.prepare(
27849
- `UPDATE history_sync
27850
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27851
- WHERE id = 1`
27852
- );
27853
- this.disownCapturesStmt = db.prepare(
27854
- `UPDATE audit_events SET outbox_owed = NULL
27855
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27856
- );
27857
- this.rearmStmt = db.prepare(
27858
- `UPDATE audit_events SET synced_at = NULL
27859
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27860
- );
27861
- this.claimStmt = db.prepare(
27862
- `UPDATE history_sync
27863
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27864
- WHERE id = 1
27865
- AND (owner_pid IS NULL
27866
- OR heartbeat_at IS NULL
27867
- OR heartbeat_at < :staleBefore
27868
- OR heartbeat_at > :now)`
27869
- );
27870
- this.heartbeatStmt = db.prepare(
27871
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27872
- );
27873
- this.releaseStmt = db.prepare(
27874
- `UPDATE history_sync
27875
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27876
- WHERE id = 1 AND owner_pid = :pid`
27877
- );
27878
- this.closeWindowStmt = db.prepare(
27879
- `UPDATE audit_events SET synced_at = :at
27880
- WHERE synced_at IS NULL
27881
- AND event_type IN (${TYPE_LIST})
27882
- AND started_at >= :attachedAt`
27883
- );
27884
- this.releaseBoundaryStmt = db.prepare(
27885
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27886
- );
27887
- this.freezeBoundaryStmt = db.prepare(
27888
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27889
- );
27890
- this.leaseStmt = db.prepare(
27891
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27892
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27893
- FROM history_sync WHERE id = 1`
27894
- );
27895
- this.inspectionsStmt = db.prepare(
27896
- `SELECT d.rule_id AS ruleId,
27897
- d.name AS ruleName,
27898
- d.version AS ruleVersion,
27899
- d.category AS category,
27900
- d.severity AS severity,
27901
- f.span_start AS spanStart,
27902
- f.span_end AS spanEnd,
27903
- f.masked_match AS maskedMatch,
27904
- f.action_taken AS actionTaken,
27905
- f.confidence AS confidence
27906
- FROM inspection_findings f
27907
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27908
- WHERE f.audit_event_id = :auditEventId
27909
- ORDER BY f.span_start, f.id`
27910
- );
27911
- }
27912
- db;
27913
- ensureRowStmt;
27914
- sessionsStmt;
27915
- rowsStmt;
27916
- stampStmt;
27917
- countsStmt;
27918
- fingerprintStmt;
27919
- setFingerprintStmt;
27920
- rearmStmt;
27921
- claimStmt;
27922
- heartbeatStmt;
27923
- releaseStmt;
27924
- leaseStmt;
27925
- inspectionsStmt;
27926
- closeWindowStmt;
27927
- releaseBoundaryStmt;
27928
- freezeBoundaryStmt;
27929
- captureRowsStmt;
27930
- markOwedStmt;
27931
- captureSkipCountStmt;
27932
- disownCapturesStmt;
27933
- partitionStmt;
27934
- claimRowStmt;
27935
- releaseRowStmt;
27936
- releaseStaleClaimsStmt;
27937
- /**
27938
- * The masked detections recorded against one tool call.
27939
- *
27940
- * These travel with the event because a tool call's target is not
27941
- * re-inspectable from the event alone — unlike a capture, where the text
27942
- * itself is re-scannable. What crosses is the masked match and the rule that
27943
- * produced it, never the value.
27944
- */
27945
- inspectionsFor(auditEventId) {
27946
- return allRows(this.inspectionsStmt, { auditEventId });
27947
- }
27948
- /**
27949
- * Sessions with structural rows still to send, oldest first.
27950
- *
27951
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27952
- * read. Anything recorded after the machine attached is the live forward
27953
- * path's to deliver; this drain exists for what was recorded before it, and a
27954
- * row both paths send is at best a duplicate request and at worst — for a
27955
- * session root — an overwrite of the inventory ids the live path resolved.
27956
- */
27957
- pendingSessions(limit, before) {
27958
- return allRows(this.sessionsStmt, { limit, before }).map(
27959
- (r) => r.sessionId
27960
- );
27961
- }
27962
- /** One session's undelivered structural rows within the backlog, root first. */
27963
- pendingRows(sessionId, limit, before) {
27964
- return allRows(this.rowsStmt, { sessionId, limit, before });
27965
- }
27966
- /**
27967
- * Captures this machine still owes the deployment, oldest first.
27968
- *
27969
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27970
- * by a time window — see captureRowsStmt for why a window could not express
27971
- * this. `before` is the grace window that leaves a just-recorded capture to
27972
- * the live path.
27973
- */
27974
- pendingCaptureRows(limit, before) {
27975
- return allRows(this.captureRowsStmt, { limit, before });
27976
- }
27977
- /**
27978
- * Record that a capture is OWED to the deployment.
27979
- *
27980
- * Written by the attached forward path when a live send did not confirm
27981
- * delivery, and read by the drain as the whole of its eligibility test. It is
27982
- * a fact rather than an inference: the machine was attached, the send did not
27983
- * land, so the row is owed — which no time window can state, because the same
27984
- * window that holds the rows a past attachment left owed also holds every
27985
- * capture recorded while the machine was DETACHED, and those were never
27986
- * offered to anyone.
27987
- *
27988
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27989
- * out of the drain's read.
27990
- */
27991
- markCaptureOwed(id) {
27992
- this.markOwedStmt.run({ id });
27993
- }
27994
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27995
- markSynced(ids, atMs) {
27996
- this.stampAll(ids, atMs);
27997
- }
27998
- /**
27999
- * Record that a row will never be sent.
28000
- *
28001
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
28002
- * payload. A row that merely failed to reach the deployment stays NULL, so it
28003
- * is retried; marking those would turn one outage into permanent data loss.
28004
- */
28005
- markSkipped(ids) {
28006
- this.stampAll(ids, SKIPPED);
28007
- }
28008
- eachInTransaction(ids, run) {
28009
- if (ids.length === 0) return;
28010
- withTransaction(
28011
- this.db,
28012
- () => {
28013
- for (const id of ids) run(id);
28014
- },
28015
- "IMMEDIATE"
28016
- );
28017
- }
28018
- stampAll(ids, value) {
28019
- if (ids.length === 0) return;
28020
- withTransaction(
28021
- this.db,
28022
- () => {
28023
- for (const id of ids) this.stampStmt.run({ at: value, id });
28024
- },
28025
- "IMMEDIATE"
28026
- );
28027
- }
28028
- /**
28029
- * Claim rows as in-flight.
28030
- *
28031
- * Advisory in exactly the sense the lease is: it records that a send is in
28032
- * progress so a surface can say so, and a lost claim costs a row showing as
28033
- * queued while it is actually being sent. It is not exclusion — the far side
28034
- * settles a duplicate on the row id.
28035
- */
28036
- claimRows(ids, atMs) {
28037
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28038
- }
28039
- /** Give back a claim without settling — the send failed, the row is queued again. */
28040
- releaseRows(ids) {
28041
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28042
- }
28043
- /**
28044
- * Clear claims older than `staleBefore`, and report how many were cleared.
28045
- *
28046
- * A process killed between claiming and settling leaves rows claimed with
28047
- * nothing left to settle them. Without this they read as "sending" for ever.
28048
- */
28049
- releaseStaleClaims(staleBefore) {
28050
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28051
- }
28052
- /**
28053
- * Every tracked row in exactly one delivery state.
28054
- *
28055
- * Takes no boundary on purpose. The boundary answers "what should the drain
28056
- * pick up now", which is a different question from "what state is this row
28057
- * in" — and a machine that has never attached has no boundary to pass, so
28058
- * requiring one would force a caller to invent one and report the whole store
28059
- * as queued.
28060
- */
28061
- partition() {
28062
- const row = getRow(this.partitionStmt, {});
28063
- return {
28064
- queued: row?.queued ?? 0,
28065
- inProgress: row?.inProgress ?? 0,
28066
- synced: row?.synced ?? 0,
28067
- failed: row?.failed ?? 0,
28068
- total: row?.total ?? 0
28069
- };
28070
- }
28071
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28072
- counts(before) {
28073
- const row = getRow(
28074
- this.countsStmt,
28075
- { before }
28076
- );
28077
- const captures = getRow(this.captureSkipCountStmt);
28078
- return {
28079
- pending: row?.pending ?? 0,
28080
- sent: row?.sent ?? 0,
28081
- skipped: row?.skipped ?? 0,
28082
- capturesSkipped: captures?.skipped ?? 0
28083
- };
28084
- }
28085
- /**
28086
- * The deployment the current stamps were made against, and where its backlog
28087
- * ends.
28088
- *
28089
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28090
- * machine that has never drained is — and every writer below seeds the row
28091
- * before it needs one, so nothing depends on this creating it. Keeping the
28092
- * write off the gate path matters because the gate runs on every pass while a
28093
- * write has to take the database's write lock.
28094
- */
28095
- deployment() {
28096
- const row = getRow(
28097
- this.fingerprintStmt
28098
- );
28099
- return {
28100
- fingerprint: row?.fingerprint ?? void 0,
28101
- backlogBefore: row?.backlogBefore ?? void 0
28102
- };
28103
- }
28104
- /**
28105
- * Point the ledger at a different deployment, discarding what it recorded
28106
- * about the previous one.
28107
- *
28108
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28109
- * machine has just left are undelivered as far as the new one is concerned.
28110
- * All three in one transaction, so a crash between them cannot leave stamps
28111
- * attributed to the wrong deployment, or a boundary that belongs to another.
28112
- *
28113
- * The boundary is written HERE and only here, which is what freezes it: a
28114
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28115
- * unchanged, so this never runs and the backlog does not widen back over rows
28116
- * the live path has since delivered.
28117
- */
28118
- rearmFor(fingerprint, backlogBefore) {
28119
- this.ensureRowStmt.run();
28120
- withTransaction(
28121
- this.db,
28122
- () => {
28123
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28124
- this.rearmStmt.run();
28125
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28126
- this.disownCapturesStmt.run();
28127
- }
28128
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28129
- },
28130
- "IMMEDIATE"
28131
- );
28132
- }
28133
- /**
28134
- * End the attached period: hand its rows to the live path, and release the
28135
- * boundary so the next attachment can freeze a new one.
28136
- *
28137
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28138
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28139
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28140
- * during the detached period, because the machine is not attached. Rows
28141
- * recorded in that window sit after the boundary and before the re-attach, so
28142
- * neither path takes them, and the pending count reports none outstanding.
28143
- *
28144
- * Stamping the attached window is not a claim that every one of those rows
28145
- * reached the deployment — the live path drops on failure and says so
28146
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28147
- * status quo: they sit outside the frozen boundary today and are equally never
28148
- * re-sent. Making it explicit is what lets the boundary move.
28149
- *
28150
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28151
- * window unstamped — that half-state would re-send the whole attached period
28152
- * on the next attach, which is the failure the boundary exists to prevent.
28153
- */
28154
- closeAttachedWindow(attachedAtMs, atMs) {
28155
- this.ensureRowStmt.run();
28156
- withTransaction(
28157
- this.db,
28158
- () => {
28159
- const row = getRow(this.fingerprintStmt);
28160
- const from = row?.backlogBefore ?? attachedAtMs;
28161
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28162
- this.releaseBoundaryStmt.run();
28163
- },
28164
- "IMMEDIATE"
28165
- );
28166
- }
28167
- /**
28168
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28169
- *
28170
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28171
- * different deployment and therefore discards what was delivered to the old
28172
- * one: here the recipient is the same, so everything already sent to it stays
28173
- * sent.
28174
- */
28175
- freezeBoundary(backlogBefore) {
28176
- this.ensureRowStmt.run();
28177
- this.freezeBoundaryStmt.run({ backlogBefore });
28178
- }
28179
- /** Take the claim, or report that someone live already holds it. */
28180
- claim(pid, host, nowMs, staleAfterMs) {
28181
- this.ensureRowStmt.run();
28182
- let taken = false;
28183
- withTransaction(
28184
- this.db,
28185
- () => {
28186
- const result = this.claimStmt.run({
28187
- pid,
28188
- host,
28189
- now: nowMs,
28190
- staleBefore: nowMs - staleAfterMs
28191
- });
28192
- taken = result.changes === 1;
28193
- },
28194
- "IMMEDIATE"
28195
- );
28196
- return taken;
28197
- }
28198
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28199
- heartbeat(pid, nowMs) {
28200
- this.heartbeatStmt.run({ now: nowMs, pid });
28201
- }
28202
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28203
- release(pid) {
28204
- this.releaseStmt.run({ pid });
28205
- }
28206
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28207
- lease() {
28208
- return getRow(this.leaseStmt);
28209
- }
28210
- };
28211
-
28212
28916
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28213
28917
  var SqliteInspectionDefinitionsRepository = class {
28214
28918
  constructor(db) {
@@ -28403,7 +29107,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28403
29107
  }
28404
29108
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28405
29109
  }
28406
- function readManagedSettings(paths = managedSettingsPaths()) {
29110
+ var testOnlyManagedPaths = null;
29111
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28407
29112
  for (const path of paths) {
28408
29113
  let text;
28409
29114
  try {
@@ -28438,6 +29143,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28438
29143
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28439
29144
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28440
29145
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29146
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28441
29147
  if (values.vaultConsent !== void 0) {
28442
29148
  merged.vaultConsent = values.vaultConsent ? (
28443
29149
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30883,7 +31589,7 @@ function toUtcDateString(ms) {
30883
31589
  return new Date(ms).toISOString().slice(0, 10);
30884
31590
  }
30885
31591
  function isTimeseriesSeverity(s) {
30886
- return s === "critical" || s === "high" || s === "medium";
31592
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30887
31593
  }
30888
31594
  var SqliteSecurityRepository = class {
30889
31595
  constructor(db, now = () => Date.now()) {
@@ -30945,7 +31651,7 @@ var SqliteSecurityRepository = class {
30945
31651
  ELSE 0
30946
31652
  END) AS open_at_rest
30947
31653
  FROM inspection_findings f
30948
- JOIN audit_events e ON e.id = f.audit_event_id
31654
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30949
31655
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30950
31656
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30951
31657
  ON latest.finding_key = f.finding_key
@@ -31012,12 +31718,16 @@ var SqliteSecurityRepository = class {
31012
31718
  const now = this.now();
31013
31719
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
31014
31720
  const rows = this.findingsInRange(windowStart, now);
31015
- const points = Array.from({ length: numBuckets }, (_, i) => ({
31016
- timestamp: toUtcDateString(windowStart + i * bucketMs),
31017
- critical: 0,
31018
- high: 0,
31019
- medium: 0
31020
- }));
31721
+ const points = Array.from(
31722
+ { length: numBuckets },
31723
+ (_, i) => ({
31724
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31725
+ critical: 0,
31726
+ high: 0,
31727
+ medium: 0,
31728
+ low: 0
31729
+ })
31730
+ );
31021
31731
  for (const r of rows) {
31022
31732
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
31023
31733
  const bucket = points[idx];
@@ -31167,7 +31877,7 @@ var SqliteSecurityRepository = class {
31167
31877
  this.db.prepare(
31168
31878
  `SELECT e.repo AS repo, count(*) AS c
31169
31879
  FROM inspection_findings f
31170
- JOIN audit_events e ON e.id = f.audit_event_id
31880
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31171
31881
  WHERE e.started_at >= :from AND e.started_at < :to
31172
31882
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31173
31883
  AND e.repo IS NOT NULL
@@ -31235,6 +31945,7 @@ var SqliteSecurityRepository = class {
31235
31945
  `SELECT f.finding_key AS finding_key,
31236
31946
  d.rule_id AS rule_id,
31237
31947
  d.severity AS severity,
31948
+ e.repo AS repo,
31238
31949
  e.file_path AS path,
31239
31950
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31240
31951
  latest.resolved_at AS latest_resolved_at
@@ -31254,6 +31965,7 @@ var SqliteSecurityRepository = class {
31254
31965
  const items = rows.map((r) => ({
31255
31966
  findingKey: r.finding_key,
31256
31967
  ruleId: r.rule_id,
31968
+ repo: r.repo ?? "",
31257
31969
  severity: r.severity,
31258
31970
  path: r.path ?? "",
31259
31971
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31263,15 +31975,68 @@ var SqliteSecurityRepository = class {
31263
31975
  }));
31264
31976
  return Promise.resolve({ items });
31265
31977
  }
31978
+ /**
31979
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31980
+ *
31981
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31982
+ * list: a secret committed three weeks ago and never rotated is still the most
31983
+ * important thing to fix, and any window hides it. It carried a "newest N
31984
+ * findings" cap and then a range; the first meant a different span on every
31985
+ * machine, and the second reported "no recommendations" over live exposure.
31986
+ *
31987
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31988
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31989
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31990
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31991
+ * The two answer different questions and only this one has to match a link.
31992
+ *
31993
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31994
+ * whole-store scope costs a grouped scan rather than a row per finding.
31995
+ */
31996
+ recommendationInputs() {
31997
+ const rows = allRows(
31998
+ this.db.prepare(
31999
+ `SELECT d.rule_id AS rule_id,
32000
+ d.category AS category,
32001
+ d.severity AS severity,
32002
+ COUNT(*) AS count
32003
+ FROM inspection_findings f
32004
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
32005
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
32006
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
32007
+ ON latest.finding_key = f.finding_key
32008
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
32009
+ AND e.event_type = 'code_change'
32010
+ AND (
32011
+ f.finding_key IS NULL
32012
+ OR latest.status IS NULL
32013
+ OR latest.status NOT IN ('resolved', 'dismissed')
32014
+ )
32015
+ GROUP BY d.rule_id, d.category, d.severity`
32016
+ )
32017
+ );
32018
+ return Promise.resolve(
32019
+ rows.map((r) => ({
32020
+ ruleId: r.rule_id,
32021
+ category: r.category,
32022
+ severity: r.severity,
32023
+ count: r.count
32024
+ }))
32025
+ );
32026
+ }
31266
32027
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31267
32028
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31268
32029
  // numeric and the JS aggregations bucket/split on ms directly.
31269
32030
  findingsInRange(fromMs, toMs) {
31270
32031
  const rows = allRows(
31271
32032
  this.db.prepare(
31272
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
32033
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
32034
+ // joined for `severity`, so they are two more columns off a row this read
32035
+ // already fetches. They feed the recommended-actions rollup.
32036
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
32037
+ d.rule_id AS rule_id, d.category AS category
31273
32038
  FROM inspection_findings f
31274
- JOIN audit_events e ON e.id = f.audit_event_id
32039
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31275
32040
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31276
32041
  WHERE e.started_at >= :from AND e.started_at < :to
31277
32042
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31282,7 +32047,9 @@ var SqliteSecurityRepository = class {
31282
32047
  return rows.map((r) => ({
31283
32048
  occurredAt: r.occurred_at,
31284
32049
  severity: r.severity,
31285
- actionTaken: r.action_taken
32050
+ actionTaken: r.action_taken,
32051
+ ruleId: r.rule_id,
32052
+ category: r.category
31286
32053
  }));
31287
32054
  }
31288
32055
  };
@@ -32110,6 +32877,7 @@ function openWithPragmas(file2) {
32110
32877
  db.exec("PRAGMA journal_mode = WAL");
32111
32878
  db.exec("PRAGMA busy_timeout = 2000");
32112
32879
  db.exec("PRAGMA foreign_keys = ON");
32880
+ registerSqlFunctions(db);
32113
32881
  } catch (err) {
32114
32882
  closeQuietly(db);
32115
32883
  throw err;
@@ -32139,7 +32907,7 @@ function backupLegacyStore(db, file2) {
32139
32907
  discardStore(file2, backup);
32140
32908
  return backup;
32141
32909
  }
32142
- function openAndInitialize(file2, base) {
32910
+ function openAndInitialize(file2, base, skipTags) {
32143
32911
  let db = openWithPragmas(file2);
32144
32912
  try {
32145
32913
  if (isForeignSqliteLineage(db)) {
@@ -32149,7 +32917,7 @@ function openAndInitialize(file2, base) {
32149
32917
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32150
32918
  );
32151
32919
  }
32152
- applyMigrations(db, file2);
32920
+ applyMigrations(db, file2, { skipTags });
32153
32921
  tightenPerms(file2);
32154
32922
  const policies = new SqlitePoliciesRepository(db);
32155
32923
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32164,6 +32932,7 @@ function openAndInitialize(file2, base) {
32164
32932
  exceptions: new SqliteExceptionsRepository(db),
32165
32933
  resolutions: new SqliteResolutionsRepository(db),
32166
32934
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32935
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32167
32936
  security: new SqliteSecurityRepository(db),
32168
32937
  detections: new SqliteDetectionsRepository(db),
32169
32938
  shares: new SqliteSharesRepository(db),
@@ -32186,7 +32955,8 @@ function openAndInitialize(file2, base) {
32186
32955
  throw err;
32187
32956
  }
32188
32957
  }
32189
- function openLocalDatabase(dir) {
32958
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32959
+ function openLocalDatabase(dir, options = {}) {
32190
32960
  ensureDataDirSync(dir);
32191
32961
  const file2 = join7(dir, DB_FILENAME);
32192
32962
  reapStalePartials(file2);
@@ -32198,6 +32968,7 @@ function openLocalDatabase(dir) {
32198
32968
  installedPacks,
32199
32969
  scanLedger,
32200
32970
  historySync,
32971
+ bodyRetention,
32201
32972
  secretVault,
32202
32973
  exceptions,
32203
32974
  resolutions,
@@ -32221,7 +32992,8 @@ function openLocalDatabase(dir) {
32221
32992
  // `dir` is always `<base>/data` — every caller resolves it through
32222
32993
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32223
32994
  // settings/ and data/, and the pack-policy floor needs both halves.
32224
- dirname2(dir)
32995
+ dirname2(dir),
32996
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32225
32997
  );
32226
32998
  function captureRowId(event) {
32227
32999
  return captureId(
@@ -32414,6 +33186,7 @@ function openLocalDatabase(dir) {
32414
33186
  installedPacks,
32415
33187
  scanLedger,
32416
33188
  historySync,
33189
+ bodyRetention,
32417
33190
  secretVault,
32418
33191
  exceptions,
32419
33192
  resolutions,
@@ -32452,8 +33225,72 @@ function openLocalDatabase(dir) {
32452
33225
  };
32453
33226
  }
32454
33227
 
32455
- // ../../packages/persistence/src/finding-key.ts
33228
+ // ../../packages/persistence/src/egress-wire.ts
32456
33229
  import { createHash as createHash3 } from "crypto";
33230
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33231
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33232
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33233
+ var FILE_URL = /^file:\/\//i;
33234
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33235
+ var SLASH = "/".charCodeAt(0);
33236
+ var GIT_SUFFIX = ".git";
33237
+ function trimSlashes(path) {
33238
+ let start = 0;
33239
+ let end = path.length;
33240
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33241
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33242
+ return path.slice(start, end);
33243
+ }
33244
+ function canonicalGitUrl(url2) {
33245
+ const trimmed = url2.trim();
33246
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33247
+ const scheme = SCHEME_FORM.exec(trimmed);
33248
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33249
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33250
+ if (host === void 0) return trimmed;
33251
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33252
+ const bare = trimSlashes(path);
33253
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33254
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33255
+ }
33256
+ function hashProjectKey(projectKey) {
33257
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33258
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33259
+ }
33260
+ function toIngestHit(hit) {
33261
+ return {
33262
+ host: hit.host,
33263
+ kind: hit.kind,
33264
+ name: hit.name,
33265
+ category: hit.category,
33266
+ trust: hit.trust,
33267
+ network: hit.network,
33268
+ method: hit.method,
33269
+ transport: hit.transport,
33270
+ url: hit.url,
33271
+ template: hit.template,
33272
+ dataClass: hit.dataClass,
33273
+ site: {
33274
+ file: hit.site.file,
33275
+ line: hit.site.line,
33276
+ dynamic: hit.site.dynamic,
33277
+ vendored: hit.site.vendored
33278
+ }
33279
+ };
33280
+ }
33281
+ function toEgressIngestRequest(input2) {
33282
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33283
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33284
+ return {
33285
+ projectKey: hashProjectKey(input2.projectKey),
33286
+ project: input2.project,
33287
+ reconcile,
33288
+ hits: hits.map(toIngestHit)
33289
+ };
33290
+ }
33291
+
33292
+ // ../../packages/persistence/src/finding-key.ts
33293
+ import { createHash as createHash4 } from "crypto";
32457
33294
 
32458
33295
  // ../../packages/persistence/src/fingerprint.ts
32459
33296
  import { createHmac, randomBytes } from "crypto";
@@ -32494,14 +33331,50 @@ function readFingerprintKey(dataDir2) {
32494
33331
  return parseKeyFile(raw);
32495
33332
  }
32496
33333
 
32497
- // ../../packages/persistence/src/history-preview.ts
32498
- import { existsSync as existsSync4 } from "fs";
33334
+ // ../../packages/persistence/src/forward-health.ts
33335
+ import { readFileSync as readFileSync7 } from "fs";
32499
33336
  import { join as join9 } from "path";
33337
+ var FAILURES = /* @__PURE__ */ new Set([
33338
+ "unauthorized",
33339
+ "forbidden",
33340
+ "unreachable"
33341
+ ]);
33342
+ var BREAKER_COOLDOWN_MS = 3e4;
33343
+ function parseForwardHealth(raw, nowMs) {
33344
+ try {
33345
+ const parsed2 = JSON.parse(raw);
33346
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33347
+ const record2 = parsed2;
33348
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33349
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33350
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33351
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33352
+ } catch {
33353
+ return null;
33354
+ }
33355
+ }
33356
+ function isForwardPaused(health, nowMs) {
33357
+ const openedAtMs = health?.openedAtMs ?? null;
33358
+ if (openedAtMs === null) return false;
33359
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33360
+ }
33361
+
33362
+ // ../../packages/persistence/src/history-backfill.ts
33363
+ import { existsSync as existsSync4 } from "fs";
33364
+ import { join as join10 } from "path";
33365
+
33366
+ // ../../packages/persistence/src/history-preview.ts
33367
+ import { existsSync as existsSync5 } from "fs";
33368
+ import { join as join11 } from "path";
32500
33369
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32501
33370
 
33371
+ // ../../packages/persistence/src/history-sync-state.ts
33372
+ import { readFileSync as readFileSync8 } from "fs";
33373
+ import { join as join12 } from "path";
33374
+
32502
33375
  // ../../packages/persistence/src/store-symlinks.ts
32503
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32504
- import { dirname as dirname3, join as join10, resolve } from "path";
33376
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33377
+ import { dirname as dirname3, join as join13, resolve } from "path";
32505
33378
  var STORE_DB = "the store database (including the prompt corpus)";
32506
33379
  var STORE_SETTINGS = "your settings file";
32507
33380
  function storeContents(home) {
@@ -32510,7 +33383,7 @@ function storeContents(home) {
32510
33383
  [settingsDir(home), STORE_SETTINGS],
32511
33384
  [dataDir(home), STORE_DB],
32512
33385
  [keysDir(home), "the vault key"],
32513
- [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
33386
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32514
33387
  [dbPath(home), STORE_DB]
32515
33388
  ]);
32516
33389
  }
@@ -32525,7 +33398,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
32525
33398
  holds,
32526
33399
  // existsSync follows the link, so a target that is gone reads as
32527
33400
  // absent here while lstat above still sees the link itself.
32528
- missing: !existsSync5(path),
33401
+ missing: !existsSync6(path),
32529
33402
  mode: targetMode(path, platform2)
32530
33403
  }
32531
33404
  ];
@@ -32562,62 +33435,26 @@ import {
32562
33435
  // ../../packages/persistence/src/vault/key-provider.ts
32563
33436
  import { execFileSync } from "child_process";
32564
33437
  import { randomBytes as randomBytes2 } from "crypto";
32565
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32566
- import { join as join11 } from "path";
33438
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33439
+ import { join as join14 } from "path";
32567
33440
 
32568
33441
  // ../../packages/persistence/src/vault/vault.ts
32569
33442
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32570
33443
 
32571
33444
  // ../../packages/persistence/src/warn-era-cap.ts
32572
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32573
- import { join as join12 } from "path";
33445
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33446
+ import { join as join15 } from "path";
32574
33447
  var MARKER = "warn-era-capped";
32575
33448
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32576
33449
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32577
- const marker = join12(dataDir2, MARKER);
32578
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33450
+ const marker = join15(dataDir2, MARKER);
33451
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32579
33452
  const capped = db.policies.capCategoryActions();
32580
33453
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32581
33454
  `, { mode: DATA_FILE_MODE });
32582
33455
  return { capped };
32583
33456
  }
32584
33457
 
32585
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32586
- function hashProjectKey(projectKey) {
32587
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32588
- }
32589
- function toIngestHit(hit) {
32590
- return {
32591
- host: hit.host,
32592
- kind: hit.kind,
32593
- name: hit.name,
32594
- category: hit.category,
32595
- trust: hit.trust,
32596
- network: hit.network,
32597
- method: hit.method,
32598
- transport: hit.transport,
32599
- url: hit.url,
32600
- template: hit.template,
32601
- dataClass: hit.dataClass,
32602
- site: {
32603
- file: hit.site.file,
32604
- line: hit.site.line,
32605
- dynamic: hit.site.dynamic,
32606
- vendored: hit.site.vendored
32607
- }
32608
- };
32609
- }
32610
- function toEgressIngestRequest(input2) {
32611
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32612
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32613
- return {
32614
- projectKey: hashProjectKey(input2.projectKey),
32615
- project: input2.project,
32616
- reconcile,
32617
- hits: hits.map(toIngestHit)
32618
- };
32619
- }
32620
-
32621
33458
  // ../../packages/remote/src/http.ts
32622
33459
  import { request as httpRequest } from "http";
32623
33460
  import { request as httpsRequest } from "https";
@@ -32801,10 +33638,10 @@ function parsed(schema, body, route) {
32801
33638
  }
32802
33639
  function withoutTrailingSlashes(endpoint) {
32803
33640
  let end = endpoint.length;
32804
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33641
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32805
33642
  return endpoint.slice(0, end);
32806
33643
  }
32807
- var SLASH = "/".charCodeAt(0);
33644
+ var SLASH2 = "/".charCodeAt(0);
32808
33645
  function createRemoteClient(options) {
32809
33646
  const base = withoutTrailingSlashes(options.endpoint);
32810
33647
  const url2 = (route) => `${base}${route}`;
@@ -32897,6 +33734,7 @@ function createRemoteClient(options) {
32897
33734
  url: url2(ROUTES.shares),
32898
33735
  body: JSON.stringify(validated.data)
32899
33736
  });
33737
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32900
33738
  okBody(response);
32901
33739
  },
32902
33740
  async pollCommand() {
@@ -32919,19 +33757,51 @@ function createRemoteClient(options) {
32919
33757
  };
32920
33758
  }
32921
33759
 
32922
- // ../../packages/plugin-runtime/src/attached/failure.ts
33760
+ // ../../packages/remote/src/failure-kind.ts
32923
33761
  function statusOf(err) {
32924
33762
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32925
33763
  const { status } = err;
32926
33764
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32927
33765
  return status >= 100 && status <= 599 ? status : null;
32928
33766
  }
32929
- function classifyFailure(err) {
32930
- switch (statusOf(err)) {
33767
+ function nameOf(err) {
33768
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33769
+ return typeof err.name === "string" ? err.name : null;
33770
+ }
33771
+ function classifyRemoteFailure(err) {
33772
+ switch (nameOf(err)) {
33773
+ case "RemoteRouteAbsent":
33774
+ return "route-absent";
33775
+ case "RemoteRequestInvalid":
33776
+ return "invalid-request";
33777
+ case "RemoteResponseInvalid":
33778
+ return "rejected";
33779
+ default:
33780
+ break;
33781
+ }
33782
+ const status = statusOf(err);
33783
+ if (status === null) return "unreachable";
33784
+ switch (status) {
32931
33785
  case 401:
32932
33786
  return "unauthorized";
32933
33787
  case 403:
32934
33788
  return "forbidden";
33789
+ case 429:
33790
+ return "unreachable";
33791
+ case 404:
33792
+ return "unreachable";
33793
+ default:
33794
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33795
+ }
33796
+ }
33797
+
33798
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33799
+ function classifyFailure(err) {
33800
+ switch (classifyRemoteFailure(err)) {
33801
+ case "unauthorized":
33802
+ return "unauthorized";
33803
+ case "forbidden":
33804
+ return "forbidden";
32935
33805
  default:
32936
33806
  return "unreachable";
32937
33807
  }
@@ -32953,11 +33823,11 @@ function withTimeout(promise2, ms) {
32953
33823
  }
32954
33824
 
32955
33825
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32956
- import { readFileSync as readFileSync8 } from "fs";
32957
- import { join as join13 } from "path";
33826
+ import { readFileSync as readFileSync10 } from "fs";
33827
+ import { join as join16 } from "path";
32958
33828
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32959
33829
  function forwardDropsPath(dataDir2) {
32960
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33830
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
32961
33831
  }
32962
33832
  function recordForwardDrops(dataDir2, count, nowMs) {
32963
33833
  if (count <= 0) return;
@@ -32975,7 +33845,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
32975
33845
  }
32976
33846
  function readForwardDrops(dataDir2) {
32977
33847
  try {
32978
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33848
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
32979
33849
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
32980
33850
  const record2 = parsed2;
32981
33851
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -32993,13 +33863,12 @@ function readForwardDrops(dataDir2) {
32993
33863
 
32994
33864
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32995
33865
  import { randomUUID as randomUUID15 } from "crypto";
32996
- import { readFileSync as readFileSync14 } from "fs";
32997
33866
  import { readFile, rename, writeFile } from "fs/promises";
32998
- import { join as join22 } from "path";
33867
+ import { join as join26 } from "path";
32999
33868
 
33000
33869
  // ../../packages/plugin-sdk/src/config.ts
33001
- import { existsSync as existsSync7 } from "fs";
33002
- import { join as join14 } from "path";
33870
+ import { existsSync as existsSync8 } from "fs";
33871
+ import { join as join17 } from "path";
33003
33872
 
33004
33873
  // ../../packages/plugin-sdk/src/provider-env.ts
33005
33874
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33053,8 +33922,8 @@ function resolveProvider() {
33053
33922
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33054
33923
  try {
33055
33924
  ensureLayoutDirSync(base);
33056
- const settingsFile = join14(settingsDir(base), "settings.json");
33057
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33925
+ const settingsFile = join17(settingsDir(base), "settings.json");
33926
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33058
33927
  } catch {
33059
33928
  }
33060
33929
  migrateLegacyLayout(base);
@@ -33077,9 +33946,9 @@ function resolveProviderSafe(resolveProviderFn) {
33077
33946
  }
33078
33947
 
33079
33948
  // ../../packages/plugin-sdk/src/config-inventory.ts
33080
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33949
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33081
33950
  import { homedir as homedir2 } from "os";
33082
- import { basename as basename4, join as join16 } from "path";
33951
+ import { basename as basename4, join as join19 } from "path";
33083
33952
 
33084
33953
  // ../../packages/detections/src/egress/registry.ts
33085
33954
  var EXTRACTOR_VERSION = "1";
@@ -36208,8 +37077,8 @@ function maskText(text) {
36208
37077
  }
36209
37078
 
36210
37079
  // ../../packages/plugin-sdk/src/repo.ts
36211
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36212
- import { basename as basename3, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37080
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37081
+ import { basename as basename3, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36213
37082
  function resolveRepoIdentity(cwd) {
36214
37083
  try {
36215
37084
  const root = findGitRoot(cwd);
@@ -36259,7 +37128,7 @@ function resolveGitBranch(cwd) {
36259
37128
  try {
36260
37129
  const root = findGitRoot(cwd);
36261
37130
  if (!root) return void 0;
36262
- const dotGit = join15(root, ".git");
37131
+ const dotGit = join18(root, ".git");
36263
37132
  let gitdir;
36264
37133
  try {
36265
37134
  gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
@@ -36267,7 +37136,7 @@ function resolveGitBranch(cwd) {
36267
37136
  return void 0;
36268
37137
  }
36269
37138
  if (gitdir === void 0) return void 0;
36270
- const head = safeRead(join15(gitdir, "HEAD"));
37139
+ const head = safeRead(join18(gitdir, "HEAD"));
36271
37140
  if (!head) return void 0;
36272
37141
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
36273
37142
  } catch {
@@ -36277,41 +37146,41 @@ function resolveGitBranch(cwd) {
36277
37146
  function resolveWorktreeGitdir(root, dotGitFile) {
36278
37147
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
36279
37148
  if (!target) return void 0;
36280
- return isAbsolute(target) ? target : join15(root, target);
37149
+ return isAbsolute(target) ? target : join18(root, target);
36281
37150
  }
36282
37151
  function findGitRoot(start) {
36283
37152
  let dir = start;
36284
37153
  for (; ; ) {
36285
- if (existsSync8(join15(dir, ".git"))) return dir;
37154
+ if (existsSync9(join18(dir, ".git"))) return dir;
36286
37155
  const parent = dirname4(dir);
36287
37156
  if (parent === dir) return void 0;
36288
37157
  dir = parent;
36289
37158
  }
36290
37159
  }
36291
37160
  function resolveGitContext(root) {
36292
- const dotGit = join15(root, ".git");
37161
+ const dotGit = join18(root, ".git");
36293
37162
  try {
36294
37163
  if (statSync6(dotGit).isDirectory()) {
36295
- return { configPath: join15(dotGit, "config"), headRoot: root };
37164
+ return { configPath: join18(dotGit, "config"), headRoot: root };
36296
37165
  }
36297
37166
  } catch {
36298
37167
  return void 0;
36299
37168
  }
36300
37169
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36301
37170
  if (!target) return void 0;
36302
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36303
- if (existsSync8(join15(gitdir, "config"))) {
36304
- return { configPath: join15(gitdir, "config"), headRoot: root };
37171
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
37172
+ if (existsSync9(join18(gitdir, "config"))) {
37173
+ return { configPath: join18(gitdir, "config"), headRoot: root };
36305
37174
  }
36306
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
37175
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
36307
37176
  if (!commonRaw) return void 0;
36308
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
37177
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
36309
37178
  const headRoot = basename3(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36310
- return { configPath: join15(commonGitDir, "config"), headRoot };
37179
+ return { configPath: join18(commonGitDir, "config"), headRoot };
36311
37180
  }
36312
37181
  function safeRead(path) {
36313
37182
  try {
36314
- return readFileSync9(path, "utf8");
37183
+ return readFileSync11(path, "utf8");
36315
37184
  } catch {
36316
37185
  return void 0;
36317
37186
  }
@@ -36373,31 +37242,31 @@ function resolveConfigInventory(input2) {
36373
37242
  };
36374
37243
  try {
36375
37244
  const home = input2.homeDir ?? homedir2();
36376
- const claudeDir = join16(home, ".claude");
37245
+ const claudeDir = join19(home, ".claude");
36377
37246
  const repo = resolveRepoIdentity(input2.cwd);
36378
37247
  const repoIdentity = repo?.url ?? input2.cwd;
36379
37248
  const projectSource = `project:${repoIdentity}`;
36380
- collectSettingsHooks(scan2, join16(claudeDir, "settings.json"), "user");
36381
- collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.json"), "project");
36382
- collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.local.json"), "local");
37249
+ collectSettingsHooks(scan2, join19(claudeDir, "settings.json"), "user");
37250
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.json"), "project");
37251
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.local.json"), "local");
36383
37252
  const projectOrigin = { scope: "project", project: repoIdentity };
36384
- collectMcpFile(scan2, join16(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
36385
- collectUserClaudeJson(scan2, join16(home, ".claude.json"), input2.cwd, repoIdentity);
36386
- collectMcpFile(scan2, join16(claudeDir, "settings.json"), { scope: "user" });
36387
- collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.json"), projectOrigin);
36388
- collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.local.json"), {
37253
+ collectMcpFile(scan2, join19(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
37254
+ collectUserClaudeJson(scan2, join19(home, ".claude.json"), input2.cwd, repoIdentity);
37255
+ collectMcpFile(scan2, join19(claudeDir, "settings.json"), { scope: "user" });
37256
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.json"), projectOrigin);
37257
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.local.json"), {
36389
37258
  scope: "local",
36390
37259
  project: repoIdentity
36391
37260
  });
36392
37261
  collectConfigFiles(scan2, claudeDir, input2.cwd);
36393
- collectSkillsDir(scan2, join16(claudeDir, "skills"), { source: "local", scope: "user" });
36394
- collectSkillsDir(scan2, join16(input2.cwd, ".claude", "skills"), {
37262
+ collectSkillsDir(scan2, join19(claudeDir, "skills"), { source: "local", scope: "user" });
37263
+ collectSkillsDir(scan2, join19(input2.cwd, ".claude", "skills"), {
36395
37264
  source: projectSource,
36396
37265
  scope: "project"
36397
37266
  });
36398
37267
  collectInstalledPlugins(scan2, claudeDir);
36399
37268
  collectMarketplaceSkills(scan2, claudeDir);
36400
- collectSkillsDir(scan2, join16(input2.cwd, "skills"), { source: projectSource, scope: "project" });
37269
+ collectSkillsDir(scan2, join19(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36401
37270
  scan2.skills = dedupeSkills(scan2.skills);
36402
37271
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
36403
37272
  } catch (err) {
@@ -36526,7 +37395,7 @@ function projectEntryFor(projects, cwd) {
36526
37395
  return void 0;
36527
37396
  }
36528
37397
  function collectPluginManifestMcp(scan2, installPath, origin) {
36529
- const manifestPath = join16(installPath, ".claude-plugin", "plugin.json");
37398
+ const manifestPath = join19(installPath, ".claude-plugin", "plugin.json");
36530
37399
  const raw = readOptional(manifestPath);
36531
37400
  if (raw === void 0) return;
36532
37401
  try {
@@ -36534,7 +37403,7 @@ function collectPluginManifestMcp(scan2, installPath, origin) {
36534
37403
  if (typeof parsed2 !== "object" || parsed2 === null) return;
36535
37404
  const declared = parsed2.mcpServers;
36536
37405
  if (typeof declared === "string" && declared.length > 0) {
36537
- collectMcpFile(scan2, join16(installPath, declared), origin, { recordErrors: true });
37406
+ collectMcpFile(scan2, join19(installPath, declared), origin, { recordErrors: true });
36538
37407
  } else {
36539
37408
  collectMcpObject(scan2, declared, manifestPath, origin);
36540
37409
  }
@@ -36551,14 +37420,14 @@ var SETTINGS_KEY_LABELS = [
36551
37420
  ["statusLine", "status line"]
36552
37421
  ];
36553
37422
  function collectConfigFiles(scan2, claudeDir, cwd) {
36554
- settingsConfigFile(scan2, join16(claudeDir, "settings.json"), "user", "User settings");
36555
- settingsConfigFile(scan2, join16(cwd, ".claude", "settings.json"), "project", "Project settings");
36556
- settingsConfigFile(scan2, join16(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
36557
- memoryConfigFile(scan2, join16(claudeDir, "CLAUDE.md"), "user", "User memory");
36558
- memoryConfigFile(scan2, join16(cwd, "CLAUDE.md"), "project", "Project memory");
36559
- mcpJsonConfigFile(scan2, join16(cwd, ".mcp.json"));
36560
- dirConfigFile(scan2, join16(cwd, ".claude", "commands"), "Slash commands", "command");
36561
- dirConfigFile(scan2, join16(cwd, ".claude", "agents"), "Subagents", "subagent");
37423
+ settingsConfigFile(scan2, join19(claudeDir, "settings.json"), "user", "User settings");
37424
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.json"), "project", "Project settings");
37425
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
37426
+ memoryConfigFile(scan2, join19(claudeDir, "CLAUDE.md"), "user", "User memory");
37427
+ memoryConfigFile(scan2, join19(cwd, "CLAUDE.md"), "project", "Project memory");
37428
+ mcpJsonConfigFile(scan2, join19(cwd, ".mcp.json"));
37429
+ dirConfigFile(scan2, join19(cwd, ".claude", "commands"), "Slash commands", "command");
37430
+ dirConfigFile(scan2, join19(cwd, ".claude", "agents"), "Subagents", "subagent");
36562
37431
  }
36563
37432
  function configFileEntry(path, scope, kind) {
36564
37433
  try {
@@ -36633,7 +37502,7 @@ function countMarkdownFiles(dir, depth) {
36633
37502
  let count = 0;
36634
37503
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
36635
37504
  if (dirent.name.startsWith(".")) continue;
36636
- if (dirent.isDirectory()) count += countMarkdownFiles(join16(dir, dirent.name), depth + 1);
37505
+ if (dirent.isDirectory()) count += countMarkdownFiles(join19(dir, dirent.name), depth + 1);
36637
37506
  else if (dirent.name.endsWith(".md")) count += 1;
36638
37507
  }
36639
37508
  return count;
@@ -36646,7 +37515,7 @@ function collectSkillsDir(scan2, dir, origin) {
36646
37515
  return;
36647
37516
  }
36648
37517
  for (const name of names) {
36649
- const skillFile = join16(dir, name, "SKILL.md");
37518
+ const skillFile = join19(dir, name, "SKILL.md");
36650
37519
  try {
36651
37520
  const raw = readOptional(skillFile);
36652
37521
  if (raw === void 0) continue;
@@ -36655,7 +37524,7 @@ function collectSkillsDir(scan2, dir, origin) {
36655
37524
  name: front.name ?? name,
36656
37525
  source: origin.source,
36657
37526
  scope: origin.scope,
36658
- location: join16(dir, name),
37527
+ location: join19(dir, name),
36659
37528
  updatedAt: statSync7(skillFile).mtime.toISOString()
36660
37529
  };
36661
37530
  const version2 = front.version ?? origin.defaultVersion;
@@ -36686,7 +37555,7 @@ function parseFrontmatter(raw) {
36686
37555
  return out;
36687
37556
  }
36688
37557
  function collectInstalledPlugins(scan2, claudeDir) {
36689
- const manifestPath = join16(claudeDir, "plugins", "installed_plugins.json");
37558
+ const manifestPath = join19(claudeDir, "plugins", "installed_plugins.json");
36690
37559
  const raw = readOptional(manifestPath);
36691
37560
  if (raw === void 0) return;
36692
37561
  let plugins;
@@ -36711,7 +37580,7 @@ function collectInstalledPlugins(scan2, claudeDir) {
36711
37580
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
36712
37581
  seen.add(installPath);
36713
37582
  const version2 = install.version;
36714
- const hooksPath = join16(installPath, "hooks", "hooks.json");
37583
+ const hooksPath = join19(installPath, "hooks", "hooks.json");
36715
37584
  const hooksRaw = readOptional(hooksPath);
36716
37585
  if (hooksRaw !== void 0) {
36717
37586
  try {
@@ -36731,22 +37600,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
36731
37600
  }
36732
37601
  const origin = { source: marketplace, scope: "plugin", pluginName };
36733
37602
  if (typeof version2 === "string") origin.defaultVersion = version2;
36734
- collectSkillsDir(scan2, join16(installPath, "skills"), origin);
37603
+ collectSkillsDir(scan2, join19(installPath, "skills"), origin);
36735
37604
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
36736
- collectMcpFile(scan2, join16(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
37605
+ collectMcpFile(scan2, join19(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
36737
37606
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
36738
37607
  }
36739
37608
  }
36740
37609
  }
36741
37610
  function collectMarketplaceSkills(scan2, claudeDir) {
36742
- for (const mp of readMarketplaces(join16(claudeDir, "plugins", "known_marketplaces.json"))) {
37611
+ for (const mp of readMarketplaces(join19(claudeDir, "plugins", "known_marketplaces.json"))) {
36743
37612
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
36744
- collectSkillsDir(scan2, join16(mp.installLocation, "skills"), {
37613
+ collectSkillsDir(scan2, join19(mp.installLocation, "skills"), {
36745
37614
  source: mp.name,
36746
37615
  scope: "plugin"
36747
37616
  });
36748
- collectPluginSkillDirs(scan2, join16(mp.installLocation, "plugins"), mp.name);
36749
- collectPluginSkillDirs(scan2, join16(mp.installLocation, "external_plugins"), mp.name);
37617
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "plugins"), mp.name);
37618
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "external_plugins"), mp.name);
36750
37619
  }
36751
37620
  }
36752
37621
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -36757,7 +37626,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
36757
37626
  return;
36758
37627
  }
36759
37628
  for (const plugin of plugins) {
36760
- collectSkillsDir(scan2, join16(pluginsDir, plugin, "skills"), {
37629
+ collectSkillsDir(scan2, join19(pluginsDir, plugin, "skills"), {
36761
37630
  source: marketplace,
36762
37631
  scope: "plugin",
36763
37632
  pluginName: plugin
@@ -36811,7 +37680,7 @@ function dedupeMcpServers(servers) {
36811
37680
  }
36812
37681
  function readOptional(path) {
36813
37682
  try {
36814
- return readFileSync10(path, "utf8");
37683
+ return readFileSync12(path, "utf8");
36815
37684
  } catch {
36816
37685
  return void 0;
36817
37686
  }
@@ -36839,17 +37708,52 @@ function offersMaintenance(gateway, member) {
36839
37708
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36840
37709
 
36841
37710
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36842
- import { existsSync as existsSync9 } from "fs";
37711
+ import { existsSync as existsSync10 } from "fs";
36843
37712
  import { fileURLToPath } from "url";
36844
37713
  import { Worker } from "worker_threads";
36845
37714
 
37715
+ // ../../packages/plugin-sdk/src/host-floor.ts
37716
+ import { readFileSync as readFileSync14 } from "fs";
37717
+ import { join as join21 } from "path";
37718
+
37719
+ // ../../packages/plugin-sdk/src/model-governance.ts
37720
+ import {
37721
+ closeSync as closeSync2,
37722
+ fstatSync,
37723
+ mkdirSync as mkdirSync2,
37724
+ openSync as openSync2,
37725
+ readFileSync as readFileSync13,
37726
+ readSync,
37727
+ writeFileSync as writeFileSync5
37728
+ } from "fs";
37729
+ import { join as join20 } from "path";
37730
+ var TAIL_BYTES = 256 * 1024;
37731
+
37732
+ // ../../packages/plugin-sdk/src/host-floor.ts
37733
+ var HOST_FEATURE = {
37734
+ ModelSwitch: "model-switch",
37735
+ VaultPointerDisplay: "vault-pointer-display"
37736
+ };
37737
+ var HOST_FLOORS = {
37738
+ [HOST_FEATURE.ModelSwitch]: {
37739
+ label: "model-switch protection",
37740
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37741
+ since: "2.1.251"
37742
+ },
37743
+ [HOST_FEATURE.VaultPointerDisplay]: {
37744
+ label: "vault pointer display",
37745
+ hookEvents: ["MessageDisplay"],
37746
+ since: "2.1.152"
37747
+ }
37748
+ };
37749
+
36846
37750
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36847
37751
  var import_ignore = __toESM(require_ignore(), 1);
36848
- import { readFileSync as readFileSync11 } from "fs";
36849
- import { join as join17 } from "path";
37752
+ import { readFileSync as readFileSync15 } from "fs";
37753
+ import { join as join22 } from "path";
36850
37754
  function readIgnoreLayer(dir, filename, anchorLen) {
36851
37755
  try {
36852
- return { matcher: (0, import_ignore.default)().add(readFileSync11(join17(dir, filename), "utf8")), anchorLen };
37756
+ return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
36853
37757
  } catch {
36854
37758
  return void 0;
36855
37759
  }
@@ -36905,31 +37809,18 @@ function resolveInventoryContext(input2) {
36905
37809
  return ctx;
36906
37810
  }
36907
37811
 
36908
- // ../../packages/plugin-sdk/src/model-governance.ts
36909
- import {
36910
- closeSync as closeSync2,
36911
- fstatSync,
36912
- mkdirSync as mkdirSync2,
36913
- openSync as openSync2,
36914
- readFileSync as readFileSync12,
36915
- readSync,
36916
- writeFileSync as writeFileSync5
36917
- } from "fs";
36918
- import { join as join18 } from "path";
36919
- var TAIL_BYTES = 256 * 1024;
36920
-
36921
37812
  // ../../packages/plugin-sdk/src/nudge.ts
36922
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36923
- import { join as join19 } from "path";
37813
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
37814
+ import { join as join23 } from "path";
36924
37815
  var SESSION_START_MARKER = "session-start-last";
36925
37816
  function claimSessionStart(dataDir2, sessionId) {
36926
37817
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
36927
37818
  }
36928
37819
  function claimOncePerSession(dataDir2, marker, sessionId) {
36929
37820
  if (!sessionId) return true;
36930
- const path = join19(dataDir2, marker);
37821
+ const path = join23(dataDir2, marker);
36931
37822
  try {
36932
- if (readFileSync13(path, "utf8") === sessionId) return false;
37823
+ if (readFileSync16(path, "utf8") === sessionId) return false;
36933
37824
  } catch {
36934
37825
  }
36935
37826
  try {
@@ -36945,8 +37836,8 @@ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
36945
37836
  import { basename as basename5, dirname as dirname5, sep as sep3 } from "path";
36946
37837
 
36947
37838
  // ../../packages/plugin-sdk/src/project-files.ts
36948
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36949
- import { basename as basename6, join as join20 } from "path";
37839
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37840
+ import { basename as basename6, join as join24 } from "path";
36950
37841
  var SKIP_DIRS = /* @__PURE__ */ new Set([
36951
37842
  ".git",
36952
37843
  "node_modules",
@@ -37043,8 +37934,8 @@ function resolveProjectFiles(cwd, opts = {}) {
37043
37934
  }
37044
37935
  if (entry.isDirectory()) {
37045
37936
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
37046
- const fullPath = join20(dir, entry.name);
37047
- if (existsSync10(join20(fullPath, ".git"))) continue;
37937
+ const fullPath = join24(dir, entry.name);
37938
+ if (existsSync11(join24(fullPath, ".git"))) continue;
37048
37939
  if (depth >= bounds.maxDepth) {
37049
37940
  walk.omitted = true;
37050
37941
  continue;
@@ -37145,9 +38036,9 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37145
38036
 
37146
38037
  // ../../packages/plugin-sdk/src/throttle.ts
37147
38038
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37148
- import { join as join21 } from "path";
38039
+ import { join as join25 } from "path";
37149
38040
  function throttled(dataDir2, markerName, windowMs) {
37150
- const marker = join21(dataDir2, markerName);
38041
+ const marker = join25(dataDir2, markerName);
37151
38042
  try {
37152
38043
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
37153
38044
  } catch {
@@ -37174,31 +38065,12 @@ function isServerRejection(err) {
37174
38065
  var FORWARD_BUDGET_MS = 1500;
37175
38066
  var DECISION_PATH_BUDGET_MS = 800;
37176
38067
  var BREAKER_FAILURE_THRESHOLD = 3;
37177
- var BREAKER_COOLDOWN_MS = 3e4;
37178
38068
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
37179
- var FAILURES = /* @__PURE__ */ new Set([
37180
- "unauthorized",
37181
- "forbidden",
37182
- "unreachable"
37183
- ]);
37184
38069
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
37185
38070
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
37186
- function parseBreakerState(raw, nowMs) {
37187
- try {
37188
- const parsed2 = JSON.parse(raw);
37189
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
37190
- const record2 = parsed2;
37191
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
37192
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
37193
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
37194
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
37195
- } catch {
37196
- return null;
37197
- }
37198
- }
37199
38071
  function createForwardPolicy(deps) {
37200
38072
  const now = deps.now ?? (() => Date.now());
37201
- const file2 = join22(deps.dir, STATE_FILENAME);
38073
+ const file2 = join26(deps.dir, STATE_FILENAME);
37202
38074
  let state = null;
37203
38075
  let loading = null;
37204
38076
  async function readState() {
@@ -37208,7 +38080,7 @@ function createForwardPolicy(deps) {
37208
38080
  } catch {
37209
38081
  return { ...CLOSED };
37210
38082
  }
37211
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
38083
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
37212
38084
  }
37213
38085
  async function load() {
37214
38086
  if (state !== null) return state;
@@ -37254,7 +38126,7 @@ function createForwardPolicy(deps) {
37254
38126
  };
37255
38127
  const at = now();
37256
38128
  if (current.openedAtMs !== null) {
37257
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
38129
+ if (isForwardPaused(current, at)) {
37258
38130
  return { ok: false, reason: "breaker-open" };
37259
38131
  }
37260
38132
  await persist({
@@ -37791,7 +38663,18 @@ var AttachedDataGateway = class {
37791
38663
  // and the spread above would otherwise drop the field silently — which is
37792
38664
  // exactly what it did, leaving the whole control inert on every device
37793
38665
  // while every test around it stayed green.
37794
- prohibitedModels: cached2.prohibitedModels
38666
+ prohibitedModels: cached2.prohibitedModels,
38667
+ // NAMED for the same reason as the line above, and it is the same defect
38668
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
38669
+ // only the cache carries is dropped in silence. That is what left
38670
+ // `prohibitedModels` inert on every attached device with every test
38671
+ // around it green.
38672
+ //
38673
+ // Taken from the cache rather than merged here, because merging it needs
38674
+ // the device's own SETTING — which is not a bundle field and is not in
38675
+ // scope at this seam. The runtime does that merge, raise-only, where both
38676
+ // values are in hand (createPluginRuntime's ensureInitialized).
38677
+ redactFallback: cached2.redactFallback
37795
38678
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
37796
38679
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
37797
38680
  // it emits, so an 'authored' policy arriving from the control plane
@@ -37919,10 +38802,6 @@ function toolAuditEvent(input2) {
37919
38802
  };
37920
38803
  }
37921
38804
 
37922
- // ../../packages/plugin-runtime/src/attached/history-state.ts
37923
- import { readFileSync as readFileSync15 } from "fs";
37924
- import { join as join23 } from "path";
37925
-
37926
38805
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37927
38806
  import { createHash as createHash6 } from "crypto";
37928
38807
  import { hostname as hostname5 } from "os";
@@ -37931,6 +38810,10 @@ import { hostname as hostname5 } from "os";
37931
38810
  var CORRELATION_ID = EventMetadata.shape.correlationId;
37932
38811
  var TRACE_ID = EventMetadata.shape.traceId;
37933
38812
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
38813
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
38814
+
38815
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
38816
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
37934
38817
 
37935
38818
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37936
38819
  import { spawn } from "child_process";
@@ -37962,14 +38845,14 @@ function spawnDetached(scriptPath) {
37962
38845
  }
37963
38846
 
37964
38847
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37965
- import { readFileSync as readFileSync16 } from "fs";
38848
+ import { readFileSync as readFileSync17 } from "fs";
37966
38849
  var manifestBuildCache = /* @__PURE__ */ new Map();
37967
38850
  function readManifestBuild(manifestUrl, packageName) {
37968
38851
  const key = manifestUrl.href;
37969
38852
  if (!manifestBuildCache.has(key)) {
37970
38853
  let build;
37971
38854
  try {
37972
- const manifest = JSON.parse(readFileSync16(manifestUrl, "utf8"));
38855
+ const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
37973
38856
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
37974
38857
  } catch {
37975
38858
  build = void 0;
@@ -37996,7 +38879,7 @@ function createPluginBlock(build, policyStore) {
37996
38879
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37997
38880
  import { randomUUID as randomUUID16 } from "crypto";
37998
38881
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
37999
- import { join as join24 } from "path";
38882
+ import { join as join27 } from "path";
38000
38883
 
38001
38884
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38002
38885
  import { rename as rename2 } from "fs/promises";
@@ -38020,7 +38903,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38020
38903
 
38021
38904
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38022
38905
  function createPolicyStore(dir = dataDir()) {
38023
- const file2 = join24(dir, "policy-cache.json");
38906
+ const file2 = join27(dir, "policy-cache.json");
38024
38907
  async function read() {
38025
38908
  try {
38026
38909
  const raw = await readFile2(file2, "utf8");
@@ -38251,11 +39134,11 @@ function readStorePosture(dbPath2) {
38251
39134
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38252
39135
  import { randomUUID as randomUUID17 } from "crypto";
38253
39136
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38254
- import { join as join25 } from "path";
39137
+ import { join as join28 } from "path";
38255
39138
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38256
39139
  function createPostureStore(dir = settingsDir(), legacyDir) {
38257
- const file2 = join25(dir, "posture-state.json");
38258
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
39140
+ const file2 = join28(dir, "posture-state.json");
39141
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
38259
39142
  async function persist(state) {
38260
39143
  await ensureDataDir(dir);
38261
39144
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38323,8 +39206,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38323
39206
  }
38324
39207
 
38325
39208
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38326
- import { readFileSync as readFileSync17 } from "fs";
38327
- import { join as join26 } from "path";
39209
+ import { readFileSync as readFileSync18 } from "fs";
39210
+ import { join as join29 } from "path";
38328
39211
 
38329
39212
  // ../../packages/plugin-runtime/src/attached/status.ts
38330
39213
  var REFUSAL_LINES = {
@@ -38366,6 +39249,34 @@ function spawnDetached2(scriptPath) {
38366
39249
  child.unref();
38367
39250
  }
38368
39251
 
39252
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
39253
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39254
+
39255
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
39256
+ import { spawn as spawn3 } from "child_process";
39257
+ import { fileURLToPath as fileURLToPath4 } from "url";
39258
+ var CONTENT_RETENTION_MARKER_NAME = "content-retention-last-attempt";
39259
+ var CONTENT_RETENTION_SCRIPT_NAME = "content-retention.js";
39260
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
39261
+ function triggerContentRetention(config2, deps = {}) {
39262
+ try {
39263
+ if (!config2.settings.bodyRetention.enabled) return;
39264
+ const isThrottled = deps.isThrottled ?? ((dir) => throttled(dir, CONTENT_RETENTION_MARKER_NAME, CONTENT_RETENTION_THROTTLE_MS));
39265
+ if (isThrottled(config2.dataDir)) return;
39266
+ const scriptPath = fileURLToPath4(
39267
+ deps.scriptUrl ?? new URL(CONTENT_RETENTION_SCRIPT_NAME, import.meta.url)
39268
+ );
39269
+ (deps.spawnChild ?? spawnDetached3)(scriptPath);
39270
+ } catch {
39271
+ }
39272
+ }
39273
+ function spawnDetached3(scriptPath) {
39274
+ const child = spawn3(process.execPath, [scriptPath], { detached: true, stdio: "ignore" });
39275
+ child.on("error", () => {
39276
+ });
39277
+ child.unref();
39278
+ }
39279
+
38369
39280
  // ../../packages/plugin-runtime/src/attached/factory.ts
38370
39281
  import { hostname as hostname6 } from "os";
38371
39282
 
@@ -38882,6 +39793,7 @@ async function handleSessionStart(input2, config2 = loadConfig()) {
38882
39793
  }
38883
39794
  triggerPolicySync(config2);
38884
39795
  triggerHistorySync(config2);
39796
+ triggerContentRetention(config2);
38885
39797
  if (input2.harnessVersion !== void 0 && offersMaintenance(gateway, "staleBinaryNotice")) {
38886
39798
  return { staleBinaryNotice: gateway.staleBinaryNotice(input2.harnessVersion) };
38887
39799
  }
@@ -38963,9 +39875,9 @@ function pluginBuild() {
38963
39875
  }
38964
39876
 
38965
39877
  // src/history/reconcile-trigger.ts
38966
- import { spawn as spawn3 } from "child_process";
38967
- import { dirname as dirname6, join as join28 } from "path";
38968
- import { fileURLToPath as fileURLToPath4 } from "url";
39878
+ import { spawn as spawn4 } from "child_process";
39879
+ import { dirname as dirname6, join as join31 } from "path";
39880
+ import { fileURLToPath as fileURLToPath5 } from "url";
38969
39881
 
38970
39882
  // src/history/tail.ts
38971
39883
  import { createHash as createHash7 } from "crypto";
@@ -38974,11 +39886,11 @@ import {
38974
39886
  fstatSync as fstatSync2,
38975
39887
  mkdirSync as mkdirSync5,
38976
39888
  openSync as openSync3,
38977
- readFileSync as readFileSync18,
39889
+ readFileSync as readFileSync19,
38978
39890
  readSync as readSync2,
38979
39891
  writeFileSync as writeFileSync8
38980
39892
  } from "fs";
38981
- import { join as join27 } from "path";
39893
+ import { join as join30 } from "path";
38982
39894
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
38983
39895
  function safeSessionId(sessionId) {
38984
39896
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
@@ -38994,8 +39906,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
38994
39906
  try {
38995
39907
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
38996
39908
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
38997
- const here = dirname6(fileURLToPath4(import.meta.url));
38998
- const child = spawn3(process.execPath, [join28(here, "reconcile.js"), sessionId, transcriptPath], {
39909
+ const here = dirname6(fileURLToPath5(import.meta.url));
39910
+ const child = spawn4(process.execPath, [join31(here, "reconcile.js"), sessionId, transcriptPath], {
38999
39911
  detached: true,
39000
39912
  stdio: "ignore"
39001
39913
  });
@@ -39005,9 +39917,9 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
39005
39917
  }
39006
39918
 
39007
39919
  // src/history/transcripts.ts
39008
- import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync19, readSync as readSync3, statSync as statSync10 } from "fs";
39920
+ import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync20, readSync as readSync3, statSync as statSync10 } from "fs";
39009
39921
  import { homedir as homedir3 } from "os";
39010
- import { join as join29 } from "path";
39922
+ import { join as join32 } from "path";
39011
39923
  function isRecord(value) {
39012
39924
  return typeof value === "object" && value !== null;
39013
39925
  }
@@ -39081,8 +39993,8 @@ function getString(record2, key) {
39081
39993
  }
39082
39994
 
39083
39995
  // src/hooks/store-health.ts
39084
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync20, writeFileSync as writeFileSync9 } from "fs";
39085
- import { dirname as dirname7, join as join30 } from "path";
39996
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync21, writeFileSync as writeFileSync9 } from "fs";
39997
+ import { dirname as dirname7, join as join33 } from "path";
39086
39998
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
39087
39999
  function markerDirs(dataDir2) {
39088
40000
  return [dataDir2, dirname7(dataDir2)];
@@ -39090,7 +40002,7 @@ function markerDirs(dataDir2) {
39090
40002
  function alreadyClaimed(dirs, marker, sessionId) {
39091
40003
  return dirs.some((dir) => {
39092
40004
  try {
39093
- return readFileSync20(join30(dir, marker), "utf8") === sessionId;
40005
+ return readFileSync21(join33(dir, marker), "utf8") === sessionId;
39094
40006
  } catch {
39095
40007
  return false;
39096
40008
  }
@@ -39100,7 +40012,7 @@ function recordClaim(dirs, marker, sessionId) {
39100
40012
  for (const dir of dirs) {
39101
40013
  try {
39102
40014
  mkdirSync6(dir, { recursive: true, mode: DATA_DIR_MODE });
39103
- writeFileSync9(join30(dir, marker), sessionId, { mode: DATA_FILE_MODE });
40015
+ writeFileSync9(join33(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39104
40016
  return;
39105
40017
  } catch {
39106
40018
  }
@@ -39144,7 +40056,7 @@ function harnessVersion() {
39144
40056
  const manifestPath = process.argv[2];
39145
40057
  if (!manifestPath) return void 0;
39146
40058
  try {
39147
- const manifest = JSON.parse(readFileSync21(manifestPath, "utf8"));
40059
+ const manifest = JSON.parse(readFileSync22(manifestPath, "utf8"));
39148
40060
  return typeof manifest.version === "string" ? manifest.version : void 0;
39149
40061
  } catch {
39150
40062
  return void 0;