@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
@@ -502,6 +502,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
502
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
503
503
  import { join as join2 } from "path";
504
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
505
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
506
514
  var SQLITE_MIGRATIONS = [
507
515
  {
@@ -619,6 +627,30 @@ var SQLITE_MIGRATIONS = [
619
627
  {
620
628
  tag: "0028_activity_session_probe_indexes",
621
629
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
622
654
  }
623
655
  ];
624
656
 
@@ -20420,6 +20452,93 @@ function epochMillisToIso(ms) {
20420
20452
  return new Date(ms).toISOString();
20421
20453
  }
20422
20454
 
20455
+ // ../../packages/schema/src/security/recommendations.ts
20456
+ var SEVERITY_WEIGHT = {
20457
+ critical: 4,
20458
+ high: 3,
20459
+ medium: 2,
20460
+ low: 1
20461
+ };
20462
+ function severityWeight(severity) {
20463
+ return Object.hasOwn(SEVERITY_WEIGHT, severity) ? SEVERITY_WEIGHT[severity] : 0;
20464
+ }
20465
+ var ADVICE = {
20466
+ secret: "Rotate the exposed credentials and move them out of prompts (secrets manager / env vars).",
20467
+ pii: "Remove or mask personal data before it reaches the model.",
20468
+ financial: "Strip card and account numbers; share only non-sensitive references.",
20469
+ phi: "Remove protected health information \u2014 it should never reach an external model.",
20470
+ code_context: "Confirm this proprietary code context is safe to share.",
20471
+ code_flaw: "Review the flagged pattern and apply the secure alternative (parameterized queries, safe deserializers, etc.).",
20472
+ config: "Review the setting \u2014 a hook conflict or an egress change applies to every session that follows.",
20473
+ custom: "Review against your organization\u2019s custom policy."
20474
+ };
20475
+ var REC_TEMPLATE = {
20476
+ secret: { title: "Exposed secret detected", action: "Rotate" },
20477
+ pii: { title: "Personal data in a prompt", action: "Remove" },
20478
+ financial: { title: "Financial data detected", action: "Strip" },
20479
+ phi: { title: "Health information detected", action: "Remove" },
20480
+ code_context: { title: "Proprietary code shared", action: "Review" },
20481
+ code_flaw: { title: "Insecure code pattern", action: "Fix" },
20482
+ config: { title: "Weakened configuration", action: "Review" },
20483
+ custom: { title: "Custom policy match", action: "Review" }
20484
+ };
20485
+ var MAX_RECOMMENDATIONS = 10;
20486
+ function bucketizeRecommendations(findings) {
20487
+ const byRule = /* @__PURE__ */ new Map();
20488
+ const buckets = /* @__PURE__ */ new Map();
20489
+ for (const f of findings) {
20490
+ const n = f.count ?? 1;
20491
+ byRule.set(f.ruleId, (byRule.get(f.ruleId) ?? 0) + n);
20492
+ const b = buckets.get(f.category) ?? {
20493
+ category: f.category,
20494
+ count: 0,
20495
+ categoryCount: 0,
20496
+ severity: f.severity,
20497
+ weight: 0,
20498
+ ruleId: f.ruleId
20499
+ };
20500
+ b.categoryCount += n;
20501
+ const w = severityWeight(f.severity);
20502
+ if (w > b.weight) {
20503
+ b.weight = w;
20504
+ b.severity = f.severity;
20505
+ b.ruleId = f.ruleId;
20506
+ }
20507
+ buckets.set(f.category, b);
20508
+ }
20509
+ for (const b of buckets.values()) b.count = byRule.get(b.ruleId) ?? 0;
20510
+ return [...buckets.values()].sort((a, b) => b.weight - a.weight || b.categoryCount - a.categoryCount).slice(0, MAX_RECOMMENDATIONS);
20511
+ }
20512
+ function buildRecommendations(findings) {
20513
+ return bucketizeRecommendations(findings).map((b) => {
20514
+ const copy = recommendationCopy(b.category);
20515
+ return {
20516
+ severity: b.severity,
20517
+ title: copy.title,
20518
+ description: copy.advice,
20519
+ context: `${b.ruleId} \xB7 ${String(b.count)} finding${b.count === 1 ? "" : "s"}`,
20520
+ action: copy.action
20521
+ };
20522
+ });
20523
+ }
20524
+ function recommendationCopy(category) {
20525
+ const template = REC_TEMPLATE_BY_STRING[category] ?? {
20526
+ title: `${category} finding`,
20527
+ action: "Review"
20528
+ };
20529
+ return {
20530
+ ...template,
20531
+ advice: ADVICE_BY_STRING[category] ?? "Review this finding against your policy."
20532
+ };
20533
+ }
20534
+ var ADVICE_BY_STRING = ADVICE;
20535
+ var REC_TEMPLATE_BY_STRING = REC_TEMPLATE;
20536
+ function healthScore(summary) {
20537
+ const handled = summary.byAction.block + summary.byAction.redact + summary.byAction.warn;
20538
+ const handledRatio = summary.findings === 0 ? 1 : handled / summary.findings;
20539
+ return Math.round(100 * (0.6 * summary.coverage + 0.4 * handledRatio));
20540
+ }
20541
+
20423
20542
  // ../../packages/schema/src/token/cost-model.ts
20424
20543
  var PROVIDER_PLATFORM = /* @__PURE__ */ new Map([
20425
20544
  ["anthropic", "anthropic"],
@@ -20666,6 +20785,15 @@ var FindingCategory = external_exports.enum([
20666
20785
  ]).meta({ id: "FindingCategory" });
20667
20786
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20668
20787
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20788
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20789
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20790
+ var FindingDelivery = external_exports.object({
20791
+ state: FindingDeliveryState,
20792
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20793
+ at: external_exports.iso.datetime().optional(),
20794
+ // Only on `not_sent`, and only when a known reason was recorded.
20795
+ reason: SyncFailureReason.optional()
20796
+ }).meta({ id: "FindingDelivery" });
20669
20797
  var ResolutionMethod = external_exports.enum([
20670
20798
  "enforced-in-flight",
20671
20799
  "fixed-at-source",
@@ -20722,7 +20850,10 @@ var FindingInstance = external_exports.object({
20722
20850
  // The session that event belongs to, when it has one — the seam a
20723
20851
  // per-instance "view session" link needs. Absent for events captured
20724
20852
  // outside a session.
20725
- sessionId: external_exports.string().optional()
20853
+ sessionId: external_exports.string().optional(),
20854
+ // The delivery state of the event above (see FindingDelivery). Optional so
20855
+ // readers that do not project it stay valid.
20856
+ delivery: FindingDelivery.optional()
20726
20857
  }).meta({ id: "FindingInstance" });
20727
20858
  var FindingGroup = external_exports.object({
20728
20859
  id: external_exports.string(),
@@ -20739,13 +20870,11 @@ var FindingGroup = external_exports.object({
20739
20870
  latestDetectedAt: external_exports.iso.datetime(),
20740
20871
  instances: external_exports.array(FindingInstance),
20741
20872
  // Derived from instances' statuses with open-dominates precedence (see
20742
- // buildFindingGroups). Undefined only when no instance carries a status.
20873
+ // foldGroupStatus). Undefined only when no instance carries a status.
20743
20874
  status: FindingStatus.optional(),
20744
- // The distinct people across the WHOLE group, not just the `instances`
20745
- // preview — from the store's whole-group aggregate when it supplies one,
20746
- // else folded from the rows (see buildFindingGroups). Undefined when no
20747
- // instance carries a user, or when the store supplied whole-group folds
20748
- // without one.
20875
+ // The distinct people across the WHOLE group, not just the instances
20876
+ // carried here. Undefined when no instance carries a user, or when the
20877
+ // store supplied whole-group folds without one.
20749
20878
  users: external_exports.array(FindingUser).optional()
20750
20879
  }).meta({ id: "FindingGroup" });
20751
20880
  var FindingStats = external_exports.object({
@@ -20774,21 +20903,34 @@ var FindingFacets = external_exports.object({
20774
20903
  // counted under no value.
20775
20904
  status: external_exports.array(FindingFacetItem),
20776
20905
  // Host tool (attributes.tool_name). Present only on the instance-level
20777
- // reads, which can filter by it; the grouped read omits the dimension
20906
+ // reads, which can filter by it; the type-level read omits the dimension
20778
20907
  // because a group spans tools.
20779
- tool: external_exports.array(FindingFacetItem).optional()
20908
+ tool: external_exports.array(FindingFacetItem).optional(),
20909
+ // Delivery states (FindingDeliveryState). Present only on the
20910
+ // instance-level reads, like `tool`.
20911
+ deployment: external_exports.array(FindingFacetItem).optional()
20780
20912
  }).meta({ id: "FindingFacets" });
20781
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20782
- var ListGroupedFindingsQuery = external_exports.object({
20913
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20914
+ id: "FindingTypeSummary"
20915
+ });
20916
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20917
+ var MAX_FINDING_TYPES_LIMIT = 100;
20918
+ var ListFindingTypesQuery = external_exports.object({
20783
20919
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20784
- // FindingAction.
20920
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20921
+ // firing version carries, and this list pages types.
20922
+ //
20923
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20924
+ // definition versions at different severities, so a type kept by this filter
20925
+ // can hold findings that individually do not match — see totals.findings on
20926
+ // ListFindingTypesResponse, which counts them all.
20785
20927
  severity: external_exports.array(Severity).optional(),
20786
20928
  subtype: external_exports.array(external_exports.string()).optional(),
20787
20929
  provider: external_exports.array(FindingProvider).optional(),
20788
20930
  action: external_exports.array(FindingAction).optional(),
20789
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20790
- // individual instances' — so a filtered group's Status column always reads
20791
- // one of the requested values.
20931
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20932
+ // individual findings' — so a filtered row's status always reads one of the
20933
+ // requested values.
20792
20934
  status: external_exports.array(FindingStatus).optional(),
20793
20935
  q: external_exports.string().optional(),
20794
20936
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20798,23 +20940,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20798
20940
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20799
20941
  // means all time — this list has no default window.
20800
20942
  from: external_exports.iso.datetime().optional(),
20801
- // A group or instance id that must appear in the page even when the cursor
20802
- // has already advanced past its sort position. This is what keeps the
20803
- // Findings page's one-shot ?finding= deep link resolving once the list
20804
- // paginates: the target group is appended out of sort order rather than
20805
- // scanning forward for it. Never affects totals, facets or the cursor.
20943
+ // A RULE id that must appear in the page even when the cursor has already
20944
+ // advanced past its sort position. This is what keeps the selected type
20945
+ // visible in the list once it paginates: the target is appended out of sort
20946
+ // order rather than scanned forward for. Never affects totals, facets or the
20947
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20948
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20949
+ // and so is not bounded by what any page happens to hold.
20806
20950
  includeId: external_exports.string().optional(),
20807
- groupBy: external_exports.literal("type").optional(),
20808
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20951
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20809
20952
  cursor: external_exports.string().optional()
20810
20953
  });
20811
- var ListGroupedFindingsResponse = external_exports.object({
20954
+ var ListFindingTypesResponse = external_exports.object({
20812
20955
  totals: external_exports.object({
20956
+ // Findings belonging to the matching TYPES — not findings that each match
20957
+ // the filters. The filters here select types, so a type that survives
20958
+ // contributes its whole instanceCount.
20959
+ //
20960
+ // `status` is the one exception, narrowed per finding via
20961
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20962
+ // this can exceed what the instance read reports for the same filters: a
20963
+ // rule whose severity moved between versions is kept on its newest and
20964
+ // still counts its older findings. Narrowing the other three needs
20965
+ // per-dimension counts the aggregate does not carry today.
20813
20966
  findings: external_exports.number().int().nonnegative(),
20814
- groups: external_exports.number().int().nonnegative()
20967
+ // Counts TYPES, which is the unit this read pages. The instance read's
20968
+ // own totals count findings; the two deliberately answer different
20969
+ // questions and are never summed.
20970
+ types: external_exports.number().int().nonnegative()
20815
20971
  }),
20816
20972
  facets: FindingFacets,
20817
- items: external_exports.array(FindingGroup),
20973
+ items: external_exports.array(FindingTypeSummary),
20818
20974
  nextCursor: external_exports.string().nullable(),
20819
20975
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20820
20976
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20822,7 +20978,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20822
20978
  // every firing, so the two numbers legitimately differ — this map lets a
20823
20979
  // session-scoped view show both.
20824
20980
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20825
- }).meta({ id: "ListGroupedFindingsResponse" });
20981
+ }).meta({ id: "ListFindingTypesResponse" });
20826
20982
  var ApplyFindingActionRequest = external_exports.object({
20827
20983
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20828
20984
  // it, so it is excluded from the request contract. The mapping helper
@@ -20852,16 +21008,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20852
21008
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20853
21009
  var ListFindingInstancesQuery = external_exports.object({
20854
21010
  severity: external_exports.array(Severity).optional(),
20855
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
21011
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
21012
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20856
21013
  subtype: external_exports.array(external_exports.string()).optional(),
20857
21014
  provider: external_exports.array(FindingProvider).optional(),
20858
21015
  action: external_exports.array(FindingAction).optional(),
20859
21016
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20860
- // the grouped query's group-level fold.
21017
+ // the types query's type-level fold.
20861
21018
  status: external_exports.array(FindingStatus).optional(),
20862
21019
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20863
21020
  // where the free-text `q` can only match the rendered "via Bash" label.
20864
21021
  tool: external_exports.array(external_exports.string()).optional(),
21022
+ // The delivery state of each finding's event (see FindingDelivery).
21023
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20865
21024
  // Exact repository / file-path matches, for the drill-down out of the
20866
21025
  // locations view. A row whose event carries no repo/file matches neither.
20867
21026
  repo: external_exports.string().optional(),
@@ -20874,37 +21033,51 @@ var ListFindingInstancesQuery = external_exports.object({
20874
21033
  });
20875
21034
  var ListFindingInstancesResponse = external_exports.object({
20876
21035
  // Instances matching the filters across the whole scope, not just this
20877
- // page — cursor-independent, like the grouped list's totals.
21036
+ // page — cursor-independent, like the types list's totals.
20878
21037
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20879
- // Counts in INSTANCES here, where the grouped response counts groups. Each
21038
+ // Counts in INSTANCES here, where the types response counts types. Each
20880
21039
  // dimension still excludes its own filter.
20881
21040
  facets: FindingFacets,
20882
21041
  items: external_exports.array(FindingInstanceDetail),
20883
21042
  nextCursor: external_exports.string().nullable()
20884
21043
  }).meta({ id: "ListFindingInstancesResponse" });
20885
- var FindingLocationFile = external_exports.object({
20886
- // Empty when the instances carried no file path (a prompt or a tool call
20887
- // with no file attribution).
20888
- file: external_exports.string(),
20889
- instanceCount: external_exports.number().int().nonnegative(),
20890
- maxSeverity: Severity,
20891
- latestDetectedAt: external_exports.iso.datetime(),
20892
- // Folded from the instances' derived statuses with the same
20893
- // open-dominates precedence a group uses.
20894
- status: FindingStatus.optional(),
20895
- // Distinct rules seen at this location, capped — the row shows them as
20896
- // chips, and the count is what conveys scale.
20897
- ruleIds: external_exports.array(external_exports.string())
20898
- }).meta({ id: "FindingLocationFile" });
20899
- var FindingLocationRepo = external_exports.object({
21044
+ var ListFindingInstancesPage = external_exports.object({
21045
+ items: external_exports.array(FindingInstanceDetail),
21046
+ nextCursor: external_exports.string().nullable()
21047
+ }).meta({ id: "ListFindingInstancesPage" });
21048
+ var FindingLocationSummary = external_exports.object({
21049
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
21050
+ // because a location's identity is two values and a URL param carries one:
21051
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
21052
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
21053
+ // client's page dedupe — never decoded, and never a sort key.
21054
+ id: external_exports.string(),
20900
21055
  /** Empty when the instances carried no repo attribute. */
20901
21056
  repo: external_exports.string(),
21057
+ // Empty when the instances carried no file path (a prompt, or a tool call
21058
+ // with no file attribution). Both halves empty is a real location — usually
21059
+ // the largest one in a store — and is selectable like any other.
21060
+ file: external_exports.string(),
20902
21061
  instanceCount: external_exports.number().int().nonnegative(),
21062
+ // The WORST severity present, not the first row's. It is this list's primary
21063
+ // sort key, so it is also what explains why a row is where it is, and it is
21064
+ // how a reader decides what to open without opening everything.
20903
21065
  maxSeverity: Severity,
20904
21066
  latestDetectedAt: external_exports.iso.datetime(),
21067
+ // Folded from the instances' derived statuses with the same open-dominates
21068
+ // precedence a group uses, so it answers "is anything left to do here" and
21069
+ // not much more: a location holding 1 open among 40 resolved reads like one
21070
+ // holding 40 open. That loss is accepted — the panel beside this list
21071
+ // carries each finding's own status, and instanceCount sits next to the
21072
+ // badge.
20905
21073
  status: FindingStatus.optional(),
20906
- files: external_exports.array(FindingLocationFile)
20907
- }).meta({ id: "FindingLocationRepo" });
21074
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
21075
+ // tally rather than a sample and a row can say how many there are. Bounded
21076
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
21077
+ ruleIds: external_exports.array(external_exports.string())
21078
+ }).meta({ id: "FindingLocationSummary" });
21079
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
21080
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20908
21081
  var ListFindingLocationsQuery = external_exports.object({
20909
21082
  severity: external_exports.array(Severity).optional(),
20910
21083
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20914,21 +21087,47 @@ var ListFindingLocationsQuery = external_exports.object({
20914
21087
  // instances that match, and folds its status from those.
20915
21088
  status: external_exports.array(FindingStatus).optional(),
20916
21089
  tool: external_exports.array(external_exports.string()).optional(),
21090
+ // The delivery state of each finding's event (see FindingDelivery).
21091
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20917
21092
  q: external_exports.string().optional(),
20918
21093
  sessionId: external_exports.string().optional(),
20919
21094
  from: external_exports.iso.datetime().optional(),
20920
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
21095
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
21096
+ // even when the cursor has already advanced past its sort position — the
21097
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
21098
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
21099
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
21100
+ // into the thousands, a selection sitting off page 0 is the ordinary case
21101
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
21102
+ includeId: external_exports.string().optional(),
21103
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
21104
+ cursor: external_exports.string().optional()
20921
21105
  });
20922
21106
  var ListFindingLocationsResponse = external_exports.object({
20923
21107
  totals: external_exports.object({
21108
+ // Findings matching the filters across the whole scope. Unlike the types
21109
+ // read's same-named field this needs no caveat: the filters here narrow
21110
+ // per finding, so this is the sum of every row's instanceCount.
20924
21111
  findings: external_exports.number().int().nonnegative(),
20925
- repos: external_exports.number().int().nonnegative(),
20926
- files: external_exports.number().int().nonnegative()
21112
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
21113
+ // states. The facets beside it count FINDINGS (see below); a surface
21114
+ // showing both says which is which.
21115
+ locations: external_exports.number().int().nonnegative()
20927
21116
  }),
20928
- /** Sorted by max severity, then most recent. */
20929
- items: external_exports.array(FindingLocationRepo),
20930
- /** Whether `limit` truncated the repo list. */
20931
- hasMore: external_exports.boolean()
21117
+ // Counts in FINDINGS, where the types response counts types, each dimension
21118
+ // still excluding its own filter. Deliberately not locations: counting those
21119
+ // needs a set of location keys per dimension per value — memory tracking the
21120
+ // store times the vocabulary, in a read whose scan promises flat memory —
21121
+ // and the cheap per-location version is not an approximation but WRONG. A
21122
+ // location holding {claudecode, block} and {codex, warn} would survive
21123
+ // provider=claudecode AND action=warn, under which no single finding
21124
+ // matches, so the facet would contradict the instanceCount this whole view
21125
+ // rests on. Findings also keep the toolbar in the same unit as the page
21126
+ // tally and the panel it sits above.
21127
+ facets: FindingFacets,
21128
+ /** Sorted by max severity, then most recent, then (repo, file). */
21129
+ items: external_exports.array(FindingLocationSummary),
21130
+ nextCursor: external_exports.string().nullable()
20932
21131
  }).meta({ id: "ListFindingLocationsResponse" });
20933
21132
 
20934
21133
  // ../../packages/schema/src/zod/meta.ts
@@ -21092,6 +21291,10 @@ var CaptureAttributes = external_exports.object({
21092
21291
  // to 'allow' — the enforcement audit trail's link back to the grant that
21093
21292
  // authorized the bypass.
21094
21293
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21294
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21295
+ // join back to the `llm_call` leaf for the same assistant turn.
21296
+ message_id: external_exports.string().optional(),
21297
+ conversation_id: external_exports.string().optional(),
21095
21298
  // Whole milliseconds this capture's inspection blocked its caller — the
21096
21299
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21097
21300
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21100,7 +21303,19 @@ var CaptureAttributes = external_exports.object({
21100
21303
  // inline json_extract and is not itself an optimization.
21101
21304
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21102
21305
  // before the measurement shipped — never present as a placeholder 0.
21103
- inspection_ms: external_exports.number().int().nonnegative().optional()
21306
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21307
+ // What a `redact` this capture could not carry out became instead (see
21308
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21309
+ // degrade actually happened, so absence is the ordinary case rather than a
21310
+ // reader having to distinguish it from a zero.
21311
+ //
21312
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21313
+ // so on a multi-finding row this does not say which finding degraded, and
21314
+ // its presence does not mean the fallback decided the capture's action. A
21315
+ // capture denied by another finding's own Block policy carries `block`
21316
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21317
+ // repeated rather than referenced because a store reader opens this file.
21318
+ redact_degraded_to: ActionTaken.optional()
21104
21319
  }).catchall(external_exports.unknown());
21105
21320
  var ToolCallInspection = external_exports.object({
21106
21321
  ruleId: external_exports.string().min(1),
@@ -21299,7 +21514,17 @@ var AuditEvent = external_exports.object({
21299
21514
  /** `share` to a first-party/internal destination. */
21300
21515
  internal: external_exports.boolean(),
21301
21516
  /** Event needs review (e.g. unverified egress). */
21302
- flagged: external_exports.boolean()
21517
+ flagged: external_exports.boolean(),
21518
+ /**
21519
+ * The body this event's `title` is drawn from was cleared by local body
21520
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21521
+ *
21522
+ * A separate flag rather than a sentinel written into `title`: the title is
21523
+ * rendered text, and a store-layer module that invented display copy for it
21524
+ * would be choosing words the view is supposed to choose. Additive and
21525
+ * defaulted, so an older producer still validates.
21526
+ */
21527
+ bodyExpired: external_exports.boolean().default(false)
21303
21528
  }).meta({ id: "ActivityAuditEvent" });
21304
21529
  var ActivitySessionSummary = external_exports.object({
21305
21530
  id: external_exports.string(),
@@ -22097,6 +22322,14 @@ var ControlPlaneErrorBody = external_exports.object({
22097
22322
  message: external_exports.string().optional()
22098
22323
  }).optional()
22099
22324
  });
22325
+ var RemoteFailureKind = external_exports.enum([
22326
+ "unauthorized",
22327
+ "forbidden",
22328
+ "route-absent",
22329
+ "invalid-request",
22330
+ "rejected",
22331
+ "unreachable"
22332
+ ]);
22100
22333
  var AttachDeviceRequest = external_exports.object({
22101
22334
  // This machine's own continuity id, so re-attaching ROTATES the credential
22102
22335
  // on one machine record instead of producing a second one. Client-minted
@@ -22632,6 +22865,12 @@ var EventMetadata = external_exports.object({
22632
22865
  // to 'allow' — the enforcement audit trail's link back to the grant that
22633
22866
  // authorized the bypass. Absent on captures where no exception applied.
22634
22867
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22868
+ // The assistant message this capture belongs to, and the conversation it sits
22869
+ // in — set by the browser extension's network capture so a stored `response`
22870
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22871
+ // on every other capture path, which has no such id.
22872
+ messageId: external_exports.string().optional(),
22873
+ conversationId: external_exports.string().optional(),
22635
22874
  // How long THIS capture's inspection blocked its caller, in whole
22636
22875
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22637
22876
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22644,7 +22883,37 @@ var EventMetadata = external_exports.object({
22644
22883
  // Absent is also what every pre-measurement client writes, and what a
22645
22884
  // clock failure degrades to — a reader must treat absence as "not measured"
22646
22885
  // and never as a zero, which would read as "inspection is free".
22647
- inspectionMs: external_exports.number().int().nonnegative().optional()
22886
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22887
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22888
+ // workspace's `redactFallback`, applied because the field could not be
22889
+ // masked in place (a shell command, a URL, or any argument on a host whose
22890
+ // hook contract offers no rewrite channel).
22891
+ //
22892
+ // It exists because the action alone cannot say why. A finding recorded as
22893
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22894
+ // assigned Redact on a field that could not take one — and those are
22895
+ // different facts about the same row: the first is a policy the user chose,
22896
+ // the second is a masking the host could not perform. Absent means no
22897
+ // degrade happened, which is every ordinary capture.
22898
+ //
22899
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22900
+ // is the CAPTURE while `actionTaken` is per FINDING:
22901
+ //
22902
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22903
+ // `redact` alongside a finding ASSIGNED the same action stores both
22904
+ // identically and one reason for the pair; attributing it to both
22905
+ // describes the assigned one wrongly, and to neither loses the degrade.
22906
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22907
+ // became, not the reason the capture ended as it did — a capture denied
22908
+ // by some other finding's own Block policy still carries `block` here,
22909
+ // and clearing the workspace's fallback would not have let it through.
22910
+ // Gate on the value against what a fallback can produce; never read the
22911
+ // field's presence as "this was the fallback's doing".
22912
+ //
22913
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22914
+ // Closing either means moving the reason onto the finding row, which
22915
+ // already carries its own action.
22916
+ redactDegradedTo: ActionTaken.optional()
22648
22917
  }).meta({ id: "EventMetadata" });
22649
22918
  var Event = external_exports.object({
22650
22919
  id: external_exports.guid(),
@@ -22754,7 +23023,32 @@ var RotateKeyInput = external_exports.object({
22754
23023
  confirmation: external_exports.string()
22755
23024
  });
22756
23025
 
23026
+ // ../../packages/schema/src/zod/finding-delivery.ts
23027
+ var KNOWN_REASONS = SyncFailureReason.options;
23028
+ function knownReason(value) {
23029
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23030
+ }
23031
+ function deriveFindingDelivery(row) {
23032
+ if (row.kind === "code_change") return { state: "local_scan" };
23033
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23034
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23035
+ }
23036
+ if (row.syncedAt !== null) {
23037
+ const reason = knownReason(row.syncFailure);
23038
+ return {
23039
+ state: "not_sent",
23040
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23041
+ ...reason === void 0 ? {} : { reason }
23042
+ };
23043
+ }
23044
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23045
+ return { state: "never_offered" };
23046
+ }
23047
+
22757
23048
  // ../../packages/schema/src/zod/findings-group-build.ts
23049
+ function lookupOwn(map2, key) {
23050
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23051
+ }
22758
23052
  function toApiAction(dbVal) {
22759
23053
  const map2 = {
22760
23054
  log: "monitored",
@@ -22763,7 +23057,7 @@ function toApiAction(dbVal) {
22763
23057
  warn: "warned",
22764
23058
  allow: "allowed"
22765
23059
  };
22766
- return map2[dbVal] ?? "allowed";
23060
+ return lookupOwn(map2, dbVal) ?? "allowed";
22767
23061
  }
22768
23062
  function toApiCategory(dbVal) {
22769
23063
  if (dbVal === "code_context") return "source_code";
@@ -22771,13 +23065,18 @@ function toApiCategory(dbVal) {
22771
23065
  return parsed2.success ? parsed2.data : "custom";
22772
23066
  }
22773
23067
  function toApiProvider(sourceTool) {
22774
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23068
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22775
23069
  }
22776
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23070
+ var FINDING_STATUS_PRECEDENCE = [
23071
+ "open",
23072
+ "handled",
23073
+ "dismissed",
23074
+ "resolved"
23075
+ ];
22777
23076
  function foldGroupStatus(instanceStatuses) {
22778
23077
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22779
23078
  if (statuses.size === 0) return void 0;
22780
- for (const candidate of STATUS_PRECEDENCE) {
23079
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22781
23080
  if (statuses.has(candidate)) return candidate;
22782
23081
  }
22783
23082
  return void 0;
@@ -22790,139 +23089,62 @@ function deriveFindingStatus(row) {
22790
23089
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22791
23090
  return "open";
22792
23091
  }
22793
- function distinctUsers(instances) {
22794
- const seen = /* @__PURE__ */ new Set();
22795
- const users = [];
22796
- for (const i of instances) {
22797
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22798
- seen.add(i.user.id);
22799
- users.push(i.user);
22800
- }
22801
- return users;
22802
- }
22803
23092
  function sortUsers(users) {
22804
23093
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22805
23094
  }
22806
- function buildFindingGroups(rows, opts = {}) {
22807
- const overrides = opts.overrides;
23095
+ function buildFindingTypes(aggregates, opts = {}) {
22808
23096
  const packNames = opts.packNames;
22809
- const aggregates = opts.aggregates;
22810
- const byRuleId = /* @__PURE__ */ new Map();
22811
- for (const row of rows) {
22812
- const existing = byRuleId.get(row.ruleId);
22813
- if (existing) existing.push(row);
22814
- else byRuleId.set(row.ruleId, [row]);
22815
- }
22816
- const groups = [];
22817
- for (const [ruleId, ruleRows] of byRuleId) {
22818
- const instances = ruleRows.map((r) => {
22819
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22820
- return {
22821
- id: r.id,
22822
- provider: toApiProvider(r.sourceTool),
22823
- repo: r.repo,
22824
- file: r.file,
22825
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22826
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22827
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22828
- ...r.user === void 0 ? {} : { user: r.user },
22829
- action: toApiAction(effectiveDbAction),
22830
- detectedAt: r.occurredAt,
22831
- confidence: r.confidence,
22832
- status: r.status
22833
- };
22834
- });
22835
- const agg = aggregates?.get(ruleId);
22836
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22837
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22838
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22839
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22840
- );
22841
- const seenProviders = /* @__PURE__ */ new Set();
22842
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22843
- if (seenProviders.has(p)) return false;
22844
- seenProviders.add(p);
22845
- return true;
22846
- });
22847
- const actionSet = new Set(
22848
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22849
- );
23097
+ const types = [];
23098
+ for (const [ruleId, agg] of aggregates) {
23099
+ const users = sortUsers(agg.users ?? []);
23100
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
23101
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22850
23102
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22851
- const severity = ruleRows[0]?.severity ?? "low";
22852
- const detection = {
22853
- id: ruleId,
22854
- name: packNames?.get(ruleId) ?? null
22855
- };
22856
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22857
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22858
- const match = {
22859
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22860
- contextPrefix: ""
22861
- // empty (pending privacy review)
22862
- };
22863
- const status = foldGroupStatus(
22864
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22865
- );
22866
- const group = {
23103
+ const apiCategory = toApiCategory(agg.category ?? "custom");
23104
+ const type = {
22867
23105
  id: ruleId,
22868
23106
  category: apiCategory,
22869
23107
  subtype: ruleId,
22870
23108
  // human label comes with pack metadata later
22871
- severity,
22872
- match,
22873
- detection,
22874
- policy,
22875
- instanceCount: agg?.instanceCount ?? instances.length,
23109
+ severity: agg.severity ?? "low",
23110
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
23111
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
23112
+ instanceCount: agg.instanceCount,
22876
23113
  providers,
22877
23114
  aggregateAction,
22878
- latestDetectedAt,
22879
- instances,
22880
- status,
23115
+ latestDetectedAt: agg.latestDetectedAt,
23116
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22881
23117
  ...users.length > 0 ? { users } : {}
22882
23118
  };
22883
- if (agg) {
22884
- actionsCache.set(group, [...actionSet]);
22885
- if (agg.searchText !== void 0) {
22886
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22887
- }
23119
+ actionsCache.set(type, [...actionSet]);
23120
+ if (agg.searchText !== void 0) {
23121
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22888
23122
  }
22889
- groups.push(group);
23123
+ types.push(type);
22890
23124
  }
22891
- return groups;
23125
+ return types;
22892
23126
  }
22893
23127
  var haystackCache = /* @__PURE__ */ new WeakMap();
22894
- function buildHaystack(g, extra) {
23128
+ function buildHaystack(t, extra) {
22895
23129
  return [
22896
- g.subtype,
22897
- g.category,
22898
- g.match.maskedValue,
22899
- g.policy.name,
22900
- g.id,
22901
- ...g.instances.map((i) => i.repo),
22902
- ...g.instances.map((i) => i.file),
22903
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22904
- ...g.instances.map((i) => i.id),
22905
- // The people: the whole group's list when the store folded one, plus the
22906
- // preview's own — the two overlap, and a haystack does not mind.
22907
- ...(g.users ?? []).map((u) => u.name),
22908
- ...g.instances.map((i) => i.user?.name ?? ""),
23130
+ t.subtype,
23131
+ t.category,
23132
+ t.policy.name,
23133
+ t.id,
23134
+ ...(t.users ?? []).map((u) => u.name),
22909
23135
  ...extra === void 0 ? [] : [extra]
22910
23136
  ].join(" ").toLowerCase();
22911
23137
  }
22912
- function groupHaystack(g) {
22913
- const cached2 = haystackCache.get(g);
23138
+ function typeHaystack(t) {
23139
+ const cached2 = haystackCache.get(t);
22914
23140
  if (cached2 !== void 0) return cached2;
22915
- const haystack = buildHaystack(g);
22916
- haystackCache.set(g, haystack);
23141
+ const haystack = buildHaystack(t);
23142
+ haystackCache.set(t, haystack);
22917
23143
  return haystack;
22918
23144
  }
22919
23145
  var actionsCache = /* @__PURE__ */ new WeakMap();
22920
- function groupActions(g) {
22921
- const cached2 = actionsCache.get(g);
22922
- if (cached2 !== void 0) return cached2;
22923
- const actions = [...new Set(g.instances.map((i) => i.action))];
22924
- actionsCache.set(g, actions);
22925
- return actions;
23146
+ function typeActions(t) {
23147
+ return actionsCache.get(t) ?? [];
22926
23148
  }
22927
23149
  function countInstancesByStatus(statusInputs, statuses) {
22928
23150
  const statusSet = new Set(statuses);
@@ -22933,8 +23155,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22933
23155
  }
22934
23156
  return sum;
22935
23157
  }
22936
- function applyFindingFilters(groups, opts) {
22937
- let filtered = groups;
23158
+ function applyFindingFilters(types, opts) {
23159
+ let filtered = types;
22938
23160
  if (opts.severity && opts.severity.length > 0) {
22939
23161
  const sevSet = new Set(opts.severity);
22940
23162
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22945,7 +23167,7 @@ function applyFindingFilters(groups, opts) {
22945
23167
  }
22946
23168
  if (opts.actions && opts.actions.length > 0) {
22947
23169
  const actionSet = new Set(opts.actions);
22948
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23170
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22949
23171
  }
22950
23172
  if (opts.subtype && opts.subtype.length > 0) {
22951
23173
  const subtypeSet = new Set(opts.subtype);
@@ -22957,26 +23179,31 @@ function applyFindingFilters(groups, opts) {
22957
23179
  }
22958
23180
  if (opts.q) {
22959
23181
  const q = opts.q.toLowerCase();
22960
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23182
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22961
23183
  }
22962
23184
  return filtered;
22963
23185
  }
22964
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22965
- var SEVERITY_RANK = SEVERITY_ORDER;
23186
+ function rankByOrder(members2) {
23187
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23188
+ }
23189
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23190
+ function severityRank(severity) {
23191
+ return lookupOwn(SEVERITY_RANK, severity);
23192
+ }
22966
23193
  function compareFindingGroupOrder(a, b) {
22967
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22968
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23194
+ const rankA = severityRank(a.severity) ?? -1;
23195
+ const rankB = severityRank(b.severity) ?? -1;
22969
23196
  const severityDiff = rankA - rankB;
22970
23197
  if (severityDiff !== 0) return severityDiff;
22971
23198
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
22972
23199
  if (recencyDiff !== 0) return recencyDiff;
22973
23200
  return a.id.localeCompare(b.id);
22974
23201
  }
22975
- function sortFindingGroups(groups) {
22976
- return [...groups].sort(compareFindingGroupOrder);
23202
+ function sortFindingTypes(types) {
23203
+ return [...types].sort(compareFindingGroupOrder);
22977
23204
  }
22978
- function computeFindingFacets(allGroups, opts) {
22979
- const forSeverity = applyFindingFilters(allGroups, {
23205
+ function computeFindingFacets(allTypes, opts) {
23206
+ const forSeverity = applyFindingFilters(allTypes, {
22980
23207
  providers: opts.providers,
22981
23208
  actions: opts.actions,
22982
23209
  statuses: opts.statuses,
@@ -22987,7 +23214,7 @@ function computeFindingFacets(allGroups, opts) {
22987
23214
  for (const g of forSeverity) {
22988
23215
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22989
23216
  }
22990
- const forProvider = applyFindingFilters(allGroups, {
23217
+ const forProvider = applyFindingFilters(allTypes, {
22991
23218
  actions: opts.actions,
22992
23219
  statuses: opts.statuses,
22993
23220
  q: opts.q,
@@ -22998,7 +23225,7 @@ function computeFindingFacets(allGroups, opts) {
22998
23225
  for (const g of forProvider) {
22999
23226
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23000
23227
  }
23001
- const forAction = applyFindingFilters(allGroups, {
23228
+ const forAction = applyFindingFilters(allTypes, {
23002
23229
  providers: opts.providers,
23003
23230
  statuses: opts.statuses,
23004
23231
  q: opts.q,
@@ -23007,9 +23234,9 @@ function computeFindingFacets(allGroups, opts) {
23007
23234
  });
23008
23235
  const actionMap = /* @__PURE__ */ new Map();
23009
23236
  for (const g of forAction) {
23010
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23237
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23011
23238
  }
23012
- const forSubtype = applyFindingFilters(allGroups, {
23239
+ const forSubtype = applyFindingFilters(allTypes, {
23013
23240
  providers: opts.providers,
23014
23241
  actions: opts.actions,
23015
23242
  statuses: opts.statuses,
@@ -23018,7 +23245,7 @@ function computeFindingFacets(allGroups, opts) {
23018
23245
  });
23019
23246
  const subtypeMap = /* @__PURE__ */ new Map();
23020
23247
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23021
- const forStatus = applyFindingFilters(allGroups, {
23248
+ const forStatus = applyFindingFilters(allTypes, {
23022
23249
  providers: opts.providers,
23023
23250
  actions: opts.actions,
23024
23251
  q: opts.q,
@@ -23040,6 +23267,20 @@ function computeFindingFacets(allGroups, opts) {
23040
23267
  }
23041
23268
 
23042
23269
  // ../../packages/schema/src/zod/findings-flat-build.ts
23270
+ function compareCodePoints(a, b) {
23271
+ const aIter = a[Symbol.iterator]();
23272
+ const bIter = b[Symbol.iterator]();
23273
+ for (; ; ) {
23274
+ const aNext = aIter.next();
23275
+ const bNext = bIter.next();
23276
+ if (aNext.done && bNext.done) return 0;
23277
+ if (aNext.done) return -1;
23278
+ if (bNext.done) return 1;
23279
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23280
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23281
+ if (aPoint !== bPoint) return aPoint - bPoint;
23282
+ }
23283
+ }
23043
23284
  function rowHaystack(row) {
23044
23285
  return [
23045
23286
  row.ruleId,
@@ -23064,12 +23305,24 @@ function matchesDimension(row, opts, dimension) {
23064
23305
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23065
23306
  case "statuses":
23066
23307
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23308
+ case "deliveries":
23309
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23067
23310
  case "tools":
23068
23311
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23312
+ // An EMPTY value is a real filter here, not an absent one. The location
23313
+ // list buckets a finding whose event recorded no repo — or no file — under
23314
+ // the empty string, and selecting that bucket has to narrow the panel to
23315
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23316
+ // row omits the key, which every call site already does.
23317
+ //
23318
+ // Reading '' as unset is what this replaced, and it failed in the one place
23319
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23320
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23321
+ // — a row reading 3 findings beside a panel listing every finding there is.
23069
23322
  case "repo":
23070
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23323
+ return opts.repo === void 0 || row.repo === opts.repo;
23071
23324
  case "file":
23072
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23325
+ return opts.file === void 0 || row.file === opts.file;
23073
23326
  case "q":
23074
23327
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23075
23328
  }
@@ -23080,6 +23333,7 @@ var DIMENSIONS = [
23080
23333
  "providers",
23081
23334
  "actions",
23082
23335
  "statuses",
23336
+ "deliveries",
23083
23337
  "tools",
23084
23338
  "repo",
23085
23339
  "file",
@@ -23093,10 +23347,19 @@ function matchesInstanceFilters(row, opts, except) {
23093
23347
  return true;
23094
23348
  }
23095
23349
  function toItems(counts) {
23096
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23350
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23351
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23352
+ // NFD spelling of the same text) as equal, so a count tie between
23353
+ // them would otherwise be ordered by whichever the Map iteration
23354
+ // produced. compareCodePoints breaks that tie deterministically, which
23355
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23356
+ // which it need not: foldFacetTuples runs this same sort over grouped
23357
+ // tuples, so both paths order facets identically by construction.
23358
+ compareCodePoints(a.value, b.value)
23359
+ );
23097
23360
  }
23098
- function bump(counts, value) {
23099
- counts.set(value, (counts.get(value) ?? 0) + 1);
23361
+ function bump(counts, value, by = 1) {
23362
+ counts.set(value, (counts.get(value) ?? 0) + by);
23100
23363
  }
23101
23364
  function createInstanceFacetAccumulator(opts) {
23102
23365
  const severity = /* @__PURE__ */ new Map();
@@ -23105,6 +23368,7 @@ function createInstanceFacetAccumulator(opts) {
23105
23368
  const action = /* @__PURE__ */ new Map();
23106
23369
  const status = /* @__PURE__ */ new Map();
23107
23370
  const tool = /* @__PURE__ */ new Map();
23371
+ const deployment = /* @__PURE__ */ new Map();
23108
23372
  return {
23109
23373
  add(row) {
23110
23374
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23119,6 +23383,9 @@ function createInstanceFacetAccumulator(opts) {
23119
23383
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23120
23384
  bump(tool, row.toolName);
23121
23385
  }
23386
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23387
+ bump(deployment, row.delivery.state);
23388
+ }
23122
23389
  },
23123
23390
  facets: () => ({
23124
23391
  severity: toItems(severity),
@@ -23126,7 +23393,8 @@ function createInstanceFacetAccumulator(opts) {
23126
23393
  provider: toItems(provider),
23127
23394
  action: toItems(action),
23128
23395
  status: toItems(status),
23129
- tool: toItems(tool)
23396
+ tool: toItems(tool),
23397
+ deployment: toItems(deployment)
23130
23398
  })
23131
23399
  };
23132
23400
  }
@@ -23140,6 +23408,7 @@ function toInstanceDetail(row) {
23140
23408
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23141
23409
  eventId: row.eventId,
23142
23410
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23411
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23143
23412
  ...row.user === void 0 ? {} : { user: row.user },
23144
23413
  action: toApiAction(row.actionTaken),
23145
23414
  detectedAt: row.occurredAt,
@@ -23154,12 +23423,6 @@ function toInstanceDetail(row) {
23154
23423
  policy: { id: `category:${category}`, name: category }
23155
23424
  };
23156
23425
  }
23157
- var SEVERITY_ORDER2 = {
23158
- critical: 0,
23159
- high: 1,
23160
- medium: 2,
23161
- low: 3
23162
- };
23163
23426
  function newLocationAccumulator() {
23164
23427
  return {
23165
23428
  instanceCount: 0,
@@ -23174,7 +23437,7 @@ function newLocationAccumulator() {
23174
23437
  }
23175
23438
  function addToLocation(acc, row) {
23176
23439
  acc.instanceCount += 1;
23177
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23440
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23178
23441
  if (rank < acc.maxSeverityRank) {
23179
23442
  acc.maxSeverityRank = rank;
23180
23443
  acc.maxSeverity = row.severity;
@@ -23183,6 +23446,23 @@ function addToLocation(acc, row) {
23183
23446
  acc.statuses.push(row.status);
23184
23447
  acc.ruleIds.add(row.ruleId);
23185
23448
  }
23449
+ function compareLocationOrder(a, b) {
23450
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23451
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23452
+ if (rankA !== rankB) return rankA - rankB;
23453
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23454
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23455
+ }
23456
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23457
+ if (repoDiff !== 0) return repoDiff;
23458
+ return compareCodePoints(a.file, b.file);
23459
+ }
23460
+ function encodeLocationId(repo, file2) {
23461
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23462
+ }
23463
+ function encodePart(value) {
23464
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23465
+ }
23186
23466
 
23187
23467
  // ../../packages/schema/src/zod/installed-pack.ts
23188
23468
  var InstalledPack = external_exports.object({
@@ -23250,6 +23530,11 @@ var Policy = external_exports.object({
23250
23530
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23251
23531
  provenance: PolicyProvenance.optional()
23252
23532
  }).meta({ id: "Policy" });
23533
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23534
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23535
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23536
+ id: "RedactFallback"
23537
+ });
23253
23538
  var PolicyBundle = external_exports.object({
23254
23539
  version: external_exports.string(),
23255
23540
  policies: external_exports.array(Policy),
@@ -23297,6 +23582,16 @@ var PolicyBundle = external_exports.object({
23297
23582
  // control plane), so no name resolution stands between the decision and the
23298
23583
  // comparison.
23299
23584
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23585
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23586
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23587
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23588
+ // a control plane can tighten a machine and never loosen one — the same
23589
+ // direction `mergeRaiseOnly` enforces for policies.
23590
+ //
23591
+ // Optional so an older backend, and an older on-disk cache, still parses;
23592
+ // absent leaves the device's own setting in force, which is the behaviour
23593
+ // that predates the field and the safe direction to default.
23594
+ redactFallback: RedactFallback.optional(),
23300
23595
  customKeywords: external_exports.array(external_exports.string()),
23301
23596
  fetchedAt: external_exports.iso.datetime()
23302
23597
  }).meta({ id: "PolicyBundle" });
@@ -23326,11 +23621,6 @@ function severityFloorPolicy(category) {
23326
23621
  const peak = CATEGORY_PEAK_SEVERITY[category];
23327
23622
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23328
23623
  }
23329
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23330
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23331
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23332
- id: "RedactFallback"
23333
- });
23334
23624
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23335
23625
  var BUILTIN_POLICY_SPECS = {
23336
23626
  monitor: {
@@ -23623,7 +23913,7 @@ var VaultConsent = external_exports.object({
23623
23913
  });
23624
23914
 
23625
23915
  // ../../packages/schema/src/zod/local.ts
23626
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23916
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23627
23917
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23628
23918
  var RunMode = external_exports.enum(["standalone", "attached"]);
23629
23919
  var ControlPlaneConnection = external_exports.object({
@@ -23643,6 +23933,15 @@ var HistorySyncConsent = external_exports.object({
23643
23933
  payloadVersion: external_exports.number().int().positive(),
23644
23934
  endpoint: external_exports.string()
23645
23935
  });
23936
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23937
+ var BodyRetention = external_exports.object({
23938
+ enabled: external_exports.boolean().default(false),
23939
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23940
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23941
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23942
+ // candidate set that is already bounded by "delivered, or never owed".
23943
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23944
+ }).meta({ id: "BodyRetention" });
23646
23945
  var WorkspaceSettings = external_exports.object({
23647
23946
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23648
23947
  runMode: RunMode.default("standalone"),
@@ -23686,12 +23985,18 @@ var WorkspaceSettings = external_exports.object({
23686
23985
  // covers the current payload and must be re-granted.
23687
23986
  modelJudgeConsent: ModelJudgeConsent.optional(),
23688
23987
  // Records that the user consented to the DEFERRED send — the outbox — along
23689
- // with the payload shape and the endpoint they agreed to. Since payload v2
23690
- // that covers both the pre-attach backlog and undelivered captures (which
23691
- // carry prompt/reply text in `content`); the key name predates the widening.
23692
- // Absent until granted, and a grant for a different endpoint or an older
23693
- // payload no longer counts.
23694
- historySyncConsent: HistorySyncConsent.optional()
23988
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23989
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23990
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23991
+ // both widenings. Absent until granted, and a grant for a different endpoint
23992
+ // or an older payload no longer counts.
23993
+ historySyncConsent: HistorySyncConsent.optional(),
23994
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23995
+ // body never removes the row or its findings.
23996
+ bodyRetention: BodyRetention.default({
23997
+ enabled: false,
23998
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23999
+ })
23695
24000
  });
23696
24001
  function defaultWorkspaceSettings() {
23697
24002
  return WorkspaceSettings.parse({});
@@ -23786,12 +24091,15 @@ function toCaptureAttributes(event) {
23786
24091
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23787
24092
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23788
24093
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24094
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23789
24095
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23790
24096
  // has ever populated either), but every legacy metadata key still rides
23791
24097
  // the bag rather than being silently dropped — CaptureAttributes'
23792
24098
  // `.catchall(z.unknown())` carries the long tail.
23793
24099
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23794
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24100
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24101
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24102
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23795
24103
  };
23796
24104
  }
23797
24105
  function captureDefinitionVersion(finding) {
@@ -23819,10 +24127,22 @@ var ManagedSettingKey = external_exports.enum([
23819
24127
  "vaultInlineReveal",
23820
24128
  "modelJudgeConsent",
23821
24129
  "dataSharesInPlace",
23822
- "redactFallback"
24130
+ "redactFallback",
24131
+ // Pins the toggle and the day count together — see BodyRetention on why the
24132
+ // two are one unit. An administrator mandating a window wants the count
24133
+ // enforced with it, not one a user can widen while the toggle stays on.
24134
+ "bodyRetention"
23823
24135
  ]).meta({ id: "ManagedSettingKey" });
24136
+ function isManagedSettingKey(value) {
24137
+ return ManagedSettingKey.safeParse(value).success;
24138
+ }
23824
24139
  var ManagedSettingsValues = external_exports.object({
23825
24140
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24141
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24142
+ // plain, non-strict objects: a key under either that this build does not know
24143
+ // is stripped and nothing reports it. The unknown-value split in
24144
+ // ManagedSettings below classifies top-level names only, so it stops at
24145
+ // these boundaries.
23826
24146
  controlPlane: external_exports.object({
23827
24147
  endpoint: external_exports.string().min(1),
23828
24148
  label: external_exports.string().min(1).optional()
@@ -23833,7 +24153,8 @@ var ManagedSettingsValues = external_exports.object({
23833
24153
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23834
24154
  modelJudgeConsent: external_exports.boolean().optional(),
23835
24155
  dataSharesInPlace: external_exports.boolean().optional(),
23836
- redactFallback: RedactFallback.optional()
24156
+ redactFallback: RedactFallback.optional(),
24157
+ bodyRetention: BodyRetention.optional()
23837
24158
  }).meta({ id: "ManagedSettingsValues" });
23838
24159
  var ManagedSettings = external_exports.object({
23839
24160
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23841,11 +24162,59 @@ var ManagedSettings = external_exports.object({
23841
24162
  // decision from a bug. Absent renders as a generic "your organization".
23842
24163
  organization: external_exports.string().min(1).optional(),
23843
24164
  // What the administrator pinned.
23844
- values: ManagedSettingsValues.default({}),
24165
+ //
24166
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24167
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24168
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24169
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24170
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24171
+ // exactly the file an administrator is most likely to write while a fleet
24172
+ // is mid-upgrade.
24173
+ //
24174
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24175
+ // file, which is the outcome the lock half already rejected — an older
24176
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24177
+ // value still fails, because the nested schema is re-run over the known
24178
+ // subset and its issues are re-raised on this parse.
24179
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23845
24180
  // Which of those the user may not change. A key here with no matching value
23846
24181
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23847
24182
  // the user may still override. The two are separable on purpose.
23848
- lockedFields: external_exports.array(ManagedSettingKey).default([])
24183
+ //
24184
+ // Parsed as NAMES rather than as the enum, and split below: a name this
24185
+ // build does not know is dropped from the locked set and reported, never a
24186
+ // reason to refuse the file. The same shape reaches an older build whenever
24187
+ // an administrator locks a key a newer build added, and refusing it there
24188
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24189
+ // the fleets most likely to carry a version skew. A name outside the enum
24190
+ // is still never HONOURED: the lockable set stays explicit above.
24191
+ lockedFields: external_exports.array(external_exports.string()).default([])
24192
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
24193
+ const known = [];
24194
+ const unknown2 = [];
24195
+ for (const name of lockedFields) {
24196
+ if (isManagedSettingKey(name)) known.push(name);
24197
+ else unknown2.push(name);
24198
+ }
24199
+ const knownValues = /* @__PURE__ */ Object.create(null);
24200
+ const unknownValues = [];
24201
+ for (const [name, value] of Object.entries(values)) {
24202
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24203
+ else unknownValues.push(name);
24204
+ }
24205
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24206
+ if (!pinned.success) {
24207
+ for (const issue2 of pinned.error.issues)
24208
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24209
+ return external_exports.NEVER;
24210
+ }
24211
+ return {
24212
+ ...rest,
24213
+ values: pinned.data,
24214
+ lockedFields: known,
24215
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24216
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
24217
+ };
23849
24218
  }).meta({ id: "ManagedSettings" });
23850
24219
 
23851
24220
  // ../../packages/schema/src/zod/project-files.ts
@@ -23969,7 +24338,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23969
24338
  timestamp: external_exports.iso.date(),
23970
24339
  critical: external_exports.number().int().nonnegative(),
23971
24340
  high: external_exports.number().int().nonnegative(),
23972
- medium: external_exports.number().int().nonnegative()
24341
+ medium: external_exports.number().int().nonnegative(),
24342
+ // Optional and additive, so a producer written against the earlier
24343
+ // three-series contract keeps validating. A consumer plotting it resolves the
24344
+ // absent case itself — the chart point requires a number.
24345
+ low: external_exports.number().int().nonnegative().optional()
23973
24346
  }).meta({ id: "FindingsTimeseriesPoint" });
23974
24347
  var FindingsTimeseriesResponse = external_exports.object({
23975
24348
  range: TimeRange,
@@ -23995,6 +24368,10 @@ var ResolvedFeedItem = external_exports.object({
23995
24368
  findingKey: external_exports.string(),
23996
24369
  ruleId: external_exports.string(),
23997
24370
  severity: Severity,
24371
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24372
+ // identifies the file: a bare path matches the same name in every repo.
24373
+ // Optional and additive; empty when the event carried no repo.
24374
+ repo: external_exports.string().optional(),
23998
24375
  path: external_exports.string(),
23999
24376
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24000
24377
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -24100,7 +24477,23 @@ var SaveSettingsInput = external_exports.object({
24100
24477
  modelJudgeConsent: ModelJudgeConsentChoice,
24101
24478
  historySyncConsent: HistorySyncConsentChoice,
24102
24479
  vaultConsent: external_exports.string(),
24103
- vaultInlineReveal: external_exports.string()
24480
+ vaultInlineReveal: external_exports.string(),
24481
+ // Widened to `string` like its neighbours rather than typed as
24482
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24483
+ // the call site, so the domain check receives the type it was written for.
24484
+ //
24485
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24486
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24487
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24488
+ // trade against. The real cost runs the other way and is the part worth
24489
+ // knowing: a value this schema admits and the domain enum then rejects lands
24490
+ // on the action's shared refusal, which names NO field, where a shape
24491
+ // rejection reaches `malformedInput` and names the schema key.
24492
+ redactFallback: external_exports.string(),
24493
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24494
+ // `BodyRetention`'s and the action checks it there, so there is one place
24495
+ // that decides what a legal horizon is rather than two that can drift.
24496
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24104
24497
  });
24105
24498
  var AttachInput = external_exports.object({
24106
24499
  endpoint: external_exports.string(),
@@ -24272,6 +24665,52 @@ function reviewSeverityRank(reasons) {
24272
24665
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24273
24666
  }
24274
24667
 
24668
+ // ../../packages/schema/src/zod/web-capture.ts
24669
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24670
+ var WebUsage = external_exports.object({
24671
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24672
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24673
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24674
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24675
+ });
24676
+ var WebToolCall = external_exports.object({
24677
+ toolUseId: external_exports.string().min(1),
24678
+ toolName: external_exports.string().min(1),
24679
+ target: external_exports.string().optional(),
24680
+ isError: external_exports.boolean().optional(),
24681
+ inputSize: external_exports.number().int().nonnegative().optional(),
24682
+ outputSize: external_exports.number().int().nonnegative().optional()
24683
+ });
24684
+ var WebExchange = external_exports.object({
24685
+ messageId: external_exports.string().min(1),
24686
+ startedAt: external_exports.iso.datetime(),
24687
+ model: external_exports.string().optional(),
24688
+ usage: WebUsage.optional(),
24689
+ usageSource: WebUsageSource,
24690
+ stopReason: external_exports.string().optional(),
24691
+ conversationId: external_exports.string().optional(),
24692
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24693
+ toolCalls: external_exports.array(WebToolCall).default([]),
24694
+ // Absent when the adapter recovered no text. Capped by the caller at
24695
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24696
+ // short capture is never mistaken for a short reply.
24697
+ responseText: external_exports.string().optional(),
24698
+ truncated: external_exports.boolean().default(false)
24699
+ });
24700
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24701
+ var WebCaptureStatus = external_exports.object({
24702
+ patched: external_exports.boolean(),
24703
+ live: external_exports.boolean(),
24704
+ blind: external_exports.boolean(),
24705
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24706
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24707
+ parseFailures: external_exports.number().int().nonnegative(),
24708
+ unparsedBodies: external_exports.number().int().nonnegative(),
24709
+ // The adapter-declared JSON key paths that were absent from a real payload —
24710
+ // the earliest signal that a site's contract moved.
24711
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24712
+ });
24713
+
24275
24714
  // ../../packages/persistence/src/paths.ts
24276
24715
  import {
24277
24716
  chmodSync,
@@ -24602,6 +25041,22 @@ function discardStore(file2, backup) {
24602
25041
  }
24603
25042
  }
24604
25043
 
25044
+ // ../../packages/persistence/src/internal/sql-functions.ts
25045
+ var utf8 = new TextDecoder();
25046
+ function akaLower(value) {
25047
+ if (value === null) return null;
25048
+ if (typeof value === "string") return value.toLowerCase();
25049
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25050
+ return utf8.decode(value).toLowerCase();
25051
+ }
25052
+ function registerSqlFunctions(db) {
25053
+ db.function(
25054
+ "aka_lower",
25055
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25056
+ akaLower
25057
+ );
25058
+ }
25059
+
24605
25060
  // ../../packages/persistence/src/internal/sql-text.ts
24606
25061
  function escapeLikePattern(s) {
24607
25062
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24686,6 +25141,11 @@ function schemaObjectExists(db, kind, name) {
24686
25141
  function indexExists(db, name) {
24687
25142
  return schemaObjectExists(db, "index", name);
24688
25143
  }
25144
+ function indexColumns(db, name) {
25145
+ if (!indexExists(db, name)) return [];
25146
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25147
+ return columns.map((c) => c.name).filter((c) => c !== null);
25148
+ }
24689
25149
  function columnNames(db, table2, opts) {
24690
25150
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24691
25151
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24747,6 +25207,647 @@ function mapRowsTolerant(rows, map2) {
24747
25207
  return out;
24748
25208
  }
24749
25209
 
25210
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25211
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25212
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25213
+
25214
+ // ../../packages/persistence/src/sync-failure.ts
25215
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25216
+ function syncFailureRejectCondition(column = "sync_failure") {
25217
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25218
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
25219
+ }
25220
+
25221
+ // ../../packages/persistence/src/repositories/history-sync.ts
25222
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25223
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25224
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25225
+ var COUNTED_EVENT_TYPES = [
25226
+ ...STRUCTURAL_EVENT_TYPES,
25227
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25228
+ ];
25229
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25230
+ var PARTITION_BUCKETS = `
25231
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25232
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25233
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25234
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25235
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25236
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25237
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25238
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25239
+ -- added later lands in no bucket and fails the sum assertion, instead
25240
+ -- of silently joining this one.
25241
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25242
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25243
+ THEN 1 ELSE 0 END) AS failed,
25244
+ COUNT(*) AS total`;
25245
+ var COUNTED_SCOPE = `
25246
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25247
+ AND (
25248
+ event_type IN (${TYPE_LIST})
25249
+ OR synced_at IS NOT NULL
25250
+ OR outbox_owed = 1
25251
+ )`;
25252
+ var SKIPPED = -1;
25253
+ var ROW_COLUMNS = `id,
25254
+ parent_id AS parentId,
25255
+ root_session_id AS rootSessionId,
25256
+ event_type AS eventType,
25257
+ host_id AS hostId,
25258
+ harness_id AS harnessId,
25259
+ source_project_id AS sourceProjectId,
25260
+ started_at AS startedAt,
25261
+ ended_at AS endedAt,
25262
+ severity,
25263
+ priority,
25264
+ content,
25265
+ content_hash AS contentHash,
25266
+ attributes`;
25267
+ var SqliteHistorySyncRepository = class {
25268
+ constructor(db) {
25269
+ this.db = db;
25270
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25271
+ this.sessionsStmt = db.prepare(
25272
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25273
+ FROM audit_events
25274
+ WHERE synced_at IS NULL
25275
+ AND event_type IN (${TYPE_LIST})
25276
+ AND started_at < :before
25277
+ GROUP BY sessionId
25278
+ ORDER BY earliest
25279
+ LIMIT :limit`
25280
+ );
25281
+ this.rowsStmt = db.prepare(
25282
+ `SELECT ${ROW_COLUMNS}
25283
+ FROM audit_events
25284
+ WHERE synced_at IS NULL
25285
+ AND event_type IN (${TYPE_LIST})
25286
+ AND started_at < :before
25287
+ AND COALESCE(root_session_id, id) = :sessionId
25288
+ ORDER BY (event_type = 'session') DESC, started_at
25289
+ LIMIT :limit`
25290
+ );
25291
+ this.captureRowsStmt = db.prepare(
25292
+ `SELECT ${ROW_COLUMNS}
25293
+ FROM audit_events
25294
+ WHERE synced_at IS NULL
25295
+ AND sync_claimed_at IS NULL
25296
+ AND outbox_owed = 1
25297
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25298
+ AND started_at < :before
25299
+ ORDER BY started_at
25300
+ LIMIT :limit`
25301
+ );
25302
+ this.markOwedStmt = db.prepare(
25303
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25304
+ );
25305
+ this.markCaptureBacklogOwedStmt = db.prepare(
25306
+ `UPDATE audit_events SET outbox_owed = 1
25307
+ WHERE synced_at IS NULL
25308
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25309
+ AND started_at < :before`
25310
+ );
25311
+ this.stampStmt = db.prepare(
25312
+ `UPDATE audit_events
25313
+ SET synced_at = :at,
25314
+ sync_claimed_at = NULL,
25315
+ sync_failed_at = :failedAt,
25316
+ sync_failure = :failure
25317
+ WHERE id = :id`
25318
+ );
25319
+ this.claimRowStmt = db.prepare(
25320
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25321
+ );
25322
+ this.releaseRowStmt = db.prepare(
25323
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25324
+ );
25325
+ this.releaseStaleClaimsStmt = db.prepare(
25326
+ `UPDATE audit_events SET sync_claimed_at = NULL
25327
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25328
+ );
25329
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25330
+ FROM audit_events${COUNTED_SCOPE}`);
25331
+ this.partitionByKindStmt = db.prepare(
25332
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25333
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25334
+ GROUP BY event_type`
25335
+ );
25336
+ this.countsStmt = db.prepare(
25337
+ `SELECT
25338
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25339
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25340
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25341
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25342
+ THEN 1 ELSE 0 END) AS skipped,
25343
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25344
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25345
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25346
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25347
+ FROM audit_events
25348
+ WHERE event_type IN (${TYPE_LIST})`
25349
+ );
25350
+ this.captureSkipCountStmt = db.prepare(
25351
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25352
+ // way the structural totals are. The split exists because a refusal is
25353
+ // terminal only against the deployment that gave it, and the structural
25354
+ // re-arm frees it on a change of deployment. The capture lane has no such
25355
+ // escape: re-arming a capture would offer one deployment's undelivered
25356
+ // prompts, with their text, to a deployment that never saw them, which is
25357
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25358
+ // reasons mean the same thing — this row will not be sent — and splitting
25359
+ // them would put refused captures in a bucket nothing reads and nothing
25360
+ // frees.
25361
+ `SELECT COUNT(*) AS skipped
25362
+ FROM audit_events
25363
+ WHERE synced_at = ${String(SKIPPED)}
25364
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25365
+ );
25366
+ this.fingerprintStmt = db.prepare(
25367
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25368
+ FROM history_sync WHERE id = 1`
25369
+ );
25370
+ this.setFingerprintStmt = db.prepare(
25371
+ `UPDATE history_sync
25372
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25373
+ WHERE id = 1`
25374
+ );
25375
+ this.disownCapturesStmt = db.prepare(
25376
+ `UPDATE audit_events SET outbox_owed = NULL
25377
+ WHERE outbox_owed IS NOT NULL
25378
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25379
+ AND started_at < :attachedAt`
25380
+ );
25381
+ this.rearmStmt = db.prepare(
25382
+ `UPDATE audit_events
25383
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25384
+ WHERE (synced_at > 0
25385
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25386
+ AND event_type IN (${TYPE_LIST})`
25387
+ );
25388
+ this.claimStmt = db.prepare(
25389
+ `UPDATE history_sync
25390
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25391
+ WHERE id = 1
25392
+ AND (owner_pid IS NULL
25393
+ OR heartbeat_at IS NULL
25394
+ OR heartbeat_at < :staleBefore
25395
+ OR heartbeat_at > :now)`
25396
+ );
25397
+ this.heartbeatStmt = db.prepare(
25398
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25399
+ );
25400
+ this.releaseStmt = db.prepare(
25401
+ `UPDATE history_sync
25402
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25403
+ WHERE id = 1 AND owner_pid = :pid`
25404
+ );
25405
+ this.closeWindowStmt = db.prepare(
25406
+ `UPDATE audit_events
25407
+ SET synced_at = ${String(SKIPPED)},
25408
+ sync_failed_at = :at,
25409
+ sync_failure = 'detached_undelivered'
25410
+ WHERE synced_at IS NULL
25411
+ AND event_type IN (${TYPE_LIST})
25412
+ AND started_at >= :attachedAt`
25413
+ );
25414
+ this.releaseBoundaryStmt = db.prepare(
25415
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25416
+ );
25417
+ this.freezeBoundaryStmt = db.prepare(
25418
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25419
+ );
25420
+ this.leaseStmt = db.prepare(
25421
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25422
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25423
+ FROM history_sync WHERE id = 1`
25424
+ );
25425
+ this.inspectionsStmt = db.prepare(
25426
+ `SELECT d.rule_id AS ruleId,
25427
+ d.name AS ruleName,
25428
+ d.version AS ruleVersion,
25429
+ d.category AS category,
25430
+ d.severity AS severity,
25431
+ f.span_start AS spanStart,
25432
+ f.span_end AS spanEnd,
25433
+ f.masked_match AS maskedMatch,
25434
+ f.action_taken AS actionTaken,
25435
+ f.confidence AS confidence
25436
+ FROM inspection_findings f
25437
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25438
+ WHERE f.audit_event_id = :auditEventId
25439
+ ORDER BY f.span_start, f.id`
25440
+ );
25441
+ }
25442
+ db;
25443
+ ensureRowStmt;
25444
+ sessionsStmt;
25445
+ rowsStmt;
25446
+ stampStmt;
25447
+ countsStmt;
25448
+ fingerprintStmt;
25449
+ setFingerprintStmt;
25450
+ rearmStmt;
25451
+ claimStmt;
25452
+ heartbeatStmt;
25453
+ releaseStmt;
25454
+ leaseStmt;
25455
+ inspectionsStmt;
25456
+ closeWindowStmt;
25457
+ releaseBoundaryStmt;
25458
+ freezeBoundaryStmt;
25459
+ captureRowsStmt;
25460
+ markOwedStmt;
25461
+ markCaptureBacklogOwedStmt;
25462
+ captureSkipCountStmt;
25463
+ disownCapturesStmt;
25464
+ partitionStmt;
25465
+ partitionByKindStmt;
25466
+ claimRowStmt;
25467
+ releaseRowStmt;
25468
+ releaseStaleClaimsStmt;
25469
+ /**
25470
+ * The masked detections recorded against one tool call.
25471
+ *
25472
+ * These travel with the event because a tool call's target is not
25473
+ * re-inspectable from the event alone — unlike a capture, where the text
25474
+ * itself is re-scannable. What crosses is the masked match and the rule that
25475
+ * produced it, never the value.
25476
+ */
25477
+ inspectionsFor(auditEventId) {
25478
+ return allRows(this.inspectionsStmt, { auditEventId });
25479
+ }
25480
+ /**
25481
+ * Sessions with structural rows still to send, oldest first.
25482
+ *
25483
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25484
+ * read. Anything recorded after the machine attached is the live forward
25485
+ * path's to deliver; this drain exists for what was recorded before it, and a
25486
+ * row both paths send is at best a duplicate request and at worst — for a
25487
+ * session root — an overwrite of the inventory ids the live path resolved.
25488
+ */
25489
+ pendingSessions(limit, before) {
25490
+ return allRows(this.sessionsStmt, { limit, before }).map(
25491
+ (r) => r.sessionId
25492
+ );
25493
+ }
25494
+ /** One session's undelivered structural rows within the backlog, root first. */
25495
+ pendingRows(sessionId, limit, before) {
25496
+ return allRows(this.rowsStmt, { sessionId, limit, before });
25497
+ }
25498
+ /**
25499
+ * Captures this machine still owes the deployment, oldest first.
25500
+ *
25501
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25502
+ * by a time window — see captureRowsStmt for why a window could not express
25503
+ * this. `before` is the grace window that leaves a just-recorded capture to
25504
+ * the live path.
25505
+ */
25506
+ pendingCaptureRows(limit, before) {
25507
+ return allRows(this.captureRowsStmt, { limit, before });
25508
+ }
25509
+ /**
25510
+ * Record that a capture is OWED to the deployment.
25511
+ *
25512
+ * Written by the attached forward path when a live send did not confirm
25513
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25514
+ * a fact rather than an inference: the machine was attached, the send did not
25515
+ * land, so the row is owed — which no time window can state, because the same
25516
+ * window that holds the rows a past attachment left owed also holds every
25517
+ * capture recorded while the machine was DETACHED, and those were never
25518
+ * offered to anyone.
25519
+ *
25520
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25521
+ * out of the drain's read.
25522
+ */
25523
+ markCaptureOwed(id) {
25524
+ this.markOwedStmt.run({ id });
25525
+ }
25526
+ /**
25527
+ * Mark every capture already on disk as owed, as of `before`.
25528
+ *
25529
+ * The consent-time backfill, called once from `aka attach` when a human
25530
+ * grants existing-history consent — never from an ongoing drain pass, and
25531
+ * never inferred from a boundary that could later move. `before` is the
25532
+ * caller's own "now" at the moment consent was granted, so what this marks
25533
+ * is exactly the backlog the consent prompt already counted, not whatever a
25534
+ * later re-attach or key rotation might widen it to.
25535
+ *
25536
+ * Returns how many rows matched, for the caller to log or test against. Not a
25537
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25538
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25539
+ */
25540
+ markCaptureBacklogOwed(before) {
25541
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25542
+ }
25543
+ /**
25544
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25545
+ *
25546
+ * CLEARS any failure reason in the same statement. A row that failed against
25547
+ * one deployment and then landed is delivered, and leaving the reason behind
25548
+ * would leave the store holding two contradictory answers about one row —
25549
+ * with the surface free to render either.
25550
+ */
25551
+ markSynced(ids, atMs) {
25552
+ this.stampAll(ids, atMs, null);
25553
+ }
25554
+ /**
25555
+ * Record that THIS MACHINE cannot express the row on the wire.
25556
+ *
25557
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25558
+ * payload, or a body the client itself refused to send. It fails identically
25559
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25560
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25561
+ * is retried; marking those would turn one outage into permanent data loss.
25562
+ */
25563
+ markSkipped(ids, atMs) {
25564
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25565
+ }
25566
+ /**
25567
+ * Record that THIS DEPLOYMENT refused the row.
25568
+ *
25569
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25570
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25571
+ * row is outstanding rather than why. What separates them is the reason, and
25572
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25573
+ * on one body, so it is terminal only for as long as this machine points at
25574
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25575
+ *
25576
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25577
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25578
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25579
+ */
25580
+ markRefused(ids, atMs) {
25581
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25582
+ }
25583
+ eachInTransaction(ids, run) {
25584
+ if (ids.length === 0) return;
25585
+ withTransaction(
25586
+ this.db,
25587
+ () => {
25588
+ for (const id of ids) run(id);
25589
+ },
25590
+ "IMMEDIATE"
25591
+ );
25592
+ }
25593
+ stampAll(ids, value, failure, failedAtMs) {
25594
+ if (ids.length === 0) return;
25595
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25596
+ withTransaction(
25597
+ this.db,
25598
+ () => {
25599
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25600
+ },
25601
+ "IMMEDIATE"
25602
+ );
25603
+ }
25604
+ /**
25605
+ * Claim rows as in-flight.
25606
+ *
25607
+ * Advisory in exactly the sense the lease is: it records that a send is in
25608
+ * progress so a surface can say so, and a lost claim costs a row showing as
25609
+ * queued while it is actually being sent. It is not exclusion — the far side
25610
+ * settles a duplicate on the row id.
25611
+ */
25612
+ claimRows(ids, atMs) {
25613
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25614
+ }
25615
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25616
+ releaseRows(ids) {
25617
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25618
+ }
25619
+ /**
25620
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25621
+ *
25622
+ * A process killed between claiming and settling leaves rows claimed with
25623
+ * nothing left to settle them. Without this they read as "sending" for ever.
25624
+ */
25625
+ releaseStaleClaims(staleBefore) {
25626
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25627
+ }
25628
+ /**
25629
+ * Every tracked row in exactly one delivery state.
25630
+ *
25631
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25632
+ * pick up now", which is a different question from "what state is this row
25633
+ * in" — and a machine that has never attached has no boundary to pass, so
25634
+ * requiring one would force a caller to invent one and report the whole store
25635
+ * as queued.
25636
+ */
25637
+ /**
25638
+ * The same partition, one row per kind that a lane carries.
25639
+ *
25640
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25641
+ * scope decides which rows exist at all, so a kind that has never been
25642
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25643
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25644
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25645
+ * different things.
25646
+ */
25647
+ partitionByKind() {
25648
+ return allRows(
25649
+ this.partitionByKindStmt,
25650
+ {}
25651
+ ).map((row) => ({
25652
+ kind: row.kind,
25653
+ queued: row.queued ?? 0,
25654
+ inProgress: row.inProgress ?? 0,
25655
+ synced: row.synced ?? 0,
25656
+ failed: row.failed ?? 0,
25657
+ refused: row.refused ?? 0,
25658
+ detached: row.detached ?? 0,
25659
+ total: row.total ?? 0
25660
+ }));
25661
+ }
25662
+ partition() {
25663
+ const row = getRow(this.partitionStmt, {});
25664
+ return {
25665
+ queued: row?.queued ?? 0,
25666
+ inProgress: row?.inProgress ?? 0,
25667
+ synced: row?.synced ?? 0,
25668
+ failed: row?.failed ?? 0,
25669
+ refused: row?.refused ?? 0,
25670
+ detached: row?.detached ?? 0,
25671
+ total: row?.total ?? 0
25672
+ };
25673
+ }
25674
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25675
+ counts(before) {
25676
+ const row = getRow(this.countsStmt, { before });
25677
+ const captures = getRow(this.captureSkipCountStmt);
25678
+ return {
25679
+ pending: row?.pending ?? 0,
25680
+ sent: row?.sent ?? 0,
25681
+ skipped: row?.skipped ?? 0,
25682
+ refused: row?.refused ?? 0,
25683
+ detached: row?.detached ?? 0,
25684
+ capturesSkipped: captures?.skipped ?? 0
25685
+ };
25686
+ }
25687
+ /**
25688
+ * The deployment the current stamps were made against, and where its backlog
25689
+ * ends.
25690
+ *
25691
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25692
+ * machine that has never drained is — and every writer below seeds the row
25693
+ * before it needs one, so nothing depends on this creating it. Keeping the
25694
+ * write off the gate path matters because the gate runs on every pass while a
25695
+ * write has to take the database's write lock.
25696
+ */
25697
+ deployment() {
25698
+ const row = getRow(
25699
+ this.fingerprintStmt
25700
+ );
25701
+ return {
25702
+ fingerprint: row?.fingerprint ?? void 0,
25703
+ backlogBefore: row?.backlogBefore ?? void 0
25704
+ };
25705
+ }
25706
+ /**
25707
+ * Point the ledger at a different deployment, discarding what it recorded
25708
+ * about the previous one.
25709
+ *
25710
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25711
+ * machine has just left are undelivered as far as the new one is concerned.
25712
+ * All four in one transaction, so a crash between them cannot leave stamps
25713
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25714
+ * a disown with no re-mark to follow it.
25715
+ *
25716
+ * The boundary is written HERE and only here, which is what freezes it: a
25717
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25718
+ * unchanged, so this never runs and the backlog does not widen back over rows
25719
+ * the live path has since delivered.
25720
+ *
25721
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25722
+ * granted existing-history consent for the deployment this call is arming —
25723
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25724
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25725
+ * apart. Passed only when that grant is valid, since this method has no way
25726
+ * to check consent itself and must not mark a row owed for a machine that
25727
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25728
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25729
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25730
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25731
+ * on the cleared side of that bound — and the re-mark in the same
25732
+ * transaction is what puts those rows back. A crash between the two cannot
25733
+ * strand the ledger disowned with nothing re-marked — the transaction either
25734
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25735
+ * committed re-enters this method on the very next pass. Omit it (the
25736
+ * structural-only tests do) to exercise the disown in isolation.
25737
+ *
25738
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25739
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25740
+ * live path can mark a capture owed from the moment `aka attach` writes the
25741
+ * descriptor, before the drain's first pass ever reaches this method, and
25742
+ * such a row sits at or after the bound rather than below it. What keeps the
25743
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25744
+ * bound — disown runs first, re-mark second, both inside the one
25745
+ * transaction above.
25746
+ */
25747
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25748
+ this.ensureRowStmt.run();
25749
+ withTransaction(
25750
+ this.db,
25751
+ () => {
25752
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25753
+ this.rearmStmt.run();
25754
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25755
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25756
+ }
25757
+ if (backfillCapturesBefore !== void 0) {
25758
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25759
+ }
25760
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25761
+ },
25762
+ "IMMEDIATE"
25763
+ );
25764
+ }
25765
+ /**
25766
+ * End the attached period: hand its rows to the live path, and release the
25767
+ * boundary so the next attachment can freeze a new one.
25768
+ *
25769
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25770
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25771
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25772
+ * during the detached period, because the machine is not attached. Rows
25773
+ * recorded in that window sit after the boundary and before the re-attach, so
25774
+ * neither path takes them, and the pending count reports none outstanding.
25775
+ *
25776
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25777
+ * closing attachment's to deliver and are no longer outstanding — that is what
25778
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25779
+ * distinction is not academic: this used to write a delivery TIME, which every
25780
+ * read treats as delivery, so one detach turned a window of undelivered rows
25781
+ * into a window of delivered ones and no surface could tell. It writes the
25782
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25783
+ * "received" stop being the same fact.
25784
+ *
25785
+ * A change of deployment still frees them (see the re-arm), because the next
25786
+ * deployment has seen none of this machine's history — so the rows reach it
25787
+ * exactly as they did when this wrote a delivery time.
25788
+ *
25789
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25790
+ * window unstamped — that half-state would re-send the whole attached period
25791
+ * on the next attach, which is the failure the boundary exists to prevent.
25792
+ */
25793
+ closeAttachedWindow(attachedAtMs, atMs) {
25794
+ this.ensureRowStmt.run();
25795
+ withTransaction(
25796
+ this.db,
25797
+ () => {
25798
+ const row = getRow(this.fingerprintStmt);
25799
+ const from = row?.backlogBefore ?? attachedAtMs;
25800
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25801
+ this.releaseBoundaryStmt.run();
25802
+ },
25803
+ "IMMEDIATE"
25804
+ );
25805
+ }
25806
+ /**
25807
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25808
+ *
25809
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25810
+ * different deployment and therefore discards what was delivered to the old
25811
+ * one: here the recipient is the same, so everything already sent to it stays
25812
+ * sent.
25813
+ */
25814
+ freezeBoundary(backlogBefore) {
25815
+ this.ensureRowStmt.run();
25816
+ this.freezeBoundaryStmt.run({ backlogBefore });
25817
+ }
25818
+ /** Take the claim, or report that someone live already holds it. */
25819
+ claim(pid, host, nowMs, staleAfterMs) {
25820
+ this.ensureRowStmt.run();
25821
+ let taken = false;
25822
+ withTransaction(
25823
+ this.db,
25824
+ () => {
25825
+ const result = this.claimStmt.run({
25826
+ pid,
25827
+ host,
25828
+ now: nowMs,
25829
+ staleBefore: nowMs - staleAfterMs
25830
+ });
25831
+ taken = result.changes === 1;
25832
+ },
25833
+ "IMMEDIATE"
25834
+ );
25835
+ return taken;
25836
+ }
25837
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25838
+ heartbeat(pid, nowMs) {
25839
+ this.heartbeatStmt.run({ now: nowMs, pid });
25840
+ }
25841
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25842
+ release(pid) {
25843
+ this.releaseStmt.run({ pid });
25844
+ }
25845
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25846
+ lease() {
25847
+ return getRow(this.leaseStmt);
25848
+ }
25849
+ };
25850
+
24750
25851
  // ../../packages/persistence/src/migrations.ts
24751
25852
  function describeObject(object2) {
24752
25853
  return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
@@ -24759,7 +25860,7 @@ function createdIndexName(statement) {
24759
25860
  return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
24760
25861
  }
24761
25862
  var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24762
- function applyMigrations(db, file2) {
25863
+ function applyMigrations(db, file2, options = {}) {
24763
25864
  const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24764
25865
  db.exec(
24765
25866
  "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
@@ -24773,6 +25874,7 @@ function applyMigrations(db, file2) {
24773
25874
  );
24774
25875
  for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24775
25876
  if (applied.has(migration.tag)) continue;
25877
+ if (options.skipTags?.has(migration.tag) === true) continue;
24776
25878
  if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24777
25879
  const evidence = evidenceObjects(migration.sql);
24778
25880
  const present = evidence.filter((o) => evidenceExists(db, o));
@@ -25179,10 +26281,62 @@ function ensureSyncedAtColumn(db, table2) {
25179
26281
  if (!columns.includes("outbox_owed")) {
25180
26282
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25181
26283
  }
26284
+ if (!columns.includes("sync_failed_at")) {
26285
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26286
+ }
26287
+ if (!columns.includes("sync_failure")) {
26288
+ withTransaction(
26289
+ db,
26290
+ () => {
26291
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26292
+ db.exec(
26293
+ `UPDATE ${table2} SET synced_at = NULL
26294
+ WHERE synced_at = -1
26295
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26296
+ );
26297
+ },
26298
+ "IMMEDIATE"
26299
+ );
26300
+ }
25182
26301
  db.exec(
25183
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25184
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26302
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26303
+ BEFORE UPDATE OF sync_failure ON ${table2}
26304
+ WHEN ${syncFailureRejectCondition()}
26305
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25185
26306
  );
26307
+ const syncIndexColumns = [
26308
+ "event_type",
26309
+ "synced_at",
26310
+ "sync_claimed_at",
26311
+ "started_at",
26312
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26313
+ // has to be in the index for the read to stay covered — but putting it
26314
+ // ahead of `started_at` would reorder the prefix the structural drain's
26315
+ // reads match on.
26316
+ "sync_failure"
26317
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26318
+ //
26319
+ // The delivery-state read tests it — a capture's state depends on whether a
26320
+ // live forward marked it owed — so carrying it here makes that read covering
26321
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26322
+ // But a sixth column changes what the planner charges for this index, and
26323
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26324
+ // then stops choosing the per-session index for the token rollup and walks
26325
+ // every `llm_call` in the store through the event-type index instead. That
26326
+ // read grows with the store; this one does not.
26327
+ //
26328
+ // 40 ms on the largest store measured, once per render, is a cost worth
26329
+ // paying to leave every other read's plan where it was.
26330
+ ];
26331
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26332
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26333
+ if (!syncIndexMatches) {
26334
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26335
+ db.exec(
26336
+ `CREATE INDEX idx_audit_events_sync
26337
+ ON audit_events (${syncIndexColumns.join(", ")})`
26338
+ );
26339
+ }
25186
26340
  db.exec(
25187
26341
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25188
26342
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25404,7 +26558,11 @@ function buildAuditEvent(row) {
25404
26558
  link: linkParsed?.success ? linkParsed.data : null,
25405
26559
  targetId: row.target_id,
25406
26560
  internal: intToBool(row.internal),
25407
- flagged: intToBool(row.flagged)
26561
+ flagged: intToBool(row.flagged),
26562
+ // Only meaningful when the title came out empty — a row whose body was
26563
+ // expired but whose title fell back to `tool_name` still has something to
26564
+ // render, and flagging it would make the view apologise for nothing.
26565
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25408
26566
  };
25409
26567
  }
25410
26568
  var TIMELINE_COLUMNS = `
@@ -25412,6 +26570,7 @@ var TIMELINE_COLUMNS = `
25412
26570
  event_type,
25413
26571
  started_at,
25414
26572
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26573
+ content_expired_at,
25415
26574
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25416
26575
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25417
26576
  json_extract(attributes, '$.severity') AS severity,
@@ -25538,7 +26697,8 @@ var SqliteActivityRepository = class {
25538
26697
  SELECT 1 FROM audit_events d
25539
26698
  WHERE d.root_session_id = audit_events.id
25540
26699
  AND (d.content LIKE ? ESCAPE '\\'
25541
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
26700
+ OR coalesce(json_extract(d.attributes, '$.detail'),
26701
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25542
26702
  );
25543
26703
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25544
26704
  }
@@ -26076,6 +27236,88 @@ var SqliteAuditEventsRepository = class {
26076
27236
  }
26077
27237
  };
26078
27238
 
27239
+ // ../../packages/persistence/src/repositories/body-retention.ts
27240
+ var DEFAULT_BATCH_SIZE = 500;
27241
+ var DEFAULT_MAX_ROWS = 5e4;
27242
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27243
+ var SqliteBodyRetentionRepository = class {
27244
+ constructor(db) {
27245
+ this.db = db;
27246
+ const select = (laneClause) => `
27247
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27248
+ FROM audit_events
27249
+ WHERE content IS NOT NULL
27250
+ AND started_at < :cutoff
27251
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27252
+ ${laneClause}
27253
+ ORDER BY started_at
27254
+ LIMIT :limit`;
27255
+ this.candidatesStmt = this.db.prepare(select(""));
27256
+ this.candidatesSyncSafeStmt = this.db.prepare(
27257
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27258
+ );
27259
+ this.heldBySyncStmt = this.db.prepare(`
27260
+ SELECT COUNT(*) AS n
27261
+ FROM audit_events
27262
+ WHERE content IS NOT NULL
27263
+ AND started_at < :cutoff
27264
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27265
+ AND synced_at IS NULL`);
27266
+ this.expireStmt = this.db.prepare(
27267
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27268
+ );
27269
+ }
27270
+ db;
27271
+ candidatesStmt;
27272
+ candidatesSyncSafeStmt;
27273
+ heldBySyncStmt;
27274
+ expireStmt;
27275
+ /** How many bytes a pass with these options would free, changing nothing. */
27276
+ preview(opts) {
27277
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27278
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27279
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27280
+ return {
27281
+ rowsExpired: rows.length,
27282
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27283
+ rowsHeldBySync: this.countHeldBySync(opts)
27284
+ };
27285
+ }
27286
+ /** Clear eligible bodies, in bounded batches. */
27287
+ expire(opts) {
27288
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27289
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27290
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27291
+ let rowsExpired = 0;
27292
+ let bytesFreed = 0;
27293
+ let done = true;
27294
+ while (rowsExpired < maxRows) {
27295
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27296
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27297
+ if (batch.length === 0) break;
27298
+ withTransaction(
27299
+ this.db,
27300
+ () => {
27301
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27302
+ },
27303
+ "IMMEDIATE"
27304
+ );
27305
+ rowsExpired += batch.length;
27306
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27307
+ if (batch.length < remaining) break;
27308
+ if (rowsExpired >= maxRows) {
27309
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27310
+ }
27311
+ }
27312
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27313
+ }
27314
+ countHeldBySync(opts) {
27315
+ if (opts.sweepSyncLane) return 0;
27316
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27317
+ return row.n;
27318
+ }
27319
+ };
27320
+
26079
27321
  // ../../packages/persistence/src/repositories/classified-data.ts
26080
27322
  var SqliteClassifiedDataRepository = class {
26081
27323
  constructor(db) {
@@ -26876,23 +28118,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26876
28118
  )`;
26877
28119
 
26878
28120
  // ../../packages/persistence/src/repositories/findings.ts
26879
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26880
- var DEFAULT_LOCATIONS_LIMIT = 100;
26881
- var LOCATION_RULE_IDS_CAP = 20;
26882
- function compareLocationOrder(a, b) {
26883
- return compareFindingGroupOrder(
26884
- {
26885
- severity: a.maxSeverity,
26886
- latestDetectedAt: a.latestDetectedAt,
26887
- id: ""
26888
- },
26889
- {
26890
- severity: b.maxSeverity,
26891
- latestDetectedAt: b.latestDetectedAt,
26892
- id: ""
26893
- }
26894
- );
26895
- }
26896
28121
  var CONCAT_SEP = ",";
26897
28122
  var TUPLE_SEP = "|";
26898
28123
  function splitConcat(value) {
@@ -26921,7 +28146,15 @@ function toFlatFindingRow(r) {
26921
28146
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26922
28147
  eventId: r.event_id,
26923
28148
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26924
- status: deriveInstanceStatus(r)
28149
+ status: deriveInstanceStatus(r),
28150
+ delivery: deriveFindingDelivery({
28151
+ kind: r.kind,
28152
+ syncedAt: r.synced_at,
28153
+ syncClaimedAt: r.sync_claimed_at,
28154
+ syncFailedAt: r.sync_failed_at,
28155
+ syncFailure: r.sync_failure,
28156
+ outboxOwed: r.outbox_owed
28157
+ })
26925
28158
  };
26926
28159
  }
26927
28160
  function encodeGroupCursor(group) {
@@ -26944,13 +28177,51 @@ function decodeGroupCursor(cursor) {
26944
28177
  return null;
26945
28178
  }
26946
28179
  function firstAfter(sorted, cursor) {
26947
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
28180
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26948
28181
  return index === -1 ? sorted.length : index;
26949
28182
  }
26950
28183
  function findDeepLinked(sorted, page, id) {
26951
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26952
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
28184
+ if (page.some((t) => t.id === id)) return void 0;
28185
+ return sorted.find((t) => t.id === id);
26953
28186
  }
28187
+ function encodeLocationCursor(location) {
28188
+ const payload = {
28189
+ sev: location.maxSeverity,
28190
+ t: location.latestDetectedAt,
28191
+ r: location.repo,
28192
+ f: location.file
28193
+ };
28194
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
28195
+ }
28196
+ function decodeLocationCursor(cursor) {
28197
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
28198
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
28199
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
28200
+ }
28201
+ return null;
28202
+ }
28203
+ function firstLocationAfter(sorted, cursor) {
28204
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
28205
+ return index === -1 ? sorted.length : index;
28206
+ }
28207
+ function findDeepLinkedLocation(sorted, page, id) {
28208
+ if (page.some((l) => l.id === id)) return void 0;
28209
+ return sorted.find((l) => l.id === id);
28210
+ }
28211
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
28212
+ d.severity AS severity, f.masked_match AS masked_match,
28213
+ f.action_taken AS action_taken, f.confidence AS confidence,
28214
+ e.started_at AS occurred_at,
28215
+ e.source_tool AS source_tool,
28216
+ e.repo AS repo,
28217
+ e.file_path AS file,
28218
+ e.tool_name AS tool_name,
28219
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
28220
+ e.event_type AS kind, f.finding_key AS finding_key,
28221
+ ${latestResolutionStatusSql("f")} AS latest_status,
28222
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28223
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28224
+ e.outbox_owed AS outbox_owed`;
26954
28225
  var DAY_MS3 = 864e5;
26955
28226
  var SqliteFindingsRepository = class {
26956
28227
  constructor(db) {
@@ -27071,30 +28342,26 @@ var SqliteFindingsRepository = class {
27071
28342
  );
27072
28343
  }
27073
28344
  /**
27074
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27075
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27076
- * attributes bag, rule_id/category/severity from the definition), scoped to
27077
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27078
- * rows this list must never surface), groups by ruleId, computes
27079
- * per-filter-excluded facets, applies the requested filters, and sorts by
27080
- * severity then recency. Filtering
27081
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27082
- * reflect the full filtered set; `items` is the requested
27083
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27084
- * filter, `totals.findings` counts only instances whose derived status was
27085
- * requested, and each item's instance preview is narrowed the same way.
28345
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
28346
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
28347
+ * list must never surface), with per-filter-excluded facets, the requested
28348
+ * filters applied, and sorted by severity then recency. Filtering and faceting
28349
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
28350
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
28351
+ * Under a `status` filter, `totals.findings` counts only findings whose
28352
+ * derived status was requested.
28353
+ *
28354
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
28355
+ * folding EVERY finding into the numbers a type row and the filters need
28356
+ * (count, severity, category, providers, actions, statuses, latest, search
28357
+ * text). The findings OF a type come from listFindingInstances scoped to
28358
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27086
28359
  *
27087
- * Two reads, neither of which materializes a row per finding:
27088
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27089
- * the group and the filters need (count, providers, actions, statuses,
27090
- * latest, search text);
27091
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27092
- * populate `instances` for the table's expanded rows.
27093
28360
  * The aggregates carry raw DB values and are translated by the same
27094
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27095
- * rule is ever restated in SQL.
28361
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
28362
+ * status rule is ever restated in SQL.
27096
28363
  */
27097
- listGroupedFindings(query) {
28364
+ listFindingTypes(query) {
27098
28365
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27099
28366
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27100
28367
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27107,12 +28374,7 @@ var SqliteFindingsRepository = class {
27107
28374
  predicate,
27108
28375
  params: sessionParams
27109
28376
  });
27110
- const rows = this.previewRows(aggregates, {
27111
- sessionId: query.sessionId,
27112
- from: query.from
27113
- });
27114
- const groupable = rows.map(toFlatFindingRow);
27115
- const allGroups = buildFindingGroups(groupable, { aggregates });
28377
+ const allTypes = buildFindingTypes(aggregates);
27116
28378
  const filterOpts = {
27117
28379
  severity: query.severity,
27118
28380
  providers: query.provider,
@@ -27121,30 +28383,25 @@ var SqliteFindingsRepository = class {
27121
28383
  subtype: query.subtype,
27122
28384
  q: query.q
27123
28385
  };
27124
- const facets = computeFindingFacets(allGroups, filterOpts);
27125
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
28386
+ const facets = computeFindingFacets(allTypes, filterOpts);
28387
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27126
28388
  const statusFilter = query.status ?? [];
27127
28389
  const totals = {
27128
- findings: sorted.reduce((acc, g) => {
27129
- if (statusFilter.length === 0) return acc + g.instanceCount;
27130
- const agg = aggregates.get(g.id);
27131
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
28390
+ findings: sorted.reduce((acc, t) => {
28391
+ if (statusFilter.length === 0) return acc + t.instanceCount;
28392
+ const agg = aggregates.get(t.id);
28393
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27132
28394
  }, 0),
27133
- groups: sorted.length
28395
+ types: sorted.length
27134
28396
  };
27135
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
28397
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27136
28398
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27137
28399
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27138
28400
  const page = sorted.slice(start, start + limit);
27139
28401
  const lastOnPage = page.at(-1);
27140
28402
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27141
28403
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27142
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27143
- const narrow = (g) => statusSet ? {
27144
- ...g,
27145
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27146
- } : g;
27147
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
28404
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27148
28405
  return Promise.resolve({
27149
28406
  totals,
27150
28407
  facets,
@@ -27155,7 +28412,7 @@ var SqliteFindingsRepository = class {
27155
28412
  }
27156
28413
  /**
27157
28414
  * One row per rule_id, folding EVERY instance of the group into the values
27158
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
28415
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27159
28416
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27160
28417
  *
27161
28418
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27209,6 +28466,7 @@ var SqliteFindingsRepository = class {
27209
28466
  providers: query.provider,
27210
28467
  actions: query.action,
27211
28468
  statuses: query.status,
28469
+ deliveries: query.deployment,
27212
28470
  tools: query.tool,
27213
28471
  repo: query.repo,
27214
28472
  file: query.file,
@@ -27249,13 +28507,25 @@ var SqliteFindingsRepository = class {
27249
28507
  });
27250
28508
  }
27251
28509
  /**
27252
- * The same findings folded by location: repository, then file within it.
28510
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27253
28511
  *
27254
28512
  * The grouping keys come from the capturing event's attributes, which is what
27255
- * the local store relates a finding to — there is no finding↔asset row to
27256
- * group by instead. A repo or file the event did not record folds into the
27257
- * empty-string bucket, which the view renders but does not link, since no
27258
- * filter can name it.
28513
+ * the local store relates a finding to; there is no finding↔asset row to group
28514
+ * by instead. A repo or file the event did not record folds into the
28515
+ * empty-string bucket, which is a real location like any other: it is listed,
28516
+ * it is selectable, and its `?loc=` token is as good as any other row's.
28517
+ *
28518
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
28519
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
28520
+ * list was rebuilt to remove — and two-level pagination inside an
28521
+ * expand/collapse table is what pushed that view to master/detail in the first
28522
+ * place.
28523
+ *
28524
+ * Every filter narrows the FINDINGS and the locations fall out of what
28525
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
28526
+ * reports for the same filters scoped to that pair. The view depends on it:
28527
+ * one toolbar sits over both panels precisely because a location owns none of
28528
+ * its fields.
27259
28529
  */
27260
28530
  listFindingLocations(query) {
27261
28531
  const opts = {
@@ -27264,16 +28534,20 @@ var SqliteFindingsRepository = class {
27264
28534
  providers: query.provider,
27265
28535
  actions: query.action,
27266
28536
  statuses: query.status,
28537
+ deliveries: query.deployment,
27267
28538
  tools: query.tool,
27268
28539
  q: query.q
27269
28540
  };
27270
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
28541
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
28542
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27271
28543
  const byRepo = /* @__PURE__ */ new Map();
28544
+ const accumulator = createInstanceFacetAccumulator(opts);
27272
28545
  let total = 0;
27273
28546
  for (const row of this.scanFindingRows({
27274
28547
  sessionId: query.sessionId,
27275
28548
  from: query.from
27276
28549
  })) {
28550
+ accumulator.add(row);
27277
28551
  if (!matchesInstanceFilters(row, opts)) continue;
27278
28552
  total += 1;
27279
28553
  let files = byRepo.get(row.repo);
@@ -27288,103 +28562,35 @@ var SqliteFindingsRepository = class {
27288
28562
  }
27289
28563
  addToLocation(acc, row);
27290
28564
  }
27291
- let fileCount = 0;
27292
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27293
- fileCount += files.size;
27294
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27295
- file: file2,
27296
- instanceCount: acc.instanceCount,
27297
- maxSeverity: acc.maxSeverity,
27298
- latestDetectedAt: acc.latestDetectedAt,
27299
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27300
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27301
- })).sort(compareLocationOrder);
27302
- const rollup = fileRows.reduce(
27303
- (a, f) => ({
27304
- instanceCount: a.instanceCount + f.instanceCount,
27305
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27306
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27307
- }),
27308
- {
27309
- instanceCount: 0,
27310
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27311
- latestDetectedAt: ""
27312
- }
27313
- );
27314
- const statuses = fileRows.map((f) => f.status);
27315
- const folded = foldGroupStatus(statuses);
27316
- return {
27317
- repo,
27318
- instanceCount: rollup.instanceCount,
27319
- maxSeverity: rollup.maxSeverity,
27320
- latestDetectedAt: rollup.latestDetectedAt,
27321
- ...folded === void 0 ? {} : { status: folded },
27322
- files: fileRows
27323
- };
27324
- });
27325
- repos.sort(compareLocationOrder);
28565
+ const sorted = [];
28566
+ for (const [repo, files] of byRepo) {
28567
+ for (const [file2, acc] of files) {
28568
+ const status = foldGroupStatus(acc.statuses);
28569
+ sorted.push({
28570
+ id: encodeLocationId(repo, file2),
28571
+ repo,
28572
+ file: file2,
28573
+ instanceCount: acc.instanceCount,
28574
+ maxSeverity: acc.maxSeverity,
28575
+ latestDetectedAt: acc.latestDetectedAt,
28576
+ ...status === void 0 ? {} : { status },
28577
+ ruleIds: [...acc.ruleIds]
28578
+ });
28579
+ }
28580
+ }
28581
+ sorted.sort(compareLocationOrder);
28582
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
28583
+ const page = sorted.slice(start, start + limit);
28584
+ const lastOnPage = page.at(-1);
28585
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
28586
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27326
28587
  return Promise.resolve({
27327
- totals: { findings: total, repos: repos.length, files: fileCount },
27328
- items: repos.slice(0, limit),
27329
- hasMore: repos.length > limit
28588
+ totals: { findings: total, locations: sorted.length },
28589
+ facets: accumulator.facets(),
28590
+ items: [...page, ...deepLinked ? [deepLinked] : []],
28591
+ nextCursor
27330
28592
  });
27331
28593
  }
27332
- /**
27333
- * Each group's newest instances, for the table's expanded rows.
27334
- *
27335
- * ONE index-ordered scan with early termination, and the shape is the point.
27336
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27337
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27338
- * through a temp B-tree to keep a bounded preview of each group, and then
27339
- * sorts the survivors again for the page order. Both sorts grow with the
27340
- * store while the answer does not.
27341
- *
27342
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27343
- * (or the session or window index the scope names — see `findingScanSql`),
27344
- * which is already the order the page wants, and keeps rows per rule until
27345
- * each rule has as many as it can show. The aggregate the caller already holds
27346
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27347
- * per rule, summed, is the number of rows this scan has to find, and it stops
27348
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27349
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27350
- * store with many firing rules widens it. The bound that DOES hold
27351
- * unconditionally is the sorted form's floor: this scan visits at most as
27352
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27353
- * sorted, and stops the moment every rule has its cap, where the sorted form
27354
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27355
- * wanted instances sitting at the tail of the scope — is one pass over
27356
- * everything in scope with a block sort of the id tie-break only, never a
27357
- * sort of the scope, which is still that floor.
27358
- *
27359
- * A row whose rule the aggregate did not see is skipped: the two statements
27360
- * run without a shared snapshot, so a capture landing between them can add a
27361
- * rule here that has no counts there, and the counts are what the group is
27362
- * built from.
27363
- */
27364
- previewRows(aggregates, scope) {
27365
- const wanted = /* @__PURE__ */ new Map();
27366
- let remaining = 0;
27367
- for (const [ruleId, agg] of aggregates) {
27368
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27369
- wanted.set(ruleId, n);
27370
- remaining += n;
27371
- }
27372
- const rows = [];
27373
- if (remaining === 0) return rows;
27374
- const { sql, params } = this.findingScanSql(scope);
27375
- const taken = /* @__PURE__ */ new Map();
27376
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27377
- const want = wanted.get(r.rule_id);
27378
- if (want === void 0) continue;
27379
- const have = taken.get(r.rule_id) ?? 0;
27380
- if (have >= want) continue;
27381
- taken.set(r.rule_id, have + 1);
27382
- rows.push(r);
27383
- remaining -= 1;
27384
- if (remaining === 0) break;
27385
- }
27386
- return rows;
27387
- }
27388
28594
  /**
27389
28595
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27390
28596
  *
@@ -27411,6 +28617,33 @@ var SqliteFindingsRepository = class {
27411
28617
  yield toFlatFindingRow(r);
27412
28618
  }
27413
28619
  }
28620
+ /**
28621
+ * One finding by its own id, or null when no such row exists.
28622
+ *
28623
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
28624
+ * the store — and, unlike anything derived from a list page, it resolves a
28625
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
28626
+ * deep link needs: the id it carries may name a finding thousands of rows
28627
+ * older than anything a first page holds.
28628
+ *
28629
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
28630
+ * RESOLVES an id; whether that row would survive the list's current filters is
28631
+ * a different question, and hiding the target because a filter excludes it is
28632
+ * worse than showing it.
28633
+ *
28634
+ * `groupId` on the result IS the rule id, so this one read answers both "which
28635
+ * type should the list select?" and "what does the drawer show?".
28636
+ */
28637
+ findingInstance(id) {
28638
+ const row = this.db.prepare(
28639
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
28640
+ FROM inspection_findings f
28641
+ JOIN audit_events e ON e.id = f.audit_event_id
28642
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
28643
+ WHERE f.id = ?`
28644
+ ).get(id);
28645
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
28646
+ }
27414
28647
  /**
27415
28648
  * The one statement both instance-level scans run: every finding in scope,
27416
28649
  * joined to its event and definition, newest first.
@@ -27444,17 +28677,7 @@ var SqliteFindingsRepository = class {
27444
28677
  conditions.push("e.started_at >= ?");
27445
28678
  params.push(isoToEpochMillis(scope.from));
27446
28679
  }
27447
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27448
- d.severity AS severity, f.masked_match AS masked_match,
27449
- f.action_taken AS action_taken, f.confidence AS confidence,
27450
- e.started_at AS occurred_at,
27451
- e.source_tool AS source_tool,
27452
- e.repo AS repo,
27453
- e.file_path AS file,
27454
- e.tool_name AS tool_name,
27455
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27456
- e.event_type AS kind, f.finding_key AS finding_key,
27457
- ${latestResolutionStatusSql("f")} AS latest_status
28680
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27458
28681
  FROM audit_events e
27459
28682
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27460
28683
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27468,6 +28691,26 @@ var SqliteFindingsRepository = class {
27468
28691
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27469
28692
  const rows = this.db.prepare(
27470
28693
  `SELECT rule_id,
28694
+ -- BARE columns beside max(latest_at), which is deliberate and
28695
+ -- is SQLite's documented behaviour: with a single min()/max()
28696
+ -- in an aggregate query, every bare column takes its value from
28697
+ -- the row that produced the extremum. So these are the severity
28698
+ -- and category of the definition whose finding is NEWEST, which
28699
+ -- is what the row-based build they replaced read off its first
28700
+ -- (newest-first) row.
28701
+ --
28702
+ -- min() is WRONG here and was the defect: inspection_definitions
28703
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
28704
+ -- mints a new row), so a rule whose severity moved between
28705
+ -- versions has several, and min() picks the ALPHABETICALLY
28706
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
28707
+ -- That is arbitrary in direction, and it feeds the badge, the
28708
+ -- filter, the facet counts and the primary sort key.
28709
+ --
28710
+ -- Adding a second min()/max() aggregate here would make these
28711
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
28712
+ severity,
28713
+ category,
27471
28714
  sum(tuple_count) AS instance_count,
27472
28715
  max(latest_at) AS latest_at,
27473
28716
  group_concat(source_tools) AS source_tools,
@@ -27478,6 +28721,14 @@ var SqliteFindingsRepository = class {
27478
28721
  group_concat(tool_names) AS tool_names
27479
28722
  FROM (
27480
28723
  SELECT d.rule_id AS rule_id,
28724
+ -- Severity and category are columns of the DEFINITION, and
28725
+ -- a rule can have SEVERAL definitions (one per version), so
28726
+ -- these are grouped on below and resolved to the newest
28727
+ -- firing version by the outer query's bare-column select.
28728
+ -- They ride the aggregate because the type build has no rows
28729
+ -- to read them off \u2014 see buildFindingTypes.
28730
+ d.severity AS severity,
28731
+ d.category AS category,
27481
28732
  e.event_type || '${TUPLE_SEP}' ||
27482
28733
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27483
28734
  coalesce(latest.status, '') AS status_tuple,
@@ -27492,7 +28743,7 @@ var SqliteFindingsRepository = class {
27492
28743
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27493
28744
  ON latest.finding_key = f.finding_key
27494
28745
  ${scope.predicate}
27495
- GROUP BY d.rule_id, status_tuple
28746
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27496
28747
  )
27497
28748
  GROUP BY rule_id`
27498
28749
  ).all(scope.params);
@@ -27501,6 +28752,8 @@ var SqliteFindingsRepository = class {
27501
28752
  r.rule_id,
27502
28753
  {
27503
28754
  instanceCount: r.instance_count,
28755
+ severity: r.severity,
28756
+ category: r.category,
27504
28757
  sourceTools: splitConcat(r.source_tools),
27505
28758
  actionsTaken: splitConcat(r.actions_taken),
27506
28759
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27517,7 +28770,7 @@ var SqliteFindingsRepository = class {
27517
28770
  latestDetectedAt: epochMillisToIso(r.latest_at),
27518
28771
  // Free text only — joined and substring-matched, so group_concat's
27519
28772
  // commas need no unpicking (a repo/path containing one still matches).
27520
- // Left undefined (not '') when unfetched, so buildFindingGroups can
28773
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27521
28774
  // tell "no q this request" from "a group with no repo/file at all"
27522
28775
  // and skip priming a haystack nothing will read.
27523
28776
  ...withSearchText ? {
@@ -27545,7 +28798,9 @@ var SqliteFindingsRepository = class {
27545
28798
  )
27546
28799
  );
27547
28800
  for (const row of grouped) {
27548
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28801
+ if (Object.hasOwn(byAction, row.action_taken)) {
28802
+ byAction[row.action_taken] = row.c;
28803
+ }
27549
28804
  }
27550
28805
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27551
28806
  const sevRows = allRows(
@@ -27562,7 +28817,9 @@ var SqliteFindingsRepository = class {
27562
28817
  )
27563
28818
  );
27564
28819
  for (const row of sevRows) {
27565
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28820
+ if (Object.hasOwn(bySeverity, row.severity)) {
28821
+ bySeverity[row.severity] = row.c;
28822
+ }
27566
28823
  }
27567
28824
  const categories = ENFORCEABLE_CATEGORIES;
27568
28825
  const enabledRows = allRows(
@@ -27611,469 +28868,6 @@ function isoDay(ms) {
27611
28868
  return new Date(ms).toISOString().slice(0, 10);
27612
28869
  }
27613
28870
 
27614
- // ../../packages/persistence/src/repositories/history-sync.ts
27615
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27616
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27617
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27618
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27619
- var SKIPPED = -1;
27620
- var ROW_COLUMNS = `id,
27621
- parent_id AS parentId,
27622
- root_session_id AS rootSessionId,
27623
- event_type AS eventType,
27624
- host_id AS hostId,
27625
- harness_id AS harnessId,
27626
- source_project_id AS sourceProjectId,
27627
- started_at AS startedAt,
27628
- ended_at AS endedAt,
27629
- severity,
27630
- priority,
27631
- content,
27632
- content_hash AS contentHash,
27633
- attributes`;
27634
- var SqliteHistorySyncRepository = class {
27635
- constructor(db) {
27636
- this.db = db;
27637
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27638
- this.sessionsStmt = db.prepare(
27639
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27640
- FROM audit_events
27641
- WHERE synced_at IS NULL
27642
- AND event_type IN (${TYPE_LIST})
27643
- AND started_at < :before
27644
- GROUP BY sessionId
27645
- ORDER BY earliest
27646
- LIMIT :limit`
27647
- );
27648
- this.rowsStmt = db.prepare(
27649
- `SELECT ${ROW_COLUMNS}
27650
- FROM audit_events
27651
- WHERE synced_at IS NULL
27652
- AND event_type IN (${TYPE_LIST})
27653
- AND started_at < :before
27654
- AND COALESCE(root_session_id, id) = :sessionId
27655
- ORDER BY (event_type = 'session') DESC, started_at
27656
- LIMIT :limit`
27657
- );
27658
- this.captureRowsStmt = db.prepare(
27659
- `SELECT ${ROW_COLUMNS}
27660
- FROM audit_events
27661
- WHERE synced_at IS NULL
27662
- AND sync_claimed_at IS NULL
27663
- AND outbox_owed = 1
27664
- AND event_type IN (${CAPTURE_TYPE_LIST})
27665
- AND started_at < :before
27666
- ORDER BY started_at
27667
- LIMIT :limit`
27668
- );
27669
- this.markOwedStmt = db.prepare(
27670
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27671
- );
27672
- this.stampStmt = db.prepare(
27673
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27674
- );
27675
- this.claimRowStmt = db.prepare(
27676
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27677
- );
27678
- this.releaseRowStmt = db.prepare(
27679
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27680
- );
27681
- this.releaseStaleClaimsStmt = db.prepare(
27682
- `UPDATE audit_events SET sync_claimed_at = NULL
27683
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27684
- );
27685
- this.partitionStmt = db.prepare(
27686
- `SELECT
27687
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27688
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27689
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27690
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27691
- COUNT(*) AS total
27692
- FROM audit_events
27693
- WHERE event_type IN (${TYPE_LIST})`
27694
- );
27695
- this.countsStmt = db.prepare(
27696
- `SELECT
27697
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27698
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27699
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27700
- FROM audit_events
27701
- WHERE event_type IN (${TYPE_LIST})`
27702
- );
27703
- this.captureSkipCountStmt = db.prepare(
27704
- `SELECT COUNT(*) AS skipped
27705
- FROM audit_events
27706
- WHERE synced_at = ${String(SKIPPED)}
27707
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27708
- );
27709
- this.fingerprintStmt = db.prepare(
27710
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27711
- FROM history_sync WHERE id = 1`
27712
- );
27713
- this.setFingerprintStmt = db.prepare(
27714
- `UPDATE history_sync
27715
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27716
- WHERE id = 1`
27717
- );
27718
- this.disownCapturesStmt = db.prepare(
27719
- `UPDATE audit_events SET outbox_owed = NULL
27720
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27721
- );
27722
- this.rearmStmt = db.prepare(
27723
- `UPDATE audit_events SET synced_at = NULL
27724
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27725
- );
27726
- this.claimStmt = db.prepare(
27727
- `UPDATE history_sync
27728
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27729
- WHERE id = 1
27730
- AND (owner_pid IS NULL
27731
- OR heartbeat_at IS NULL
27732
- OR heartbeat_at < :staleBefore
27733
- OR heartbeat_at > :now)`
27734
- );
27735
- this.heartbeatStmt = db.prepare(
27736
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27737
- );
27738
- this.releaseStmt = db.prepare(
27739
- `UPDATE history_sync
27740
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27741
- WHERE id = 1 AND owner_pid = :pid`
27742
- );
27743
- this.closeWindowStmt = db.prepare(
27744
- `UPDATE audit_events SET synced_at = :at
27745
- WHERE synced_at IS NULL
27746
- AND event_type IN (${TYPE_LIST})
27747
- AND started_at >= :attachedAt`
27748
- );
27749
- this.releaseBoundaryStmt = db.prepare(
27750
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27751
- );
27752
- this.freezeBoundaryStmt = db.prepare(
27753
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27754
- );
27755
- this.leaseStmt = db.prepare(
27756
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27757
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27758
- FROM history_sync WHERE id = 1`
27759
- );
27760
- this.inspectionsStmt = db.prepare(
27761
- `SELECT d.rule_id AS ruleId,
27762
- d.name AS ruleName,
27763
- d.version AS ruleVersion,
27764
- d.category AS category,
27765
- d.severity AS severity,
27766
- f.span_start AS spanStart,
27767
- f.span_end AS spanEnd,
27768
- f.masked_match AS maskedMatch,
27769
- f.action_taken AS actionTaken,
27770
- f.confidence AS confidence
27771
- FROM inspection_findings f
27772
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27773
- WHERE f.audit_event_id = :auditEventId
27774
- ORDER BY f.span_start, f.id`
27775
- );
27776
- }
27777
- db;
27778
- ensureRowStmt;
27779
- sessionsStmt;
27780
- rowsStmt;
27781
- stampStmt;
27782
- countsStmt;
27783
- fingerprintStmt;
27784
- setFingerprintStmt;
27785
- rearmStmt;
27786
- claimStmt;
27787
- heartbeatStmt;
27788
- releaseStmt;
27789
- leaseStmt;
27790
- inspectionsStmt;
27791
- closeWindowStmt;
27792
- releaseBoundaryStmt;
27793
- freezeBoundaryStmt;
27794
- captureRowsStmt;
27795
- markOwedStmt;
27796
- captureSkipCountStmt;
27797
- disownCapturesStmt;
27798
- partitionStmt;
27799
- claimRowStmt;
27800
- releaseRowStmt;
27801
- releaseStaleClaimsStmt;
27802
- /**
27803
- * The masked detections recorded against one tool call.
27804
- *
27805
- * These travel with the event because a tool call's target is not
27806
- * re-inspectable from the event alone — unlike a capture, where the text
27807
- * itself is re-scannable. What crosses is the masked match and the rule that
27808
- * produced it, never the value.
27809
- */
27810
- inspectionsFor(auditEventId) {
27811
- return allRows(this.inspectionsStmt, { auditEventId });
27812
- }
27813
- /**
27814
- * Sessions with structural rows still to send, oldest first.
27815
- *
27816
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27817
- * read. Anything recorded after the machine attached is the live forward
27818
- * path's to deliver; this drain exists for what was recorded before it, and a
27819
- * row both paths send is at best a duplicate request and at worst — for a
27820
- * session root — an overwrite of the inventory ids the live path resolved.
27821
- */
27822
- pendingSessions(limit, before) {
27823
- return allRows(this.sessionsStmt, { limit, before }).map(
27824
- (r) => r.sessionId
27825
- );
27826
- }
27827
- /** One session's undelivered structural rows within the backlog, root first. */
27828
- pendingRows(sessionId, limit, before) {
27829
- return allRows(this.rowsStmt, { sessionId, limit, before });
27830
- }
27831
- /**
27832
- * Captures this machine still owes the deployment, oldest first.
27833
- *
27834
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27835
- * by a time window — see captureRowsStmt for why a window could not express
27836
- * this. `before` is the grace window that leaves a just-recorded capture to
27837
- * the live path.
27838
- */
27839
- pendingCaptureRows(limit, before) {
27840
- return allRows(this.captureRowsStmt, { limit, before });
27841
- }
27842
- /**
27843
- * Record that a capture is OWED to the deployment.
27844
- *
27845
- * Written by the attached forward path when a live send did not confirm
27846
- * delivery, and read by the drain as the whole of its eligibility test. It is
27847
- * a fact rather than an inference: the machine was attached, the send did not
27848
- * land, so the row is owed — which no time window can state, because the same
27849
- * window that holds the rows a past attachment left owed also holds every
27850
- * capture recorded while the machine was DETACHED, and those were never
27851
- * offered to anyone.
27852
- *
27853
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27854
- * out of the drain's read.
27855
- */
27856
- markCaptureOwed(id) {
27857
- this.markOwedStmt.run({ id });
27858
- }
27859
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27860
- markSynced(ids, atMs) {
27861
- this.stampAll(ids, atMs);
27862
- }
27863
- /**
27864
- * Record that a row will never be sent.
27865
- *
27866
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27867
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27868
- * is retried; marking those would turn one outage into permanent data loss.
27869
- */
27870
- markSkipped(ids) {
27871
- this.stampAll(ids, SKIPPED);
27872
- }
27873
- eachInTransaction(ids, run) {
27874
- if (ids.length === 0) return;
27875
- withTransaction(
27876
- this.db,
27877
- () => {
27878
- for (const id of ids) run(id);
27879
- },
27880
- "IMMEDIATE"
27881
- );
27882
- }
27883
- stampAll(ids, value) {
27884
- if (ids.length === 0) return;
27885
- withTransaction(
27886
- this.db,
27887
- () => {
27888
- for (const id of ids) this.stampStmt.run({ at: value, id });
27889
- },
27890
- "IMMEDIATE"
27891
- );
27892
- }
27893
- /**
27894
- * Claim rows as in-flight.
27895
- *
27896
- * Advisory in exactly the sense the lease is: it records that a send is in
27897
- * progress so a surface can say so, and a lost claim costs a row showing as
27898
- * queued while it is actually being sent. It is not exclusion — the far side
27899
- * settles a duplicate on the row id.
27900
- */
27901
- claimRows(ids, atMs) {
27902
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27903
- }
27904
- /** Give back a claim without settling — the send failed, the row is queued again. */
27905
- releaseRows(ids) {
27906
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27907
- }
27908
- /**
27909
- * Clear claims older than `staleBefore`, and report how many were cleared.
27910
- *
27911
- * A process killed between claiming and settling leaves rows claimed with
27912
- * nothing left to settle them. Without this they read as "sending" for ever.
27913
- */
27914
- releaseStaleClaims(staleBefore) {
27915
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27916
- }
27917
- /**
27918
- * Every tracked row in exactly one delivery state.
27919
- *
27920
- * Takes no boundary on purpose. The boundary answers "what should the drain
27921
- * pick up now", which is a different question from "what state is this row
27922
- * in" — and a machine that has never attached has no boundary to pass, so
27923
- * requiring one would force a caller to invent one and report the whole store
27924
- * as queued.
27925
- */
27926
- partition() {
27927
- const row = getRow(this.partitionStmt, {});
27928
- return {
27929
- queued: row?.queued ?? 0,
27930
- inProgress: row?.inProgress ?? 0,
27931
- synced: row?.synced ?? 0,
27932
- failed: row?.failed ?? 0,
27933
- total: row?.total ?? 0
27934
- };
27935
- }
27936
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27937
- counts(before) {
27938
- const row = getRow(
27939
- this.countsStmt,
27940
- { before }
27941
- );
27942
- const captures = getRow(this.captureSkipCountStmt);
27943
- return {
27944
- pending: row?.pending ?? 0,
27945
- sent: row?.sent ?? 0,
27946
- skipped: row?.skipped ?? 0,
27947
- capturesSkipped: captures?.skipped ?? 0
27948
- };
27949
- }
27950
- /**
27951
- * The deployment the current stamps were made against, and where its backlog
27952
- * ends.
27953
- *
27954
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27955
- * machine that has never drained is — and every writer below seeds the row
27956
- * before it needs one, so nothing depends on this creating it. Keeping the
27957
- * write off the gate path matters because the gate runs on every pass while a
27958
- * write has to take the database's write lock.
27959
- */
27960
- deployment() {
27961
- const row = getRow(
27962
- this.fingerprintStmt
27963
- );
27964
- return {
27965
- fingerprint: row?.fingerprint ?? void 0,
27966
- backlogBefore: row?.backlogBefore ?? void 0
27967
- };
27968
- }
27969
- /**
27970
- * Point the ledger at a different deployment, discarding what it recorded
27971
- * about the previous one.
27972
- *
27973
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
27974
- * machine has just left are undelivered as far as the new one is concerned.
27975
- * All three in one transaction, so a crash between them cannot leave stamps
27976
- * attributed to the wrong deployment, or a boundary that belongs to another.
27977
- *
27978
- * The boundary is written HERE and only here, which is what freezes it: a
27979
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
27980
- * unchanged, so this never runs and the backlog does not widen back over rows
27981
- * the live path has since delivered.
27982
- */
27983
- rearmFor(fingerprint, backlogBefore) {
27984
- this.ensureRowStmt.run();
27985
- withTransaction(
27986
- this.db,
27987
- () => {
27988
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
27989
- this.rearmStmt.run();
27990
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
27991
- this.disownCapturesStmt.run();
27992
- }
27993
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27994
- },
27995
- "IMMEDIATE"
27996
- );
27997
- }
27998
- /**
27999
- * End the attached period: hand its rows to the live path, and release the
28000
- * boundary so the next attachment can freeze a new one.
28001
- *
28002
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28003
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28004
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28005
- * during the detached period, because the machine is not attached. Rows
28006
- * recorded in that window sit after the boundary and before the re-attach, so
28007
- * neither path takes them, and the pending count reports none outstanding.
28008
- *
28009
- * Stamping the attached window is not a claim that every one of those rows
28010
- * reached the deployment — the live path drops on failure and says so
28011
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28012
- * status quo: they sit outside the frozen boundary today and are equally never
28013
- * re-sent. Making it explicit is what lets the boundary move.
28014
- *
28015
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28016
- * window unstamped — that half-state would re-send the whole attached period
28017
- * on the next attach, which is the failure the boundary exists to prevent.
28018
- */
28019
- closeAttachedWindow(attachedAtMs, atMs) {
28020
- this.ensureRowStmt.run();
28021
- withTransaction(
28022
- this.db,
28023
- () => {
28024
- const row = getRow(this.fingerprintStmt);
28025
- const from = row?.backlogBefore ?? attachedAtMs;
28026
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28027
- this.releaseBoundaryStmt.run();
28028
- },
28029
- "IMMEDIATE"
28030
- );
28031
- }
28032
- /**
28033
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28034
- *
28035
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28036
- * different deployment and therefore discards what was delivered to the old
28037
- * one: here the recipient is the same, so everything already sent to it stays
28038
- * sent.
28039
- */
28040
- freezeBoundary(backlogBefore) {
28041
- this.ensureRowStmt.run();
28042
- this.freezeBoundaryStmt.run({ backlogBefore });
28043
- }
28044
- /** Take the claim, or report that someone live already holds it. */
28045
- claim(pid, host, nowMs, staleAfterMs) {
28046
- this.ensureRowStmt.run();
28047
- let taken = false;
28048
- withTransaction(
28049
- this.db,
28050
- () => {
28051
- const result = this.claimStmt.run({
28052
- pid,
28053
- host,
28054
- now: nowMs,
28055
- staleBefore: nowMs - staleAfterMs
28056
- });
28057
- taken = result.changes === 1;
28058
- },
28059
- "IMMEDIATE"
28060
- );
28061
- return taken;
28062
- }
28063
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28064
- heartbeat(pid, nowMs) {
28065
- this.heartbeatStmt.run({ now: nowMs, pid });
28066
- }
28067
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28068
- release(pid) {
28069
- this.releaseStmt.run({ pid });
28070
- }
28071
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28072
- lease() {
28073
- return getRow(this.leaseStmt);
28074
- }
28075
- };
28076
-
28077
28871
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28078
28872
  var SqliteInspectionDefinitionsRepository = class {
28079
28873
  constructor(db) {
@@ -28265,7 +29059,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28265
29059
  }
28266
29060
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28267
29061
  }
28268
- function readManagedSettings(paths = managedSettingsPaths()) {
29062
+ var testOnlyManagedPaths = null;
29063
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28269
29064
  for (const path of paths) {
28270
29065
  let text;
28271
29066
  try {
@@ -28300,6 +29095,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28300
29095
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28301
29096
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28302
29097
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29098
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28303
29099
  if (values.vaultConsent !== void 0) {
28304
29100
  merged.vaultConsent = values.vaultConsent ? (
28305
29101
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30745,7 +31541,7 @@ function toUtcDateString(ms) {
30745
31541
  return new Date(ms).toISOString().slice(0, 10);
30746
31542
  }
30747
31543
  function isTimeseriesSeverity(s) {
30748
- return s === "critical" || s === "high" || s === "medium";
31544
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30749
31545
  }
30750
31546
  var SqliteSecurityRepository = class {
30751
31547
  constructor(db, now = () => Date.now()) {
@@ -30807,7 +31603,7 @@ var SqliteSecurityRepository = class {
30807
31603
  ELSE 0
30808
31604
  END) AS open_at_rest
30809
31605
  FROM inspection_findings f
30810
- JOIN audit_events e ON e.id = f.audit_event_id
31606
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30811
31607
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30812
31608
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30813
31609
  ON latest.finding_key = f.finding_key
@@ -30874,12 +31670,16 @@ var SqliteSecurityRepository = class {
30874
31670
  const now = this.now();
30875
31671
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30876
31672
  const rows = this.findingsInRange(windowStart, now);
30877
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30878
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30879
- critical: 0,
30880
- high: 0,
30881
- medium: 0
30882
- }));
31673
+ const points = Array.from(
31674
+ { length: numBuckets },
31675
+ (_, i) => ({
31676
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31677
+ critical: 0,
31678
+ high: 0,
31679
+ medium: 0,
31680
+ low: 0
31681
+ })
31682
+ );
30883
31683
  for (const r of rows) {
30884
31684
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30885
31685
  const bucket = points[idx];
@@ -31029,7 +31829,7 @@ var SqliteSecurityRepository = class {
31029
31829
  this.db.prepare(
31030
31830
  `SELECT e.repo AS repo, count(*) AS c
31031
31831
  FROM inspection_findings f
31032
- JOIN audit_events e ON e.id = f.audit_event_id
31832
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31033
31833
  WHERE e.started_at >= :from AND e.started_at < :to
31034
31834
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31035
31835
  AND e.repo IS NOT NULL
@@ -31097,6 +31897,7 @@ var SqliteSecurityRepository = class {
31097
31897
  `SELECT f.finding_key AS finding_key,
31098
31898
  d.rule_id AS rule_id,
31099
31899
  d.severity AS severity,
31900
+ e.repo AS repo,
31100
31901
  e.file_path AS path,
31101
31902
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31102
31903
  latest.resolved_at AS latest_resolved_at
@@ -31116,6 +31917,7 @@ var SqliteSecurityRepository = class {
31116
31917
  const items = rows.map((r) => ({
31117
31918
  findingKey: r.finding_key,
31118
31919
  ruleId: r.rule_id,
31920
+ repo: r.repo ?? "",
31119
31921
  severity: r.severity,
31120
31922
  path: r.path ?? "",
31121
31923
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31125,15 +31927,68 @@ var SqliteSecurityRepository = class {
31125
31927
  }));
31126
31928
  return Promise.resolve({ items });
31127
31929
  }
31930
+ /**
31931
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31932
+ *
31933
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31934
+ * list: a secret committed three weeks ago and never rotated is still the most
31935
+ * important thing to fix, and any window hides it. It carried a "newest N
31936
+ * findings" cap and then a range; the first meant a different span on every
31937
+ * machine, and the second reported "no recommendations" over live exposure.
31938
+ *
31939
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31940
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31941
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31942
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31943
+ * The two answer different questions and only this one has to match a link.
31944
+ *
31945
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31946
+ * whole-store scope costs a grouped scan rather than a row per finding.
31947
+ */
31948
+ recommendationInputs() {
31949
+ const rows = allRows(
31950
+ this.db.prepare(
31951
+ `SELECT d.rule_id AS rule_id,
31952
+ d.category AS category,
31953
+ d.severity AS severity,
31954
+ COUNT(*) AS count
31955
+ FROM inspection_findings f
31956
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31957
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31958
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31959
+ ON latest.finding_key = f.finding_key
31960
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31961
+ AND e.event_type = 'code_change'
31962
+ AND (
31963
+ f.finding_key IS NULL
31964
+ OR latest.status IS NULL
31965
+ OR latest.status NOT IN ('resolved', 'dismissed')
31966
+ )
31967
+ GROUP BY d.rule_id, d.category, d.severity`
31968
+ )
31969
+ );
31970
+ return Promise.resolve(
31971
+ rows.map((r) => ({
31972
+ ruleId: r.rule_id,
31973
+ category: r.category,
31974
+ severity: r.severity,
31975
+ count: r.count
31976
+ }))
31977
+ );
31978
+ }
31128
31979
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31129
31980
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31130
31981
  // numeric and the JS aggregations bucket/split on ms directly.
31131
31982
  findingsInRange(fromMs, toMs) {
31132
31983
  const rows = allRows(
31133
31984
  this.db.prepare(
31134
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31985
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31986
+ // joined for `severity`, so they are two more columns off a row this read
31987
+ // already fetches. They feed the recommended-actions rollup.
31988
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31989
+ d.rule_id AS rule_id, d.category AS category
31135
31990
  FROM inspection_findings f
31136
- JOIN audit_events e ON e.id = f.audit_event_id
31991
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31137
31992
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31138
31993
  WHERE e.started_at >= :from AND e.started_at < :to
31139
31994
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -31144,7 +31999,9 @@ var SqliteSecurityRepository = class {
31144
31999
  return rows.map((r) => ({
31145
32000
  occurredAt: r.occurred_at,
31146
32001
  severity: r.severity,
31147
- actionTaken: r.action_taken
32002
+ actionTaken: r.action_taken,
32003
+ ruleId: r.rule_id,
32004
+ category: r.category
31148
32005
  }));
31149
32006
  }
31150
32007
  };
@@ -31972,6 +32829,7 @@ function openWithPragmas(file2) {
31972
32829
  db.exec("PRAGMA journal_mode = WAL");
31973
32830
  db.exec("PRAGMA busy_timeout = 2000");
31974
32831
  db.exec("PRAGMA foreign_keys = ON");
32832
+ registerSqlFunctions(db);
31975
32833
  } catch (err) {
31976
32834
  closeQuietly(db);
31977
32835
  throw err;
@@ -32001,7 +32859,7 @@ function backupLegacyStore(db, file2) {
32001
32859
  discardStore(file2, backup);
32002
32860
  return backup;
32003
32861
  }
32004
- function openAndInitialize(file2, base) {
32862
+ function openAndInitialize(file2, base, skipTags) {
32005
32863
  let db = openWithPragmas(file2);
32006
32864
  try {
32007
32865
  if (isForeignSqliteLineage(db)) {
@@ -32011,7 +32869,7 @@ function openAndInitialize(file2, base) {
32011
32869
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32012
32870
  );
32013
32871
  }
32014
- applyMigrations(db, file2);
32872
+ applyMigrations(db, file2, { skipTags });
32015
32873
  tightenPerms(file2);
32016
32874
  const policies = new SqlitePoliciesRepository(db);
32017
32875
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32026,6 +32884,7 @@ function openAndInitialize(file2, base) {
32026
32884
  exceptions: new SqliteExceptionsRepository(db),
32027
32885
  resolutions: new SqliteResolutionsRepository(db),
32028
32886
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32887
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32029
32888
  security: new SqliteSecurityRepository(db),
32030
32889
  detections: new SqliteDetectionsRepository(db),
32031
32890
  shares: new SqliteSharesRepository(db),
@@ -32048,7 +32907,8 @@ function openAndInitialize(file2, base) {
32048
32907
  throw err;
32049
32908
  }
32050
32909
  }
32051
- function openLocalDatabase(dir) {
32910
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32911
+ function openLocalDatabase(dir, options = {}) {
32052
32912
  ensureDataDirSync(dir);
32053
32913
  const file2 = join7(dir, DB_FILENAME);
32054
32914
  reapStalePartials(file2);
@@ -32060,6 +32920,7 @@ function openLocalDatabase(dir) {
32060
32920
  installedPacks,
32061
32921
  scanLedger,
32062
32922
  historySync,
32923
+ bodyRetention,
32063
32924
  secretVault,
32064
32925
  exceptions,
32065
32926
  resolutions,
@@ -32083,7 +32944,8 @@ function openLocalDatabase(dir) {
32083
32944
  // `dir` is always `<base>/data` — every caller resolves it through
32084
32945
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32085
32946
  // settings/ and data/, and the pack-policy floor needs both halves.
32086
- dirname2(dir)
32947
+ dirname2(dir),
32948
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32087
32949
  );
32088
32950
  function captureRowId(event) {
32089
32951
  return captureId(
@@ -32276,6 +33138,7 @@ function openLocalDatabase(dir) {
32276
33138
  installedPacks,
32277
33139
  scanLedger,
32278
33140
  historySync,
33141
+ bodyRetention,
32279
33142
  secretVault,
32280
33143
  exceptions,
32281
33144
  resolutions,
@@ -32314,8 +33177,72 @@ function openLocalDatabase(dir) {
32314
33177
  };
32315
33178
  }
32316
33179
 
32317
- // ../../packages/persistence/src/finding-key.ts
33180
+ // ../../packages/persistence/src/egress-wire.ts
32318
33181
  import { createHash as createHash3 } from "crypto";
33182
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33183
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33184
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33185
+ var FILE_URL = /^file:\/\//i;
33186
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33187
+ var SLASH = "/".charCodeAt(0);
33188
+ var GIT_SUFFIX = ".git";
33189
+ function trimSlashes(path) {
33190
+ let start = 0;
33191
+ let end = path.length;
33192
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33193
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33194
+ return path.slice(start, end);
33195
+ }
33196
+ function canonicalGitUrl(url2) {
33197
+ const trimmed = url2.trim();
33198
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33199
+ const scheme = SCHEME_FORM.exec(trimmed);
33200
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33201
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33202
+ if (host === void 0) return trimmed;
33203
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33204
+ const bare = trimSlashes(path);
33205
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33206
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33207
+ }
33208
+ function hashProjectKey(projectKey) {
33209
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33210
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
33211
+ }
33212
+ function toIngestHit(hit) {
33213
+ return {
33214
+ host: hit.host,
33215
+ kind: hit.kind,
33216
+ name: hit.name,
33217
+ category: hit.category,
33218
+ trust: hit.trust,
33219
+ network: hit.network,
33220
+ method: hit.method,
33221
+ transport: hit.transport,
33222
+ url: hit.url,
33223
+ template: hit.template,
33224
+ dataClass: hit.dataClass,
33225
+ site: {
33226
+ file: hit.site.file,
33227
+ line: hit.site.line,
33228
+ dynamic: hit.site.dynamic,
33229
+ vendored: hit.site.vendored
33230
+ }
33231
+ };
33232
+ }
33233
+ function toEgressIngestRequest(input2) {
33234
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
33235
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
33236
+ return {
33237
+ projectKey: hashProjectKey(input2.projectKey),
33238
+ project: input2.project,
33239
+ reconcile,
33240
+ hits: hits.map(toIngestHit)
33241
+ };
33242
+ }
33243
+
33244
+ // ../../packages/persistence/src/finding-key.ts
33245
+ import { createHash as createHash4 } from "crypto";
32319
33246
 
32320
33247
  // ../../packages/persistence/src/fingerprint.ts
32321
33248
  import { createHmac, randomBytes } from "crypto";
@@ -32356,14 +33283,50 @@ function readFingerprintKey(dataDir2) {
32356
33283
  return parseKeyFile(raw);
32357
33284
  }
32358
33285
 
32359
- // ../../packages/persistence/src/history-preview.ts
32360
- import { existsSync as existsSync4 } from "fs";
33286
+ // ../../packages/persistence/src/forward-health.ts
33287
+ import { readFileSync as readFileSync7 } from "fs";
32361
33288
  import { join as join9 } from "path";
33289
+ var FAILURES = /* @__PURE__ */ new Set([
33290
+ "unauthorized",
33291
+ "forbidden",
33292
+ "unreachable"
33293
+ ]);
33294
+ var BREAKER_COOLDOWN_MS = 3e4;
33295
+ function parseForwardHealth(raw, nowMs) {
33296
+ try {
33297
+ const parsed2 = JSON.parse(raw);
33298
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33299
+ const record2 = parsed2;
33300
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33301
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33302
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33303
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33304
+ } catch {
33305
+ return null;
33306
+ }
33307
+ }
33308
+ function isForwardPaused(health, nowMs) {
33309
+ const openedAtMs = health?.openedAtMs ?? null;
33310
+ if (openedAtMs === null) return false;
33311
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33312
+ }
33313
+
33314
+ // ../../packages/persistence/src/history-backfill.ts
33315
+ import { existsSync as existsSync4 } from "fs";
33316
+ import { join as join10 } from "path";
33317
+
33318
+ // ../../packages/persistence/src/history-preview.ts
33319
+ import { existsSync as existsSync5 } from "fs";
33320
+ import { join as join11 } from "path";
32362
33321
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32363
33322
 
33323
+ // ../../packages/persistence/src/history-sync-state.ts
33324
+ import { readFileSync as readFileSync8 } from "fs";
33325
+ import { join as join12 } from "path";
33326
+
32364
33327
  // ../../packages/persistence/src/store-symlinks.ts
32365
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32366
- import { dirname as dirname3, join as join10, resolve } from "path";
33328
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
33329
+ import { dirname as dirname3, join as join13, resolve } from "path";
32367
33330
 
32368
33331
  // ../../packages/persistence/src/vault/crypto.ts
32369
33332
  import {
@@ -32377,63 +33340,26 @@ import {
32377
33340
  // ../../packages/persistence/src/vault/key-provider.ts
32378
33341
  import { execFileSync } from "child_process";
32379
33342
  import { randomBytes as randomBytes2 } from "crypto";
32380
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32381
- import { join as join11 } from "path";
33343
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33344
+ import { join as join14 } from "path";
32382
33345
 
32383
33346
  // ../../packages/persistence/src/vault/vault.ts
32384
33347
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32385
33348
 
32386
33349
  // ../../packages/persistence/src/warn-era-cap.ts
32387
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32388
- import { join as join12 } from "path";
33350
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33351
+ import { join as join15 } from "path";
32389
33352
  var MARKER = "warn-era-capped";
32390
33353
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32391
33354
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32392
- const marker = join12(dataDir2, MARKER);
32393
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
33355
+ const marker = join15(dataDir2, MARKER);
33356
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32394
33357
  const capped = db.policies.capCategoryActions();
32395
33358
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32396
33359
  `, { mode: DATA_FILE_MODE });
32397
33360
  return { capped };
32398
33361
  }
32399
33362
 
32400
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32401
- import { createHash as createHash4 } from "crypto";
32402
- function hashProjectKey(projectKey) {
32403
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32404
- }
32405
- function toIngestHit(hit) {
32406
- return {
32407
- host: hit.host,
32408
- kind: hit.kind,
32409
- name: hit.name,
32410
- category: hit.category,
32411
- trust: hit.trust,
32412
- network: hit.network,
32413
- method: hit.method,
32414
- transport: hit.transport,
32415
- url: hit.url,
32416
- template: hit.template,
32417
- dataClass: hit.dataClass,
32418
- site: {
32419
- file: hit.site.file,
32420
- line: hit.site.line,
32421
- dynamic: hit.site.dynamic,
32422
- vendored: hit.site.vendored
32423
- }
32424
- };
32425
- }
32426
- function toEgressIngestRequest(input2) {
32427
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32428
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32429
- return {
32430
- projectKey: hashProjectKey(input2.projectKey),
32431
- project: input2.project,
32432
- reconcile,
32433
- hits: hits.map(toIngestHit)
32434
- };
32435
- }
32436
-
32437
33363
  // ../../packages/remote/src/http.ts
32438
33364
  import { request as httpRequest } from "http";
32439
33365
  import { request as httpsRequest } from "https";
@@ -32617,10 +33543,10 @@ function parsed(schema, body, route) {
32617
33543
  }
32618
33544
  function withoutTrailingSlashes(endpoint) {
32619
33545
  let end = endpoint.length;
32620
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33546
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32621
33547
  return endpoint.slice(0, end);
32622
33548
  }
32623
- var SLASH = "/".charCodeAt(0);
33549
+ var SLASH2 = "/".charCodeAt(0);
32624
33550
  function createRemoteClient(options) {
32625
33551
  const base = withoutTrailingSlashes(options.endpoint);
32626
33552
  const url2 = (route) => `${base}${route}`;
@@ -32713,6 +33639,7 @@ function createRemoteClient(options) {
32713
33639
  url: url2(ROUTES.shares),
32714
33640
  body: JSON.stringify(validated.data)
32715
33641
  });
33642
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32716
33643
  okBody(response);
32717
33644
  },
32718
33645
  async pollCommand() {
@@ -32735,19 +33662,51 @@ function createRemoteClient(options) {
32735
33662
  };
32736
33663
  }
32737
33664
 
32738
- // ../../packages/plugin-runtime/src/attached/failure.ts
33665
+ // ../../packages/remote/src/failure-kind.ts
32739
33666
  function statusOf(err) {
32740
33667
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32741
33668
  const { status } = err;
32742
33669
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32743
33670
  return status >= 100 && status <= 599 ? status : null;
32744
33671
  }
32745
- function classifyFailure(err) {
32746
- switch (statusOf(err)) {
33672
+ function nameOf(err) {
33673
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33674
+ return typeof err.name === "string" ? err.name : null;
33675
+ }
33676
+ function classifyRemoteFailure(err) {
33677
+ switch (nameOf(err)) {
33678
+ case "RemoteRouteAbsent":
33679
+ return "route-absent";
33680
+ case "RemoteRequestInvalid":
33681
+ return "invalid-request";
33682
+ case "RemoteResponseInvalid":
33683
+ return "rejected";
33684
+ default:
33685
+ break;
33686
+ }
33687
+ const status = statusOf(err);
33688
+ if (status === null) return "unreachable";
33689
+ switch (status) {
32747
33690
  case 401:
32748
33691
  return "unauthorized";
32749
33692
  case 403:
32750
33693
  return "forbidden";
33694
+ case 429:
33695
+ return "unreachable";
33696
+ case 404:
33697
+ return "unreachable";
33698
+ default:
33699
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33700
+ }
33701
+ }
33702
+
33703
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33704
+ function classifyFailure(err) {
33705
+ switch (classifyRemoteFailure(err)) {
33706
+ case "unauthorized":
33707
+ return "unauthorized";
33708
+ case "forbidden":
33709
+ return "forbidden";
32751
33710
  default:
32752
33711
  return "unreachable";
32753
33712
  }
@@ -32769,11 +33728,11 @@ function withTimeout(promise2, ms) {
32769
33728
  }
32770
33729
 
32771
33730
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32772
- import { readFileSync as readFileSync8 } from "fs";
32773
- import { join as join13 } from "path";
33731
+ import { readFileSync as readFileSync10 } from "fs";
33732
+ import { join as join16 } from "path";
32774
33733
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32775
33734
  function forwardDropsPath(dataDir2) {
32776
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33735
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
32777
33736
  }
32778
33737
  function recordForwardDrops(dataDir2, count, nowMs) {
32779
33738
  if (count <= 0) return;
@@ -32791,7 +33750,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
32791
33750
  }
32792
33751
  function readForwardDrops(dataDir2) {
32793
33752
  try {
32794
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33753
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
32795
33754
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
32796
33755
  const record2 = parsed2;
32797
33756
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -32809,13 +33768,12 @@ function readForwardDrops(dataDir2) {
32809
33768
 
32810
33769
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32811
33770
  import { randomUUID as randomUUID15 } from "crypto";
32812
- import { readFileSync as readFileSync14 } from "fs";
32813
33771
  import { readFile, rename, writeFile } from "fs/promises";
32814
- import { join as join22 } from "path";
33772
+ import { join as join26 } from "path";
32815
33773
 
32816
33774
  // ../../packages/plugin-sdk/src/config.ts
32817
- import { existsSync as existsSync7 } from "fs";
32818
- import { join as join14 } from "path";
33775
+ import { existsSync as existsSync8 } from "fs";
33776
+ import { join as join17 } from "path";
32819
33777
 
32820
33778
  // ../../packages/plugin-sdk/src/provider-env.ts
32821
33779
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -32869,8 +33827,8 @@ function resolveProvider() {
32869
33827
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32870
33828
  try {
32871
33829
  ensureLayoutDirSync(base);
32872
- const settingsFile = join14(settingsDir(base), "settings.json");
32873
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33830
+ const settingsFile = join17(settingsDir(base), "settings.json");
33831
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
32874
33832
  } catch {
32875
33833
  }
32876
33834
  migrateLegacyLayout(base);
@@ -32893,9 +33851,9 @@ function resolveProviderSafe(resolveProviderFn) {
32893
33851
  }
32894
33852
 
32895
33853
  // ../../packages/plugin-sdk/src/config-inventory.ts
32896
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33854
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32897
33855
  import { homedir as homedir2 } from "os";
32898
- import { basename as basename3, join as join16 } from "path";
33856
+ import { basename as basename3, join as join19 } from "path";
32899
33857
 
32900
33858
  // ../../packages/detections/src/egress/registry.ts
32901
33859
  var EXTRACTOR_VERSION = "1";
@@ -35678,24 +36636,20 @@ function bundledDetections() {
35678
36636
  }
35679
36637
 
35680
36638
  // ../../packages/plugin-sdk/src/repo.ts
35681
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
35682
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36639
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
36640
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
35683
36641
 
35684
36642
  // ../../packages/plugin-sdk/src/events.ts
35685
36643
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
35686
36644
 
35687
36645
  // ../../packages/plugin-sdk/src/isolated-scan.ts
35688
- import { existsSync as existsSync9 } from "fs";
36646
+ import { existsSync as existsSync10 } from "fs";
35689
36647
  import { fileURLToPath } from "url";
35690
36648
  import { Worker } from "worker_threads";
35691
36649
 
35692
- // ../../packages/plugin-sdk/src/ignore-layers.ts
35693
- var import_ignore = __toESM(require_ignore(), 1);
35694
- import { readFileSync as readFileSync11 } from "fs";
35695
- import { join as join17 } from "path";
35696
-
35697
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
35698
- import { arch, hostname as hostname4, platform, release } from "os";
36650
+ // ../../packages/plugin-sdk/src/host-floor.ts
36651
+ import { readFileSync as readFileSync14 } from "fs";
36652
+ import { join as join21 } from "path";
35699
36653
 
35700
36654
  // ../../packages/plugin-sdk/src/model-governance.ts
35701
36655
  import {
@@ -35703,24 +36657,50 @@ import {
35703
36657
  fstatSync,
35704
36658
  mkdirSync as mkdirSync2,
35705
36659
  openSync as openSync2,
35706
- readFileSync as readFileSync12,
36660
+ readFileSync as readFileSync13,
35707
36661
  readSync,
35708
36662
  writeFileSync as writeFileSync5
35709
36663
  } from "fs";
35710
- import { join as join18 } from "path";
36664
+ import { join as join20 } from "path";
35711
36665
  var TAIL_BYTES = 256 * 1024;
35712
36666
 
36667
+ // ../../packages/plugin-sdk/src/host-floor.ts
36668
+ var HOST_FEATURE = {
36669
+ ModelSwitch: "model-switch",
36670
+ VaultPointerDisplay: "vault-pointer-display"
36671
+ };
36672
+ var HOST_FLOORS = {
36673
+ [HOST_FEATURE.ModelSwitch]: {
36674
+ label: "model-switch protection",
36675
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
36676
+ since: "2.1.251"
36677
+ },
36678
+ [HOST_FEATURE.VaultPointerDisplay]: {
36679
+ label: "vault pointer display",
36680
+ hookEvents: ["MessageDisplay"],
36681
+ since: "2.1.152"
36682
+ }
36683
+ };
36684
+
36685
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
36686
+ var import_ignore = __toESM(require_ignore(), 1);
36687
+ import { readFileSync as readFileSync15 } from "fs";
36688
+ import { join as join22 } from "path";
36689
+
36690
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
36691
+ import { arch, hostname as hostname4, platform, release } from "os";
36692
+
35713
36693
  // ../../packages/plugin-sdk/src/nudge.ts
35714
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
35715
- import { join as join19 } from "path";
36694
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
36695
+ import { join as join23 } from "path";
35716
36696
 
35717
36697
  // ../../packages/plugin-sdk/src/paths.ts
35718
36698
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
35719
36699
  import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
35720
36700
 
35721
36701
  // ../../packages/plugin-sdk/src/project-files.ts
35722
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
35723
- import { basename as basename5, join as join20 } from "path";
36702
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36703
+ import { basename as basename5, join as join24 } from "path";
35724
36704
 
35725
36705
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35726
36706
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35756,7 +36736,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
35756
36736
 
35757
36737
  // ../../packages/plugin-sdk/src/throttle.ts
35758
36738
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35759
- import { join as join21 } from "path";
36739
+ import { join as join25 } from "path";
35760
36740
 
35761
36741
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35762
36742
  function isInvalidRequest(err) {
@@ -35772,31 +36752,12 @@ function isServerRejection(err) {
35772
36752
  var FORWARD_BUDGET_MS = 1500;
35773
36753
  var DECISION_PATH_BUDGET_MS = 800;
35774
36754
  var BREAKER_FAILURE_THRESHOLD = 3;
35775
- var BREAKER_COOLDOWN_MS = 3e4;
35776
36755
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
35777
- var FAILURES = /* @__PURE__ */ new Set([
35778
- "unauthorized",
35779
- "forbidden",
35780
- "unreachable"
35781
- ]);
35782
36756
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
35783
36757
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
35784
- function parseBreakerState(raw, nowMs) {
35785
- try {
35786
- const parsed2 = JSON.parse(raw);
35787
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
35788
- const record2 = parsed2;
35789
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
35790
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
35791
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
35792
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
35793
- } catch {
35794
- return null;
35795
- }
35796
- }
35797
36758
  function createForwardPolicy(deps) {
35798
36759
  const now = deps.now ?? (() => Date.now());
35799
- const file2 = join22(deps.dir, STATE_FILENAME);
36760
+ const file2 = join26(deps.dir, STATE_FILENAME);
35800
36761
  let state = null;
35801
36762
  let loading = null;
35802
36763
  async function readState() {
@@ -35806,7 +36767,7 @@ function createForwardPolicy(deps) {
35806
36767
  } catch {
35807
36768
  return { ...CLOSED };
35808
36769
  }
35809
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
36770
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
35810
36771
  }
35811
36772
  async function load() {
35812
36773
  if (state !== null) return state;
@@ -35852,7 +36813,7 @@ function createForwardPolicy(deps) {
35852
36813
  };
35853
36814
  const at = now();
35854
36815
  if (current.openedAtMs !== null) {
35855
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
36816
+ if (isForwardPaused(current, at)) {
35856
36817
  return { ok: false, reason: "breaker-open" };
35857
36818
  }
35858
36819
  await persist({
@@ -36389,7 +37350,18 @@ var AttachedDataGateway = class {
36389
37350
  // and the spread above would otherwise drop the field silently — which is
36390
37351
  // exactly what it did, leaving the whole control inert on every device
36391
37352
  // while every test around it stayed green.
36392
- prohibitedModels: cached2.prohibitedModels
37353
+ prohibitedModels: cached2.prohibitedModels,
37354
+ // NAMED for the same reason as the line above, and it is the same defect
37355
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
37356
+ // only the cache carries is dropped in silence. That is what left
37357
+ // `prohibitedModels` inert on every attached device with every test
37358
+ // around it green.
37359
+ //
37360
+ // Taken from the cache rather than merged here, because merging it needs
37361
+ // the device's own SETTING — which is not a bundle field and is not in
37362
+ // scope at this seam. The runtime does that merge, raise-only, where both
37363
+ // values are in hand (createPluginRuntime's ensureInitialized).
37364
+ redactFallback: cached2.redactFallback
36393
37365
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
36394
37366
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
36395
37367
  // it emits, so an 'authored' policy arriving from the control plane
@@ -36517,10 +37489,6 @@ function toolAuditEvent(input2) {
36517
37489
  };
36518
37490
  }
36519
37491
 
36520
- // ../../packages/plugin-runtime/src/attached/history-state.ts
36521
- import { readFileSync as readFileSync15 } from "fs";
36522
- import { join as join23 } from "path";
36523
-
36524
37492
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36525
37493
  import { createHash as createHash6 } from "crypto";
36526
37494
  import { hostname as hostname5 } from "os";
@@ -36529,6 +37497,10 @@ import { hostname as hostname5 } from "os";
36529
37497
  var CORRELATION_ID = EventMetadata.shape.correlationId;
36530
37498
  var TRACE_ID = EventMetadata.shape.traceId;
36531
37499
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37500
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
37501
+
37502
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
37503
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
36532
37504
 
36533
37505
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36534
37506
  import { spawn } from "child_process";
@@ -36536,7 +37508,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
36536
37508
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
36537
37509
 
36538
37510
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
36539
- import { readFileSync as readFileSync16 } from "fs";
37511
+ import { readFileSync as readFileSync17 } from "fs";
36540
37512
  function createPluginBlock(build, policyStore) {
36541
37513
  return async () => {
36542
37514
  const cached2 = await policyStore.read();
@@ -36555,7 +37527,7 @@ function createPluginBlock(build, policyStore) {
36555
37527
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36556
37528
  import { randomUUID as randomUUID16 } from "crypto";
36557
37529
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36558
- import { join as join24 } from "path";
37530
+ import { join as join27 } from "path";
36559
37531
 
36560
37532
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36561
37533
  import { rename as rename2 } from "fs/promises";
@@ -36579,7 +37551,7 @@ async function publishByRename(tmp, file2, move = rename2) {
36579
37551
 
36580
37552
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36581
37553
  function createPolicyStore(dir = dataDir()) {
36582
- const file2 = join24(dir, "policy-cache.json");
37554
+ const file2 = join27(dir, "policy-cache.json");
36583
37555
  async function read() {
36584
37556
  try {
36585
37557
  const raw = await readFile2(file2, "utf8");
@@ -36810,11 +37782,11 @@ function readStorePosture(dbPath2) {
36810
37782
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
36811
37783
  import { randomUUID as randomUUID17 } from "crypto";
36812
37784
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
36813
- import { join as join25 } from "path";
37785
+ import { join as join28 } from "path";
36814
37786
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
36815
37787
  function createPostureStore(dir = settingsDir(), legacyDir) {
36816
- const file2 = join25(dir, "posture-state.json");
36817
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
37788
+ const file2 = join28(dir, "posture-state.json");
37789
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
36818
37790
  async function persist(state) {
36819
37791
  await ensureDataDir(dir);
36820
37792
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -36882,8 +37854,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
36882
37854
  }
36883
37855
 
36884
37856
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
36885
- import { readFileSync as readFileSync17 } from "fs";
36886
- import { join as join26 } from "path";
37857
+ import { readFileSync as readFileSync18 } from "fs";
37858
+ import { join as join29 } from "path";
36887
37859
 
36888
37860
  // ../../packages/plugin-runtime/src/attached/status.ts
36889
37861
  var REFUSAL_LINES = {
@@ -36904,6 +37876,14 @@ import { spawn as spawn2 } from "child_process";
36904
37876
  import { fileURLToPath as fileURLToPath3 } from "url";
36905
37877
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
36906
37878
 
37879
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
37880
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
37881
+
37882
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
37883
+ import { spawn as spawn3 } from "child_process";
37884
+ import { fileURLToPath as fileURLToPath4 } from "url";
37885
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
37886
+
36907
37887
  // ../../packages/plugin-runtime/src/attached/factory.ts
36908
37888
  import { hostname as hostname6 } from "os";
36909
37889
 
@@ -37355,9 +38335,9 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
37355
38335
 
37356
38336
  // src/command-registry.ts
37357
38337
  import { readdirSync as readdirSync5 } from "fs";
37358
- import { fileURLToPath as fileURLToPath4 } from "url";
38338
+ import { fileURLToPath as fileURLToPath5 } from "url";
37359
38339
  var COMMAND_NAMESPACE = "aka";
37360
- var COMMANDS_DIR = fileURLToPath4(new URL("../commands", import.meta.url));
38340
+ var COMMANDS_DIR = fileURLToPath5(new URL("../commands", import.meta.url));
37361
38341
  function readRegisteredCommands() {
37362
38342
  return readdirSync5(COMMANDS_DIR).filter((f) => f.endsWith(".md")).map((f) => `/${COMMAND_NAMESPACE}:${f.replace(/\.md$/, "")}`);
37363
38343
  }
@@ -37467,7 +38447,7 @@ function show(body) {
37467
38447
 
37468
38448
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
37469
38449
  import { writeFileSync as writeFileSync8 } from "fs";
37470
- import { join as join27 } from "path";
38450
+ import { join as join30 } from "path";
37471
38451
 
37472
38452
  // ../../packages/setup-wizard/src/triage/merge.ts
37473
38453
  var RANK = Object.fromEntries(
@@ -37475,9 +38455,9 @@ var RANK = Object.fromEntries(
37475
38455
  );
37476
38456
 
37477
38457
  // ../../packages/setup-wizard/src/triage/plan-file.ts
37478
- import { mkdtempSync, readFileSync as readFileSync18, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
38458
+ import { mkdtempSync, readFileSync as readFileSync19, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
37479
38459
  import { tmpdir } from "os";
37480
- import { basename as basename6, dirname as dirname6, join as join28 } from "path";
38460
+ import { basename as basename6, dirname as dirname6, join as join31 } from "path";
37481
38461
  var SuppressionEntrySchema = external_exports.object({
37482
38462
  ruleId: external_exports.string(),
37483
38463
  category: DetectionCategory,
@@ -37520,7 +38500,6 @@ var PersistedPlanSchema = external_exports.object({
37520
38500
 
37521
38501
  // src/render.ts
37522
38502
  var STORE_UNAVAILABLE_NOTE = "I couldn't check my records just now \u2014 we can check again soon. Your Claude session keeps going, and I'll fill in as you work.";
37523
- var SEVERITY_WEIGHT = { critical: 4, high: 3, medium: 2, low: 1 };
37524
38503
  var SEVERITY_GLYPH = {
37525
38504
  critical: SHADE.full,
37526
38505
  high: SHADE.dark,
@@ -37530,15 +38509,6 @@ var SEVERITY_GLYPH = {
37530
38509
  function severityGlyph(severity) {
37531
38510
  return SEVERITY_GLYPH[severity] ?? SHADE.light;
37532
38511
  }
37533
- var ADVICE = {
37534
- secret: "Rotate the exposed credentials and move them out of prompts (secrets manager / env vars).",
37535
- pii: "Remove or mask personal data before it reaches the model.",
37536
- financial: "Strip card and account numbers; share only non-sensitive references.",
37537
- phi: "Remove protected health information \u2014 it should never reach an external model.",
37538
- code_context: "Confirm this proprietary code context is safe to share.",
37539
- code_flaw: "Review the flagged pattern and apply the secure alternative (parameterized queries, safe deserializers, etc.).",
37540
- custom: "Review against your organization\u2019s custom policy."
37541
- };
37542
38512
  var ACTION_LABEL = {
37543
38513
  log: "monitor",
37544
38514
  warn: "warn",
@@ -37556,15 +38526,10 @@ function renderPosture(rows) {
37556
38526
  return [...rows].sort((a, b) => categoryRank(a.category) - categoryRank(b.category)).map((r) => ` ${r.category.padEnd(width)} ${ACTION_LABEL[r.action] ?? r.action}`).join("\n");
37557
38527
  }
37558
38528
  var RULE_WIDTH = 64;
37559
- function healthScore(summary) {
37560
- const handled = summary.byAction.block + summary.byAction.redact + summary.byAction.warn;
37561
- const handledRatio = summary.findings === 0 ? 1 : handled / summary.findings;
37562
- return Math.round(100 * (0.6 * summary.coverage + 0.4 * handledRatio));
37563
- }
37564
38529
  var TRY_COMMANDS = ["/aka:dashboard", "/aka:scan"];
37565
38530
  function topFindings(findings, limit = 10) {
37566
38531
  return [...findings].sort((a, b) => {
37567
- const sev = (SEVERITY_WEIGHT[b.severity] ?? 0) - (SEVERITY_WEIGHT[a.severity] ?? 0);
38532
+ const sev = severityWeight(b.severity) - severityWeight(a.severity);
37568
38533
  return sev !== 0 ? sev : b.occurredAt.localeCompare(a.occurredAt);
37569
38534
  }).slice(0, limit);
37570
38535
  }
@@ -37624,45 +38589,6 @@ function renderFirstRun(s, registry2) {
37624
38589
  }
37625
38590
  return lines.join("\n");
37626
38591
  }
37627
- var REC_TEMPLATE = {
37628
- secret: { title: "Exposed secret detected", action: "Rotate" },
37629
- pii: { title: "Personal data in a prompt", action: "Remove" },
37630
- financial: { title: "Financial data detected", action: "Strip" },
37631
- phi: { title: "Health information detected", action: "Remove" },
37632
- code_context: { title: "Proprietary code shared", action: "Review" },
37633
- custom: { title: "Custom policy match", action: "Review" }
37634
- };
37635
- var MAX_RECOMMENDATIONS = 10;
37636
- function buildRecommendations(findings) {
37637
- const buckets = /* @__PURE__ */ new Map();
37638
- for (const f of findings) {
37639
- const b = buckets.get(f.category) ?? {
37640
- category: f.category,
37641
- count: 0,
37642
- severity: f.severity,
37643
- weight: 0,
37644
- ruleId: f.ruleId
37645
- };
37646
- b.count++;
37647
- const w = SEVERITY_WEIGHT[f.severity] ?? 0;
37648
- if (w > b.weight) {
37649
- b.weight = w;
37650
- b.severity = f.severity;
37651
- b.ruleId = f.ruleId;
37652
- }
37653
- buckets.set(f.category, b);
37654
- }
37655
- return [...buckets.values()].sort((a, b) => b.weight - a.weight || b.count - a.count).slice(0, MAX_RECOMMENDATIONS).map((b) => {
37656
- const t = REC_TEMPLATE[b.category] ?? { title: `${b.category} finding`, action: "Review" };
37657
- return {
37658
- severity: b.severity,
37659
- title: t.title,
37660
- description: ADVICE[b.category] ?? "Review this finding against your policy.",
37661
- context: `${b.ruleId} \xB7 ${String(b.count)} finding${b.count === 1 ? "" : "s"}`,
37662
- action: t.action
37663
- };
37664
- });
37665
- }
37666
38592
 
37667
38593
  // src/firstrun-core.ts
37668
38594
  function parseSurfacedCount(argv) {