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

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.
@@ -491,9 +491,6 @@ var require_ignore = __commonJS({
491
491
  }
492
492
  });
493
493
 
494
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
495
- import { createHash as createHash4 } from "crypto";
496
-
497
494
  // ../../packages/persistence/src/attached-derived.ts
498
495
  import { rmSync } from "fs";
499
496
  import { join } from "path";
@@ -20742,13 +20739,11 @@ var FindingGroup = external_exports.object({
20742
20739
  latestDetectedAt: external_exports.iso.datetime(),
20743
20740
  instances: external_exports.array(FindingInstance),
20744
20741
  // Derived from instances' statuses with open-dominates precedence (see
20745
- // buildFindingGroups). Undefined only when no instance carries a status.
20742
+ // foldGroupStatus). Undefined only when no instance carries a status.
20746
20743
  status: FindingStatus.optional(),
20747
- // The distinct people across the WHOLE group, not just the `instances`
20748
- // preview — from the store's whole-group aggregate when it supplies one,
20749
- // else folded from the rows (see buildFindingGroups). Undefined when no
20750
- // instance carries a user, or when the store supplied whole-group folds
20751
- // without one.
20744
+ // The distinct people across the WHOLE group, not just the instances
20745
+ // carried here. Undefined when no instance carries a user, or when the
20746
+ // store supplied whole-group folds without one.
20752
20747
  users: external_exports.array(FindingUser).optional()
20753
20748
  }).meta({ id: "FindingGroup" });
20754
20749
  var FindingStats = external_exports.object({
@@ -20777,21 +20772,31 @@ var FindingFacets = external_exports.object({
20777
20772
  // counted under no value.
20778
20773
  status: external_exports.array(FindingFacetItem),
20779
20774
  // Host tool (attributes.tool_name). Present only on the instance-level
20780
- // reads, which can filter by it; the grouped read omits the dimension
20775
+ // reads, which can filter by it; the type-level read omits the dimension
20781
20776
  // because a group spans tools.
20782
20777
  tool: external_exports.array(FindingFacetItem).optional()
20783
20778
  }).meta({ id: "FindingFacets" });
20784
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20785
- var ListGroupedFindingsQuery = external_exports.object({
20779
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20780
+ id: "FindingTypeSummary"
20781
+ });
20782
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20783
+ var MAX_FINDING_TYPES_LIMIT = 100;
20784
+ var ListFindingTypesQuery = external_exports.object({
20786
20785
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20787
- // FindingAction.
20786
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20787
+ // firing version carries, and this list pages types.
20788
+ //
20789
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20790
+ // definition versions at different severities, so a type kept by this filter
20791
+ // can hold findings that individually do not match — see totals.findings on
20792
+ // ListFindingTypesResponse, which counts them all.
20788
20793
  severity: external_exports.array(Severity).optional(),
20789
20794
  subtype: external_exports.array(external_exports.string()).optional(),
20790
20795
  provider: external_exports.array(FindingProvider).optional(),
20791
20796
  action: external_exports.array(FindingAction).optional(),
20792
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20793
- // individual instances' — so a filtered group's Status column always reads
20794
- // one of the requested values.
20797
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20798
+ // individual findings' — so a filtered row's status always reads one of the
20799
+ // requested values.
20795
20800
  status: external_exports.array(FindingStatus).optional(),
20796
20801
  q: external_exports.string().optional(),
20797
20802
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20801,23 +20806,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20801
20806
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20802
20807
  // means all time — this list has no default window.
20803
20808
  from: external_exports.iso.datetime().optional(),
20804
- // A group or instance id that must appear in the page even when the cursor
20805
- // has already advanced past its sort position. This is what keeps the
20806
- // Findings page's one-shot ?finding= deep link resolving once the list
20807
- // paginates: the target group is appended out of sort order rather than
20808
- // scanning forward for it. Never affects totals, facets or the cursor.
20809
+ // A RULE id that must appear in the page even when the cursor has already
20810
+ // advanced past its sort position. This is what keeps the selected type
20811
+ // visible in the list once it paginates: the target is appended out of sort
20812
+ // order rather than scanned forward for. Never affects totals, facets or the
20813
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20814
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20815
+ // and so is not bounded by what any page happens to hold.
20809
20816
  includeId: external_exports.string().optional(),
20810
- groupBy: external_exports.literal("type").optional(),
20811
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20817
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20812
20818
  cursor: external_exports.string().optional()
20813
20819
  });
20814
- var ListGroupedFindingsResponse = external_exports.object({
20820
+ var ListFindingTypesResponse = external_exports.object({
20815
20821
  totals: external_exports.object({
20822
+ // Findings belonging to the matching TYPES — not findings that each match
20823
+ // the filters. The filters here select types, so a type that survives
20824
+ // contributes its whole instanceCount.
20825
+ //
20826
+ // `status` is the one exception, narrowed per finding via
20827
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20828
+ // this can exceed what the instance read reports for the same filters: a
20829
+ // rule whose severity moved between versions is kept on its newest and
20830
+ // still counts its older findings. Narrowing the other three needs
20831
+ // per-dimension counts the aggregate does not carry today.
20816
20832
  findings: external_exports.number().int().nonnegative(),
20817
- groups: external_exports.number().int().nonnegative()
20833
+ // Counts TYPES, which is the unit this read pages. The instance read's
20834
+ // own totals count findings; the two deliberately answer different
20835
+ // questions and are never summed.
20836
+ types: external_exports.number().int().nonnegative()
20818
20837
  }),
20819
20838
  facets: FindingFacets,
20820
- items: external_exports.array(FindingGroup),
20839
+ items: external_exports.array(FindingTypeSummary),
20821
20840
  nextCursor: external_exports.string().nullable(),
20822
20841
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20823
20842
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20825,7 +20844,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20825
20844
  // every firing, so the two numbers legitimately differ — this map lets a
20826
20845
  // session-scoped view show both.
20827
20846
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20828
- }).meta({ id: "ListGroupedFindingsResponse" });
20847
+ }).meta({ id: "ListFindingTypesResponse" });
20829
20848
  var ApplyFindingActionRequest = external_exports.object({
20830
20849
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20831
20850
  // it, so it is excluded from the request contract. The mapping helper
@@ -20855,12 +20874,13 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20855
20874
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20856
20875
  var ListFindingInstancesQuery = external_exports.object({
20857
20876
  severity: external_exports.array(Severity).optional(),
20858
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20877
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20878
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20859
20879
  subtype: external_exports.array(external_exports.string()).optional(),
20860
20880
  provider: external_exports.array(FindingProvider).optional(),
20861
20881
  action: external_exports.array(FindingAction).optional(),
20862
20882
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20863
- // the grouped query's group-level fold.
20883
+ // the types query's type-level fold.
20864
20884
  status: external_exports.array(FindingStatus).optional(),
20865
20885
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20866
20886
  // where the free-text `q` can only match the rendered "via Bash" label.
@@ -20877,37 +20897,47 @@ var ListFindingInstancesQuery = external_exports.object({
20877
20897
  });
20878
20898
  var ListFindingInstancesResponse = external_exports.object({
20879
20899
  // Instances matching the filters across the whole scope, not just this
20880
- // page — cursor-independent, like the grouped list's totals.
20900
+ // page — cursor-independent, like the types list's totals.
20881
20901
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20882
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20902
+ // Counts in INSTANCES here, where the types response counts types. Each
20883
20903
  // dimension still excludes its own filter.
20884
20904
  facets: FindingFacets,
20885
20905
  items: external_exports.array(FindingInstanceDetail),
20886
20906
  nextCursor: external_exports.string().nullable()
20887
20907
  }).meta({ id: "ListFindingInstancesResponse" });
20888
- var FindingLocationFile = external_exports.object({
20889
- // Empty when the instances carried no file path (a prompt or a tool call
20890
- // with no file attribution).
20891
- file: external_exports.string(),
20892
- instanceCount: external_exports.number().int().nonnegative(),
20893
- maxSeverity: Severity,
20894
- latestDetectedAt: external_exports.iso.datetime(),
20895
- // Folded from the instances' derived statuses with the same
20896
- // open-dominates precedence a group uses.
20897
- status: FindingStatus.optional(),
20898
- // Distinct rules seen at this location, capped — the row shows them as
20899
- // chips, and the count is what conveys scale.
20900
- ruleIds: external_exports.array(external_exports.string())
20901
- }).meta({ id: "FindingLocationFile" });
20902
- var FindingLocationRepo = external_exports.object({
20908
+ var FindingLocationSummary = external_exports.object({
20909
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20910
+ // because a location's identity is two values and a URL param carries one:
20911
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20912
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20913
+ // client's page dedupe — never decoded, and never a sort key.
20914
+ id: external_exports.string(),
20903
20915
  /** Empty when the instances carried no repo attribute. */
20904
20916
  repo: external_exports.string(),
20917
+ // Empty when the instances carried no file path (a prompt, or a tool call
20918
+ // with no file attribution). Both halves empty is a real location — usually
20919
+ // the largest one in a store — and is selectable like any other.
20920
+ file: external_exports.string(),
20905
20921
  instanceCount: external_exports.number().int().nonnegative(),
20922
+ // The WORST severity present, not the first row's. It is this list's primary
20923
+ // sort key, so it is also what explains why a row is where it is, and it is
20924
+ // how a reader decides what to open without opening everything.
20906
20925
  maxSeverity: Severity,
20907
20926
  latestDetectedAt: external_exports.iso.datetime(),
20927
+ // Folded from the instances' derived statuses with the same open-dominates
20928
+ // precedence a group uses, so it answers "is anything left to do here" and
20929
+ // not much more: a location holding 1 open among 40 resolved reads like one
20930
+ // holding 40 open. That loss is accepted — the panel beside this list
20931
+ // carries each finding's own status, and instanceCount sits next to the
20932
+ // badge.
20908
20933
  status: FindingStatus.optional(),
20909
- files: external_exports.array(FindingLocationFile)
20910
- }).meta({ id: "FindingLocationRepo" });
20934
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20935
+ // tally rather than a sample and a row can say how many there are. Bounded
20936
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20937
+ ruleIds: external_exports.array(external_exports.string())
20938
+ }).meta({ id: "FindingLocationSummary" });
20939
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20940
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20911
20941
  var ListFindingLocationsQuery = external_exports.object({
20912
20942
  severity: external_exports.array(Severity).optional(),
20913
20943
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20920,18 +20950,42 @@ var ListFindingLocationsQuery = external_exports.object({
20920
20950
  q: external_exports.string().optional(),
20921
20951
  sessionId: external_exports.string().optional(),
20922
20952
  from: external_exports.iso.datetime().optional(),
20923
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
20953
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
20954
+ // even when the cursor has already advanced past its sort position — the
20955
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
20956
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
20957
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
20958
+ // into the thousands, a selection sitting off page 0 is the ordinary case
20959
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
20960
+ includeId: external_exports.string().optional(),
20961
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
20962
+ cursor: external_exports.string().optional()
20924
20963
  });
20925
20964
  var ListFindingLocationsResponse = external_exports.object({
20926
20965
  totals: external_exports.object({
20966
+ // Findings matching the filters across the whole scope. Unlike the types
20967
+ // read's same-named field this needs no caveat: the filters here narrow
20968
+ // per finding, so this is the sum of every row's instanceCount.
20927
20969
  findings: external_exports.number().int().nonnegative(),
20928
- repos: external_exports.number().int().nonnegative(),
20929
- files: external_exports.number().int().nonnegative()
20970
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
20971
+ // states. The facets beside it count FINDINGS (see below); a surface
20972
+ // showing both says which is which.
20973
+ locations: external_exports.number().int().nonnegative()
20930
20974
  }),
20931
- /** Sorted by max severity, then most recent. */
20932
- items: external_exports.array(FindingLocationRepo),
20933
- /** Whether `limit` truncated the repo list. */
20934
- hasMore: external_exports.boolean()
20975
+ // Counts in FINDINGS, where the types response counts types, each dimension
20976
+ // still excluding its own filter. Deliberately not locations: counting those
20977
+ // needs a set of location keys per dimension per value — memory tracking the
20978
+ // store times the vocabulary, in a read whose scan promises flat memory —
20979
+ // and the cheap per-location version is not an approximation but WRONG. A
20980
+ // location holding {claudecode, block} and {codex, warn} would survive
20981
+ // provider=claudecode AND action=warn, under which no single finding
20982
+ // matches, so the facet would contradict the instanceCount this whole view
20983
+ // rests on. Findings also keep the toolbar in the same unit as the page
20984
+ // tally and the panel it sits above.
20985
+ facets: FindingFacets,
20986
+ /** Sorted by max severity, then most recent, then (repo, file). */
20987
+ items: external_exports.array(FindingLocationSummary),
20988
+ nextCursor: external_exports.string().nullable()
20935
20989
  }).meta({ id: "ListFindingLocationsResponse" });
20936
20990
 
20937
20991
  // ../../packages/schema/src/zod/meta.ts
@@ -22100,6 +22154,14 @@ var ControlPlaneErrorBody = external_exports.object({
22100
22154
  message: external_exports.string().optional()
22101
22155
  }).optional()
22102
22156
  });
22157
+ var RemoteFailureKind = external_exports.enum([
22158
+ "unauthorized",
22159
+ "forbidden",
22160
+ "route-absent",
22161
+ "invalid-request",
22162
+ "rejected",
22163
+ "unreachable"
22164
+ ]);
22103
22165
  var AttachDeviceRequest = external_exports.object({
22104
22166
  // This machine's own continuity id, so re-attaching ROTATES the credential
22105
22167
  // on one machine record instead of producing a second one. Client-minted
@@ -22793,139 +22855,62 @@ function deriveFindingStatus(row) {
22793
22855
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22794
22856
  return "open";
22795
22857
  }
22796
- function distinctUsers(instances) {
22797
- const seen = /* @__PURE__ */ new Set();
22798
- const users = [];
22799
- for (const i of instances) {
22800
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22801
- seen.add(i.user.id);
22802
- users.push(i.user);
22803
- }
22804
- return users;
22805
- }
22806
22858
  function sortUsers(users) {
22807
22859
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22808
22860
  }
22809
- function buildFindingGroups(rows, opts = {}) {
22810
- const overrides = opts.overrides;
22861
+ function buildFindingTypes(aggregates, opts = {}) {
22811
22862
  const packNames = opts.packNames;
22812
- const aggregates = opts.aggregates;
22813
- const byRuleId = /* @__PURE__ */ new Map();
22814
- for (const row of rows) {
22815
- const existing = byRuleId.get(row.ruleId);
22816
- if (existing) existing.push(row);
22817
- else byRuleId.set(row.ruleId, [row]);
22818
- }
22819
- const groups = [];
22820
- for (const [ruleId, ruleRows] of byRuleId) {
22821
- const instances = ruleRows.map((r) => {
22822
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22823
- return {
22824
- id: r.id,
22825
- provider: toApiProvider(r.sourceTool),
22826
- repo: r.repo,
22827
- file: r.file,
22828
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22829
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22830
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22831
- ...r.user === void 0 ? {} : { user: r.user },
22832
- action: toApiAction(effectiveDbAction),
22833
- detectedAt: r.occurredAt,
22834
- confidence: r.confidence,
22835
- status: r.status
22836
- };
22837
- });
22838
- const agg = aggregates?.get(ruleId);
22839
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22840
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22841
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22842
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22843
- );
22844
- const seenProviders = /* @__PURE__ */ new Set();
22845
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22846
- if (seenProviders.has(p)) return false;
22847
- seenProviders.add(p);
22848
- return true;
22849
- });
22850
- const actionSet = new Set(
22851
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22852
- );
22863
+ const types = [];
22864
+ for (const [ruleId, agg] of aggregates) {
22865
+ const users = sortUsers(agg.users ?? []);
22866
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
22867
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22853
22868
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22854
- const severity = ruleRows[0]?.severity ?? "low";
22855
- const detection = {
22856
- id: ruleId,
22857
- name: packNames?.get(ruleId) ?? null
22858
- };
22859
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22860
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22861
- const match = {
22862
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22863
- contextPrefix: ""
22864
- // empty (pending privacy review)
22865
- };
22866
- const status = foldGroupStatus(
22867
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22868
- );
22869
- const group = {
22869
+ const apiCategory = toApiCategory(agg.category ?? "custom");
22870
+ const type = {
22870
22871
  id: ruleId,
22871
22872
  category: apiCategory,
22872
22873
  subtype: ruleId,
22873
22874
  // human label comes with pack metadata later
22874
- severity,
22875
- match,
22876
- detection,
22877
- policy,
22878
- instanceCount: agg?.instanceCount ?? instances.length,
22875
+ severity: agg.severity ?? "low",
22876
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
22877
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
22878
+ instanceCount: agg.instanceCount,
22879
22879
  providers,
22880
22880
  aggregateAction,
22881
- latestDetectedAt,
22882
- instances,
22883
- status,
22881
+ latestDetectedAt: agg.latestDetectedAt,
22882
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22884
22883
  ...users.length > 0 ? { users } : {}
22885
22884
  };
22886
- if (agg) {
22887
- actionsCache.set(group, [...actionSet]);
22888
- if (agg.searchText !== void 0) {
22889
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22890
- }
22885
+ actionsCache.set(type, [...actionSet]);
22886
+ if (agg.searchText !== void 0) {
22887
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22891
22888
  }
22892
- groups.push(group);
22889
+ types.push(type);
22893
22890
  }
22894
- return groups;
22891
+ return types;
22895
22892
  }
22896
22893
  var haystackCache = /* @__PURE__ */ new WeakMap();
22897
- function buildHaystack(g, extra) {
22894
+ function buildHaystack(t, extra) {
22898
22895
  return [
22899
- g.subtype,
22900
- g.category,
22901
- g.match.maskedValue,
22902
- g.policy.name,
22903
- g.id,
22904
- ...g.instances.map((i) => i.repo),
22905
- ...g.instances.map((i) => i.file),
22906
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22907
- ...g.instances.map((i) => i.id),
22908
- // The people: the whole group's list when the store folded one, plus the
22909
- // preview's own — the two overlap, and a haystack does not mind.
22910
- ...(g.users ?? []).map((u) => u.name),
22911
- ...g.instances.map((i) => i.user?.name ?? ""),
22896
+ t.subtype,
22897
+ t.category,
22898
+ t.policy.name,
22899
+ t.id,
22900
+ ...(t.users ?? []).map((u) => u.name),
22912
22901
  ...extra === void 0 ? [] : [extra]
22913
22902
  ].join(" ").toLowerCase();
22914
22903
  }
22915
- function groupHaystack(g) {
22916
- const cached2 = haystackCache.get(g);
22904
+ function typeHaystack(t) {
22905
+ const cached2 = haystackCache.get(t);
22917
22906
  if (cached2 !== void 0) return cached2;
22918
- const haystack = buildHaystack(g);
22919
- haystackCache.set(g, haystack);
22907
+ const haystack = buildHaystack(t);
22908
+ haystackCache.set(t, haystack);
22920
22909
  return haystack;
22921
22910
  }
22922
22911
  var actionsCache = /* @__PURE__ */ new WeakMap();
22923
- function groupActions(g) {
22924
- const cached2 = actionsCache.get(g);
22925
- if (cached2 !== void 0) return cached2;
22926
- const actions = [...new Set(g.instances.map((i) => i.action))];
22927
- actionsCache.set(g, actions);
22928
- return actions;
22912
+ function typeActions(t) {
22913
+ return actionsCache.get(t) ?? [];
22929
22914
  }
22930
22915
  function countInstancesByStatus(statusInputs, statuses) {
22931
22916
  const statusSet = new Set(statuses);
@@ -22936,8 +22921,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22936
22921
  }
22937
22922
  return sum;
22938
22923
  }
22939
- function applyFindingFilters(groups, opts) {
22940
- let filtered = groups;
22924
+ function applyFindingFilters(types, opts) {
22925
+ let filtered = types;
22941
22926
  if (opts.severity && opts.severity.length > 0) {
22942
22927
  const sevSet = new Set(opts.severity);
22943
22928
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22948,7 +22933,7 @@ function applyFindingFilters(groups, opts) {
22948
22933
  }
22949
22934
  if (opts.actions && opts.actions.length > 0) {
22950
22935
  const actionSet = new Set(opts.actions);
22951
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
22936
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22952
22937
  }
22953
22938
  if (opts.subtype && opts.subtype.length > 0) {
22954
22939
  const subtypeSet = new Set(opts.subtype);
@@ -22960,7 +22945,7 @@ function applyFindingFilters(groups, opts) {
22960
22945
  }
22961
22946
  if (opts.q) {
22962
22947
  const q = opts.q.toLowerCase();
22963
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
22948
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22964
22949
  }
22965
22950
  return filtered;
22966
22951
  }
@@ -22975,11 +22960,11 @@ function compareFindingGroupOrder(a, b) {
22975
22960
  if (recencyDiff !== 0) return recencyDiff;
22976
22961
  return a.id.localeCompare(b.id);
22977
22962
  }
22978
- function sortFindingGroups(groups) {
22979
- return [...groups].sort(compareFindingGroupOrder);
22963
+ function sortFindingTypes(types) {
22964
+ return [...types].sort(compareFindingGroupOrder);
22980
22965
  }
22981
- function computeFindingFacets(allGroups, opts) {
22982
- const forSeverity = applyFindingFilters(allGroups, {
22966
+ function computeFindingFacets(allTypes, opts) {
22967
+ const forSeverity = applyFindingFilters(allTypes, {
22983
22968
  providers: opts.providers,
22984
22969
  actions: opts.actions,
22985
22970
  statuses: opts.statuses,
@@ -22990,7 +22975,7 @@ function computeFindingFacets(allGroups, opts) {
22990
22975
  for (const g of forSeverity) {
22991
22976
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22992
22977
  }
22993
- const forProvider = applyFindingFilters(allGroups, {
22978
+ const forProvider = applyFindingFilters(allTypes, {
22994
22979
  actions: opts.actions,
22995
22980
  statuses: opts.statuses,
22996
22981
  q: opts.q,
@@ -23001,7 +22986,7 @@ function computeFindingFacets(allGroups, opts) {
23001
22986
  for (const g of forProvider) {
23002
22987
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23003
22988
  }
23004
- const forAction = applyFindingFilters(allGroups, {
22989
+ const forAction = applyFindingFilters(allTypes, {
23005
22990
  providers: opts.providers,
23006
22991
  statuses: opts.statuses,
23007
22992
  q: opts.q,
@@ -23010,9 +22995,9 @@ function computeFindingFacets(allGroups, opts) {
23010
22995
  });
23011
22996
  const actionMap = /* @__PURE__ */ new Map();
23012
22997
  for (const g of forAction) {
23013
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
22998
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23014
22999
  }
23015
- const forSubtype = applyFindingFilters(allGroups, {
23000
+ const forSubtype = applyFindingFilters(allTypes, {
23016
23001
  providers: opts.providers,
23017
23002
  actions: opts.actions,
23018
23003
  statuses: opts.statuses,
@@ -23021,7 +23006,7 @@ function computeFindingFacets(allGroups, opts) {
23021
23006
  });
23022
23007
  const subtypeMap = /* @__PURE__ */ new Map();
23023
23008
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23024
- const forStatus = applyFindingFilters(allGroups, {
23009
+ const forStatus = applyFindingFilters(allTypes, {
23025
23010
  providers: opts.providers,
23026
23011
  actions: opts.actions,
23027
23012
  q: opts.q,
@@ -23069,10 +23054,20 @@ function matchesDimension(row, opts, dimension) {
23069
23054
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23070
23055
  case "tools":
23071
23056
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23057
+ // An EMPTY value is a real filter here, not an absent one. The location
23058
+ // list buckets a finding whose event recorded no repo — or no file — under
23059
+ // the empty string, and selecting that bucket has to narrow the panel to
23060
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23061
+ // row omits the key, which every call site already does.
23062
+ //
23063
+ // Reading '' as unset is what this replaced, and it failed in the one place
23064
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23065
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23066
+ // — a row reading 3 findings beside a panel listing every finding there is.
23072
23067
  case "repo":
23073
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23068
+ return opts.repo === void 0 || row.repo === opts.repo;
23074
23069
  case "file":
23075
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23070
+ return opts.file === void 0 || row.file === opts.file;
23076
23071
  case "q":
23077
23072
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23078
23073
  }
@@ -23186,6 +23181,23 @@ function addToLocation(acc, row) {
23186
23181
  acc.statuses.push(row.status);
23187
23182
  acc.ruleIds.add(row.ruleId);
23188
23183
  }
23184
+ function compareLocationOrder(a, b) {
23185
+ const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23186
+ const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23187
+ if (rankA !== rankB) return rankA - rankB;
23188
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23189
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23190
+ }
23191
+ if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23192
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23193
+ return 0;
23194
+ }
23195
+ function encodeLocationId(repo, file2) {
23196
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23197
+ }
23198
+ function encodePart(value) {
23199
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23200
+ }
23189
23201
 
23190
23202
  // ../../packages/schema/src/zod/installed-pack.ts
23191
23203
  var InstalledPack = external_exports.object({
@@ -23628,7 +23640,7 @@ var VaultConsent = external_exports.object({
23628
23640
  // ../../packages/schema/src/zod/local.ts
23629
23641
  var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23630
23642
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23631
- var HISTORY_SYNC_PAYLOAD_VERSION = 2;
23643
+ var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23632
23644
  var RunMode = external_exports.enum(["standalone", "attached"]);
23633
23645
  var ControlPlaneConnection = external_exports.object({
23634
23646
  endpoint: external_exports.string().min(1),
@@ -23694,11 +23706,11 @@ var WorkspaceSettings = external_exports.object({
23694
23706
  // covers the current payload and must be re-granted.
23695
23707
  modelJudgeConsent: ModelJudgeConsent.optional(),
23696
23708
  // Records that the user consented to the DEFERRED send — the outbox — along
23697
- // with the payload shape and the endpoint they agreed to. Since payload v2
23698
- // that covers both the pre-attach backlog and undelivered captures (which
23699
- // carry prompt/reply text in `content`); the key name predates the widening.
23700
- // Absent until granted, and a grant for a different endpoint or an older
23701
- // payload no longer counts.
23709
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23710
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23711
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23712
+ // both widenings. Absent until granted, and a grant for a different endpoint
23713
+ // or an older payload no longer counts.
23702
23714
  historySyncConsent: HistorySyncConsent.optional()
23703
23715
  });
23704
23716
  function defaultWorkspaceSettings() {
@@ -23829,6 +23841,9 @@ var ManagedSettingKey = external_exports.enum([
23829
23841
  "dataSharesInPlace",
23830
23842
  "redactFallback"
23831
23843
  ]).meta({ id: "ManagedSettingKey" });
23844
+ function isManagedSettingKey(value) {
23845
+ return ManagedSettingKey.safeParse(value).success;
23846
+ }
23832
23847
  var ManagedSettingsValues = external_exports.object({
23833
23848
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
23834
23849
  controlPlane: external_exports.object({
@@ -23853,7 +23868,27 @@ var ManagedSettings = external_exports.object({
23853
23868
  // Which of those the user may not change. A key here with no matching value
23854
23869
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23855
23870
  // the user may still override. The two are separable on purpose.
23856
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23871
+ //
23872
+ // Parsed as NAMES rather than as the enum, and split below: a name this
23873
+ // build does not know is dropped from the locked set and reported, never a
23874
+ // reason to refuse the file. The same shape reaches an older build whenever
23875
+ // an administrator locks a key a newer build added, and refusing it there
23876
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
23877
+ // the fleets most likely to carry a version skew. A name outside the enum
23878
+ // is still never HONOURED: the lockable set stays explicit above.
23879
+ lockedFields: external_exports.array(external_exports.string()).default([])
23880
+ }).transform(({ lockedFields, ...rest }) => {
23881
+ const known = [];
23882
+ const unknown2 = [];
23883
+ for (const name of lockedFields) {
23884
+ if (isManagedSettingKey(name)) known.push(name);
23885
+ else unknown2.push(name);
23886
+ }
23887
+ return {
23888
+ ...rest,
23889
+ lockedFields: known,
23890
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
23891
+ };
23857
23892
  }).meta({ id: "ManagedSettings" });
23858
23893
 
23859
23894
  // ../../packages/schema/src/zod/project-files.ts
@@ -23977,7 +24012,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23977
24012
  timestamp: external_exports.iso.date(),
23978
24013
  critical: external_exports.number().int().nonnegative(),
23979
24014
  high: external_exports.number().int().nonnegative(),
23980
- medium: external_exports.number().int().nonnegative()
24015
+ medium: external_exports.number().int().nonnegative(),
24016
+ // Optional and additive, so a producer written against the earlier
24017
+ // three-series contract keeps validating. A consumer plotting it resolves the
24018
+ // absent case itself — the chart point requires a number.
24019
+ low: external_exports.number().int().nonnegative().optional()
23981
24020
  }).meta({ id: "FindingsTimeseriesPoint" });
23982
24021
  var FindingsTimeseriesResponse = external_exports.object({
23983
24022
  range: TimeRange,
@@ -24003,6 +24042,10 @@ var ResolvedFeedItem = external_exports.object({
24003
24042
  findingKey: external_exports.string(),
24004
24043
  ruleId: external_exports.string(),
24005
24044
  severity: Severity,
24045
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24046
+ // identifies the file: a bare path matches the same name in every repo.
24047
+ // Optional and additive; empty when the event carried no repo.
24048
+ repo: external_exports.string().optional(),
24006
24049
  path: external_exports.string(),
24007
24050
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24008
24051
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -25504,7 +25547,8 @@ var SqliteActivityRepository = class {
25504
25547
  SELECT 1 FROM audit_events d
25505
25548
  WHERE d.root_session_id = audit_events.id
25506
25549
  AND (d.content LIKE ? ESCAPE '\\'
25507
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
25550
+ OR coalesce(json_extract(d.attributes, '$.detail'),
25551
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25508
25552
  );
25509
25553
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25510
25554
  }
@@ -26842,23 +26886,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26842
26886
  )`;
26843
26887
 
26844
26888
  // ../../packages/persistence/src/repositories/findings.ts
26845
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26846
- var DEFAULT_LOCATIONS_LIMIT = 100;
26847
- var LOCATION_RULE_IDS_CAP = 20;
26848
- function compareLocationOrder(a, b) {
26849
- return compareFindingGroupOrder(
26850
- {
26851
- severity: a.maxSeverity,
26852
- latestDetectedAt: a.latestDetectedAt,
26853
- id: ""
26854
- },
26855
- {
26856
- severity: b.maxSeverity,
26857
- latestDetectedAt: b.latestDetectedAt,
26858
- id: ""
26859
- }
26860
- );
26861
- }
26862
26889
  var CONCAT_SEP = ",";
26863
26890
  var TUPLE_SEP = "|";
26864
26891
  function splitConcat(value) {
@@ -26910,13 +26937,48 @@ function decodeGroupCursor(cursor) {
26910
26937
  return null;
26911
26938
  }
26912
26939
  function firstAfter(sorted, cursor) {
26913
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
26940
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26914
26941
  return index === -1 ? sorted.length : index;
26915
26942
  }
26916
26943
  function findDeepLinked(sorted, page, id) {
26917
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26918
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
26944
+ if (page.some((t) => t.id === id)) return void 0;
26945
+ return sorted.find((t) => t.id === id);
26946
+ }
26947
+ function encodeLocationCursor(location) {
26948
+ const payload = {
26949
+ sev: location.maxSeverity,
26950
+ t: location.latestDetectedAt,
26951
+ r: location.repo,
26952
+ f: location.file
26953
+ };
26954
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
26955
+ }
26956
+ function decodeLocationCursor(cursor) {
26957
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
26958
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
26959
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
26960
+ }
26961
+ return null;
26962
+ }
26963
+ function firstLocationAfter(sorted, cursor) {
26964
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
26965
+ return index === -1 ? sorted.length : index;
26966
+ }
26967
+ function findDeepLinkedLocation(sorted, page, id) {
26968
+ if (page.some((l) => l.id === id)) return void 0;
26969
+ return sorted.find((l) => l.id === id);
26919
26970
  }
26971
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
26972
+ d.severity AS severity, f.masked_match AS masked_match,
26973
+ f.action_taken AS action_taken, f.confidence AS confidence,
26974
+ e.started_at AS occurred_at,
26975
+ e.source_tool AS source_tool,
26976
+ e.repo AS repo,
26977
+ e.file_path AS file,
26978
+ e.tool_name AS tool_name,
26979
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
26980
+ e.event_type AS kind, f.finding_key AS finding_key,
26981
+ ${latestResolutionStatusSql("f")} AS latest_status`;
26920
26982
  var DAY_MS3 = 864e5;
26921
26983
  var SqliteFindingsRepository = class {
26922
26984
  constructor(db) {
@@ -27037,30 +27099,26 @@ var SqliteFindingsRepository = class {
27037
27099
  );
27038
27100
  }
27039
27101
  /**
27040
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27041
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27042
- * attributes bag, rule_id/category/severity from the definition), scoped to
27043
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27044
- * rows this list must never surface), groups by ruleId, computes
27045
- * per-filter-excluded facets, applies the requested filters, and sorts by
27046
- * severity then recency. Filtering
27047
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27048
- * reflect the full filtered set; `items` is the requested
27049
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27050
- * filter, `totals.findings` counts only instances whose derived status was
27051
- * requested, and each item's instance preview is narrowed the same way.
27102
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
27103
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
27104
+ * list must never surface), with per-filter-excluded facets, the requested
27105
+ * filters applied, and sorted by severity then recency. Filtering and faceting
27106
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
27107
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
27108
+ * Under a `status` filter, `totals.findings` counts only findings whose
27109
+ * derived status was requested.
27110
+ *
27111
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
27112
+ * folding EVERY finding into the numbers a type row and the filters need
27113
+ * (count, severity, category, providers, actions, statuses, latest, search
27114
+ * text). The findings OF a type come from listFindingInstances scoped to
27115
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27052
27116
  *
27053
- * Two reads, neither of which materializes a row per finding:
27054
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27055
- * the group and the filters need (count, providers, actions, statuses,
27056
- * latest, search text);
27057
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27058
- * populate `instances` for the table's expanded rows.
27059
27117
  * The aggregates carry raw DB values and are translated by the same
27060
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27061
- * rule is ever restated in SQL.
27118
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
27119
+ * status rule is ever restated in SQL.
27062
27120
  */
27063
- listGroupedFindings(query) {
27121
+ listFindingTypes(query) {
27064
27122
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27065
27123
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27066
27124
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27073,12 +27131,7 @@ var SqliteFindingsRepository = class {
27073
27131
  predicate,
27074
27132
  params: sessionParams
27075
27133
  });
27076
- const rows = this.previewRows(aggregates, {
27077
- sessionId: query.sessionId,
27078
- from: query.from
27079
- });
27080
- const groupable = rows.map(toFlatFindingRow);
27081
- const allGroups = buildFindingGroups(groupable, { aggregates });
27134
+ const allTypes = buildFindingTypes(aggregates);
27082
27135
  const filterOpts = {
27083
27136
  severity: query.severity,
27084
27137
  providers: query.provider,
@@ -27087,30 +27140,25 @@ var SqliteFindingsRepository = class {
27087
27140
  subtype: query.subtype,
27088
27141
  q: query.q
27089
27142
  };
27090
- const facets = computeFindingFacets(allGroups, filterOpts);
27091
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
27143
+ const facets = computeFindingFacets(allTypes, filterOpts);
27144
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27092
27145
  const statusFilter = query.status ?? [];
27093
27146
  const totals = {
27094
- findings: sorted.reduce((acc, g) => {
27095
- if (statusFilter.length === 0) return acc + g.instanceCount;
27096
- const agg = aggregates.get(g.id);
27097
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
27147
+ findings: sorted.reduce((acc, t) => {
27148
+ if (statusFilter.length === 0) return acc + t.instanceCount;
27149
+ const agg = aggregates.get(t.id);
27150
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27098
27151
  }, 0),
27099
- groups: sorted.length
27152
+ types: sorted.length
27100
27153
  };
27101
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
27154
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27102
27155
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27103
27156
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27104
27157
  const page = sorted.slice(start, start + limit);
27105
27158
  const lastOnPage = page.at(-1);
27106
27159
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27107
27160
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27108
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27109
- const narrow = (g) => statusSet ? {
27110
- ...g,
27111
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27112
- } : g;
27113
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
27161
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27114
27162
  return Promise.resolve({
27115
27163
  totals,
27116
27164
  facets,
@@ -27121,7 +27169,7 @@ var SqliteFindingsRepository = class {
27121
27169
  }
27122
27170
  /**
27123
27171
  * One row per rule_id, folding EVERY instance of the group into the values
27124
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
27172
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27125
27173
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27126
27174
  *
27127
27175
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27215,13 +27263,25 @@ var SqliteFindingsRepository = class {
27215
27263
  });
27216
27264
  }
27217
27265
  /**
27218
- * The same findings folded by location: repository, then file within it.
27266
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27219
27267
  *
27220
27268
  * The grouping keys come from the capturing event's attributes, which is what
27221
- * the local store relates a finding to — there is no finding↔asset row to
27222
- * group by instead. A repo or file the event did not record folds into the
27223
- * empty-string bucket, which the view renders but does not link, since no
27224
- * filter can name it.
27269
+ * the local store relates a finding to; there is no finding↔asset row to group
27270
+ * by instead. A repo or file the event did not record folds into the
27271
+ * empty-string bucket, which is a real location like any other: it is listed,
27272
+ * it is selectable, and its `?loc=` token is as good as any other row's.
27273
+ *
27274
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
27275
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
27276
+ * list was rebuilt to remove — and two-level pagination inside an
27277
+ * expand/collapse table is what pushed that view to master/detail in the first
27278
+ * place.
27279
+ *
27280
+ * Every filter narrows the FINDINGS and the locations fall out of what
27281
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
27282
+ * reports for the same filters scoped to that pair. The view depends on it:
27283
+ * one toolbar sits over both panels precisely because a location owns none of
27284
+ * its fields.
27225
27285
  */
27226
27286
  listFindingLocations(query) {
27227
27287
  const opts = {
@@ -27233,13 +27293,16 @@ var SqliteFindingsRepository = class {
27233
27293
  tools: query.tool,
27234
27294
  q: query.q
27235
27295
  };
27236
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
27296
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
27297
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27237
27298
  const byRepo = /* @__PURE__ */ new Map();
27299
+ const accumulator = createInstanceFacetAccumulator(opts);
27238
27300
  let total = 0;
27239
27301
  for (const row of this.scanFindingRows({
27240
27302
  sessionId: query.sessionId,
27241
27303
  from: query.from
27242
27304
  })) {
27305
+ accumulator.add(row);
27243
27306
  if (!matchesInstanceFilters(row, opts)) continue;
27244
27307
  total += 1;
27245
27308
  let files = byRepo.get(row.repo);
@@ -27254,103 +27317,35 @@ var SqliteFindingsRepository = class {
27254
27317
  }
27255
27318
  addToLocation(acc, row);
27256
27319
  }
27257
- let fileCount = 0;
27258
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27259
- fileCount += files.size;
27260
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27261
- file: file2,
27262
- instanceCount: acc.instanceCount,
27263
- maxSeverity: acc.maxSeverity,
27264
- latestDetectedAt: acc.latestDetectedAt,
27265
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27266
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27267
- })).sort(compareLocationOrder);
27268
- const rollup = fileRows.reduce(
27269
- (a, f) => ({
27270
- instanceCount: a.instanceCount + f.instanceCount,
27271
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27272
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27273
- }),
27274
- {
27275
- instanceCount: 0,
27276
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27277
- latestDetectedAt: ""
27278
- }
27279
- );
27280
- const statuses = fileRows.map((f) => f.status);
27281
- const folded = foldGroupStatus(statuses);
27282
- return {
27283
- repo,
27284
- instanceCount: rollup.instanceCount,
27285
- maxSeverity: rollup.maxSeverity,
27286
- latestDetectedAt: rollup.latestDetectedAt,
27287
- ...folded === void 0 ? {} : { status: folded },
27288
- files: fileRows
27289
- };
27290
- });
27291
- repos.sort(compareLocationOrder);
27320
+ const sorted = [];
27321
+ for (const [repo, files] of byRepo) {
27322
+ for (const [file2, acc] of files) {
27323
+ const status = foldGroupStatus(acc.statuses);
27324
+ sorted.push({
27325
+ id: encodeLocationId(repo, file2),
27326
+ repo,
27327
+ file: file2,
27328
+ instanceCount: acc.instanceCount,
27329
+ maxSeverity: acc.maxSeverity,
27330
+ latestDetectedAt: acc.latestDetectedAt,
27331
+ ...status === void 0 ? {} : { status },
27332
+ ruleIds: [...acc.ruleIds]
27333
+ });
27334
+ }
27335
+ }
27336
+ sorted.sort(compareLocationOrder);
27337
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
27338
+ const page = sorted.slice(start, start + limit);
27339
+ const lastOnPage = page.at(-1);
27340
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
27341
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27292
27342
  return Promise.resolve({
27293
- totals: { findings: total, repos: repos.length, files: fileCount },
27294
- items: repos.slice(0, limit),
27295
- hasMore: repos.length > limit
27343
+ totals: { findings: total, locations: sorted.length },
27344
+ facets: accumulator.facets(),
27345
+ items: [...page, ...deepLinked ? [deepLinked] : []],
27346
+ nextCursor
27296
27347
  });
27297
27348
  }
27298
- /**
27299
- * Each group's newest instances, for the table's expanded rows.
27300
- *
27301
- * ONE index-ordered scan with early termination, and the shape is the point.
27302
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27303
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27304
- * through a temp B-tree to keep a bounded preview of each group, and then
27305
- * sorts the survivors again for the page order. Both sorts grow with the
27306
- * store while the answer does not.
27307
- *
27308
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27309
- * (or the session or window index the scope names — see `findingScanSql`),
27310
- * which is already the order the page wants, and keeps rows per rule until
27311
- * each rule has as many as it can show. The aggregate the caller already holds
27312
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27313
- * per rule, summed, is the number of rows this scan has to find, and it stops
27314
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27315
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27316
- * store with many firing rules widens it. The bound that DOES hold
27317
- * unconditionally is the sorted form's floor: this scan visits at most as
27318
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27319
- * sorted, and stops the moment every rule has its cap, where the sorted form
27320
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27321
- * wanted instances sitting at the tail of the scope — is one pass over
27322
- * everything in scope with a block sort of the id tie-break only, never a
27323
- * sort of the scope, which is still that floor.
27324
- *
27325
- * A row whose rule the aggregate did not see is skipped: the two statements
27326
- * run without a shared snapshot, so a capture landing between them can add a
27327
- * rule here that has no counts there, and the counts are what the group is
27328
- * built from.
27329
- */
27330
- previewRows(aggregates, scope) {
27331
- const wanted = /* @__PURE__ */ new Map();
27332
- let remaining = 0;
27333
- for (const [ruleId, agg] of aggregates) {
27334
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27335
- wanted.set(ruleId, n);
27336
- remaining += n;
27337
- }
27338
- const rows = [];
27339
- if (remaining === 0) return rows;
27340
- const { sql, params } = this.findingScanSql(scope);
27341
- const taken = /* @__PURE__ */ new Map();
27342
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27343
- const want = wanted.get(r.rule_id);
27344
- if (want === void 0) continue;
27345
- const have = taken.get(r.rule_id) ?? 0;
27346
- if (have >= want) continue;
27347
- taken.set(r.rule_id, have + 1);
27348
- rows.push(r);
27349
- remaining -= 1;
27350
- if (remaining === 0) break;
27351
- }
27352
- return rows;
27353
- }
27354
27349
  /**
27355
27350
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27356
27351
  *
@@ -27377,6 +27372,33 @@ var SqliteFindingsRepository = class {
27377
27372
  yield toFlatFindingRow(r);
27378
27373
  }
27379
27374
  }
27375
+ /**
27376
+ * One finding by its own id, or null when no such row exists.
27377
+ *
27378
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
27379
+ * the store — and, unlike anything derived from a list page, it resolves a
27380
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
27381
+ * deep link needs: the id it carries may name a finding thousands of rows
27382
+ * older than anything a first page holds.
27383
+ *
27384
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
27385
+ * RESOLVES an id; whether that row would survive the list's current filters is
27386
+ * a different question, and hiding the target because a filter excludes it is
27387
+ * worse than showing it.
27388
+ *
27389
+ * `groupId` on the result IS the rule id, so this one read answers both "which
27390
+ * type should the list select?" and "what does the drawer show?".
27391
+ */
27392
+ findingInstance(id) {
27393
+ const row = this.db.prepare(
27394
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
27395
+ FROM inspection_findings f
27396
+ JOIN audit_events e ON e.id = f.audit_event_id
27397
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27398
+ WHERE f.id = ?`
27399
+ ).get(id);
27400
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
27401
+ }
27380
27402
  /**
27381
27403
  * The one statement both instance-level scans run: every finding in scope,
27382
27404
  * joined to its event and definition, newest first.
@@ -27410,17 +27432,7 @@ var SqliteFindingsRepository = class {
27410
27432
  conditions.push("e.started_at >= ?");
27411
27433
  params.push(isoToEpochMillis(scope.from));
27412
27434
  }
27413
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27414
- d.severity AS severity, f.masked_match AS masked_match,
27415
- f.action_taken AS action_taken, f.confidence AS confidence,
27416
- e.started_at AS occurred_at,
27417
- e.source_tool AS source_tool,
27418
- e.repo AS repo,
27419
- e.file_path AS file,
27420
- e.tool_name AS tool_name,
27421
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27422
- e.event_type AS kind, f.finding_key AS finding_key,
27423
- ${latestResolutionStatusSql("f")} AS latest_status
27435
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27424
27436
  FROM audit_events e
27425
27437
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27426
27438
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27434,6 +27446,26 @@ var SqliteFindingsRepository = class {
27434
27446
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27435
27447
  const rows = this.db.prepare(
27436
27448
  `SELECT rule_id,
27449
+ -- BARE columns beside max(latest_at), which is deliberate and
27450
+ -- is SQLite's documented behaviour: with a single min()/max()
27451
+ -- in an aggregate query, every bare column takes its value from
27452
+ -- the row that produced the extremum. So these are the severity
27453
+ -- and category of the definition whose finding is NEWEST, which
27454
+ -- is what the row-based build they replaced read off its first
27455
+ -- (newest-first) row.
27456
+ --
27457
+ -- min() is WRONG here and was the defect: inspection_definitions
27458
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
27459
+ -- mints a new row), so a rule whose severity moved between
27460
+ -- versions has several, and min() picks the ALPHABETICALLY
27461
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
27462
+ -- That is arbitrary in direction, and it feeds the badge, the
27463
+ -- filter, the facet counts and the primary sort key.
27464
+ --
27465
+ -- Adding a second min()/max() aggregate here would make these
27466
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
27467
+ severity,
27468
+ category,
27437
27469
  sum(tuple_count) AS instance_count,
27438
27470
  max(latest_at) AS latest_at,
27439
27471
  group_concat(source_tools) AS source_tools,
@@ -27444,6 +27476,14 @@ var SqliteFindingsRepository = class {
27444
27476
  group_concat(tool_names) AS tool_names
27445
27477
  FROM (
27446
27478
  SELECT d.rule_id AS rule_id,
27479
+ -- Severity and category are columns of the DEFINITION, and
27480
+ -- a rule can have SEVERAL definitions (one per version), so
27481
+ -- these are grouped on below and resolved to the newest
27482
+ -- firing version by the outer query's bare-column select.
27483
+ -- They ride the aggregate because the type build has no rows
27484
+ -- to read them off \u2014 see buildFindingTypes.
27485
+ d.severity AS severity,
27486
+ d.category AS category,
27447
27487
  e.event_type || '${TUPLE_SEP}' ||
27448
27488
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27449
27489
  coalesce(latest.status, '') AS status_tuple,
@@ -27458,7 +27498,7 @@ var SqliteFindingsRepository = class {
27458
27498
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27459
27499
  ON latest.finding_key = f.finding_key
27460
27500
  ${scope.predicate}
27461
- GROUP BY d.rule_id, status_tuple
27501
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27462
27502
  )
27463
27503
  GROUP BY rule_id`
27464
27504
  ).all(scope.params);
@@ -27467,6 +27507,8 @@ var SqliteFindingsRepository = class {
27467
27507
  r.rule_id,
27468
27508
  {
27469
27509
  instanceCount: r.instance_count,
27510
+ severity: r.severity,
27511
+ category: r.category,
27470
27512
  sourceTools: splitConcat(r.source_tools),
27471
27513
  actionsTaken: splitConcat(r.actions_taken),
27472
27514
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27483,7 +27525,7 @@ var SqliteFindingsRepository = class {
27483
27525
  latestDetectedAt: epochMillisToIso(r.latest_at),
27484
27526
  // Free text only — joined and substring-matched, so group_concat's
27485
27527
  // commas need no unpicking (a repo/path containing one still matches).
27486
- // Left undefined (not '') when unfetched, so buildFindingGroups can
27528
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27487
27529
  // tell "no q this request" from "a group with no repo/file at all"
27488
27530
  // and skip priming a haystack nothing will read.
27489
27531
  ...withSearchText ? {
@@ -27635,6 +27677,12 @@ var SqliteHistorySyncRepository = class {
27635
27677
  this.markOwedStmt = db.prepare(
27636
27678
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27637
27679
  );
27680
+ this.markCaptureBacklogOwedStmt = db.prepare(
27681
+ `UPDATE audit_events SET outbox_owed = 1
27682
+ WHERE synced_at IS NULL
27683
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27684
+ AND started_at < :before`
27685
+ );
27638
27686
  this.stampStmt = db.prepare(
27639
27687
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27640
27688
  );
@@ -27683,7 +27731,9 @@ var SqliteHistorySyncRepository = class {
27683
27731
  );
27684
27732
  this.disownCapturesStmt = db.prepare(
27685
27733
  `UPDATE audit_events SET outbox_owed = NULL
27686
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27734
+ WHERE outbox_owed IS NOT NULL
27735
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27736
+ AND started_at < :attachedAt`
27687
27737
  );
27688
27738
  this.rearmStmt = db.prepare(
27689
27739
  `UPDATE audit_events SET synced_at = NULL
@@ -27759,6 +27809,7 @@ var SqliteHistorySyncRepository = class {
27759
27809
  freezeBoundaryStmt;
27760
27810
  captureRowsStmt;
27761
27811
  markOwedStmt;
27812
+ markCaptureBacklogOwedStmt;
27762
27813
  captureSkipCountStmt;
27763
27814
  disownCapturesStmt;
27764
27815
  partitionStmt;
@@ -27822,6 +27873,23 @@ var SqliteHistorySyncRepository = class {
27822
27873
  markCaptureOwed(id) {
27823
27874
  this.markOwedStmt.run({ id });
27824
27875
  }
27876
+ /**
27877
+ * Mark every capture already on disk as owed, as of `before`.
27878
+ *
27879
+ * The consent-time backfill, called once from `aka attach` when a human
27880
+ * grants existing-history consent — never from an ongoing drain pass, and
27881
+ * never inferred from a boundary that could later move. `before` is the
27882
+ * caller's own "now" at the moment consent was granted, so what this marks
27883
+ * is exactly the backlog the consent prompt already counted, not whatever a
27884
+ * later re-attach or key rotation might widen it to.
27885
+ *
27886
+ * Returns how many rows matched, for the caller to log or test against. Not a
27887
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
27888
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27889
+ */
27890
+ markCaptureBacklogOwed(before) {
27891
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27892
+ }
27825
27893
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27826
27894
  markSynced(ids, atMs) {
27827
27895
  this.stampAll(ids, atMs);
@@ -27938,15 +28006,42 @@ var SqliteHistorySyncRepository = class {
27938
28006
  *
27939
28007
  * Delivery is a fact about ONE recipient: rows sent to the deployment a
27940
28008
  * machine has just left are undelivered as far as the new one is concerned.
27941
- * All three in one transaction, so a crash between them cannot leave stamps
27942
- * attributed to the wrong deployment, or a boundary that belongs to another.
28009
+ * All four in one transaction, so a crash between them cannot leave stamps
28010
+ * attributed to the wrong deployment, a boundary that belongs to another, or
28011
+ * a disown with no re-mark to follow it.
27943
28012
  *
27944
28013
  * The boundary is written HERE and only here, which is what freezes it: a
27945
28014
  * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
27946
28015
  * unchanged, so this never runs and the backlog does not widen back over rows
27947
28016
  * the live path has since delivered.
28017
+ *
28018
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28019
+ * granted existing-history consent for the deployment this call is arming —
28020
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28021
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28022
+ * apart. Passed only when that grant is valid, since this method has no way
28023
+ * to check consent itself and must not mark a row owed for a machine that
28024
+ * never agreed to it. Applied AFTER the disown above, in the SAME
28025
+ * transaction: what the disown clears is every marker below `backlogBefore`,
28026
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28027
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28028
+ * on the cleared side of that bound — and the re-mark in the same
28029
+ * transaction is what puts those rows back. A crash between the two cannot
28030
+ * strand the ledger disowned with nothing re-marked — the transaction either
28031
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
28032
+ * committed re-enters this method on the very next pass. Omit it (the
28033
+ * structural-only tests do) to exercise the disown in isolation.
28034
+ *
28035
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
28036
+ * touching a marker the NEW deployment's OWN live path has already set: B's
28037
+ * live path can mark a capture owed from the moment `aka attach` writes the
28038
+ * descriptor, before the drain's first pass ever reaches this method, and
28039
+ * such a row sits at or after the bound rather than below it. What keeps the
28040
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
28041
+ * bound — disown runs first, re-mark second, both inside the one
28042
+ * transaction above.
27948
28043
  */
27949
- rearmFor(fingerprint, backlogBefore) {
28044
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
27950
28045
  this.ensureRowStmt.run();
27951
28046
  withTransaction(
27952
28047
  this.db,
@@ -27954,7 +28049,10 @@ var SqliteHistorySyncRepository = class {
27954
28049
  const previous = getRow(this.fingerprintStmt)?.fingerprint;
27955
28050
  this.rearmStmt.run();
27956
28051
  if (previous !== null && previous !== void 0 && previous !== fingerprint) {
27957
- this.disownCapturesStmt.run();
28052
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28053
+ }
28054
+ if (backfillCapturesBefore !== void 0) {
28055
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
27958
28056
  }
27959
28057
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27960
28058
  },
@@ -28206,7 +28304,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28206
28304
  }
28207
28305
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28208
28306
  }
28209
- function readManagedSettings(paths = managedSettingsPaths()) {
28307
+ var testOnlyManagedPaths = null;
28308
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28210
28309
  for (const path of paths) {
28211
28310
  let text;
28212
28311
  try {
@@ -30686,7 +30785,7 @@ function toUtcDateString(ms) {
30686
30785
  return new Date(ms).toISOString().slice(0, 10);
30687
30786
  }
30688
30787
  function isTimeseriesSeverity(s) {
30689
- return s === "critical" || s === "high" || s === "medium";
30788
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30690
30789
  }
30691
30790
  var SqliteSecurityRepository = class {
30692
30791
  constructor(db, now = () => Date.now()) {
@@ -30815,12 +30914,16 @@ var SqliteSecurityRepository = class {
30815
30914
  const now = this.now();
30816
30915
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30817
30916
  const rows = this.findingsInRange(windowStart, now);
30818
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30819
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30820
- critical: 0,
30821
- high: 0,
30822
- medium: 0
30823
- }));
30917
+ const points = Array.from(
30918
+ { length: numBuckets },
30919
+ (_, i) => ({
30920
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
30921
+ critical: 0,
30922
+ high: 0,
30923
+ medium: 0,
30924
+ low: 0
30925
+ })
30926
+ );
30824
30927
  for (const r of rows) {
30825
30928
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30826
30929
  const bucket = points[idx];
@@ -31038,6 +31141,7 @@ var SqliteSecurityRepository = class {
31038
31141
  `SELECT f.finding_key AS finding_key,
31039
31142
  d.rule_id AS rule_id,
31040
31143
  d.severity AS severity,
31144
+ e.repo AS repo,
31041
31145
  e.file_path AS path,
31042
31146
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31043
31147
  latest.resolved_at AS latest_resolved_at
@@ -31057,6 +31161,7 @@ var SqliteSecurityRepository = class {
31057
31161
  const items = rows.map((r) => ({
31058
31162
  findingKey: r.finding_key,
31059
31163
  ruleId: r.rule_id,
31164
+ repo: r.repo ?? "",
31060
31165
  severity: r.severity,
31061
31166
  path: r.path ?? "",
31062
31167
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31066,13 +31171,66 @@ var SqliteSecurityRepository = class {
31066
31171
  }));
31067
31172
  return Promise.resolve({ items });
31068
31173
  }
31174
+ /**
31175
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31176
+ *
31177
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31178
+ * list: a secret committed three weeks ago and never rotated is still the most
31179
+ * important thing to fix, and any window hides it. It carried a "newest N
31180
+ * findings" cap and then a range; the first meant a different span on every
31181
+ * machine, and the second reported "no recommendations" over live exposure.
31182
+ *
31183
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31184
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31185
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31186
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31187
+ * The two answer different questions and only this one has to match a link.
31188
+ *
31189
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31190
+ * whole-store scope costs a grouped scan rather than a row per finding.
31191
+ */
31192
+ recommendationInputs() {
31193
+ const rows = allRows(
31194
+ this.db.prepare(
31195
+ `SELECT d.rule_id AS rule_id,
31196
+ d.category AS category,
31197
+ d.severity AS severity,
31198
+ COUNT(*) AS count
31199
+ FROM inspection_findings f
31200
+ JOIN audit_events e ON e.id = f.audit_event_id
31201
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31202
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31203
+ ON latest.finding_key = f.finding_key
31204
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31205
+ AND e.event_type = 'code_change'
31206
+ AND (
31207
+ f.finding_key IS NULL
31208
+ OR latest.status IS NULL
31209
+ OR latest.status NOT IN ('resolved', 'dismissed')
31210
+ )
31211
+ GROUP BY d.rule_id, d.category, d.severity`
31212
+ )
31213
+ );
31214
+ return Promise.resolve(
31215
+ rows.map((r) => ({
31216
+ ruleId: r.rule_id,
31217
+ category: r.category,
31218
+ severity: r.severity,
31219
+ count: r.count
31220
+ }))
31221
+ );
31222
+ }
31069
31223
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31070
31224
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31071
31225
  // numeric and the JS aggregations bucket/split on ms directly.
31072
31226
  findingsInRange(fromMs, toMs) {
31073
31227
  const rows = allRows(
31074
31228
  this.db.prepare(
31075
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31229
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31230
+ // joined for `severity`, so they are two more columns off a row this read
31231
+ // already fetches. They feed the recommended-actions rollup.
31232
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31233
+ d.rule_id AS rule_id, d.category AS category
31076
31234
  FROM inspection_findings f
31077
31235
  JOIN audit_events e ON e.id = f.audit_event_id
31078
31236
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -31085,7 +31243,9 @@ var SqliteSecurityRepository = class {
31085
31243
  return rows.map((r) => ({
31086
31244
  occurredAt: r.occurred_at,
31087
31245
  severity: r.severity,
31088
- actionTaken: r.action_taken
31246
+ actionTaken: r.action_taken,
31247
+ ruleId: r.rule_id,
31248
+ category: r.category
31089
31249
  }));
31090
31250
  }
31091
31251
  };
@@ -32255,23 +32415,30 @@ function openLocalDatabase(dir) {
32255
32415
  };
32256
32416
  }
32257
32417
 
32258
- // ../../packages/persistence/src/finding-key.ts
32418
+ // ../../packages/persistence/src/egress-wire.ts
32259
32419
  import { createHash as createHash3 } from "crypto";
32260
32420
 
32421
+ // ../../packages/persistence/src/finding-key.ts
32422
+ import { createHash as createHash4 } from "crypto";
32423
+
32261
32424
  // ../../packages/persistence/src/fingerprint.ts
32262
32425
  import { createHmac, randomBytes } from "crypto";
32263
32426
  import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32264
32427
  import { join as join8 } from "path";
32265
32428
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
32266
32429
 
32267
- // ../../packages/persistence/src/history-preview.ts
32430
+ // ../../packages/persistence/src/history-backfill.ts
32268
32431
  import { existsSync as existsSync4 } from "fs";
32269
32432
  import { join as join9 } from "path";
32433
+
32434
+ // ../../packages/persistence/src/history-preview.ts
32435
+ import { existsSync as existsSync5 } from "fs";
32436
+ import { join as join10 } from "path";
32270
32437
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32271
32438
 
32272
32439
  // ../../packages/persistence/src/store-symlinks.ts
32273
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32274
- import { dirname as dirname3, join as join10, resolve } from "path";
32440
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32441
+ import { dirname as dirname3, join as join11, resolve } from "path";
32275
32442
 
32276
32443
  // ../../packages/persistence/src/vault/crypto.ts
32277
32444
  import {
@@ -32286,14 +32453,14 @@ import {
32286
32453
  import { execFileSync } from "child_process";
32287
32454
  import { randomBytes as randomBytes2 } from "crypto";
32288
32455
  import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32289
- import { join as join11 } from "path";
32456
+ import { join as join12 } from "path";
32290
32457
 
32291
32458
  // ../../packages/persistence/src/vault/vault.ts
32292
32459
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32293
32460
 
32294
32461
  // ../../packages/persistence/src/warn-era-cap.ts
32295
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32296
- import { join as join12 } from "path";
32462
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32463
+ import { join as join13 } from "path";
32297
32464
 
32298
32465
  // ../../packages/remote/src/http.ts
32299
32466
  import { request as httpRequest } from "http";
@@ -32574,6 +32741,7 @@ function createRemoteClient(options) {
32574
32741
  url: url2(ROUTES.shares),
32575
32742
  body: JSON.stringify(validated.data)
32576
32743
  });
32744
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32577
32745
  okBody(response);
32578
32746
  },
32579
32747
  async pollCommand() {
@@ -32598,17 +32766,17 @@ function createRemoteClient(options) {
32598
32766
 
32599
32767
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32600
32768
  import { readFileSync as readFileSync8 } from "fs";
32601
- import { join as join13 } from "path";
32769
+ import { join as join14 } from "path";
32602
32770
 
32603
32771
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32604
32772
  import { randomUUID as randomUUID15 } from "crypto";
32605
- import { readFileSync as readFileSync14 } from "fs";
32773
+ import { readFileSync as readFileSync15 } from "fs";
32606
32774
  import { readFile, rename, writeFile } from "fs/promises";
32607
- import { join as join22 } from "path";
32775
+ import { join as join24 } from "path";
32608
32776
 
32609
32777
  // ../../packages/plugin-sdk/src/config.ts
32610
- import { existsSync as existsSync7 } from "fs";
32611
- import { join as join14 } from "path";
32778
+ import { existsSync as existsSync8 } from "fs";
32779
+ import { join as join15 } from "path";
32612
32780
 
32613
32781
  // ../../packages/plugin-sdk/src/provider-env.ts
32614
32782
  var booleanish = external_exports.string().optional().transform((v) => {
@@ -32631,7 +32799,7 @@ var ProviderEnvSchema = external_exports.object(providerEnvShape);
32631
32799
  // ../../packages/plugin-sdk/src/config-inventory.ts
32632
32800
  import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32633
32801
  import { homedir as homedir2 } from "os";
32634
- import { basename as basename3, join as join16 } from "path";
32802
+ import { basename as basename3, join as join17 } from "path";
32635
32803
 
32636
32804
  // ../../packages/detections/src/egress/registry.ts
32637
32805
  var EXTRACTOR_VERSION = "1";
@@ -33389,24 +33557,20 @@ var CPU_CORROBORATION_SHARE = 0.2;
33389
33557
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
33390
33558
 
33391
33559
  // ../../packages/plugin-sdk/src/repo.ts
33392
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
33393
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
33560
+ import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
33561
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
33394
33562
 
33395
33563
  // ../../packages/plugin-sdk/src/events.ts
33396
33564
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
33397
33565
 
33398
33566
  // ../../packages/plugin-sdk/src/isolated-scan.ts
33399
- import { existsSync as existsSync9 } from "fs";
33567
+ import { existsSync as existsSync10 } from "fs";
33400
33568
  import { fileURLToPath } from "url";
33401
33569
  import { Worker } from "worker_threads";
33402
33570
 
33403
- // ../../packages/plugin-sdk/src/ignore-layers.ts
33404
- var import_ignore = __toESM(require_ignore(), 1);
33405
- import { readFileSync as readFileSync11 } from "fs";
33406
- import { join as join17 } from "path";
33407
-
33408
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
33409
- import { arch, hostname as hostname4, platform, release } from "os";
33571
+ // ../../packages/plugin-sdk/src/host-floor.ts
33572
+ import { readFileSync as readFileSync12 } from "fs";
33573
+ import { join as join19 } from "path";
33410
33574
 
33411
33575
  // ../../packages/plugin-sdk/src/model-governance.ts
33412
33576
  import {
@@ -33414,24 +33578,50 @@ import {
33414
33578
  fstatSync,
33415
33579
  mkdirSync as mkdirSync2,
33416
33580
  openSync as openSync2,
33417
- readFileSync as readFileSync12,
33581
+ readFileSync as readFileSync11,
33418
33582
  readSync,
33419
33583
  writeFileSync as writeFileSync5
33420
33584
  } from "fs";
33421
33585
  import { join as join18 } from "path";
33422
33586
  var TAIL_BYTES = 256 * 1024;
33423
33587
 
33588
+ // ../../packages/plugin-sdk/src/host-floor.ts
33589
+ var HOST_FEATURE = {
33590
+ ModelSwitch: "model-switch",
33591
+ VaultPointerDisplay: "vault-pointer-display"
33592
+ };
33593
+ var HOST_FLOORS = {
33594
+ [HOST_FEATURE.ModelSwitch]: {
33595
+ label: "model-switch protection",
33596
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
33597
+ since: "2.1.251"
33598
+ },
33599
+ [HOST_FEATURE.VaultPointerDisplay]: {
33600
+ label: "vault pointer display",
33601
+ hookEvents: ["MessageDisplay"],
33602
+ since: "2.1.152"
33603
+ }
33604
+ };
33605
+
33606
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
33607
+ var import_ignore = __toESM(require_ignore(), 1);
33608
+ import { readFileSync as readFileSync13 } from "fs";
33609
+ import { join as join20 } from "path";
33610
+
33611
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
33612
+ import { arch, hostname as hostname4, platform, release } from "os";
33613
+
33424
33614
  // ../../packages/plugin-sdk/src/nudge.ts
33425
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
33426
- import { join as join19 } from "path";
33615
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
33616
+ import { join as join21 } from "path";
33427
33617
 
33428
33618
  // ../../packages/plugin-sdk/src/paths.ts
33429
33619
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
33430
33620
  import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
33431
33621
 
33432
33622
  // ../../packages/plugin-sdk/src/project-files.ts
33433
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
33434
- import { basename as basename5, join as join20 } from "path";
33623
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
33624
+ import { basename as basename5, join as join22 } from "path";
33435
33625
 
33436
33626
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
33437
33627
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -33467,7 +33657,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
33467
33657
 
33468
33658
  // ../../packages/plugin-sdk/src/throttle.ts
33469
33659
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
33470
- import { join as join21 } from "path";
33660
+ import { join as join23 } from "path";
33471
33661
 
33472
33662
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33473
33663
  var BREAKER_COOLDOWN_MS = 3e4;
@@ -33493,15 +33683,15 @@ function parseBreakerState(raw, nowMs) {
33493
33683
  }
33494
33684
  function readForwardHealth(dir, nowMs = Date.now()) {
33495
33685
  try {
33496
- return parseBreakerState(readFileSync14(join22(dir, STATE_FILENAME), "utf8"), nowMs);
33686
+ return parseBreakerState(readFileSync15(join24(dir, STATE_FILENAME), "utf8"), nowMs);
33497
33687
  } catch {
33498
33688
  return null;
33499
33689
  }
33500
33690
  }
33501
33691
 
33502
33692
  // ../../packages/plugin-runtime/src/attached/history-state.ts
33503
- import { readFileSync as readFileSync15 } from "fs";
33504
- import { join as join23 } from "path";
33693
+ import { readFileSync as readFileSync16 } from "fs";
33694
+ import { join as join25 } from "path";
33505
33695
  var HISTORY_SYNC_STATE_FILENAME = ATTACHED_HISTORY_SYNC_STATE_FILENAME;
33506
33696
  var PHASES = /* @__PURE__ */ new Set(["filling", "complete"]);
33507
33697
  var OUTCOMES = /* @__PURE__ */ new Set([
@@ -33512,7 +33702,7 @@ var OUTCOMES = /* @__PURE__ */ new Set([
33512
33702
  ]);
33513
33703
  var SPEC_VERSION = 1;
33514
33704
  function historySyncStatePath(dataDir2) {
33515
- return join23(dataDir2, HISTORY_SYNC_STATE_FILENAME);
33705
+ return join25(dataDir2, HISTORY_SYNC_STATE_FILENAME);
33516
33706
  }
33517
33707
  function writeHistorySyncState(dataDir2, state) {
33518
33708
  try {
@@ -33525,7 +33715,7 @@ function writeHistorySyncState(dataDir2, state) {
33525
33715
  }
33526
33716
  function readHistorySyncState(dataDir2) {
33527
33717
  try {
33528
- const parsed2 = JSON.parse(readFileSync15(historySyncStatePath(dataDir2), "utf8"));
33718
+ const parsed2 = JSON.parse(readFileSync16(historySyncStatePath(dataDir2), "utf8"));
33529
33719
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
33530
33720
  const r = parsed2;
33531
33721
  if (r.specVersion !== SPEC_VERSION) return null;
@@ -33738,9 +33928,12 @@ async function runHistorySync(deps) {
33738
33928
  if (!isAttached(settings)) return didNotRun("not-attached");
33739
33929
  const connection = settings.controlPlane;
33740
33930
  if (connection === void 0) return didNotRun("not-attached");
33741
- if (!isHistorySyncConsentValid(settings.historySyncConsent, connection.endpoint)) {
33931
+ const consent = settings.historySyncConsent;
33932
+ if (!isHistorySyncConsentValid(consent, connection.endpoint) || consent === void 0) {
33742
33933
  return didNotRun("no-consent");
33743
33934
  }
33935
+ const consentAcknowledgedAtMs = Date.parse(consent.acknowledgedAt);
33936
+ if (!Number.isFinite(consentAcknowledgedAtMs)) return didNotRun("attachment-unreadable");
33744
33937
  const state = readControlPlaneCredentialFile(deps.settingsDir, connection);
33745
33938
  if (!state.usable) return didNotRun("credential-unusable");
33746
33939
  const nowMs = now();
@@ -33756,7 +33949,7 @@ async function runHistorySync(deps) {
33756
33949
  const recorded = ledger.deployment();
33757
33950
  let backlogBefore;
33758
33951
  if (recorded.fingerprint !== fingerprint) {
33759
- ledger.rearmFor(fingerprint, attachedAtMs);
33952
+ ledger.rearmFor(fingerprint, attachedAtMs, consentAcknowledgedAtMs);
33760
33953
  backlogBefore = attachedAtMs;
33761
33954
  } else if (recorded.backlogBefore === void 0) {
33762
33955
  ledger.freezeBoundary(attachedAtMs);
@@ -34132,12 +34325,12 @@ import { fileURLToPath as fileURLToPath2 } from "url";
34132
34325
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
34133
34326
 
34134
34327
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
34135
- import { readFileSync as readFileSync16 } from "fs";
34328
+ import { readFileSync as readFileSync17 } from "fs";
34136
34329
 
34137
34330
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
34138
34331
  import { randomUUID as randomUUID16 } from "crypto";
34139
34332
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
34140
- import { join as join24 } from "path";
34333
+ import { join as join26 } from "path";
34141
34334
 
34142
34335
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
34143
34336
  import { rename as rename2 } from "fs/promises";
@@ -34152,11 +34345,11 @@ import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
34152
34345
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
34153
34346
  import { randomUUID as randomUUID17 } from "crypto";
34154
34347
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
34155
- import { join as join25 } from "path";
34348
+ import { join as join27 } from "path";
34156
34349
 
34157
34350
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
34158
- import { readFileSync as readFileSync17 } from "fs";
34159
- import { join as join26 } from "path";
34351
+ import { readFileSync as readFileSync18 } from "fs";
34352
+ import { join as join28 } from "path";
34160
34353
 
34161
34354
  // ../../packages/plugin-runtime/src/attached/status.ts
34162
34355
  var REFUSAL_LINES = {