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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,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: {
@@ -23752,9 +23952,9 @@ function isVaultConsentValid(consent) {
23752
23952
  }
23753
23953
 
23754
23954
  // ../../packages/schema/src/zod/local.ts
23755
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23955
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23756
23956
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23757
- var HISTORY_SYNC_PAYLOAD_VERSION = 2;
23957
+ var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23758
23958
  var RunMode = external_exports.enum(["standalone", "attached"]);
23759
23959
  var ControlPlaneConnection = external_exports.object({
23760
23960
  endpoint: external_exports.string().min(1),
@@ -23777,6 +23977,15 @@ function isHistorySyncConsentValid(consent, endpoint) {
23777
23977
  if (consent === void 0 || endpoint === void 0) return false;
23778
23978
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23779
23979
  }
23980
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23981
+ var BodyRetention = external_exports.object({
23982
+ enabled: external_exports.boolean().default(false),
23983
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23984
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23985
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23986
+ // candidate set that is already bounded by "delivered, or never owed".
23987
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23988
+ }).meta({ id: "BodyRetention" });
23780
23989
  var WorkspaceSettings = external_exports.object({
23781
23990
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23782
23991
  runMode: RunMode.default("standalone"),
@@ -23820,12 +24029,18 @@ var WorkspaceSettings = external_exports.object({
23820
24029
  // covers the current payload and must be re-granted.
23821
24030
  modelJudgeConsent: ModelJudgeConsent.optional(),
23822
24031
  // Records that the user consented to the DEFERRED send — the outbox — along
23823
- // with the payload shape and the endpoint they agreed to. Since payload v2
23824
- // that covers both the pre-attach backlog and undelivered captures (which
23825
- // carry prompt/reply text in `content`); the key name predates the widening.
23826
- // Absent until granted, and a grant for a different endpoint or an older
23827
- // payload no longer counts.
23828
- historySyncConsent: HistorySyncConsent.optional()
24032
+ // with the payload shape and the endpoint they agreed to. Since payload v3
24033
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
24034
+ // carry prompt/reply/tool-output text in `content`; the key name predates
24035
+ // both widenings. Absent until granted, and a grant for a different endpoint
24036
+ // or an older payload no longer counts.
24037
+ historySyncConsent: HistorySyncConsent.optional(),
24038
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
24039
+ // body never removes the row or its findings.
24040
+ bodyRetention: BodyRetention.default({
24041
+ enabled: false,
24042
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
24043
+ })
23829
24044
  });
23830
24045
  function defaultWorkspaceSettings() {
23831
24046
  return WorkspaceSettings.parse({});
@@ -23920,12 +24135,15 @@ function toCaptureAttributes(event) {
23920
24135
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23921
24136
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23922
24137
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24138
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23923
24139
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23924
24140
  // has ever populated either), but every legacy metadata key still rides
23925
24141
  // the bag rather than being silently dropped — CaptureAttributes'
23926
24142
  // `.catchall(z.unknown())` carries the long tail.
23927
24143
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23928
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24144
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24145
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24146
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23929
24147
  };
23930
24148
  }
23931
24149
  function captureDefinitionVersion(finding2) {
@@ -23953,10 +24171,22 @@ var ManagedSettingKey = external_exports.enum([
23953
24171
  "vaultInlineReveal",
23954
24172
  "modelJudgeConsent",
23955
24173
  "dataSharesInPlace",
23956
- "redactFallback"
24174
+ "redactFallback",
24175
+ // Pins the toggle and the day count together — see BodyRetention on why the
24176
+ // two are one unit. An administrator mandating a window wants the count
24177
+ // enforced with it, not one a user can widen while the toggle stays on.
24178
+ "bodyRetention"
23957
24179
  ]).meta({ id: "ManagedSettingKey" });
24180
+ function isManagedSettingKey(value) {
24181
+ return ManagedSettingKey.safeParse(value).success;
24182
+ }
23958
24183
  var ManagedSettingsValues = external_exports.object({
23959
24184
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24185
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24186
+ // plain, non-strict objects: a key under either that this build does not know
24187
+ // is stripped and nothing reports it. The unknown-value split in
24188
+ // ManagedSettings below classifies top-level names only, so it stops at
24189
+ // these boundaries.
23960
24190
  controlPlane: external_exports.object({
23961
24191
  endpoint: external_exports.string().min(1),
23962
24192
  label: external_exports.string().min(1).optional()
@@ -23967,7 +24197,8 @@ var ManagedSettingsValues = external_exports.object({
23967
24197
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23968
24198
  modelJudgeConsent: external_exports.boolean().optional(),
23969
24199
  dataSharesInPlace: external_exports.boolean().optional(),
23970
- redactFallback: RedactFallback.optional()
24200
+ redactFallback: RedactFallback.optional(),
24201
+ bodyRetention: BodyRetention.optional()
23971
24202
  }).meta({ id: "ManagedSettingsValues" });
23972
24203
  var ManagedSettings = external_exports.object({
23973
24204
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23975,11 +24206,59 @@ var ManagedSettings = external_exports.object({
23975
24206
  // decision from a bug. Absent renders as a generic "your organization".
23976
24207
  organization: external_exports.string().min(1).optional(),
23977
24208
  // What the administrator pinned.
23978
- values: ManagedSettingsValues.default({}),
24209
+ //
24210
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24211
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24212
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24213
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24214
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24215
+ // exactly the file an administrator is most likely to write while a fleet
24216
+ // is mid-upgrade.
24217
+ //
24218
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24219
+ // file, which is the outcome the lock half already rejected — an older
24220
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24221
+ // value still fails, because the nested schema is re-run over the known
24222
+ // subset and its issues are re-raised on this parse.
24223
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23979
24224
  // Which of those the user may not change. A key here with no matching value
23980
24225
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23981
24226
  // the user may still override. The two are separable on purpose.
23982
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24227
+ //
24228
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24229
+ // build does not know is dropped from the locked set and reported, never a
24230
+ // reason to refuse the file. The same shape reaches an older build whenever
24231
+ // an administrator locks a key a newer build added, and refusing it there
24232
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24233
+ // the fleets most likely to carry a version skew. A name outside the enum
24234
+ // is still never HONOURED: the lockable set stays explicit above.
24235
+ lockedFields: external_exports.array(external_exports.string()).default([])
24236
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24237
+ const known = [];
24238
+ const unknown2 = [];
24239
+ for (const name of lockedFields) {
24240
+ if (isManagedSettingKey(name)) known.push(name);
24241
+ else unknown2.push(name);
24242
+ }
24243
+ const knownValues = /* @__PURE__ */ Object.create(null);
24244
+ const unknownValues = [];
24245
+ for (const [name, value] of Object.entries(values)) {
24246
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24247
+ else unknownValues.push(name);
24248
+ }
24249
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24250
+ if (!pinned.success) {
24251
+ for (const issue2 of pinned.error.issues)
24252
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24253
+ return external_exports.NEVER;
24254
+ }
24255
+ return {
24256
+ ...rest,
24257
+ values: pinned.data,
24258
+ lockedFields: known,
24259
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24260
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24261
+ };
23983
24262
  }).meta({ id: "ManagedSettings" });
23984
24263
 
23985
24264
  // ../../packages/schema/src/zod/project-files.ts
@@ -24103,7 +24382,11 @@ var FindingsTimeseriesPoint = external_exports.object({
24103
24382
  timestamp: external_exports.iso.date(),
24104
24383
  critical: external_exports.number().int().nonnegative(),
24105
24384
  high: external_exports.number().int().nonnegative(),
24106
- medium: external_exports.number().int().nonnegative()
24385
+ medium: external_exports.number().int().nonnegative(),
24386
+ // Optional and additive, so a producer written against the earlier
24387
+ // three-series contract keeps validating. A consumer plotting it resolves the
24388
+ // absent case itself — the chart point requires a number.
24389
+ low: external_exports.number().int().nonnegative().optional()
24107
24390
  }).meta({ id: "FindingsTimeseriesPoint" });
24108
24391
  var FindingsTimeseriesResponse = external_exports.object({
24109
24392
  range: TimeRange,
@@ -24129,6 +24412,10 @@ var ResolvedFeedItem = external_exports.object({
24129
24412
  findingKey: external_exports.string(),
24130
24413
  ruleId: external_exports.string(),
24131
24414
  severity: Severity,
24415
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24416
+ // identifies the file: a bare path matches the same name in every repo.
24417
+ // Optional and additive; empty when the event carried no repo.
24418
+ repo: external_exports.string().optional(),
24132
24419
  path: external_exports.string(),
24133
24420
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24134
24421
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24234,7 +24521,23 @@ var SaveSettingsInput = external_exports.object({
24234
24521
  modelJudgeConsent: ModelJudgeConsentChoice,
24235
24522
  historySyncConsent: HistorySyncConsentChoice,
24236
24523
  vaultConsent: external_exports.string(),
24237
- vaultInlineReveal: external_exports.string()
24524
+ vaultInlineReveal: external_exports.string(),
24525
+ // Widened to `string` like its neighbours rather than typed as
24526
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24527
+ // the call site, so the domain check receives the type it was written for.
24528
+ //
24529
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24530
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24531
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24532
+ // trade against. The real cost runs the other way and is the part worth
24533
+ // knowing: a value this schema admits and the domain enum then rejects lands
24534
+ // on the action's shared refusal, which names NO field, where a shape
24535
+ // rejection reaches `malformedInput` and names the schema key.
24536
+ redactFallback: external_exports.string(),
24537
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24538
+ // `BodyRetention`'s and the action checks it there, so there is one place
24539
+ // that decides what a legal horizon is rather than two that can drift.
24540
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24238
24541
  });
24239
24542
  var AttachInput = external_exports.object({
24240
24543
  endpoint: external_exports.string(),
@@ -24406,6 +24709,52 @@ function reviewSeverityRank(reasons) {
24406
24709
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24407
24710
  }
24408
24711
 
24712
+ // ../../packages/schema/src/zod/web-capture.ts
24713
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24714
+ var WebUsage = external_exports.object({
24715
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24716
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24717
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24718
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24719
+ });
24720
+ var WebToolCall = external_exports.object({
24721
+ toolUseId: external_exports.string().min(1),
24722
+ toolName: external_exports.string().min(1),
24723
+ target: external_exports.string().optional(),
24724
+ isError: external_exports.boolean().optional(),
24725
+ inputSize: external_exports.number().int().nonnegative().optional(),
24726
+ outputSize: external_exports.number().int().nonnegative().optional()
24727
+ });
24728
+ var WebExchange = external_exports.object({
24729
+ messageId: external_exports.string().min(1),
24730
+ startedAt: external_exports.iso.datetime(),
24731
+ model: external_exports.string().optional(),
24732
+ usage: WebUsage.optional(),
24733
+ usageSource: WebUsageSource,
24734
+ stopReason: external_exports.string().optional(),
24735
+ conversationId: external_exports.string().optional(),
24736
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24737
+ toolCalls: external_exports.array(WebToolCall).default([]),
24738
+ // Absent when the adapter recovered no text. Capped by the caller at
24739
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24740
+ // short capture is never mistaken for a short reply.
24741
+ responseText: external_exports.string().optional(),
24742
+ truncated: external_exports.boolean().default(false)
24743
+ });
24744
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24745
+ var WebCaptureStatus = external_exports.object({
24746
+ patched: external_exports.boolean(),
24747
+ live: external_exports.boolean(),
24748
+ blind: external_exports.boolean(),
24749
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24750
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24751
+ parseFailures: external_exports.number().int().nonnegative(),
24752
+ unparsedBodies: external_exports.number().int().nonnegative(),
24753
+ // The adapter-declared JSON key paths that were absent from a real payload —
24754
+ // the earliest signal that a site's contract moved.
24755
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24756
+ });
24757
+
24409
24758
  // ../../packages/persistence/src/paths.ts
24410
24759
  import {
24411
24760
  chmodSync,
@@ -24740,6 +25089,22 @@ function discardStore(file2, backup) {
24740
25089
  }
24741
25090
  }
24742
25091
 
25092
+ // ../../packages/persistence/src/internal/sql-functions.ts
25093
+ var utf8 = new TextDecoder();
25094
+ function akaLower(value) {
25095
+ if (value === null) return null;
25096
+ if (typeof value === "string") return value.toLowerCase();
25097
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25098
+ return utf8.decode(value).toLowerCase();
25099
+ }
25100
+ function registerSqlFunctions(db) {
25101
+ db.function(
25102
+ "aka_lower",
25103
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25104
+ akaLower
25105
+ );
25106
+ }
25107
+
24743
25108
  // ../../packages/persistence/src/internal/sql-text.ts
24744
25109
  function escapeLikePattern(s) {
24745
25110
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24824,6 +25189,11 @@ function schemaObjectExists(db, kind, name) {
24824
25189
  function indexExists(db, name) {
24825
25190
  return schemaObjectExists(db, "index", name);
24826
25191
  }
25192
+ function indexColumns(db, name) {
25193
+ if (!indexExists(db, name)) return [];
25194
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25195
+ return columns.map((c) => c.name).filter((c) => c !== null);
25196
+ }
24827
25197
  function columnNames(db, table, opts) {
24828
25198
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24829
25199
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24885,6 +25255,647 @@ function mapRowsTolerant(rows, map2) {
24885
25255
  return out;
24886
25256
  }
24887
25257
 
25258
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25259
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25260
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25261
+
25262
+ // ../../packages/persistence/src/sync-failure.ts
25263
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25264
+ function syncFailureRejectCondition(column = "sync_failure") {
25265
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25266
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
25267
+ }
25268
+
25269
+ // ../../packages/persistence/src/repositories/history-sync.ts
25270
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25271
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25272
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25273
+ var COUNTED_EVENT_TYPES = [
25274
+ ...STRUCTURAL_EVENT_TYPES,
25275
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25276
+ ];
25277
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25278
+ var PARTITION_BUCKETS = `
25279
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25280
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25281
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25282
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25283
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25284
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25285
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25286
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25287
+ -- added later lands in no bucket and fails the sum assertion, instead
25288
+ -- of silently joining this one.
25289
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25290
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25291
+ THEN 1 ELSE 0 END) AS failed,
25292
+ COUNT(*) AS total`;
25293
+ var COUNTED_SCOPE = `
25294
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25295
+ AND (
25296
+ event_type IN (${TYPE_LIST})
25297
+ OR synced_at IS NOT NULL
25298
+ OR outbox_owed = 1
25299
+ )`;
25300
+ var SKIPPED = -1;
25301
+ var ROW_COLUMNS = `id,
25302
+ parent_id AS parentId,
25303
+ root_session_id AS rootSessionId,
25304
+ event_type AS eventType,
25305
+ host_id AS hostId,
25306
+ harness_id AS harnessId,
25307
+ source_project_id AS sourceProjectId,
25308
+ started_at AS startedAt,
25309
+ ended_at AS endedAt,
25310
+ severity,
25311
+ priority,
25312
+ content,
25313
+ content_hash AS contentHash,
25314
+ attributes`;
25315
+ var SqliteHistorySyncRepository = class {
25316
+ constructor(db) {
25317
+ this.db = db;
25318
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25319
+ this.sessionsStmt = db.prepare(
25320
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25321
+ FROM audit_events
25322
+ WHERE synced_at IS NULL
25323
+ AND event_type IN (${TYPE_LIST})
25324
+ AND started_at < :before
25325
+ GROUP BY sessionId
25326
+ ORDER BY earliest
25327
+ LIMIT :limit`
25328
+ );
25329
+ this.rowsStmt = db.prepare(
25330
+ `SELECT ${ROW_COLUMNS}
25331
+ FROM audit_events
25332
+ WHERE synced_at IS NULL
25333
+ AND event_type IN (${TYPE_LIST})
25334
+ AND started_at < :before
25335
+ AND COALESCE(root_session_id, id) = :sessionId
25336
+ ORDER BY (event_type = 'session') DESC, started_at
25337
+ LIMIT :limit`
25338
+ );
25339
+ this.captureRowsStmt = db.prepare(
25340
+ `SELECT ${ROW_COLUMNS}
25341
+ FROM audit_events
25342
+ WHERE synced_at IS NULL
25343
+ AND sync_claimed_at IS NULL
25344
+ AND outbox_owed = 1
25345
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25346
+ AND started_at < :before
25347
+ ORDER BY started_at
25348
+ LIMIT :limit`
25349
+ );
25350
+ this.markOwedStmt = db.prepare(
25351
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25352
+ );
25353
+ this.markCaptureBacklogOwedStmt = db.prepare(
25354
+ `UPDATE audit_events SET outbox_owed = 1
25355
+ WHERE synced_at IS NULL
25356
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25357
+ AND started_at < :before`
25358
+ );
25359
+ this.stampStmt = db.prepare(
25360
+ `UPDATE audit_events
25361
+ SET synced_at = :at,
25362
+ sync_claimed_at = NULL,
25363
+ sync_failed_at = :failedAt,
25364
+ sync_failure = :failure
25365
+ WHERE id = :id`
25366
+ );
25367
+ this.claimRowStmt = db.prepare(
25368
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25369
+ );
25370
+ this.releaseRowStmt = db.prepare(
25371
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25372
+ );
25373
+ this.releaseStaleClaimsStmt = db.prepare(
25374
+ `UPDATE audit_events SET sync_claimed_at = NULL
25375
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25376
+ );
25377
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25378
+ FROM audit_events${COUNTED_SCOPE}`);
25379
+ this.partitionByKindStmt = db.prepare(
25380
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25381
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25382
+ GROUP BY event_type`
25383
+ );
25384
+ this.countsStmt = db.prepare(
25385
+ `SELECT
25386
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25387
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25388
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25389
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25390
+ THEN 1 ELSE 0 END) AS skipped,
25391
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25392
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25393
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25394
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25395
+ FROM audit_events
25396
+ WHERE event_type IN (${TYPE_LIST})`
25397
+ );
25398
+ this.captureSkipCountStmt = db.prepare(
25399
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25400
+ // way the structural totals are. The split exists because a refusal is
25401
+ // terminal only against the deployment that gave it, and the structural
25402
+ // re-arm frees it on a change of deployment. The capture lane has no such
25403
+ // escape: re-arming a capture would offer one deployment's undelivered
25404
+ // prompts, with their text, to a deployment that never saw them, which is
25405
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25406
+ // reasons mean the same thing — this row will not be sent — and splitting
25407
+ // them would put refused captures in a bucket nothing reads and nothing
25408
+ // frees.
25409
+ `SELECT COUNT(*) AS skipped
25410
+ FROM audit_events
25411
+ WHERE synced_at = ${String(SKIPPED)}
25412
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25413
+ );
25414
+ this.fingerprintStmt = db.prepare(
25415
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25416
+ FROM history_sync WHERE id = 1`
25417
+ );
25418
+ this.setFingerprintStmt = db.prepare(
25419
+ `UPDATE history_sync
25420
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25421
+ WHERE id = 1`
25422
+ );
25423
+ this.disownCapturesStmt = db.prepare(
25424
+ `UPDATE audit_events SET outbox_owed = NULL
25425
+ WHERE outbox_owed IS NOT NULL
25426
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25427
+ AND started_at < :attachedAt`
25428
+ );
25429
+ this.rearmStmt = db.prepare(
25430
+ `UPDATE audit_events
25431
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25432
+ WHERE (synced_at > 0
25433
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25434
+ AND event_type IN (${TYPE_LIST})`
25435
+ );
25436
+ this.claimStmt = db.prepare(
25437
+ `UPDATE history_sync
25438
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25439
+ WHERE id = 1
25440
+ AND (owner_pid IS NULL
25441
+ OR heartbeat_at IS NULL
25442
+ OR heartbeat_at < :staleBefore
25443
+ OR heartbeat_at > :now)`
25444
+ );
25445
+ this.heartbeatStmt = db.prepare(
25446
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25447
+ );
25448
+ this.releaseStmt = db.prepare(
25449
+ `UPDATE history_sync
25450
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25451
+ WHERE id = 1 AND owner_pid = :pid`
25452
+ );
25453
+ this.closeWindowStmt = db.prepare(
25454
+ `UPDATE audit_events
25455
+ SET synced_at = ${String(SKIPPED)},
25456
+ sync_failed_at = :at,
25457
+ sync_failure = 'detached_undelivered'
25458
+ WHERE synced_at IS NULL
25459
+ AND event_type IN (${TYPE_LIST})
25460
+ AND started_at >= :attachedAt`
25461
+ );
25462
+ this.releaseBoundaryStmt = db.prepare(
25463
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25464
+ );
25465
+ this.freezeBoundaryStmt = db.prepare(
25466
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25467
+ );
25468
+ this.leaseStmt = db.prepare(
25469
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25470
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25471
+ FROM history_sync WHERE id = 1`
25472
+ );
25473
+ this.inspectionsStmt = db.prepare(
25474
+ `SELECT d.rule_id AS ruleId,
25475
+ d.name AS ruleName,
25476
+ d.version AS ruleVersion,
25477
+ d.category AS category,
25478
+ d.severity AS severity,
25479
+ f.span_start AS spanStart,
25480
+ f.span_end AS spanEnd,
25481
+ f.masked_match AS maskedMatch,
25482
+ f.action_taken AS actionTaken,
25483
+ f.confidence AS confidence
25484
+ FROM inspection_findings f
25485
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25486
+ WHERE f.audit_event_id = :auditEventId
25487
+ ORDER BY f.span_start, f.id`
25488
+ );
25489
+ }
25490
+ db;
25491
+ ensureRowStmt;
25492
+ sessionsStmt;
25493
+ rowsStmt;
25494
+ stampStmt;
25495
+ countsStmt;
25496
+ fingerprintStmt;
25497
+ setFingerprintStmt;
25498
+ rearmStmt;
25499
+ claimStmt;
25500
+ heartbeatStmt;
25501
+ releaseStmt;
25502
+ leaseStmt;
25503
+ inspectionsStmt;
25504
+ closeWindowStmt;
25505
+ releaseBoundaryStmt;
25506
+ freezeBoundaryStmt;
25507
+ captureRowsStmt;
25508
+ markOwedStmt;
25509
+ markCaptureBacklogOwedStmt;
25510
+ captureSkipCountStmt;
25511
+ disownCapturesStmt;
25512
+ partitionStmt;
25513
+ partitionByKindStmt;
25514
+ claimRowStmt;
25515
+ releaseRowStmt;
25516
+ releaseStaleClaimsStmt;
25517
+ /**
25518
+ * The masked detections recorded against one tool call.
25519
+ *
25520
+ * These travel with the event because a tool call's target is not
25521
+ * re-inspectable from the event alone — unlike a capture, where the text
25522
+ * itself is re-scannable. What crosses is the masked match and the rule that
25523
+ * produced it, never the value.
25524
+ */
25525
+ inspectionsFor(auditEventId) {
25526
+ return allRows(this.inspectionsStmt, { auditEventId });
25527
+ }
25528
+ /**
25529
+ * Sessions with structural rows still to send, oldest first.
25530
+ *
25531
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25532
+ * read. Anything recorded after the machine attached is the live forward
25533
+ * path's to deliver; this drain exists for what was recorded before it, and a
25534
+ * row both paths send is at best a duplicate request and at worst — for a
25535
+ * session root — an overwrite of the inventory ids the live path resolved.
25536
+ */
25537
+ pendingSessions(limit, before) {
25538
+ return allRows(this.sessionsStmt, { limit, before }).map(
25539
+ (r) => r.sessionId
25540
+ );
25541
+ }
25542
+ /** One session's undelivered structural rows within the backlog, root first. */
25543
+ pendingRows(sessionId, limit, before) {
25544
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25545
+ }
25546
+ /**
25547
+ * Captures this machine still owes the deployment, oldest first.
25548
+ *
25549
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25550
+ * by a time window — see captureRowsStmt for why a window could not express
25551
+ * this. `before` is the grace window that leaves a just-recorded capture to
25552
+ * the live path.
25553
+ */
25554
+ pendingCaptureRows(limit, before) {
25555
+ return allRows(this.captureRowsStmt, { limit, before });
25556
+ }
25557
+ /**
25558
+ * Record that a capture is OWED to the deployment.
25559
+ *
25560
+ * Written by the attached forward path when a live send did not confirm
25561
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25562
+ * a fact rather than an inference: the machine was attached, the send did not
25563
+ * land, so the row is owed — which no time window can state, because the same
25564
+ * window that holds the rows a past attachment left owed also holds every
25565
+ * capture recorded while the machine was DETACHED, and those were never
25566
+ * offered to anyone.
25567
+ *
25568
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25569
+ * out of the drain's read.
25570
+ */
25571
+ markCaptureOwed(id) {
25572
+ this.markOwedStmt.run({ id });
25573
+ }
25574
+ /**
25575
+ * Mark every capture already on disk as owed, as of `before`.
25576
+ *
25577
+ * The consent-time backfill, called once from `aka attach` when a human
25578
+ * grants existing-history consent — never from an ongoing drain pass, and
25579
+ * never inferred from a boundary that could later move. `before` is the
25580
+ * caller's own "now" at the moment consent was granted, so what this marks
25581
+ * is exactly the backlog the consent prompt already counted, not whatever a
25582
+ * later re-attach or key rotation might widen it to.
25583
+ *
25584
+ * Returns how many rows matched, for the caller to log or test against. Not a
25585
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25586
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25587
+ */
25588
+ markCaptureBacklogOwed(before) {
25589
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25590
+ }
25591
+ /**
25592
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25593
+ *
25594
+ * CLEARS any failure reason in the same statement. A row that failed against
25595
+ * one deployment and then landed is delivered, and leaving the reason behind
25596
+ * would leave the store holding two contradictory answers about one row —
25597
+ * with the surface free to render either.
25598
+ */
25599
+ markSynced(ids, atMs) {
25600
+ this.stampAll(ids, atMs, null);
25601
+ }
25602
+ /**
25603
+ * Record that THIS MACHINE cannot express the row on the wire.
25604
+ *
25605
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25606
+ * payload, or a body the client itself refused to send. It fails identically
25607
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25608
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25609
+ * is retried; marking those would turn one outage into permanent data loss.
25610
+ */
25611
+ markSkipped(ids, atMs) {
25612
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25613
+ }
25614
+ /**
25615
+ * Record that THIS DEPLOYMENT refused the row.
25616
+ *
25617
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25618
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25619
+ * row is outstanding rather than why. What separates them is the reason, and
25620
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25621
+ * on one body, so it is terminal only for as long as this machine points at
25622
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25623
+ *
25624
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25625
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25626
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25627
+ */
25628
+ markRefused(ids, atMs) {
25629
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25630
+ }
25631
+ eachInTransaction(ids, run) {
25632
+ if (ids.length === 0) return;
25633
+ withTransaction(
25634
+ this.db,
25635
+ () => {
25636
+ for (const id of ids) run(id);
25637
+ },
25638
+ "IMMEDIATE"
25639
+ );
25640
+ }
25641
+ stampAll(ids, value, failure, failedAtMs) {
25642
+ if (ids.length === 0) return;
25643
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25644
+ withTransaction(
25645
+ this.db,
25646
+ () => {
25647
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25648
+ },
25649
+ "IMMEDIATE"
25650
+ );
25651
+ }
25652
+ /**
25653
+ * Claim rows as in-flight.
25654
+ *
25655
+ * Advisory in exactly the sense the lease is: it records that a send is in
25656
+ * progress so a surface can say so, and a lost claim costs a row showing as
25657
+ * queued while it is actually being sent. It is not exclusion — the far side
25658
+ * settles a duplicate on the row id.
25659
+ */
25660
+ claimRows(ids, atMs) {
25661
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25662
+ }
25663
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25664
+ releaseRows(ids) {
25665
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25666
+ }
25667
+ /**
25668
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25669
+ *
25670
+ * A process killed between claiming and settling leaves rows claimed with
25671
+ * nothing left to settle them. Without this they read as "sending" for ever.
25672
+ */
25673
+ releaseStaleClaims(staleBefore) {
25674
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25675
+ }
25676
+ /**
25677
+ * Every tracked row in exactly one delivery state.
25678
+ *
25679
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25680
+ * pick up now", which is a different question from "what state is this row
25681
+ * in" — and a machine that has never attached has no boundary to pass, so
25682
+ * requiring one would force a caller to invent one and report the whole store
25683
+ * as queued.
25684
+ */
25685
+ /**
25686
+ * The same partition, one row per kind that a lane carries.
25687
+ *
25688
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25689
+ * scope decides which rows exist at all, so a kind that has never been
25690
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25691
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25692
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25693
+ * different things.
25694
+ */
25695
+ partitionByKind() {
25696
+ return allRows(
25697
+ this.partitionByKindStmt,
25698
+ {}
25699
+ ).map((row) => ({
25700
+ kind: row.kind,
25701
+ queued: row.queued ?? 0,
25702
+ inProgress: row.inProgress ?? 0,
25703
+ synced: row.synced ?? 0,
25704
+ failed: row.failed ?? 0,
25705
+ refused: row.refused ?? 0,
25706
+ detached: row.detached ?? 0,
25707
+ total: row.total ?? 0
25708
+ }));
25709
+ }
25710
+ partition() {
25711
+ const row = getRow(this.partitionStmt, {});
25712
+ return {
25713
+ queued: row?.queued ?? 0,
25714
+ inProgress: row?.inProgress ?? 0,
25715
+ synced: row?.synced ?? 0,
25716
+ failed: row?.failed ?? 0,
25717
+ refused: row?.refused ?? 0,
25718
+ detached: row?.detached ?? 0,
25719
+ total: row?.total ?? 0
25720
+ };
25721
+ }
25722
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25723
+ counts(before) {
25724
+ const row = getRow(this.countsStmt, { before });
25725
+ const captures = getRow(this.captureSkipCountStmt);
25726
+ return {
25727
+ pending: row?.pending ?? 0,
25728
+ sent: row?.sent ?? 0,
25729
+ skipped: row?.skipped ?? 0,
25730
+ refused: row?.refused ?? 0,
25731
+ detached: row?.detached ?? 0,
25732
+ capturesSkipped: captures?.skipped ?? 0
25733
+ };
25734
+ }
25735
+ /**
25736
+ * The deployment the current stamps were made against, and where its backlog
25737
+ * ends.
25738
+ *
25739
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25740
+ * machine that has never drained is — and every writer below seeds the row
25741
+ * before it needs one, so nothing depends on this creating it. Keeping the
25742
+ * write off the gate path matters because the gate runs on every pass while a
25743
+ * write has to take the database's write lock.
25744
+ */
25745
+ deployment() {
25746
+ const row = getRow(
25747
+ this.fingerprintStmt
25748
+ );
25749
+ return {
25750
+ fingerprint: row?.fingerprint ?? void 0,
25751
+ backlogBefore: row?.backlogBefore ?? void 0
25752
+ };
25753
+ }
25754
+ /**
25755
+ * Point the ledger at a different deployment, discarding what it recorded
25756
+ * about the previous one.
25757
+ *
25758
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25759
+ * machine has just left are undelivered as far as the new one is concerned.
25760
+ * All four in one transaction, so a crash between them cannot leave stamps
25761
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25762
+ * a disown with no re-mark to follow it.
25763
+ *
25764
+ * The boundary is written HERE and only here, which is what freezes it: a
25765
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25766
+ * unchanged, so this never runs and the backlog does not widen back over rows
25767
+ * the live path has since delivered.
25768
+ *
25769
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25770
+ * granted existing-history consent for the deployment this call is arming —
25771
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25772
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25773
+ * apart. Passed only when that grant is valid, since this method has no way
25774
+ * to check consent itself and must not mark a row owed for a machine that
25775
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25776
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25777
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25778
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25779
+ * on the cleared side of that bound — and the re-mark in the same
25780
+ * transaction is what puts those rows back. A crash between the two cannot
25781
+ * strand the ledger disowned with nothing re-marked — the transaction either
25782
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25783
+ * committed re-enters this method on the very next pass. Omit it (the
25784
+ * structural-only tests do) to exercise the disown in isolation.
25785
+ *
25786
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25787
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25788
+ * live path can mark a capture owed from the moment `aka attach` writes the
25789
+ * descriptor, before the drain's first pass ever reaches this method, and
25790
+ * such a row sits at or after the bound rather than below it. What keeps the
25791
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25792
+ * bound — disown runs first, re-mark second, both inside the one
25793
+ * transaction above.
25794
+ */
25795
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25796
+ this.ensureRowStmt.run();
25797
+ withTransaction(
25798
+ this.db,
25799
+ () => {
25800
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25801
+ this.rearmStmt.run();
25802
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25803
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25804
+ }
25805
+ if (backfillCapturesBefore !== void 0) {
25806
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25807
+ }
25808
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25809
+ },
25810
+ "IMMEDIATE"
25811
+ );
25812
+ }
25813
+ /**
25814
+ * End the attached period: hand its rows to the live path, and release the
25815
+ * boundary so the next attachment can freeze a new one.
25816
+ *
25817
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25818
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25819
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25820
+ * during the detached period, because the machine is not attached. Rows
25821
+ * recorded in that window sit after the boundary and before the re-attach, so
25822
+ * neither path takes them, and the pending count reports none outstanding.
25823
+ *
25824
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25825
+ * closing attachment's to deliver and are no longer outstanding — that is what
25826
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25827
+ * distinction is not academic: this used to write a delivery TIME, which every
25828
+ * read treats as delivery, so one detach turned a window of undelivered rows
25829
+ * into a window of delivered ones and no surface could tell. It writes the
25830
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25831
+ * "received" stop being the same fact.
25832
+ *
25833
+ * A change of deployment still frees them (see the re-arm), because the next
25834
+ * deployment has seen none of this machine's history — so the rows reach it
25835
+ * exactly as they did when this wrote a delivery time.
25836
+ *
25837
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25838
+ * window unstamped — that half-state would re-send the whole attached period
25839
+ * on the next attach, which is the failure the boundary exists to prevent.
25840
+ */
25841
+ closeAttachedWindow(attachedAtMs, atMs) {
25842
+ this.ensureRowStmt.run();
25843
+ withTransaction(
25844
+ this.db,
25845
+ () => {
25846
+ const row = getRow(this.fingerprintStmt);
25847
+ const from = row?.backlogBefore ?? attachedAtMs;
25848
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25849
+ this.releaseBoundaryStmt.run();
25850
+ },
25851
+ "IMMEDIATE"
25852
+ );
25853
+ }
25854
+ /**
25855
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25856
+ *
25857
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25858
+ * different deployment and therefore discards what was delivered to the old
25859
+ * one: here the recipient is the same, so everything already sent to it stays
25860
+ * sent.
25861
+ */
25862
+ freezeBoundary(backlogBefore) {
25863
+ this.ensureRowStmt.run();
25864
+ this.freezeBoundaryStmt.run({ backlogBefore });
25865
+ }
25866
+ /** Take the claim, or report that someone live already holds it. */
25867
+ claim(pid, host, nowMs, staleAfterMs) {
25868
+ this.ensureRowStmt.run();
25869
+ let taken = false;
25870
+ withTransaction(
25871
+ this.db,
25872
+ () => {
25873
+ const result = this.claimStmt.run({
25874
+ pid,
25875
+ host,
25876
+ now: nowMs,
25877
+ staleBefore: nowMs - staleAfterMs
25878
+ });
25879
+ taken = result.changes === 1;
25880
+ },
25881
+ "IMMEDIATE"
25882
+ );
25883
+ return taken;
25884
+ }
25885
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25886
+ heartbeat(pid, nowMs) {
25887
+ this.heartbeatStmt.run({ now: nowMs, pid });
25888
+ }
25889
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25890
+ release(pid) {
25891
+ this.releaseStmt.run({ pid });
25892
+ }
25893
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25894
+ lease() {
25895
+ return getRow(this.leaseStmt);
25896
+ }
25897
+ };
25898
+
24888
25899
  // ../../packages/persistence/src/migrations.ts
24889
25900
  function describeObject(object2) {
24890
25901
  return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
@@ -24897,7 +25908,7 @@ function createdIndexName(statement) {
24897
25908
  return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
24898
25909
  }
24899
25910
  var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24900
- function applyMigrations(db, file2) {
25911
+ function applyMigrations(db, file2, options = {}) {
24901
25912
  const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24902
25913
  db.exec(
24903
25914
  "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
@@ -24911,6 +25922,7 @@ function applyMigrations(db, file2) {
24911
25922
  );
24912
25923
  for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24913
25924
  if (applied.has(migration.tag)) continue;
25925
+ if (options.skipTags?.has(migration.tag) === true) continue;
24914
25926
  if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24915
25927
  const evidence = evidenceObjects(migration.sql);
24916
25928
  const present = evidence.filter((o) => evidenceExists(db, o));
@@ -25317,10 +26329,62 @@ function ensureSyncedAtColumn(db, table) {
25317
26329
  if (!columns.includes("outbox_owed")) {
25318
26330
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25319
26331
  }
26332
+ if (!columns.includes("sync_failed_at")) {
26333
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26334
+ }
26335
+ if (!columns.includes("sync_failure")) {
26336
+ withTransaction(
26337
+ db,
26338
+ () => {
26339
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26340
+ db.exec(
26341
+ `UPDATE ${table} SET synced_at = NULL
26342
+ WHERE synced_at = -1
26343
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26344
+ );
26345
+ },
26346
+ "IMMEDIATE"
26347
+ );
26348
+ }
25320
26349
  db.exec(
25321
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25322
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26350
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26351
+ BEFORE UPDATE OF sync_failure ON ${table}
26352
+ WHEN ${syncFailureRejectCondition()}
26353
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25323
26354
  );
26355
+ const syncIndexColumns = [
26356
+ "event_type",
26357
+ "synced_at",
26358
+ "sync_claimed_at",
26359
+ "started_at",
26360
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26361
+ // has to be in the index for the read to stay covered — but putting it
26362
+ // ahead of `started_at` would reorder the prefix the structural drain's
26363
+ // reads match on.
26364
+ "sync_failure"
26365
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26366
+ //
26367
+ // The delivery-state read tests it — a capture's state depends on whether a
26368
+ // live forward marked it owed — so carrying it here makes that read covering
26369
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26370
+ // But a sixth column changes what the planner charges for this index, and
26371
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26372
+ // then stops choosing the per-session index for the token rollup and walks
26373
+ // every `llm_call` in the store through the event-type index instead. That
26374
+ // read grows with the store; this one does not.
26375
+ //
26376
+ // 40 ms on the largest store measured, once per render, is a cost worth
26377
+ // paying to leave every other read's plan where it was.
26378
+ ];
26379
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26380
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26381
+ if (!syncIndexMatches) {
26382
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26383
+ db.exec(
26384
+ `CREATE INDEX idx_audit_events_sync
26385
+ ON audit_events (${syncIndexColumns.join(", ")})`
26386
+ );
26387
+ }
25324
26388
  db.exec(
25325
26389
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25326
26390
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25542,7 +26606,11 @@ function buildAuditEvent(row) {
25542
26606
  link: linkParsed?.success ? linkParsed.data : null,
25543
26607
  targetId: row.target_id,
25544
26608
  internal: intToBool(row.internal),
25545
- flagged: intToBool(row.flagged)
26609
+ flagged: intToBool(row.flagged),
26610
+ // Only meaningful when the title came out empty — a row whose body was
26611
+ // expired but whose title fell back to `tool_name` still has something to
26612
+ // render, and flagging it would make the view apologise for nothing.
26613
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25546
26614
  };
25547
26615
  }
25548
26616
  var TIMELINE_COLUMNS = `
@@ -25550,6 +26618,7 @@ var TIMELINE_COLUMNS = `
25550
26618
  event_type,
25551
26619
  started_at,
25552
26620
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26621
+ content_expired_at,
25553
26622
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25554
26623
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25555
26624
  json_extract(attributes, '$.severity') AS severity,
@@ -25676,7 +26745,8 @@ var SqliteActivityRepository = class {
25676
26745
  SELECT 1 FROM audit_events d
25677
26746
  WHERE d.root_session_id = audit_events.id
25678
26747
  AND (d.content LIKE ? ESCAPE '\\'
25679
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26748
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26749
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25680
26750
  );
25681
26751
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25682
26752
  }
@@ -26214,6 +27284,88 @@ var SqliteAuditEventsRepository = class {
26214
27284
  }
26215
27285
  };
26216
27286
 
27287
+ // ../../packages/persistence/src/repositories/body-retention.ts
27288
+ var DEFAULT_BATCH_SIZE = 500;
27289
+ var DEFAULT_MAX_ROWS = 5e4;
27290
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27291
+ var SqliteBodyRetentionRepository = class {
27292
+ constructor(db) {
27293
+ this.db = db;
27294
+ const select = (laneClause) => `
27295
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27296
+ FROM audit_events
27297
+ WHERE content IS NOT NULL
27298
+ AND started_at < :cutoff
27299
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27300
+ ${laneClause}
27301
+ ORDER BY started_at
27302
+ LIMIT :limit`;
27303
+ this.candidatesStmt = this.db.prepare(select(""));
27304
+ this.candidatesSyncSafeStmt = this.db.prepare(
27305
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27306
+ );
27307
+ this.heldBySyncStmt = this.db.prepare(`
27308
+ SELECT COUNT(*) AS n
27309
+ FROM audit_events
27310
+ WHERE content IS NOT NULL
27311
+ AND started_at < :cutoff
27312
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27313
+ AND synced_at IS NULL`);
27314
+ this.expireStmt = this.db.prepare(
27315
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27316
+ );
27317
+ }
27318
+ db;
27319
+ candidatesStmt;
27320
+ candidatesSyncSafeStmt;
27321
+ heldBySyncStmt;
27322
+ expireStmt;
27323
+ /** How many bytes a pass with these options would free, changing nothing. */
27324
+ preview(opts) {
27325
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27326
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27327
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27328
+ return {
27329
+ rowsExpired: rows.length,
27330
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27331
+ rowsHeldBySync: this.countHeldBySync(opts)
27332
+ };
27333
+ }
27334
+ /** Clear eligible bodies, in bounded batches. */
27335
+ expire(opts) {
27336
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27337
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27338
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27339
+ let rowsExpired = 0;
27340
+ let bytesFreed = 0;
27341
+ let done = true;
27342
+ while (rowsExpired < maxRows) {
27343
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27344
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27345
+ if (batch.length === 0) break;
27346
+ withTransaction(
27347
+ this.db,
27348
+ () => {
27349
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27350
+ },
27351
+ "IMMEDIATE"
27352
+ );
27353
+ rowsExpired += batch.length;
27354
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27355
+ if (batch.length < remaining) break;
27356
+ if (rowsExpired >= maxRows) {
27357
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27358
+ }
27359
+ }
27360
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27361
+ }
27362
+ countHeldBySync(opts) {
27363
+ if (opts.sweepSyncLane) return 0;
27364
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27365
+ return row.n;
27366
+ }
27367
+ };
27368
+
26217
27369
  // ../../packages/persistence/src/repositories/classified-data.ts
26218
27370
  var SqliteClassifiedDataRepository = class {
26219
27371
  constructor(db) {
@@ -27014,23 +28166,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
27014
28166
  )`;
27015
28167
 
27016
28168
  // ../../packages/persistence/src/repositories/findings.ts
27017
- var PREVIEW_INSTANCES_PER_GROUP = 200;
27018
- var DEFAULT_LOCATIONS_LIMIT = 100;
27019
- var LOCATION_RULE_IDS_CAP = 20;
27020
- function compareLocationOrder(a, b) {
27021
- return compareFindingGroupOrder(
27022
- {
27023
- severity: a.maxSeverity,
27024
- latestDetectedAt: a.latestDetectedAt,
27025
- id: ""
27026
- },
27027
- {
27028
- severity: b.maxSeverity,
27029
- latestDetectedAt: b.latestDetectedAt,
27030
- id: ""
27031
- }
27032
- );
27033
- }
27034
28169
  var CONCAT_SEP = ",";
27035
28170
  var TUPLE_SEP = "|";
27036
28171
  function splitConcat(value) {
@@ -27059,7 +28194,15 @@ function toFlatFindingRow(r) {
27059
28194
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
27060
28195
  eventId: r.event_id,
27061
28196
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27062
- status: deriveInstanceStatus(r)
28197
+ status: deriveInstanceStatus(r),
28198
+ delivery: deriveFindingDelivery({
28199
+ kind: r.kind,
28200
+ syncedAt: r.synced_at,
28201
+ syncClaimedAt: r.sync_claimed_at,
28202
+ syncFailedAt: r.sync_failed_at,
28203
+ syncFailure: r.sync_failure,
28204
+ outboxOwed: r.outbox_owed
28205
+ })
27063
28206
  };
27064
28207
  }
27065
28208
  function encodeGroupCursor(group) {
@@ -27082,13 +28225,51 @@ function decodeGroupCursor(cursor) {
27082
28225
  return null;
27083
28226
  }
27084
28227
  function firstAfter(sorted, cursor) {
27085
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28228
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
27086
28229
  return index === -1 ? sorted.length : index;
27087
28230
  }
27088
28231
  function findDeepLinked(sorted, page, id) {
27089
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
27090
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28232
+ if (page.some((t) => t.id === id)) return void 0;
28233
+ return sorted.find((t) => t.id === id);
28234
+ }
28235
+ function encodeLocationCursor(location) {
28236
+ const payload = {
28237
+ sev: location.maxSeverity,
28238
+ t: location.latestDetectedAt,
28239
+ r: location.repo,
28240
+ f: location.file
28241
+ };
28242
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28243
+ }
28244
+ function decodeLocationCursor(cursor) {
28245
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28246
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28247
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28248
+ }
28249
+ return null;
27091
28250
  }
28251
+ function firstLocationAfter(sorted, cursor) {
28252
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28253
+ return index === -1 ? sorted.length : index;
28254
+ }
28255
+ function findDeepLinkedLocation(sorted, page, id) {
28256
+ if (page.some((l) => l.id === id)) return void 0;
28257
+ return sorted.find((l) => l.id === id);
28258
+ }
28259
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28260
+ d.severity AS severity, f.masked_match AS masked_match,
28261
+ f.action_taken AS action_taken, f.confidence AS confidence,
28262
+ e.started_at AS occurred_at,
28263
+ e.source_tool AS source_tool,
28264
+ e.repo AS repo,
28265
+ e.file_path AS file,
28266
+ e.tool_name AS tool_name,
28267
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28268
+ e.event_type AS kind, f.finding_key AS finding_key,
28269
+ ${latestResolutionStatusSql("f")} AS latest_status,
28270
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28271
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28272
+ e.outbox_owed AS outbox_owed`;
27092
28273
  var DAY_MS3 = 864e5;
27093
28274
  var SqliteFindingsRepository = class {
27094
28275
  constructor(db) {
@@ -27209,30 +28390,26 @@ var SqliteFindingsRepository = class {
27209
28390
  );
27210
28391
  }
27211
28392
  /**
27212
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27213
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27214
- * attributes bag, rule_id/category/severity from the definition), scoped to
27215
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27216
- * rows this list must never surface), groups by ruleId, computes
27217
- * per-filter-excluded facets, applies the requested filters, and sorts by
27218
- * severity then recency. Filtering
27219
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27220
- * reflect the full filtered set; `items` is the requested
27221
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27222
- * filter, `totals.findings` counts only instances whose derived status was
27223
- * requested, and each item's instance preview is narrowed the same way.
28393
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28394
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28395
+ * list must never surface), with per-filter-excluded facets, the requested
28396
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28397
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28398
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28399
+ * Under a `status` filter, `totals.findings` counts only findings whose
28400
+ * derived status was requested.
28401
+ *
28402
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28403
+ * folding EVERY finding into the numbers a type row and the filters need
28404
+ * (count, severity, category, providers, actions, statuses, latest, search
28405
+ * text). The findings OF a type come from listFindingInstances scoped to
28406
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27224
28407
  *
27225
- * Two reads, neither of which materializes a row per finding:
27226
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27227
- * the group and the filters need (count, providers, actions, statuses,
27228
- * latest, search text);
27229
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27230
- * populate `instances` for the table's expanded rows.
27231
28408
  * The aggregates carry raw DB values and are translated by the same
27232
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27233
- * rule is ever restated in SQL.
28409
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28410
+ * status rule is ever restated in SQL.
27234
28411
  */
27235
- listGroupedFindings(query) {
28412
+ listFindingTypes(query) {
27236
28413
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27237
28414
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27238
28415
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27245,12 +28422,7 @@ var SqliteFindingsRepository = class {
27245
28422
  predicate,
27246
28423
  params: sessionParams
27247
28424
  });
27248
- const rows = this.previewRows(aggregates, {
27249
- sessionId: query.sessionId,
27250
- from: query.from
27251
- });
27252
- const groupable = rows.map(toFlatFindingRow);
27253
- const allGroups = buildFindingGroups(groupable, { aggregates });
28425
+ const allTypes = buildFindingTypes(aggregates);
27254
28426
  const filterOpts = {
27255
28427
  severity: query.severity,
27256
28428
  providers: query.provider,
@@ -27259,30 +28431,25 @@ var SqliteFindingsRepository = class {
27259
28431
  subtype: query.subtype,
27260
28432
  q: query.q
27261
28433
  };
27262
- const facets = computeFindingFacets(allGroups, filterOpts);
27263
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28434
+ const facets = computeFindingFacets(allTypes, filterOpts);
28435
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27264
28436
  const statusFilter = query.status ?? [];
27265
28437
  const totals = {
27266
- findings: sorted.reduce((acc, g) => {
27267
- if (statusFilter.length === 0) return acc + g.instanceCount;
27268
- const agg = aggregates.get(g.id);
27269
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28438
+ findings: sorted.reduce((acc, t) => {
28439
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28440
+ const agg = aggregates.get(t.id);
28441
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27270
28442
  }, 0),
27271
- groups: sorted.length
28443
+ types: sorted.length
27272
28444
  };
27273
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28445
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27274
28446
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27275
28447
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27276
28448
  const page = sorted.slice(start, start + limit);
27277
28449
  const lastOnPage = page.at(-1);
27278
28450
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27279
28451
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27280
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27281
- const narrow = (g) => statusSet ? {
27282
- ...g,
27283
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27284
- } : g;
27285
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28452
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27286
28453
  return Promise.resolve({
27287
28454
  totals,
27288
28455
  facets,
@@ -27293,7 +28460,7 @@ var SqliteFindingsRepository = class {
27293
28460
  }
27294
28461
  /**
27295
28462
  * One row per rule_id, folding EVERY instance of the group into the values
27296
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28463
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27297
28464
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27298
28465
  *
27299
28466
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27347,6 +28514,7 @@ var SqliteFindingsRepository = class {
27347
28514
  providers: query.provider,
27348
28515
  actions: query.action,
27349
28516
  statuses: query.status,
28517
+ deliveries: query.deployment,
27350
28518
  tools: query.tool,
27351
28519
  repo: query.repo,
27352
28520
  file: query.file,
@@ -27387,13 +28555,25 @@ var SqliteFindingsRepository = class {
27387
28555
  });
27388
28556
  }
27389
28557
  /**
27390
- * The same findings folded by location: repository, then file within it.
28558
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27391
28559
  *
27392
28560
  * The grouping keys come from the capturing event's attributes, which is what
27393
- * the local store relates a finding to — there is no finding↔asset row to
27394
- * group by instead. A repo or file the event did not record folds into the
27395
- * empty-string bucket, which the view renders but does not link, since no
27396
- * filter can name it.
28561
+ * the local store relates a finding to; there is no finding↔asset row to group
28562
+ * by instead. A repo or file the event did not record folds into the
28563
+ * empty-string bucket, which is a real location like any other: it is listed,
28564
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28565
+ *
28566
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28567
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28568
+ * list was rebuilt to remove — and two-level pagination inside an
28569
+ * expand/collapse table is what pushed that view to master/detail in the first
28570
+ * place.
28571
+ *
28572
+ * Every filter narrows the FINDINGS and the locations fall out of what
28573
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28574
+ * reports for the same filters scoped to that pair. The view depends on it:
28575
+ * one toolbar sits over both panels precisely because a location owns none of
28576
+ * its fields.
27397
28577
  */
27398
28578
  listFindingLocations(query) {
27399
28579
  const opts = {
@@ -27402,16 +28582,20 @@ var SqliteFindingsRepository = class {
27402
28582
  providers: query.provider,
27403
28583
  actions: query.action,
27404
28584
  statuses: query.status,
28585
+ deliveries: query.deployment,
27405
28586
  tools: query.tool,
27406
28587
  q: query.q
27407
28588
  };
27408
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28589
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28590
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27409
28591
  const byRepo = /* @__PURE__ */ new Map();
28592
+ const accumulator = createInstanceFacetAccumulator(opts);
27410
28593
  let total = 0;
27411
28594
  for (const row of this.scanFindingRows({
27412
28595
  sessionId: query.sessionId,
27413
28596
  from: query.from
27414
28597
  })) {
28598
+ accumulator.add(row);
27415
28599
  if (!matchesInstanceFilters(row, opts)) continue;
27416
28600
  total += 1;
27417
28601
  let files = byRepo.get(row.repo);
@@ -27426,103 +28610,35 @@ var SqliteFindingsRepository = class {
27426
28610
  }
27427
28611
  addToLocation(acc, row);
27428
28612
  }
27429
- let fileCount = 0;
27430
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27431
- fileCount += files.size;
27432
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27433
- file: file2,
27434
- instanceCount: acc.instanceCount,
27435
- maxSeverity: acc.maxSeverity,
27436
- latestDetectedAt: acc.latestDetectedAt,
27437
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27438
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27439
- })).sort(compareLocationOrder);
27440
- const rollup = fileRows.reduce(
27441
- (a, f) => ({
27442
- instanceCount: a.instanceCount + f.instanceCount,
27443
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27444
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27445
- }),
27446
- {
27447
- instanceCount: 0,
27448
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27449
- latestDetectedAt: ""
27450
- }
27451
- );
27452
- const statuses = fileRows.map((f) => f.status);
27453
- const folded = foldGroupStatus(statuses);
27454
- return {
27455
- repo,
27456
- instanceCount: rollup.instanceCount,
27457
- maxSeverity: rollup.maxSeverity,
27458
- latestDetectedAt: rollup.latestDetectedAt,
27459
- ...folded === void 0 ? {} : { status: folded },
27460
- files: fileRows
27461
- };
27462
- });
27463
- repos.sort(compareLocationOrder);
28613
+ const sorted = [];
28614
+ for (const [repo, files] of byRepo) {
28615
+ for (const [file2, acc] of files) {
28616
+ const status = foldGroupStatus(acc.statuses);
28617
+ sorted.push({
28618
+ id: encodeLocationId(repo, file2),
28619
+ repo,
28620
+ file: file2,
28621
+ instanceCount: acc.instanceCount,
28622
+ maxSeverity: acc.maxSeverity,
28623
+ latestDetectedAt: acc.latestDetectedAt,
28624
+ ...status === void 0 ? {} : { status },
28625
+ ruleIds: [...acc.ruleIds]
28626
+ });
28627
+ }
28628
+ }
28629
+ sorted.sort(compareLocationOrder);
28630
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28631
+ const page = sorted.slice(start, start + limit);
28632
+ const lastOnPage = page.at(-1);
28633
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28634
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27464
28635
  return Promise.resolve({
27465
- totals: { findings: total, repos: repos.length, files: fileCount },
27466
- items: repos.slice(0, limit),
27467
- hasMore: repos.length > limit
28636
+ totals: { findings: total, locations: sorted.length },
28637
+ facets: accumulator.facets(),
28638
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28639
+ nextCursor
27468
28640
  });
27469
28641
  }
27470
- /**
27471
- * Each group's newest instances, for the table's expanded rows.
27472
- *
27473
- * ONE index-ordered scan with early termination, and the shape is the point.
27474
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27475
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27476
- * through a temp B-tree to keep a bounded preview of each group, and then
27477
- * sorts the survivors again for the page order. Both sorts grow with the
27478
- * store while the answer does not.
27479
- *
27480
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27481
- * (or the session or window index the scope names — see `findingScanSql`),
27482
- * which is already the order the page wants, and keeps rows per rule until
27483
- * each rule has as many as it can show. The aggregate the caller already holds
27484
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27485
- * per rule, summed, is the number of rows this scan has to find, and it stops
27486
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27487
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27488
- * store with many firing rules widens it. The bound that DOES hold
27489
- * unconditionally is the sorted form's floor: this scan visits at most as
27490
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27491
- * sorted, and stops the moment every rule has its cap, where the sorted form
27492
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27493
- * wanted instances sitting at the tail of the scope — is one pass over
27494
- * everything in scope with a block sort of the id tie-break only, never a
27495
- * sort of the scope, which is still that floor.
27496
- *
27497
- * A row whose rule the aggregate did not see is skipped: the two statements
27498
- * run without a shared snapshot, so a capture landing between them can add a
27499
- * rule here that has no counts there, and the counts are what the group is
27500
- * built from.
27501
- */
27502
- previewRows(aggregates, scope) {
27503
- const wanted = /* @__PURE__ */ new Map();
27504
- let remaining = 0;
27505
- for (const [ruleId, agg] of aggregates) {
27506
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27507
- wanted.set(ruleId, n);
27508
- remaining += n;
27509
- }
27510
- const rows = [];
27511
- if (remaining === 0) return rows;
27512
- const { sql, params } = this.findingScanSql(scope);
27513
- const taken = /* @__PURE__ */ new Map();
27514
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27515
- const want = wanted.get(r.rule_id);
27516
- if (want === void 0) continue;
27517
- const have = taken.get(r.rule_id) ?? 0;
27518
- if (have >= want) continue;
27519
- taken.set(r.rule_id, have + 1);
27520
- rows.push(r);
27521
- remaining -= 1;
27522
- if (remaining === 0) break;
27523
- }
27524
- return rows;
27525
- }
27526
28642
  /**
27527
28643
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27528
28644
  *
@@ -27549,6 +28665,33 @@ var SqliteFindingsRepository = class {
27549
28665
  yield toFlatFindingRow(r);
27550
28666
  }
27551
28667
  }
28668
+ /**
28669
+ * One finding by its own id, or null when no such row exists.
28670
+ *
28671
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28672
+ * the store — and, unlike anything derived from a list page, it resolves a
28673
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28674
+ * deep link needs: the id it carries may name a finding thousands of rows
28675
+ * older than anything a first page holds.
28676
+ *
28677
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28678
+ * RESOLVES an id; whether that row would survive the list's current filters is
28679
+ * a different question, and hiding the target because a filter excludes it is
28680
+ * worse than showing it.
28681
+ *
28682
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28683
+ * type should the list select?" and "what does the drawer show?".
28684
+ */
28685
+ findingInstance(id) {
28686
+ const row = this.db.prepare(
28687
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28688
+ FROM inspection_findings f
28689
+ JOIN audit_events e ON e.id = f.audit_event_id
28690
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28691
+ WHERE f.id = ?`
28692
+ ).get(id);
28693
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28694
+ }
27552
28695
  /**
27553
28696
  * The one statement both instance-level scans run: every finding in scope,
27554
28697
  * joined to its event and definition, newest first.
@@ -27582,17 +28725,7 @@ var SqliteFindingsRepository = class {
27582
28725
  conditions.push("e.started_at >= ?");
27583
28726
  params.push(isoToEpochMillis(scope.from));
27584
28727
  }
27585
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27586
- d.severity AS severity, f.masked_match AS masked_match,
27587
- f.action_taken AS action_taken, f.confidence AS confidence,
27588
- e.started_at AS occurred_at,
27589
- e.source_tool AS source_tool,
27590
- e.repo AS repo,
27591
- e.file_path AS file,
27592
- e.tool_name AS tool_name,
27593
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27594
- e.event_type AS kind, f.finding_key AS finding_key,
27595
- ${latestResolutionStatusSql("f")} AS latest_status
28728
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27596
28729
  FROM audit_events e
27597
28730
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27598
28731
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27606,6 +28739,26 @@ var SqliteFindingsRepository = class {
27606
28739
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27607
28740
  const rows = this.db.prepare(
27608
28741
  `SELECT rule_id,
28742
+ -- BARE columns beside max(latest_at), which is deliberate and
28743
+ -- is SQLite's documented behaviour: with a single min()/max()
28744
+ -- in an aggregate query, every bare column takes its value from
28745
+ -- the row that produced the extremum. So these are the severity
28746
+ -- and category of the definition whose finding is NEWEST, which
28747
+ -- is what the row-based build they replaced read off its first
28748
+ -- (newest-first) row.
28749
+ --
28750
+ -- min() is WRONG here and was the defect: inspection_definitions
28751
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28752
+ -- mints a new row), so a rule whose severity moved between
28753
+ -- versions has several, and min() picks the ALPHABETICALLY
28754
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28755
+ -- That is arbitrary in direction, and it feeds the badge, the
28756
+ -- filter, the facet counts and the primary sort key.
28757
+ --
28758
+ -- Adding a second min()/max() aggregate here would make these
28759
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28760
+ severity,
28761
+ category,
27609
28762
  sum(tuple_count) AS instance_count,
27610
28763
  max(latest_at) AS latest_at,
27611
28764
  group_concat(source_tools) AS source_tools,
@@ -27616,6 +28769,14 @@ var SqliteFindingsRepository = class {
27616
28769
  group_concat(tool_names) AS tool_names
27617
28770
  FROM (
27618
28771
  SELECT d.rule_id AS rule_id,
28772
+ -- Severity and category are columns of the DEFINITION, and
28773
+ -- a rule can have SEVERAL definitions (one per version), so
28774
+ -- these are grouped on below and resolved to the newest
28775
+ -- firing version by the outer query's bare-column select.
28776
+ -- They ride the aggregate because the type build has no rows
28777
+ -- to read them off \u2014 see buildFindingTypes.
28778
+ d.severity AS severity,
28779
+ d.category AS category,
27619
28780
  e.event_type || '${TUPLE_SEP}' ||
27620
28781
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27621
28782
  coalesce(latest.status, '') AS status_tuple,
@@ -27630,7 +28791,7 @@ var SqliteFindingsRepository = class {
27630
28791
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27631
28792
  ON latest.finding_key = f.finding_key
27632
28793
  ${scope.predicate}
27633
- GROUP BY d.rule_id, status_tuple
28794
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27634
28795
  )
27635
28796
  GROUP BY rule_id`
27636
28797
  ).all(scope.params);
@@ -27639,6 +28800,8 @@ var SqliteFindingsRepository = class {
27639
28800
  r.rule_id,
27640
28801
  {
27641
28802
  instanceCount: r.instance_count,
28803
+ severity: r.severity,
28804
+ category: r.category,
27642
28805
  sourceTools: splitConcat(r.source_tools),
27643
28806
  actionsTaken: splitConcat(r.actions_taken),
27644
28807
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27655,7 +28818,7 @@ var SqliteFindingsRepository = class {
27655
28818
  latestDetectedAt: epochMillisToIso(r.latest_at),
27656
28819
  // Free text only — joined and substring-matched, so group_concat's
27657
28820
  // commas need no unpicking (a repo/path containing one still matches).
27658
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28821
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27659
28822
  // tell "no q this request" from "a group with no repo/file at all"
27660
28823
  // and skip priming a haystack nothing will read.
27661
28824
  ...withSearchText ? {
@@ -27683,7 +28846,9 @@ var SqliteFindingsRepository = class {
27683
28846
  )
27684
28847
  );
27685
28848
  for (const row of grouped) {
27686
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28849
+ if (Object.hasOwn(byAction, row.action_taken)) {
28850
+ byAction[row.action_taken] = row.c;
28851
+ }
27687
28852
  }
27688
28853
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27689
28854
  const sevRows = allRows(
@@ -27700,7 +28865,9 @@ var SqliteFindingsRepository = class {
27700
28865
  )
27701
28866
  );
27702
28867
  for (const row of sevRows) {
27703
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28868
+ if (Object.hasOwn(bySeverity, row.severity)) {
28869
+ bySeverity[row.severity] = row.c;
28870
+ }
27704
28871
  }
27705
28872
  const categories = ENFORCEABLE_CATEGORIES;
27706
28873
  const enabledRows = allRows(
@@ -27749,469 +28916,6 @@ function isoDay(ms) {
27749
28916
  return new Date(ms).toISOString().slice(0, 10);
27750
28917
  }
27751
28918
 
27752
- // ../../packages/persistence/src/repositories/history-sync.ts
27753
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27754
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27755
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27756
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27757
- var SKIPPED = -1;
27758
- var ROW_COLUMNS = `id,
27759
- parent_id AS parentId,
27760
- root_session_id AS rootSessionId,
27761
- event_type AS eventType,
27762
- host_id AS hostId,
27763
- harness_id AS harnessId,
27764
- source_project_id AS sourceProjectId,
27765
- started_at AS startedAt,
27766
- ended_at AS endedAt,
27767
- severity,
27768
- priority,
27769
- content,
27770
- content_hash AS contentHash,
27771
- attributes`;
27772
- var SqliteHistorySyncRepository = class {
27773
- constructor(db) {
27774
- this.db = db;
27775
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27776
- this.sessionsStmt = db.prepare(
27777
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27778
- FROM audit_events
27779
- WHERE synced_at IS NULL
27780
- AND event_type IN (${TYPE_LIST})
27781
- AND started_at < :before
27782
- GROUP BY sessionId
27783
- ORDER BY earliest
27784
- LIMIT :limit`
27785
- );
27786
- this.rowsStmt = db.prepare(
27787
- `SELECT ${ROW_COLUMNS}
27788
- FROM audit_events
27789
- WHERE synced_at IS NULL
27790
- AND event_type IN (${TYPE_LIST})
27791
- AND started_at < :before
27792
- AND COALESCE(root_session_id, id) = :sessionId
27793
- ORDER BY (event_type = 'session') DESC, started_at
27794
- LIMIT :limit`
27795
- );
27796
- this.captureRowsStmt = db.prepare(
27797
- `SELECT ${ROW_COLUMNS}
27798
- FROM audit_events
27799
- WHERE synced_at IS NULL
27800
- AND sync_claimed_at IS NULL
27801
- AND outbox_owed = 1
27802
- AND event_type IN (${CAPTURE_TYPE_LIST})
27803
- AND started_at < :before
27804
- ORDER BY started_at
27805
- LIMIT :limit`
27806
- );
27807
- this.markOwedStmt = db.prepare(
27808
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27809
- );
27810
- this.stampStmt = db.prepare(
27811
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27812
- );
27813
- this.claimRowStmt = db.prepare(
27814
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27815
- );
27816
- this.releaseRowStmt = db.prepare(
27817
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27818
- );
27819
- this.releaseStaleClaimsStmt = db.prepare(
27820
- `UPDATE audit_events SET sync_claimed_at = NULL
27821
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27822
- );
27823
- this.partitionStmt = db.prepare(
27824
- `SELECT
27825
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27826
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27827
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27828
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27829
- COUNT(*) AS total
27830
- FROM audit_events
27831
- WHERE event_type IN (${TYPE_LIST})`
27832
- );
27833
- this.countsStmt = db.prepare(
27834
- `SELECT
27835
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27836
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27837
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27838
- FROM audit_events
27839
- WHERE event_type IN (${TYPE_LIST})`
27840
- );
27841
- this.captureSkipCountStmt = db.prepare(
27842
- `SELECT COUNT(*) AS skipped
27843
- FROM audit_events
27844
- WHERE synced_at = ${String(SKIPPED)}
27845
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27846
- );
27847
- this.fingerprintStmt = db.prepare(
27848
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27849
- FROM history_sync WHERE id = 1`
27850
- );
27851
- this.setFingerprintStmt = db.prepare(
27852
- `UPDATE history_sync
27853
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27854
- WHERE id = 1`
27855
- );
27856
- this.disownCapturesStmt = db.prepare(
27857
- `UPDATE audit_events SET outbox_owed = NULL
27858
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27859
- );
27860
- this.rearmStmt = db.prepare(
27861
- `UPDATE audit_events SET synced_at = NULL
27862
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27863
- );
27864
- this.claimStmt = db.prepare(
27865
- `UPDATE history_sync
27866
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27867
- WHERE id = 1
27868
- AND (owner_pid IS NULL
27869
- OR heartbeat_at IS NULL
27870
- OR heartbeat_at < :staleBefore
27871
- OR heartbeat_at > :now)`
27872
- );
27873
- this.heartbeatStmt = db.prepare(
27874
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27875
- );
27876
- this.releaseStmt = db.prepare(
27877
- `UPDATE history_sync
27878
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27879
- WHERE id = 1 AND owner_pid = :pid`
27880
- );
27881
- this.closeWindowStmt = db.prepare(
27882
- `UPDATE audit_events SET synced_at = :at
27883
- WHERE synced_at IS NULL
27884
- AND event_type IN (${TYPE_LIST})
27885
- AND started_at >= :attachedAt`
27886
- );
27887
- this.releaseBoundaryStmt = db.prepare(
27888
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27889
- );
27890
- this.freezeBoundaryStmt = db.prepare(
27891
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27892
- );
27893
- this.leaseStmt = db.prepare(
27894
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27895
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27896
- FROM history_sync WHERE id = 1`
27897
- );
27898
- this.inspectionsStmt = db.prepare(
27899
- `SELECT d.rule_id AS ruleId,
27900
- d.name AS ruleName,
27901
- d.version AS ruleVersion,
27902
- d.category AS category,
27903
- d.severity AS severity,
27904
- f.span_start AS spanStart,
27905
- f.span_end AS spanEnd,
27906
- f.masked_match AS maskedMatch,
27907
- f.action_taken AS actionTaken,
27908
- f.confidence AS confidence
27909
- FROM inspection_findings f
27910
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27911
- WHERE f.audit_event_id = :auditEventId
27912
- ORDER BY f.span_start, f.id`
27913
- );
27914
- }
27915
- db;
27916
- ensureRowStmt;
27917
- sessionsStmt;
27918
- rowsStmt;
27919
- stampStmt;
27920
- countsStmt;
27921
- fingerprintStmt;
27922
- setFingerprintStmt;
27923
- rearmStmt;
27924
- claimStmt;
27925
- heartbeatStmt;
27926
- releaseStmt;
27927
- leaseStmt;
27928
- inspectionsStmt;
27929
- closeWindowStmt;
27930
- releaseBoundaryStmt;
27931
- freezeBoundaryStmt;
27932
- captureRowsStmt;
27933
- markOwedStmt;
27934
- captureSkipCountStmt;
27935
- disownCapturesStmt;
27936
- partitionStmt;
27937
- claimRowStmt;
27938
- releaseRowStmt;
27939
- releaseStaleClaimsStmt;
27940
- /**
27941
- * The masked detections recorded against one tool call.
27942
- *
27943
- * These travel with the event because a tool call's target is not
27944
- * re-inspectable from the event alone — unlike a capture, where the text
27945
- * itself is re-scannable. What crosses is the masked match and the rule that
27946
- * produced it, never the value.
27947
- */
27948
- inspectionsFor(auditEventId) {
27949
- return allRows(this.inspectionsStmt, { auditEventId });
27950
- }
27951
- /**
27952
- * Sessions with structural rows still to send, oldest first.
27953
- *
27954
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27955
- * read. Anything recorded after the machine attached is the live forward
27956
- * path's to deliver; this drain exists for what was recorded before it, and a
27957
- * row both paths send is at best a duplicate request and at worst — for a
27958
- * session root — an overwrite of the inventory ids the live path resolved.
27959
- */
27960
- pendingSessions(limit, before) {
27961
- return allRows(this.sessionsStmt, { limit, before }).map(
27962
- (r) => r.sessionId
27963
- );
27964
- }
27965
- /** One session's undelivered structural rows within the backlog, root first. */
27966
- pendingRows(sessionId, limit, before) {
27967
- return allRows(this.rowsStmt, { sessionId, limit, before });
27968
- }
27969
- /**
27970
- * Captures this machine still owes the deployment, oldest first.
27971
- *
27972
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27973
- * by a time window — see captureRowsStmt for why a window could not express
27974
- * this. `before` is the grace window that leaves a just-recorded capture to
27975
- * the live path.
27976
- */
27977
- pendingCaptureRows(limit, before) {
27978
- return allRows(this.captureRowsStmt, { limit, before });
27979
- }
27980
- /**
27981
- * Record that a capture is OWED to the deployment.
27982
- *
27983
- * Written by the attached forward path when a live send did not confirm
27984
- * delivery, and read by the drain as the whole of its eligibility test. It is
27985
- * a fact rather than an inference: the machine was attached, the send did not
27986
- * land, so the row is owed — which no time window can state, because the same
27987
- * window that holds the rows a past attachment left owed also holds every
27988
- * capture recorded while the machine was DETACHED, and those were never
27989
- * offered to anyone.
27990
- *
27991
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27992
- * out of the drain's read.
27993
- */
27994
- markCaptureOwed(id) {
27995
- this.markOwedStmt.run({ id });
27996
- }
27997
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27998
- markSynced(ids, atMs) {
27999
- this.stampAll(ids, atMs);
28000
- }
28001
- /**
28002
- * Record that a row will never be sent.
28003
- *
28004
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
28005
- * payload. A row that merely failed to reach the deployment stays NULL, so it
28006
- * is retried; marking those would turn one outage into permanent data loss.
28007
- */
28008
- markSkipped(ids) {
28009
- this.stampAll(ids, SKIPPED);
28010
- }
28011
- eachInTransaction(ids, run) {
28012
- if (ids.length === 0) return;
28013
- withTransaction(
28014
- this.db,
28015
- () => {
28016
- for (const id of ids) run(id);
28017
- },
28018
- "IMMEDIATE"
28019
- );
28020
- }
28021
- stampAll(ids, value) {
28022
- if (ids.length === 0) return;
28023
- withTransaction(
28024
- this.db,
28025
- () => {
28026
- for (const id of ids) this.stampStmt.run({ at: value, id });
28027
- },
28028
- "IMMEDIATE"
28029
- );
28030
- }
28031
- /**
28032
- * Claim rows as in-flight.
28033
- *
28034
- * Advisory in exactly the sense the lease is: it records that a send is in
28035
- * progress so a surface can say so, and a lost claim costs a row showing as
28036
- * queued while it is actually being sent. It is not exclusion — the far side
28037
- * settles a duplicate on the row id.
28038
- */
28039
- claimRows(ids, atMs) {
28040
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28041
- }
28042
- /** Give back a claim without settling — the send failed, the row is queued again. */
28043
- releaseRows(ids) {
28044
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28045
- }
28046
- /**
28047
- * Clear claims older than `staleBefore`, and report how many were cleared.
28048
- *
28049
- * A process killed between claiming and settling leaves rows claimed with
28050
- * nothing left to settle them. Without this they read as "sending" for ever.
28051
- */
28052
- releaseStaleClaims(staleBefore) {
28053
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28054
- }
28055
- /**
28056
- * Every tracked row in exactly one delivery state.
28057
- *
28058
- * Takes no boundary on purpose. The boundary answers "what should the drain
28059
- * pick up now", which is a different question from "what state is this row
28060
- * in" — and a machine that has never attached has no boundary to pass, so
28061
- * requiring one would force a caller to invent one and report the whole store
28062
- * as queued.
28063
- */
28064
- partition() {
28065
- const row = getRow(this.partitionStmt, {});
28066
- return {
28067
- queued: row?.queued ?? 0,
28068
- inProgress: row?.inProgress ?? 0,
28069
- synced: row?.synced ?? 0,
28070
- failed: row?.failed ?? 0,
28071
- total: row?.total ?? 0
28072
- };
28073
- }
28074
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28075
- counts(before) {
28076
- const row = getRow(
28077
- this.countsStmt,
28078
- { before }
28079
- );
28080
- const captures = getRow(this.captureSkipCountStmt);
28081
- return {
28082
- pending: row?.pending ?? 0,
28083
- sent: row?.sent ?? 0,
28084
- skipped: row?.skipped ?? 0,
28085
- capturesSkipped: captures?.skipped ?? 0
28086
- };
28087
- }
28088
- /**
28089
- * The deployment the current stamps were made against, and where its backlog
28090
- * ends.
28091
- *
28092
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28093
- * machine that has never drained is — and every writer below seeds the row
28094
- * before it needs one, so nothing depends on this creating it. Keeping the
28095
- * write off the gate path matters because the gate runs on every pass while a
28096
- * write has to take the database's write lock.
28097
- */
28098
- deployment() {
28099
- const row = getRow(
28100
- this.fingerprintStmt
28101
- );
28102
- return {
28103
- fingerprint: row?.fingerprint ?? void 0,
28104
- backlogBefore: row?.backlogBefore ?? void 0
28105
- };
28106
- }
28107
- /**
28108
- * Point the ledger at a different deployment, discarding what it recorded
28109
- * about the previous one.
28110
- *
28111
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28112
- * machine has just left are undelivered as far as the new one is concerned.
28113
- * All three in one transaction, so a crash between them cannot leave stamps
28114
- * attributed to the wrong deployment, or a boundary that belongs to another.
28115
- *
28116
- * The boundary is written HERE and only here, which is what freezes it: a
28117
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28118
- * unchanged, so this never runs and the backlog does not widen back over rows
28119
- * the live path has since delivered.
28120
- */
28121
- rearmFor(fingerprint, backlogBefore) {
28122
- this.ensureRowStmt.run();
28123
- withTransaction(
28124
- this.db,
28125
- () => {
28126
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28127
- this.rearmStmt.run();
28128
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28129
- this.disownCapturesStmt.run();
28130
- }
28131
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28132
- },
28133
- "IMMEDIATE"
28134
- );
28135
- }
28136
- /**
28137
- * End the attached period: hand its rows to the live path, and release the
28138
- * boundary so the next attachment can freeze a new one.
28139
- *
28140
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28141
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28142
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28143
- * during the detached period, because the machine is not attached. Rows
28144
- * recorded in that window sit after the boundary and before the re-attach, so
28145
- * neither path takes them, and the pending count reports none outstanding.
28146
- *
28147
- * Stamping the attached window is not a claim that every one of those rows
28148
- * reached the deployment — the live path drops on failure and says so
28149
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28150
- * status quo: they sit outside the frozen boundary today and are equally never
28151
- * re-sent. Making it explicit is what lets the boundary move.
28152
- *
28153
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28154
- * window unstamped — that half-state would re-send the whole attached period
28155
- * on the next attach, which is the failure the boundary exists to prevent.
28156
- */
28157
- closeAttachedWindow(attachedAtMs, atMs) {
28158
- this.ensureRowStmt.run();
28159
- withTransaction(
28160
- this.db,
28161
- () => {
28162
- const row = getRow(this.fingerprintStmt);
28163
- const from = row?.backlogBefore ?? attachedAtMs;
28164
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28165
- this.releaseBoundaryStmt.run();
28166
- },
28167
- "IMMEDIATE"
28168
- );
28169
- }
28170
- /**
28171
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28172
- *
28173
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28174
- * different deployment and therefore discards what was delivered to the old
28175
- * one: here the recipient is the same, so everything already sent to it stays
28176
- * sent.
28177
- */
28178
- freezeBoundary(backlogBefore) {
28179
- this.ensureRowStmt.run();
28180
- this.freezeBoundaryStmt.run({ backlogBefore });
28181
- }
28182
- /** Take the claim, or report that someone live already holds it. */
28183
- claim(pid, host, nowMs, staleAfterMs) {
28184
- this.ensureRowStmt.run();
28185
- let taken = false;
28186
- withTransaction(
28187
- this.db,
28188
- () => {
28189
- const result = this.claimStmt.run({
28190
- pid,
28191
- host,
28192
- now: nowMs,
28193
- staleBefore: nowMs - staleAfterMs
28194
- });
28195
- taken = result.changes === 1;
28196
- },
28197
- "IMMEDIATE"
28198
- );
28199
- return taken;
28200
- }
28201
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28202
- heartbeat(pid, nowMs) {
28203
- this.heartbeatStmt.run({ now: nowMs, pid });
28204
- }
28205
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28206
- release(pid) {
28207
- this.releaseStmt.run({ pid });
28208
- }
28209
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28210
- lease() {
28211
- return getRow(this.leaseStmt);
28212
- }
28213
- };
28214
-
28215
28919
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28216
28920
  var SqliteInspectionDefinitionsRepository = class {
28217
28921
  constructor(db) {
@@ -28406,7 +29110,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28406
29110
  }
28407
29111
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28408
29112
  }
28409
- function readManagedSettings(paths = managedSettingsPaths()) {
29113
+ var testOnlyManagedPaths = null;
29114
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28410
29115
  for (const path of paths) {
28411
29116
  let text;
28412
29117
  try {
@@ -28441,6 +29146,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28441
29146
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28442
29147
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28443
29148
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29149
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28444
29150
  if (values.vaultConsent !== void 0) {
28445
29151
  merged.vaultConsent = values.vaultConsent ? (
28446
29152
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30886,7 +31592,7 @@ function toUtcDateString(ms) {
30886
31592
  return new Date(ms).toISOString().slice(0, 10);
30887
31593
  }
30888
31594
  function isTimeseriesSeverity(s) {
30889
- return s === "critical" || s === "high" || s === "medium";
31595
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30890
31596
  }
30891
31597
  var SqliteSecurityRepository = class {
30892
31598
  constructor(db, now = () => Date.now()) {
@@ -30948,7 +31654,7 @@ var SqliteSecurityRepository = class {
30948
31654
  ELSE 0
30949
31655
  END) AS open_at_rest
30950
31656
  FROM inspection_findings f
30951
- JOIN audit_events e ON e.id = f.audit_event_id
31657
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30952
31658
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30953
31659
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30954
31660
  ON latest.finding_key = f.finding_key
@@ -31015,12 +31721,16 @@ var SqliteSecurityRepository = class {
31015
31721
  const now = this.now();
31016
31722
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
31017
31723
  const rows = this.findingsInRange(windowStart, now);
31018
- const points = Array.from({ length: numBuckets }, (_, i) => ({
31019
- timestamp: toUtcDateString(windowStart + i * bucketMs),
31020
- critical: 0,
31021
- high: 0,
31022
- medium: 0
31023
- }));
31724
+ const points = Array.from(
31725
+ { length: numBuckets },
31726
+ (_, i) => ({
31727
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31728
+ critical: 0,
31729
+ high: 0,
31730
+ medium: 0,
31731
+ low: 0
31732
+ })
31733
+ );
31024
31734
  for (const r of rows) {
31025
31735
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
31026
31736
  const bucket = points[idx];
@@ -31170,7 +31880,7 @@ var SqliteSecurityRepository = class {
31170
31880
  this.db.prepare(
31171
31881
  `SELECT e.repo AS repo, count(*) AS c
31172
31882
  FROM inspection_findings f
31173
- JOIN audit_events e ON e.id = f.audit_event_id
31883
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31174
31884
  WHERE e.started_at >= :from AND e.started_at < :to
31175
31885
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31176
31886
  AND e.repo IS NOT NULL
@@ -31238,6 +31948,7 @@ var SqliteSecurityRepository = class {
31238
31948
  `SELECT f.finding_key AS finding_key,
31239
31949
  d.rule_id AS rule_id,
31240
31950
  d.severity AS severity,
31951
+ e.repo AS repo,
31241
31952
  e.file_path AS path,
31242
31953
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31243
31954
  latest.resolved_at AS latest_resolved_at
@@ -31257,6 +31968,7 @@ var SqliteSecurityRepository = class {
31257
31968
  const items = rows.map((r) => ({
31258
31969
  findingKey: r.finding_key,
31259
31970
  ruleId: r.rule_id,
31971
+ repo: r.repo ?? "",
31260
31972
  severity: r.severity,
31261
31973
  path: r.path ?? "",
31262
31974
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31266,15 +31978,68 @@ var SqliteSecurityRepository = class {
31266
31978
  }));
31267
31979
  return Promise.resolve({ items });
31268
31980
  }
31981
+ /**
31982
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31983
+ *
31984
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31985
+ * list: a secret committed three weeks ago and never rotated is still the most
31986
+ * important thing to fix, and any window hides it. It carried a "newest N
31987
+ * findings" cap and then a range; the first meant a different span on every
31988
+ * machine, and the second reported "no recommendations" over live exposure.
31989
+ *
31990
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31991
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31992
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31993
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31994
+ * The two answer different questions and only this one has to match a link.
31995
+ *
31996
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31997
+ * whole-store scope costs a grouped scan rather than a row per finding.
31998
+ */
31999
+ recommendationInputs() {
32000
+ const rows = allRows(
32001
+ this.db.prepare(
32002
+ `SELECT d.rule_id AS rule_id,
32003
+ d.category AS category,
32004
+ d.severity AS severity,
32005
+ COUNT(*) AS count
32006
+ FROM inspection_findings f
32007
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
32008
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
32009
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
32010
+ ON latest.finding_key = f.finding_key
32011
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
32012
+ AND e.event_type = 'code_change'
32013
+ AND (
32014
+ f.finding_key IS NULL
32015
+ OR latest.status IS NULL
32016
+ OR latest.status NOT IN ('resolved', 'dismissed')
32017
+ )
32018
+ GROUP BY d.rule_id, d.category, d.severity`
32019
+ )
32020
+ );
32021
+ return Promise.resolve(
32022
+ rows.map((r) => ({
32023
+ ruleId: r.rule_id,
32024
+ category: r.category,
32025
+ severity: r.severity,
32026
+ count: r.count
32027
+ }))
32028
+ );
32029
+ }
31269
32030
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31270
32031
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31271
32032
  // numeric and the JS aggregations bucket/split on ms directly.
31272
32033
  findingsInRange(fromMs, toMs) {
31273
32034
  const rows = allRows(
31274
32035
  this.db.prepare(
31275
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
32036
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
32037
+ // joined for `severity`, so they are two more columns off a row this read
32038
+ // already fetches. They feed the recommended-actions rollup.
32039
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
32040
+ d.rule_id AS rule_id, d.category AS category
31276
32041
  FROM inspection_findings f
31277
- JOIN audit_events e ON e.id = f.audit_event_id
32042
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31278
32043
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31279
32044
  WHERE e.started_at >= :from AND e.started_at < :to
31280
32045
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31285,7 +32050,9 @@ var SqliteSecurityRepository = class {
31285
32050
  return rows.map((r) => ({
31286
32051
  occurredAt: r.occurred_at,
31287
32052
  severity: r.severity,
31288
- actionTaken: r.action_taken
32053
+ actionTaken: r.action_taken,
32054
+ ruleId: r.rule_id,
32055
+ category: r.category
31289
32056
  }));
31290
32057
  }
31291
32058
  };
@@ -32113,6 +32880,7 @@ function openWithPragmas(file2) {
32113
32880
  db.exec("PRAGMA journal_mode = WAL");
32114
32881
  db.exec("PRAGMA busy_timeout = 2000");
32115
32882
  db.exec("PRAGMA foreign_keys = ON");
32883
+ registerSqlFunctions(db);
32116
32884
  } catch (err) {
32117
32885
  closeQuietly(db);
32118
32886
  throw err;
@@ -32142,7 +32910,7 @@ function backupLegacyStore(db, file2) {
32142
32910
  discardStore(file2, backup);
32143
32911
  return backup;
32144
32912
  }
32145
- function openAndInitialize(file2, base) {
32913
+ function openAndInitialize(file2, base, skipTags) {
32146
32914
  let db = openWithPragmas(file2);
32147
32915
  try {
32148
32916
  if (isForeignSqliteLineage(db)) {
@@ -32152,7 +32920,7 @@ function openAndInitialize(file2, base) {
32152
32920
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32153
32921
  );
32154
32922
  }
32155
- applyMigrations(db, file2);
32923
+ applyMigrations(db, file2, { skipTags });
32156
32924
  tightenPerms(file2);
32157
32925
  const policies = new SqlitePoliciesRepository(db);
32158
32926
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32167,6 +32935,7 @@ function openAndInitialize(file2, base) {
32167
32935
  exceptions: new SqliteExceptionsRepository(db),
32168
32936
  resolutions: new SqliteResolutionsRepository(db),
32169
32937
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32938
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32170
32939
  security: new SqliteSecurityRepository(db),
32171
32940
  detections: new SqliteDetectionsRepository(db),
32172
32941
  shares: new SqliteSharesRepository(db),
@@ -32189,7 +32958,8 @@ function openAndInitialize(file2, base) {
32189
32958
  throw err;
32190
32959
  }
32191
32960
  }
32192
- function openLocalDatabase(dir) {
32961
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32962
+ function openLocalDatabase(dir, options = {}) {
32193
32963
  ensureDataDirSync(dir);
32194
32964
  const file2 = join7(dir, DB_FILENAME);
32195
32965
  reapStalePartials(file2);
@@ -32201,6 +32971,7 @@ function openLocalDatabase(dir) {
32201
32971
  installedPacks,
32202
32972
  scanLedger,
32203
32973
  historySync,
32974
+ bodyRetention,
32204
32975
  secretVault,
32205
32976
  exceptions,
32206
32977
  resolutions,
@@ -32224,7 +32995,8 @@ function openLocalDatabase(dir) {
32224
32995
  // `dir` is always `<base>/data` — every caller resolves it through
32225
32996
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32226
32997
  // settings/ and data/, and the pack-policy floor needs both halves.
32227
- dirname2(dir)
32998
+ dirname2(dir),
32999
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32228
33000
  );
32229
33001
  function captureRowId(event) {
32230
33002
  return captureId(
@@ -32417,6 +33189,7 @@ function openLocalDatabase(dir) {
32417
33189
  installedPacks,
32418
33190
  scanLedger,
32419
33191
  historySync,
33192
+ bodyRetention,
32420
33193
  secretVault,
32421
33194
  exceptions,
32422
33195
  resolutions,
@@ -32455,8 +33228,72 @@ function openLocalDatabase(dir) {
32455
33228
  };
32456
33229
  }
32457
33230
 
32458
- // ../../packages/persistence/src/finding-key.ts
33231
+ // ../../packages/persistence/src/egress-wire.ts
32459
33232
  import { createHash as createHash3 } from "crypto";
33233
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33234
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33235
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33236
+ var FILE_URL = /^file:\/\//i;
33237
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33238
+ var SLASH = "/".charCodeAt(0);
33239
+ var GIT_SUFFIX = ".git";
33240
+ function trimSlashes(path) {
33241
+ let start = 0;
33242
+ let end = path.length;
33243
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33244
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33245
+ return path.slice(start, end);
33246
+ }
33247
+ function canonicalGitUrl(url2) {
33248
+ const trimmed = url2.trim();
33249
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33250
+ const scheme = SCHEME_FORM.exec(trimmed);
33251
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33252
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33253
+ if (host === void 0) return trimmed;
33254
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33255
+ const bare = trimSlashes(path);
33256
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33257
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33258
+ }
33259
+ function hashProjectKey(projectKey) {
33260
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33261
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33262
+ }
33263
+ function toIngestHit(hit) {
33264
+ return {
33265
+ host: hit.host,
33266
+ kind: hit.kind,
33267
+ name: hit.name,
33268
+ category: hit.category,
33269
+ trust: hit.trust,
33270
+ network: hit.network,
33271
+ method: hit.method,
33272
+ transport: hit.transport,
33273
+ url: hit.url,
33274
+ template: hit.template,
33275
+ dataClass: hit.dataClass,
33276
+ site: {
33277
+ file: hit.site.file,
33278
+ line: hit.site.line,
33279
+ dynamic: hit.site.dynamic,
33280
+ vendored: hit.site.vendored
33281
+ }
33282
+ };
33283
+ }
33284
+ function toEgressIngestRequest(input2) {
33285
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33286
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33287
+ return {
33288
+ projectKey: hashProjectKey(input2.projectKey),
33289
+ project: input2.project,
33290
+ reconcile,
33291
+ hits: hits.map(toIngestHit)
33292
+ };
33293
+ }
33294
+
33295
+ // ../../packages/persistence/src/finding-key.ts
33296
+ import { createHash as createHash4 } from "crypto";
32460
33297
 
32461
33298
  // ../../packages/persistence/src/fingerprint.ts
32462
33299
  import { createHmac, randomBytes } from "crypto";
@@ -32497,14 +33334,50 @@ function readFingerprintKey(dataDir2) {
32497
33334
  return parseKeyFile(raw);
32498
33335
  }
32499
33336
 
32500
- // ../../packages/persistence/src/history-preview.ts
32501
- import { existsSync as existsSync4 } from "fs";
33337
+ // ../../packages/persistence/src/forward-health.ts
33338
+ import { readFileSync as readFileSync7 } from "fs";
32502
33339
  import { join as join9 } from "path";
33340
+ var FAILURES = /* @__PURE__ */ new Set([
33341
+ "unauthorized",
33342
+ "forbidden",
33343
+ "unreachable"
33344
+ ]);
33345
+ var BREAKER_COOLDOWN_MS = 3e4;
33346
+ function parseForwardHealth(raw, nowMs) {
33347
+ try {
33348
+ const parsed2 = JSON.parse(raw);
33349
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33350
+ const record2 = parsed2;
33351
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33352
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33353
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33354
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33355
+ } catch {
33356
+ return null;
33357
+ }
33358
+ }
33359
+ function isForwardPaused(health, nowMs) {
33360
+ const openedAtMs = health?.openedAtMs ?? null;
33361
+ if (openedAtMs === null) return false;
33362
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33363
+ }
33364
+
33365
+ // ../../packages/persistence/src/history-backfill.ts
33366
+ import { existsSync as existsSync4 } from "fs";
33367
+ import { join as join10 } from "path";
33368
+
33369
+ // ../../packages/persistence/src/history-preview.ts
33370
+ import { existsSync as existsSync5 } from "fs";
33371
+ import { join as join11 } from "path";
32503
33372
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32504
33373
 
33374
+ // ../../packages/persistence/src/history-sync-state.ts
33375
+ import { readFileSync as readFileSync8 } from "fs";
33376
+ import { join as join12 } from "path";
33377
+
32505
33378
  // ../../packages/persistence/src/store-symlinks.ts
32506
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32507
- import { dirname as dirname3, join as join10, resolve } from "path";
33379
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33380
+ import { dirname as dirname3, join as join13, resolve } from "path";
32508
33381
  var STORE_DB = "the store database (including the prompt corpus)";
32509
33382
  var STORE_SETTINGS = "your settings file";
32510
33383
  function storeContents(home) {
@@ -32513,7 +33386,7 @@ function storeContents(home) {
32513
33386
  [settingsDir(home), STORE_SETTINGS],
32514
33387
  [dataDir(home), STORE_DB],
32515
33388
  [keysDir(home), "the vault key"],
32516
- [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
33389
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32517
33390
  [dbPath(home), STORE_DB]
32518
33391
  ]);
32519
33392
  }
@@ -32528,7 +33401,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
32528
33401
  holds,
32529
33402
  // existsSync follows the link, so a target that is gone reads as
32530
33403
  // absent here while lstat above still sees the link itself.
32531
- missing: !existsSync5(path),
33404
+ missing: !existsSync6(path),
32532
33405
  mode: targetMode(path, platform2)
32533
33406
  }
32534
33407
  ];
@@ -32565,62 +33438,26 @@ import {
32565
33438
  // ../../packages/persistence/src/vault/key-provider.ts
32566
33439
  import { execFileSync } from "child_process";
32567
33440
  import { randomBytes as randomBytes2 } from "crypto";
32568
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32569
- import { join as join11 } from "path";
33441
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33442
+ import { join as join14 } from "path";
32570
33443
 
32571
33444
  // ../../packages/persistence/src/vault/vault.ts
32572
33445
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32573
33446
 
32574
33447
  // ../../packages/persistence/src/warn-era-cap.ts
32575
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32576
- import { join as join12 } from "path";
33448
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33449
+ import { join as join15 } from "path";
32577
33450
  var MARKER = "warn-era-capped";
32578
33451
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32579
33452
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32580
- const marker = join12(dataDir2, MARKER);
32581
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33453
+ const marker = join15(dataDir2, MARKER);
33454
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32582
33455
  const capped = db.policies.capCategoryActions();
32583
33456
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32584
33457
  `, { mode: DATA_FILE_MODE });
32585
33458
  return { capped };
32586
33459
  }
32587
33460
 
32588
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32589
- function hashProjectKey(projectKey) {
32590
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32591
- }
32592
- function toIngestHit(hit) {
32593
- return {
32594
- host: hit.host,
32595
- kind: hit.kind,
32596
- name: hit.name,
32597
- category: hit.category,
32598
- trust: hit.trust,
32599
- network: hit.network,
32600
- method: hit.method,
32601
- transport: hit.transport,
32602
- url: hit.url,
32603
- template: hit.template,
32604
- dataClass: hit.dataClass,
32605
- site: {
32606
- file: hit.site.file,
32607
- line: hit.site.line,
32608
- dynamic: hit.site.dynamic,
32609
- vendored: hit.site.vendored
32610
- }
32611
- };
32612
- }
32613
- function toEgressIngestRequest(input2) {
32614
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32615
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32616
- return {
32617
- projectKey: hashProjectKey(input2.projectKey),
32618
- project: input2.project,
32619
- reconcile,
32620
- hits: hits.map(toIngestHit)
32621
- };
32622
- }
32623
-
32624
33461
  // ../../packages/remote/src/http.ts
32625
33462
  import { request as httpRequest } from "http";
32626
33463
  import { request as httpsRequest } from "https";
@@ -32804,10 +33641,10 @@ function parsed(schema, body, route) {
32804
33641
  }
32805
33642
  function withoutTrailingSlashes(endpoint) {
32806
33643
  let end = endpoint.length;
32807
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33644
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32808
33645
  return endpoint.slice(0, end);
32809
33646
  }
32810
- var SLASH = "/".charCodeAt(0);
33647
+ var SLASH2 = "/".charCodeAt(0);
32811
33648
  function createRemoteClient(options) {
32812
33649
  const base = withoutTrailingSlashes(options.endpoint);
32813
33650
  const url2 = (route) => `${base}${route}`;
@@ -32900,6 +33737,7 @@ function createRemoteClient(options) {
32900
33737
  url: url2(ROUTES.shares),
32901
33738
  body: JSON.stringify(validated.data)
32902
33739
  });
33740
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32903
33741
  okBody(response);
32904
33742
  },
32905
33743
  async pollCommand() {
@@ -32922,19 +33760,51 @@ function createRemoteClient(options) {
32922
33760
  };
32923
33761
  }
32924
33762
 
32925
- // ../../packages/plugin-runtime/src/attached/failure.ts
33763
+ // ../../packages/remote/src/failure-kind.ts
32926
33764
  function statusOf(err) {
32927
33765
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32928
33766
  const { status } = err;
32929
33767
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32930
33768
  return status >= 100 && status <= 599 ? status : null;
32931
33769
  }
32932
- function classifyFailure(err) {
32933
- switch (statusOf(err)) {
33770
+ function nameOf(err) {
33771
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33772
+ return typeof err.name === "string" ? err.name : null;
33773
+ }
33774
+ function classifyRemoteFailure(err) {
33775
+ switch (nameOf(err)) {
33776
+ case "RemoteRouteAbsent":
33777
+ return "route-absent";
33778
+ case "RemoteRequestInvalid":
33779
+ return "invalid-request";
33780
+ case "RemoteResponseInvalid":
33781
+ return "rejected";
33782
+ default:
33783
+ break;
33784
+ }
33785
+ const status = statusOf(err);
33786
+ if (status === null) return "unreachable";
33787
+ switch (status) {
32934
33788
  case 401:
32935
33789
  return "unauthorized";
32936
33790
  case 403:
32937
33791
  return "forbidden";
33792
+ case 429:
33793
+ return "unreachable";
33794
+ case 404:
33795
+ return "unreachable";
33796
+ default:
33797
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33798
+ }
33799
+ }
33800
+
33801
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33802
+ function classifyFailure(err) {
33803
+ switch (classifyRemoteFailure(err)) {
33804
+ case "unauthorized":
33805
+ return "unauthorized";
33806
+ case "forbidden":
33807
+ return "forbidden";
32938
33808
  default:
32939
33809
  return "unreachable";
32940
33810
  }
@@ -32956,11 +33826,11 @@ function withTimeout(promise2, ms) {
32956
33826
  }
32957
33827
 
32958
33828
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32959
- import { readFileSync as readFileSync8 } from "fs";
32960
- import { join as join13 } from "path";
33829
+ import { readFileSync as readFileSync10 } from "fs";
33830
+ import { join as join16 } from "path";
32961
33831
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32962
33832
  function forwardDropsPath(dataDir2) {
32963
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33833
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
32964
33834
  }
32965
33835
  function recordForwardDrops(dataDir2, count, nowMs) {
32966
33836
  if (count <= 0) return;
@@ -32978,7 +33848,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
32978
33848
  }
32979
33849
  function readForwardDrops(dataDir2) {
32980
33850
  try {
32981
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33851
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
32982
33852
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
32983
33853
  const record2 = parsed2;
32984
33854
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -32996,13 +33866,12 @@ function readForwardDrops(dataDir2) {
32996
33866
 
32997
33867
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32998
33868
  import { randomUUID as randomUUID15 } from "crypto";
32999
- import { readFileSync as readFileSync14 } from "fs";
33000
33869
  import { readFile, rename, writeFile } from "fs/promises";
33001
- import { join as join22 } from "path";
33870
+ import { join as join26 } from "path";
33002
33871
 
33003
33872
  // ../../packages/plugin-sdk/src/config.ts
33004
- import { existsSync as existsSync7 } from "fs";
33005
- import { join as join14 } from "path";
33873
+ import { existsSync as existsSync8 } from "fs";
33874
+ import { join as join17 } from "path";
33006
33875
 
33007
33876
  // ../../packages/plugin-sdk/src/provider-env.ts
33008
33877
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33056,8 +33925,8 @@ function resolveProvider() {
33056
33925
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33057
33926
  try {
33058
33927
  ensureLayoutDirSync(base);
33059
- const settingsFile = join14(settingsDir(base), "settings.json");
33060
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33928
+ const settingsFile = join17(settingsDir(base), "settings.json");
33929
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33061
33930
  } catch {
33062
33931
  }
33063
33932
  migrateLegacyLayout(base);
@@ -33080,9 +33949,9 @@ function resolveProviderSafe(resolveProviderFn) {
33080
33949
  }
33081
33950
 
33082
33951
  // ../../packages/plugin-sdk/src/config-inventory.ts
33083
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33952
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33084
33953
  import { homedir as homedir2 } from "os";
33085
- import { basename as basename4, join as join16 } from "path";
33954
+ import { basename as basename4, join as join19 } from "path";
33086
33955
 
33087
33956
  // ../../packages/detections/src/egress/registry.ts
33088
33957
  var EXTRACTOR_VERSION = "1";
@@ -36211,8 +37080,8 @@ function maskText(text) {
36211
37080
  }
36212
37081
 
36213
37082
  // ../../packages/plugin-sdk/src/repo.ts
36214
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36215
- import { basename as basename3, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37083
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37084
+ import { basename as basename3, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36216
37085
  function resolveRepoIdentity(cwd) {
36217
37086
  try {
36218
37087
  const root = findGitRoot(cwd);
@@ -36262,7 +37131,7 @@ function resolveGitBranch(cwd) {
36262
37131
  try {
36263
37132
  const root = findGitRoot(cwd);
36264
37133
  if (!root) return void 0;
36265
- const dotGit = join15(root, ".git");
37134
+ const dotGit = join18(root, ".git");
36266
37135
  let gitdir;
36267
37136
  try {
36268
37137
  gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
@@ -36270,7 +37139,7 @@ function resolveGitBranch(cwd) {
36270
37139
  return void 0;
36271
37140
  }
36272
37141
  if (gitdir === void 0) return void 0;
36273
- const head = safeRead(join15(gitdir, "HEAD"));
37142
+ const head = safeRead(join18(gitdir, "HEAD"));
36274
37143
  if (!head) return void 0;
36275
37144
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
36276
37145
  } catch {
@@ -36280,41 +37149,41 @@ function resolveGitBranch(cwd) {
36280
37149
  function resolveWorktreeGitdir(root, dotGitFile) {
36281
37150
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
36282
37151
  if (!target) return void 0;
36283
- return isAbsolute(target) ? target : join15(root, target);
37152
+ return isAbsolute(target) ? target : join18(root, target);
36284
37153
  }
36285
37154
  function findGitRoot(start) {
36286
37155
  let dir = start;
36287
37156
  for (; ; ) {
36288
- if (existsSync8(join15(dir, ".git"))) return dir;
37157
+ if (existsSync9(join18(dir, ".git"))) return dir;
36289
37158
  const parent = dirname4(dir);
36290
37159
  if (parent === dir) return void 0;
36291
37160
  dir = parent;
36292
37161
  }
36293
37162
  }
36294
37163
  function resolveGitContext(root) {
36295
- const dotGit = join15(root, ".git");
37164
+ const dotGit = join18(root, ".git");
36296
37165
  try {
36297
37166
  if (statSync6(dotGit).isDirectory()) {
36298
- return { configPath: join15(dotGit, "config"), headRoot: root };
37167
+ return { configPath: join18(dotGit, "config"), headRoot: root };
36299
37168
  }
36300
37169
  } catch {
36301
37170
  return void 0;
36302
37171
  }
36303
37172
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36304
37173
  if (!target) return void 0;
36305
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36306
- if (existsSync8(join15(gitdir, "config"))) {
36307
- return { configPath: join15(gitdir, "config"), headRoot: root };
37174
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
37175
+ if (existsSync9(join18(gitdir, "config"))) {
37176
+ return { configPath: join18(gitdir, "config"), headRoot: root };
36308
37177
  }
36309
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
37178
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
36310
37179
  if (!commonRaw) return void 0;
36311
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
37180
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
36312
37181
  const headRoot = basename3(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36313
- return { configPath: join15(commonGitDir, "config"), headRoot };
37182
+ return { configPath: join18(commonGitDir, "config"), headRoot };
36314
37183
  }
36315
37184
  function safeRead(path) {
36316
37185
  try {
36317
- return readFileSync9(path, "utf8");
37186
+ return readFileSync11(path, "utf8");
36318
37187
  } catch {
36319
37188
  return void 0;
36320
37189
  }
@@ -36376,31 +37245,31 @@ function resolveConfigInventory(input2) {
36376
37245
  };
36377
37246
  try {
36378
37247
  const home = input2.homeDir ?? homedir2();
36379
- const claudeDir = join16(home, ".claude");
37248
+ const claudeDir = join19(home, ".claude");
36380
37249
  const repo = resolveRepoIdentity(input2.cwd);
36381
37250
  const repoIdentity = repo?.url ?? input2.cwd;
36382
37251
  const projectSource = `project:${repoIdentity}`;
36383
- collectSettingsHooks(scan2, join16(claudeDir, "settings.json"), "user");
36384
- collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.json"), "project");
36385
- collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.local.json"), "local");
37252
+ collectSettingsHooks(scan2, join19(claudeDir, "settings.json"), "user");
37253
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.json"), "project");
37254
+ collectSettingsHooks(scan2, join19(input2.cwd, ".claude", "settings.local.json"), "local");
36386
37255
  const projectOrigin = { scope: "project", project: repoIdentity };
36387
- collectMcpFile(scan2, join16(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
36388
- collectUserClaudeJson(scan2, join16(home, ".claude.json"), input2.cwd, repoIdentity);
36389
- collectMcpFile(scan2, join16(claudeDir, "settings.json"), { scope: "user" });
36390
- collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.json"), projectOrigin);
36391
- collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.local.json"), {
37256
+ collectMcpFile(scan2, join19(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
37257
+ collectUserClaudeJson(scan2, join19(home, ".claude.json"), input2.cwd, repoIdentity);
37258
+ collectMcpFile(scan2, join19(claudeDir, "settings.json"), { scope: "user" });
37259
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.json"), projectOrigin);
37260
+ collectMcpFile(scan2, join19(input2.cwd, ".claude", "settings.local.json"), {
36392
37261
  scope: "local",
36393
37262
  project: repoIdentity
36394
37263
  });
36395
37264
  collectConfigFiles(scan2, claudeDir, input2.cwd);
36396
- collectSkillsDir(scan2, join16(claudeDir, "skills"), { source: "local", scope: "user" });
36397
- collectSkillsDir(scan2, join16(input2.cwd, ".claude", "skills"), {
37265
+ collectSkillsDir(scan2, join19(claudeDir, "skills"), { source: "local", scope: "user" });
37266
+ collectSkillsDir(scan2, join19(input2.cwd, ".claude", "skills"), {
36398
37267
  source: projectSource,
36399
37268
  scope: "project"
36400
37269
  });
36401
37270
  collectInstalledPlugins(scan2, claudeDir);
36402
37271
  collectMarketplaceSkills(scan2, claudeDir);
36403
- collectSkillsDir(scan2, join16(input2.cwd, "skills"), { source: projectSource, scope: "project" });
37272
+ collectSkillsDir(scan2, join19(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36404
37273
  scan2.skills = dedupeSkills(scan2.skills);
36405
37274
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
36406
37275
  } catch (err) {
@@ -36529,7 +37398,7 @@ function projectEntryFor(projects, cwd) {
36529
37398
  return void 0;
36530
37399
  }
36531
37400
  function collectPluginManifestMcp(scan2, installPath, origin) {
36532
- const manifestPath = join16(installPath, ".claude-plugin", "plugin.json");
37401
+ const manifestPath = join19(installPath, ".claude-plugin", "plugin.json");
36533
37402
  const raw = readOptional(manifestPath);
36534
37403
  if (raw === void 0) return;
36535
37404
  try {
@@ -36537,7 +37406,7 @@ function collectPluginManifestMcp(scan2, installPath, origin) {
36537
37406
  if (typeof parsed2 !== "object" || parsed2 === null) return;
36538
37407
  const declared = parsed2.mcpServers;
36539
37408
  if (typeof declared === "string" && declared.length > 0) {
36540
- collectMcpFile(scan2, join16(installPath, declared), origin, { recordErrors: true });
37409
+ collectMcpFile(scan2, join19(installPath, declared), origin, { recordErrors: true });
36541
37410
  } else {
36542
37411
  collectMcpObject(scan2, declared, manifestPath, origin);
36543
37412
  }
@@ -36554,14 +37423,14 @@ var SETTINGS_KEY_LABELS = [
36554
37423
  ["statusLine", "status line"]
36555
37424
  ];
36556
37425
  function collectConfigFiles(scan2, claudeDir, cwd) {
36557
- settingsConfigFile(scan2, join16(claudeDir, "settings.json"), "user", "User settings");
36558
- settingsConfigFile(scan2, join16(cwd, ".claude", "settings.json"), "project", "Project settings");
36559
- settingsConfigFile(scan2, join16(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
36560
- memoryConfigFile(scan2, join16(claudeDir, "CLAUDE.md"), "user", "User memory");
36561
- memoryConfigFile(scan2, join16(cwd, "CLAUDE.md"), "project", "Project memory");
36562
- mcpJsonConfigFile(scan2, join16(cwd, ".mcp.json"));
36563
- dirConfigFile(scan2, join16(cwd, ".claude", "commands"), "Slash commands", "command");
36564
- dirConfigFile(scan2, join16(cwd, ".claude", "agents"), "Subagents", "subagent");
37426
+ settingsConfigFile(scan2, join19(claudeDir, "settings.json"), "user", "User settings");
37427
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.json"), "project", "Project settings");
37428
+ settingsConfigFile(scan2, join19(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
37429
+ memoryConfigFile(scan2, join19(claudeDir, "CLAUDE.md"), "user", "User memory");
37430
+ memoryConfigFile(scan2, join19(cwd, "CLAUDE.md"), "project", "Project memory");
37431
+ mcpJsonConfigFile(scan2, join19(cwd, ".mcp.json"));
37432
+ dirConfigFile(scan2, join19(cwd, ".claude", "commands"), "Slash commands", "command");
37433
+ dirConfigFile(scan2, join19(cwd, ".claude", "agents"), "Subagents", "subagent");
36565
37434
  }
36566
37435
  function configFileEntry(path, scope, kind) {
36567
37436
  try {
@@ -36636,7 +37505,7 @@ function countMarkdownFiles(dir, depth) {
36636
37505
  let count = 0;
36637
37506
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
36638
37507
  if (dirent.name.startsWith(".")) continue;
36639
- if (dirent.isDirectory()) count += countMarkdownFiles(join16(dir, dirent.name), depth + 1);
37508
+ if (dirent.isDirectory()) count += countMarkdownFiles(join19(dir, dirent.name), depth + 1);
36640
37509
  else if (dirent.name.endsWith(".md")) count += 1;
36641
37510
  }
36642
37511
  return count;
@@ -36649,7 +37518,7 @@ function collectSkillsDir(scan2, dir, origin) {
36649
37518
  return;
36650
37519
  }
36651
37520
  for (const name of names) {
36652
- const skillFile = join16(dir, name, "SKILL.md");
37521
+ const skillFile = join19(dir, name, "SKILL.md");
36653
37522
  try {
36654
37523
  const raw = readOptional(skillFile);
36655
37524
  if (raw === void 0) continue;
@@ -36658,7 +37527,7 @@ function collectSkillsDir(scan2, dir, origin) {
36658
37527
  name: front.name ?? name,
36659
37528
  source: origin.source,
36660
37529
  scope: origin.scope,
36661
- location: join16(dir, name),
37530
+ location: join19(dir, name),
36662
37531
  updatedAt: statSync7(skillFile).mtime.toISOString()
36663
37532
  };
36664
37533
  const version2 = front.version ?? origin.defaultVersion;
@@ -36689,7 +37558,7 @@ function parseFrontmatter(raw) {
36689
37558
  return out;
36690
37559
  }
36691
37560
  function collectInstalledPlugins(scan2, claudeDir) {
36692
- const manifestPath = join16(claudeDir, "plugins", "installed_plugins.json");
37561
+ const manifestPath = join19(claudeDir, "plugins", "installed_plugins.json");
36693
37562
  const raw = readOptional(manifestPath);
36694
37563
  if (raw === void 0) return;
36695
37564
  let plugins;
@@ -36714,7 +37583,7 @@ function collectInstalledPlugins(scan2, claudeDir) {
36714
37583
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
36715
37584
  seen.add(installPath);
36716
37585
  const version2 = install.version;
36717
- const hooksPath = join16(installPath, "hooks", "hooks.json");
37586
+ const hooksPath = join19(installPath, "hooks", "hooks.json");
36718
37587
  const hooksRaw = readOptional(hooksPath);
36719
37588
  if (hooksRaw !== void 0) {
36720
37589
  try {
@@ -36734,22 +37603,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
36734
37603
  }
36735
37604
  const origin = { source: marketplace, scope: "plugin", pluginName };
36736
37605
  if (typeof version2 === "string") origin.defaultVersion = version2;
36737
- collectSkillsDir(scan2, join16(installPath, "skills"), origin);
37606
+ collectSkillsDir(scan2, join19(installPath, "skills"), origin);
36738
37607
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
36739
- collectMcpFile(scan2, join16(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
37608
+ collectMcpFile(scan2, join19(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
36740
37609
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
36741
37610
  }
36742
37611
  }
36743
37612
  }
36744
37613
  function collectMarketplaceSkills(scan2, claudeDir) {
36745
- for (const mp of readMarketplaces(join16(claudeDir, "plugins", "known_marketplaces.json"))) {
37614
+ for (const mp of readMarketplaces(join19(claudeDir, "plugins", "known_marketplaces.json"))) {
36746
37615
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
36747
- collectSkillsDir(scan2, join16(mp.installLocation, "skills"), {
37616
+ collectSkillsDir(scan2, join19(mp.installLocation, "skills"), {
36748
37617
  source: mp.name,
36749
37618
  scope: "plugin"
36750
37619
  });
36751
- collectPluginSkillDirs(scan2, join16(mp.installLocation, "plugins"), mp.name);
36752
- collectPluginSkillDirs(scan2, join16(mp.installLocation, "external_plugins"), mp.name);
37620
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "plugins"), mp.name);
37621
+ collectPluginSkillDirs(scan2, join19(mp.installLocation, "external_plugins"), mp.name);
36753
37622
  }
36754
37623
  }
36755
37624
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -36760,7 +37629,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
36760
37629
  return;
36761
37630
  }
36762
37631
  for (const plugin of plugins) {
36763
- collectSkillsDir(scan2, join16(pluginsDir, plugin, "skills"), {
37632
+ collectSkillsDir(scan2, join19(pluginsDir, plugin, "skills"), {
36764
37633
  source: marketplace,
36765
37634
  scope: "plugin",
36766
37635
  pluginName: plugin
@@ -36814,7 +37683,7 @@ function dedupeMcpServers(servers) {
36814
37683
  }
36815
37684
  function readOptional(path) {
36816
37685
  try {
36817
- return readFileSync10(path, "utf8");
37686
+ return readFileSync12(path, "utf8");
36818
37687
  } catch {
36819
37688
  return void 0;
36820
37689
  }
@@ -36842,17 +37711,65 @@ function offersMaintenance(gateway, member) {
36842
37711
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36843
37712
 
36844
37713
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36845
- import { existsSync as existsSync9 } from "fs";
37714
+ import { existsSync as existsSync10 } from "fs";
36846
37715
  import { fileURLToPath } from "url";
36847
37716
  import { Worker } from "worker_threads";
36848
37717
 
37718
+ // ../../packages/plugin-sdk/src/host-floor.ts
37719
+ import { readFileSync as readFileSync14 } from "fs";
37720
+ import { join as join21 } from "path";
37721
+
37722
+ // ../../packages/plugin-sdk/src/model-governance.ts
37723
+ import {
37724
+ closeSync as closeSync2,
37725
+ fstatSync,
37726
+ mkdirSync as mkdirSync2,
37727
+ openSync as openSync2,
37728
+ readFileSync as readFileSync13,
37729
+ readSync,
37730
+ writeFileSync as writeFileSync5
37731
+ } from "fs";
37732
+ import { join as join20 } from "path";
37733
+ var SESSION_MODEL_MARKER = "session-model";
37734
+ function recordSessionModel(dataDir2, sessionId, model) {
37735
+ if (sessionId === void 0 || sessionId === "") return;
37736
+ if (model === void 0 || model === "") return;
37737
+ try {
37738
+ mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
37739
+ writeFileSync5(join20(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
37740
+ encoding: "utf8",
37741
+ mode: DATA_FILE_MODE
37742
+ });
37743
+ } catch {
37744
+ }
37745
+ }
37746
+ var TAIL_BYTES = 256 * 1024;
37747
+
37748
+ // ../../packages/plugin-sdk/src/host-floor.ts
37749
+ var HOST_FEATURE = {
37750
+ ModelSwitch: "model-switch",
37751
+ VaultPointerDisplay: "vault-pointer-display"
37752
+ };
37753
+ var HOST_FLOORS = {
37754
+ [HOST_FEATURE.ModelSwitch]: {
37755
+ label: "model-switch protection",
37756
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37757
+ since: "2.1.251"
37758
+ },
37759
+ [HOST_FEATURE.VaultPointerDisplay]: {
37760
+ label: "vault pointer display",
37761
+ hookEvents: ["MessageDisplay"],
37762
+ since: "2.1.152"
37763
+ }
37764
+ };
37765
+
36849
37766
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36850
37767
  var import_ignore = __toESM(require_ignore(), 1);
36851
- import { readFileSync as readFileSync11 } from "fs";
36852
- import { join as join17 } from "path";
37768
+ import { readFileSync as readFileSync15 } from "fs";
37769
+ import { join as join22 } from "path";
36853
37770
  function readIgnoreLayer(dir, filename, anchorLen) {
36854
37771
  try {
36855
- return { matcher: (0, import_ignore.default)().add(readFileSync11(join17(dir, filename), "utf8")), anchorLen };
37772
+ return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
36856
37773
  } catch {
36857
37774
  return void 0;
36858
37775
  }
@@ -36908,44 +37825,18 @@ function resolveInventoryContext(input2) {
36908
37825
  return ctx;
36909
37826
  }
36910
37827
 
36911
- // ../../packages/plugin-sdk/src/model-governance.ts
36912
- import {
36913
- closeSync as closeSync2,
36914
- fstatSync,
36915
- mkdirSync as mkdirSync2,
36916
- openSync as openSync2,
36917
- readFileSync as readFileSync12,
36918
- readSync,
36919
- writeFileSync as writeFileSync5
36920
- } from "fs";
36921
- import { join as join18 } from "path";
36922
- var SESSION_MODEL_MARKER = "session-model";
36923
- function recordSessionModel(dataDir2, sessionId, model) {
36924
- if (sessionId === void 0 || sessionId === "") return;
36925
- if (model === void 0 || model === "") return;
36926
- try {
36927
- mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
36928
- writeFileSync5(join18(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
36929
- encoding: "utf8",
36930
- mode: DATA_FILE_MODE
36931
- });
36932
- } catch {
36933
- }
36934
- }
36935
- var TAIL_BYTES = 256 * 1024;
36936
-
36937
37828
  // ../../packages/plugin-sdk/src/nudge.ts
36938
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36939
- import { join as join19 } from "path";
37829
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
37830
+ import { join as join23 } from "path";
36940
37831
  var SESSION_START_MARKER = "session-start-last";
36941
37832
  function claimSessionStart(dataDir2, sessionId) {
36942
37833
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
36943
37834
  }
36944
37835
  function claimOncePerSession(dataDir2, marker, sessionId) {
36945
37836
  if (!sessionId) return true;
36946
- const path = join19(dataDir2, marker);
37837
+ const path = join23(dataDir2, marker);
36947
37838
  try {
36948
- if (readFileSync13(path, "utf8") === sessionId) return false;
37839
+ if (readFileSync16(path, "utf8") === sessionId) return false;
36949
37840
  } catch {
36950
37841
  }
36951
37842
  try {
@@ -36961,8 +37852,8 @@ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
36961
37852
  import { basename as basename5, dirname as dirname5, sep as sep3 } from "path";
36962
37853
 
36963
37854
  // ../../packages/plugin-sdk/src/project-files.ts
36964
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36965
- import { basename as basename6, join as join20 } from "path";
37855
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37856
+ import { basename as basename6, join as join24 } from "path";
36966
37857
  var SKIP_DIRS = /* @__PURE__ */ new Set([
36967
37858
  ".git",
36968
37859
  "node_modules",
@@ -37059,8 +37950,8 @@ function resolveProjectFiles(cwd, opts = {}) {
37059
37950
  }
37060
37951
  if (entry.isDirectory()) {
37061
37952
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
37062
- const fullPath = join20(dir, entry.name);
37063
- if (existsSync10(join20(fullPath, ".git"))) continue;
37953
+ const fullPath = join24(dir, entry.name);
37954
+ if (existsSync11(join24(fullPath, ".git"))) continue;
37064
37955
  if (depth >= bounds.maxDepth) {
37065
37956
  walk.omitted = true;
37066
37957
  continue;
@@ -37133,9 +38024,9 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37133
38024
 
37134
38025
  // ../../packages/plugin-sdk/src/throttle.ts
37135
38026
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37136
- import { join as join21 } from "path";
38027
+ import { join as join25 } from "path";
37137
38028
  function throttled(dataDir2, markerName, windowMs) {
37138
- const marker = join21(dataDir2, markerName);
38029
+ const marker = join25(dataDir2, markerName);
37139
38030
  try {
37140
38031
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
37141
38032
  } catch {
@@ -37162,31 +38053,12 @@ function isServerRejection(err) {
37162
38053
  var FORWARD_BUDGET_MS = 1500;
37163
38054
  var DECISION_PATH_BUDGET_MS = 800;
37164
38055
  var BREAKER_FAILURE_THRESHOLD = 3;
37165
- var BREAKER_COOLDOWN_MS = 3e4;
37166
38056
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
37167
- var FAILURES = /* @__PURE__ */ new Set([
37168
- "unauthorized",
37169
- "forbidden",
37170
- "unreachable"
37171
- ]);
37172
38057
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
37173
38058
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
37174
- function parseBreakerState(raw, nowMs) {
37175
- try {
37176
- const parsed2 = JSON.parse(raw);
37177
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
37178
- const record2 = parsed2;
37179
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
37180
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
37181
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
37182
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
37183
- } catch {
37184
- return null;
37185
- }
37186
- }
37187
38059
  function createForwardPolicy(deps) {
37188
38060
  const now = deps.now ?? (() => Date.now());
37189
- const file2 = join22(deps.dir, STATE_FILENAME);
38061
+ const file2 = join26(deps.dir, STATE_FILENAME);
37190
38062
  let state = null;
37191
38063
  let loading = null;
37192
38064
  async function readState() {
@@ -37196,7 +38068,7 @@ function createForwardPolicy(deps) {
37196
38068
  } catch {
37197
38069
  return { ...CLOSED };
37198
38070
  }
37199
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
38071
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
37200
38072
  }
37201
38073
  async function load() {
37202
38074
  if (state !== null) return state;
@@ -37242,7 +38114,7 @@ function createForwardPolicy(deps) {
37242
38114
  };
37243
38115
  const at = now();
37244
38116
  if (current.openedAtMs !== null) {
37245
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
38117
+ if (isForwardPaused(current, at)) {
37246
38118
  return { ok: false, reason: "breaker-open" };
37247
38119
  }
37248
38120
  await persist({
@@ -37779,7 +38651,18 @@ var AttachedDataGateway = class {
37779
38651
  // and the spread above would otherwise drop the field silently — which is
37780
38652
  // exactly what it did, leaving the whole control inert on every device
37781
38653
  // while every test around it stayed green.
37782
- prohibitedModels: cached2.prohibitedModels
38654
+ prohibitedModels: cached2.prohibitedModels,
38655
+ // NAMED for the same reason as the line above, and it is the same defect
38656
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
38657
+ // only the cache carries is dropped in silence. That is what left
38658
+ // `prohibitedModels` inert on every attached device with every test
38659
+ // around it green.
38660
+ //
38661
+ // Taken from the cache rather than merged here, because merging it needs
38662
+ // the device's own SETTING — which is not a bundle field and is not in
38663
+ // scope at this seam. The runtime does that merge, raise-only, where both
38664
+ // values are in hand (createPluginRuntime's ensureInitialized).
38665
+ redactFallback: cached2.redactFallback
37783
38666
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
37784
38667
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
37785
38668
  // it emits, so an 'authored' policy arriving from the control plane
@@ -37907,10 +38790,6 @@ function toolAuditEvent(input2) {
37907
38790
  };
37908
38791
  }
37909
38792
 
37910
- // ../../packages/plugin-runtime/src/attached/history-state.ts
37911
- import { readFileSync as readFileSync15 } from "fs";
37912
- import { join as join23 } from "path";
37913
-
37914
38793
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37915
38794
  import { createHash as createHash6 } from "crypto";
37916
38795
  import { hostname as hostname5 } from "os";
@@ -37919,6 +38798,10 @@ import { hostname as hostname5 } from "os";
37919
38798
  var CORRELATION_ID = EventMetadata.shape.correlationId;
37920
38799
  var TRACE_ID = EventMetadata.shape.traceId;
37921
38800
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
38801
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
38802
+
38803
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
38804
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
37922
38805
 
37923
38806
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37924
38807
  import { spawn } from "child_process";
@@ -37950,14 +38833,14 @@ function spawnDetached(scriptPath) {
37950
38833
  }
37951
38834
 
37952
38835
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37953
- import { readFileSync as readFileSync16 } from "fs";
38836
+ import { readFileSync as readFileSync17 } from "fs";
37954
38837
  var manifestBuildCache = /* @__PURE__ */ new Map();
37955
38838
  function readManifestBuild(manifestUrl, packageName) {
37956
38839
  const key = manifestUrl.href;
37957
38840
  if (!manifestBuildCache.has(key)) {
37958
38841
  let build;
37959
38842
  try {
37960
- const manifest = JSON.parse(readFileSync16(manifestUrl, "utf8"));
38843
+ const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
37961
38844
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
37962
38845
  } catch {
37963
38846
  build = void 0;
@@ -37984,7 +38867,7 @@ function createPluginBlock(build, policyStore) {
37984
38867
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37985
38868
  import { randomUUID as randomUUID16 } from "crypto";
37986
38869
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
37987
- import { join as join24 } from "path";
38870
+ import { join as join27 } from "path";
37988
38871
 
37989
38872
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37990
38873
  import { rename as rename2 } from "fs/promises";
@@ -38008,7 +38891,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38008
38891
 
38009
38892
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38010
38893
  function createPolicyStore(dir = dataDir()) {
38011
- const file2 = join24(dir, "policy-cache.json");
38894
+ const file2 = join27(dir, "policy-cache.json");
38012
38895
  async function read() {
38013
38896
  try {
38014
38897
  const raw = await readFile2(file2, "utf8");
@@ -38239,11 +39122,11 @@ function readStorePosture(dbPath2) {
38239
39122
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38240
39123
  import { randomUUID as randomUUID17 } from "crypto";
38241
39124
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38242
- import { join as join25 } from "path";
39125
+ import { join as join28 } from "path";
38243
39126
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38244
39127
  function createPostureStore(dir = settingsDir(), legacyDir) {
38245
- const file2 = join25(dir, "posture-state.json");
38246
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
39128
+ const file2 = join28(dir, "posture-state.json");
39129
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
38247
39130
  async function persist(state) {
38248
39131
  await ensureDataDir(dir);
38249
39132
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38311,8 +39194,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38311
39194
  }
38312
39195
 
38313
39196
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38314
- import { readFileSync as readFileSync17 } from "fs";
38315
- import { join as join26 } from "path";
39197
+ import { readFileSync as readFileSync18 } from "fs";
39198
+ import { join as join29 } from "path";
38316
39199
 
38317
39200
  // ../../packages/plugin-runtime/src/attached/status.ts
38318
39201
  var REFUSAL_LINES = {
@@ -38354,6 +39237,34 @@ function spawnDetached2(scriptPath) {
38354
39237
  child.unref();
38355
39238
  }
38356
39239
 
39240
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
39241
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39242
+
39243
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
39244
+ import { spawn as spawn3 } from "child_process";
39245
+ import { fileURLToPath as fileURLToPath4 } from "url";
39246
+ var CONTENT_RETENTION_MARKER_NAME = "content-retention-last-attempt";
39247
+ var CONTENT_RETENTION_SCRIPT_NAME = "content-retention.js";
39248
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
39249
+ function triggerContentRetention(config2, deps = {}) {
39250
+ try {
39251
+ if (!config2.settings.bodyRetention.enabled) return;
39252
+ const isThrottled = deps.isThrottled ?? ((dir) => throttled(dir, CONTENT_RETENTION_MARKER_NAME, CONTENT_RETENTION_THROTTLE_MS));
39253
+ if (isThrottled(config2.dataDir)) return;
39254
+ const scriptPath = fileURLToPath4(
39255
+ deps.scriptUrl ?? new URL(CONTENT_RETENTION_SCRIPT_NAME, import.meta.url)
39256
+ );
39257
+ (deps.spawnChild ?? spawnDetached3)(scriptPath);
39258
+ } catch {
39259
+ }
39260
+ }
39261
+ function spawnDetached3(scriptPath) {
39262
+ const child = spawn3(process.execPath, [scriptPath], { detached: true, stdio: "ignore" });
39263
+ child.on("error", () => {
39264
+ });
39265
+ child.unref();
39266
+ }
39267
+
38357
39268
  // ../../packages/plugin-runtime/src/attached/factory.ts
38358
39269
  import { hostname as hostname6 } from "os";
38359
39270
 
@@ -38870,6 +39781,7 @@ async function handleSessionStart(input2, config2 = loadConfig()) {
38870
39781
  }
38871
39782
  triggerPolicySync(config2);
38872
39783
  triggerHistorySync(config2);
39784
+ triggerContentRetention(config2);
38873
39785
  if (input2.harnessVersion !== void 0 && offersMaintenance(gateway, "staleBinaryNotice")) {
38874
39786
  return { staleBinaryNotice: gateway.staleBinaryNotice(input2.harnessVersion) };
38875
39787
  }
@@ -38916,10 +39828,10 @@ function buildSessionRoot(sessionId, input2, ctx, resolved, provider, branch) {
38916
39828
  const attributes = {};
38917
39829
  const osVersion = ctx.host?.attributes.os_version;
38918
39830
  const harnessVersion2 = ctx.harness?.attributes.harness_version;
38919
- const harnessInterface = ctx.harness?.attributes.interface;
39831
+ const harnessInterface2 = ctx.harness?.attributes.interface;
38920
39832
  if (typeof osVersion === "string") attributes.os_version = osVersion;
38921
39833
  if (typeof harnessVersion2 === "string") attributes.harness_version = harnessVersion2;
38922
- if (typeof harnessInterface === "string") attributes.harness_interface = harnessInterface;
39834
+ if (typeof harnessInterface2 === "string") attributes.harness_interface = harnessInterface2;
38923
39835
  attributes.provider = provider.provider;
38924
39836
  if (provider.gatewayHost !== void 0) attributes.gateway_host = provider.gatewayHost;
38925
39837
  attributes.harness = harnessFromTool(input2.tool);
@@ -38951,9 +39863,9 @@ function pluginBuild() {
38951
39863
  }
38952
39864
 
38953
39865
  // src/history/reconcile-trigger.ts
38954
- import { spawn as spawn3 } from "child_process";
38955
- import { dirname as dirname6, join as join28 } from "path";
38956
- import { fileURLToPath as fileURLToPath4 } from "url";
39866
+ import { spawn as spawn4 } from "child_process";
39867
+ import { dirname as dirname6, join as join31 } from "path";
39868
+ import { fileURLToPath as fileURLToPath5 } from "url";
38957
39869
 
38958
39870
  // src/history/tail.ts
38959
39871
  import { createHash as createHash7 } from "crypto";
@@ -38962,11 +39874,11 @@ import {
38962
39874
  fstatSync as fstatSync2,
38963
39875
  mkdirSync as mkdirSync5,
38964
39876
  openSync as openSync3,
38965
- readFileSync as readFileSync18,
39877
+ readFileSync as readFileSync19,
38966
39878
  readSync as readSync2,
38967
39879
  writeFileSync as writeFileSync8
38968
39880
  } from "fs";
38969
- import { join as join27 } from "path";
39881
+ import { join as join30 } from "path";
38970
39882
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
38971
39883
  function safeSessionId(sessionId) {
38972
39884
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
@@ -38982,8 +39894,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
38982
39894
  try {
38983
39895
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
38984
39896
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
38985
- const here = dirname6(fileURLToPath4(import.meta.url));
38986
- const child = spawn3(process.execPath, [join28(here, "reconcile.js"), sessionId, transcriptPath], {
39897
+ const here = dirname6(fileURLToPath5(import.meta.url));
39898
+ const child = spawn4(process.execPath, [join31(here, "reconcile.js"), sessionId, transcriptPath], {
38987
39899
  detached: true,
38988
39900
  stdio: "ignore"
38989
39901
  });
@@ -38994,17 +39906,17 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
38994
39906
 
38995
39907
  // src/protocol/marker.ts
38996
39908
  import { randomBytes as randomBytes4 } from "crypto";
38997
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync19, renameSync as renameSync5, writeFileSync as writeFileSync9 } from "fs";
38998
- import { join as join29 } from "path";
39909
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync20, renameSync as renameSync5, writeFileSync as writeFileSync9 } from "fs";
39910
+ import { join as join32 } from "path";
38999
39911
  var MARKER_FILE = "protocol-marker";
39000
39912
  function mintMarker() {
39001
39913
  return randomBytes4(8).toString("hex");
39002
39914
  }
39003
39915
  function sessionProtocolMarker(dataDir2, sessionId) {
39004
39916
  if (!sessionId) return mintMarker();
39005
- const path = join29(dataDir2, MARKER_FILE);
39917
+ const path = join32(dataDir2, MARKER_FILE);
39006
39918
  try {
39007
- const stored = JSON.parse(readFileSync19(path, "utf8"));
39919
+ const stored = JSON.parse(readFileSync20(path, "utf8"));
39008
39920
  if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
39009
39921
  return stored.marker;
39010
39922
  }
@@ -39013,7 +39925,7 @@ function sessionProtocolMarker(dataDir2, sessionId) {
39013
39925
  const marker = mintMarker();
39014
39926
  try {
39015
39927
  mkdirSync6(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
39016
- const tmp = join29(dataDir2, `${MARKER_FILE}.tmp`);
39928
+ const tmp = join32(dataDir2, `${MARKER_FILE}.tmp`);
39017
39929
  writeFileSync9(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
39018
39930
  renameSync5(tmp, path);
39019
39931
  } catch {
@@ -39076,8 +39988,8 @@ function emit(output2) {
39076
39988
  }
39077
39989
 
39078
39990
  // src/hooks/store-health.ts
39079
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync20, writeFileSync as writeFileSync10 } from "fs";
39080
- import { dirname as dirname7, join as join30 } from "path";
39991
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync10 } from "fs";
39992
+ import { dirname as dirname7, join as join33 } from "path";
39081
39993
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
39082
39994
  function markerDirs(dataDir2) {
39083
39995
  return [dataDir2, dirname7(dataDir2)];
@@ -39085,7 +39997,7 @@ function markerDirs(dataDir2) {
39085
39997
  function alreadyClaimed(dirs, marker, sessionId) {
39086
39998
  return dirs.some((dir) => {
39087
39999
  try {
39088
- return readFileSync20(join30(dir, marker), "utf8") === sessionId;
40000
+ return readFileSync21(join33(dir, marker), "utf8") === sessionId;
39089
40001
  } catch {
39090
40002
  return false;
39091
40003
  }
@@ -39095,7 +40007,7 @@ function recordClaim(dirs, marker, sessionId) {
39095
40007
  for (const dir of dirs) {
39096
40008
  try {
39097
40009
  mkdirSync7(dir, { recursive: true, mode: DATA_DIR_MODE });
39098
- writeFileSync10(join30(dir, marker), sessionId, { mode: DATA_FILE_MODE });
40010
+ writeFileSync10(join33(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39099
40011
  return;
39100
40012
  } catch {
39101
40013
  }
@@ -39135,11 +40047,15 @@ function warnIfStoreRedirected(config2, sessionId, write = (message2) => void pr
39135
40047
  }
39136
40048
 
39137
40049
  // src/hooks/session-start.ts
40050
+ function harnessInterface() {
40051
+ const value = process.env.CLAUDE_CODE_ENTRYPOINT;
40052
+ return value === void 0 || value === "" ? void 0 : value;
40053
+ }
39138
40054
  function harnessVersion() {
39139
40055
  const manifestPath = process.argv[2];
39140
40056
  if (!manifestPath) return void 0;
39141
40057
  try {
39142
- const manifest = JSON.parse(readFileSync21(manifestPath, "utf8"));
40058
+ const manifest = JSON.parse(readFileSync22(manifestPath, "utf8"));
39143
40059
  return typeof manifest.version === "string" ? manifest.version : void 0;
39144
40060
  } catch {
39145
40061
  return void 0;
@@ -39157,11 +40073,12 @@ async function main() {
39157
40073
  cwd,
39158
40074
  tool: SOURCE_TOOL.ClaudeCode,
39159
40075
  harnessVersion: version2,
39160
- pluginBuild: version2 === void 0 ? void 0 : { package: PLUGIN_PACKAGE, version: version2 }
39161
- // harnessInterface is intentionally omitted: Claude Code's SessionStart hook
39162
- // exposes no meaningful interface discriminator (terminal vs IDE vs web) yet.
39163
- // The resolver already folds it into the harness bag, so pass it here once
39164
- // the harness surfaces one — no schema change needed.
40076
+ pluginBuild: version2 === void 0 ? void 0 : { package: PLUGIN_PACKAGE, version: version2 },
40077
+ // The surface this session is running on, when the host says. Folded into
40078
+ // the harness bag by the resolver and snapshotted as `harness_interface`;
40079
+ // absent when the host stamps nothing, which reads as unknown rather than
40080
+ // as a terminal session.
40081
+ harnessInterface: harnessInterface()
39165
40082
  });
39166
40083
  if (result.staleBinaryNotice !== null) {
39167
40084
  process.stderr.write(`[aka] ${result.staleBinaryNotice}