@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.
@@ -492,8 +492,8 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync7 } from "fs";
496
- import { join as join13 } from "path";
495
+ import { existsSync as existsSync8 } from "fs";
496
+ import { join as join14 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -20743,13 +20743,11 @@ var FindingGroup = external_exports.object({
20743
20743
  latestDetectedAt: external_exports.iso.datetime(),
20744
20744
  instances: external_exports.array(FindingInstance),
20745
20745
  // Derived from instances' statuses with open-dominates precedence (see
20746
- // buildFindingGroups). Undefined only when no instance carries a status.
20746
+ // foldGroupStatus). Undefined only when no instance carries a status.
20747
20747
  status: FindingStatus.optional(),
20748
- // The distinct people across the WHOLE group, not just the `instances`
20749
- // preview — from the store's whole-group aggregate when it supplies one,
20750
- // else folded from the rows (see buildFindingGroups). Undefined when no
20751
- // instance carries a user, or when the store supplied whole-group folds
20752
- // without one.
20748
+ // The distinct people across the WHOLE group, not just the instances
20749
+ // carried here. Undefined when no instance carries a user, or when the
20750
+ // store supplied whole-group folds without one.
20753
20751
  users: external_exports.array(FindingUser).optional()
20754
20752
  }).meta({ id: "FindingGroup" });
20755
20753
  var FindingStats = external_exports.object({
@@ -20778,21 +20776,31 @@ var FindingFacets = external_exports.object({
20778
20776
  // counted under no value.
20779
20777
  status: external_exports.array(FindingFacetItem),
20780
20778
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
- // reads, which can filter by it; the grouped read omits the dimension
20779
+ // reads, which can filter by it; the type-level read omits the dimension
20782
20780
  // because a group spans tools.
20783
20781
  tool: external_exports.array(FindingFacetItem).optional()
20784
20782
  }).meta({ id: "FindingFacets" });
20785
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20786
- var ListGroupedFindingsQuery = external_exports.object({
20783
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20784
+ id: "FindingTypeSummary"
20785
+ });
20786
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20787
+ var MAX_FINDING_TYPES_LIMIT = 100;
20788
+ var ListFindingTypesQuery = external_exports.object({
20787
20789
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20788
- // FindingAction.
20790
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20791
+ // firing version carries, and this list pages types.
20792
+ //
20793
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20794
+ // definition versions at different severities, so a type kept by this filter
20795
+ // can hold findings that individually do not match — see totals.findings on
20796
+ // ListFindingTypesResponse, which counts them all.
20789
20797
  severity: external_exports.array(Severity).optional(),
20790
20798
  subtype: external_exports.array(external_exports.string()).optional(),
20791
20799
  provider: external_exports.array(FindingProvider).optional(),
20792
20800
  action: external_exports.array(FindingAction).optional(),
20793
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20794
- // individual instances' — so a filtered group's Status column always reads
20795
- // one of the requested values.
20801
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20802
+ // individual findings' — so a filtered row's status always reads one of the
20803
+ // requested values.
20796
20804
  status: external_exports.array(FindingStatus).optional(),
20797
20805
  q: external_exports.string().optional(),
20798
20806
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20802,23 +20810,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20802
20810
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20803
20811
  // means all time — this list has no default window.
20804
20812
  from: external_exports.iso.datetime().optional(),
20805
- // A group or instance id that must appear in the page even when the cursor
20806
- // has already advanced past its sort position. This is what keeps the
20807
- // Findings page's one-shot ?finding= deep link resolving once the list
20808
- // paginates: the target group is appended out of sort order rather than
20809
- // scanning forward for it. Never affects totals, facets or the cursor.
20813
+ // A RULE id that must appear in the page even when the cursor has already
20814
+ // advanced past its sort position. This is what keeps the selected type
20815
+ // visible in the list once it paginates: the target is appended out of sort
20816
+ // order rather than scanned forward for. Never affects totals, facets or the
20817
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20818
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20819
+ // and so is not bounded by what any page happens to hold.
20810
20820
  includeId: external_exports.string().optional(),
20811
- groupBy: external_exports.literal("type").optional(),
20812
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20821
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20813
20822
  cursor: external_exports.string().optional()
20814
20823
  });
20815
- var ListGroupedFindingsResponse = external_exports.object({
20824
+ var ListFindingTypesResponse = external_exports.object({
20816
20825
  totals: external_exports.object({
20826
+ // Findings belonging to the matching TYPES — not findings that each match
20827
+ // the filters. The filters here select types, so a type that survives
20828
+ // contributes its whole instanceCount.
20829
+ //
20830
+ // `status` is the one exception, narrowed per finding via
20831
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20832
+ // this can exceed what the instance read reports for the same filters: a
20833
+ // rule whose severity moved between versions is kept on its newest and
20834
+ // still counts its older findings. Narrowing the other three needs
20835
+ // per-dimension counts the aggregate does not carry today.
20817
20836
  findings: external_exports.number().int().nonnegative(),
20818
- groups: external_exports.number().int().nonnegative()
20837
+ // Counts TYPES, which is the unit this read pages. The instance read's
20838
+ // own totals count findings; the two deliberately answer different
20839
+ // questions and are never summed.
20840
+ types: external_exports.number().int().nonnegative()
20819
20841
  }),
20820
20842
  facets: FindingFacets,
20821
- items: external_exports.array(FindingGroup),
20843
+ items: external_exports.array(FindingTypeSummary),
20822
20844
  nextCursor: external_exports.string().nullable(),
20823
20845
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20824
20846
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20826,7 +20848,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20826
20848
  // every firing, so the two numbers legitimately differ — this map lets a
20827
20849
  // session-scoped view show both.
20828
20850
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20829
- }).meta({ id: "ListGroupedFindingsResponse" });
20851
+ }).meta({ id: "ListFindingTypesResponse" });
20830
20852
  var ApplyFindingActionRequest = external_exports.object({
20831
20853
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20832
20854
  // it, so it is excluded from the request contract. The mapping helper
@@ -20856,12 +20878,13 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20856
20878
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20857
20879
  var ListFindingInstancesQuery = external_exports.object({
20858
20880
  severity: external_exports.array(Severity).optional(),
20859
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20881
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20882
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20860
20883
  subtype: external_exports.array(external_exports.string()).optional(),
20861
20884
  provider: external_exports.array(FindingProvider).optional(),
20862
20885
  action: external_exports.array(FindingAction).optional(),
20863
20886
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20864
- // the grouped query's group-level fold.
20887
+ // the types query's type-level fold.
20865
20888
  status: external_exports.array(FindingStatus).optional(),
20866
20889
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20867
20890
  // where the free-text `q` can only match the rendered "via Bash" label.
@@ -20878,37 +20901,47 @@ var ListFindingInstancesQuery = external_exports.object({
20878
20901
  });
20879
20902
  var ListFindingInstancesResponse = external_exports.object({
20880
20903
  // Instances matching the filters across the whole scope, not just this
20881
- // page — cursor-independent, like the grouped list's totals.
20904
+ // page — cursor-independent, like the types list's totals.
20882
20905
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20883
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20906
+ // Counts in INSTANCES here, where the types response counts types. Each
20884
20907
  // dimension still excludes its own filter.
20885
20908
  facets: FindingFacets,
20886
20909
  items: external_exports.array(FindingInstanceDetail),
20887
20910
  nextCursor: external_exports.string().nullable()
20888
20911
  }).meta({ id: "ListFindingInstancesResponse" });
20889
- var FindingLocationFile = external_exports.object({
20890
- // Empty when the instances carried no file path (a prompt or a tool call
20891
- // with no file attribution).
20892
- file: external_exports.string(),
20893
- instanceCount: external_exports.number().int().nonnegative(),
20894
- maxSeverity: Severity,
20895
- latestDetectedAt: external_exports.iso.datetime(),
20896
- // Folded from the instances' derived statuses with the same
20897
- // open-dominates precedence a group uses.
20898
- status: FindingStatus.optional(),
20899
- // Distinct rules seen at this location, capped — the row shows them as
20900
- // chips, and the count is what conveys scale.
20901
- ruleIds: external_exports.array(external_exports.string())
20902
- }).meta({ id: "FindingLocationFile" });
20903
- var FindingLocationRepo = external_exports.object({
20912
+ var FindingLocationSummary = external_exports.object({
20913
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20914
+ // because a location's identity is two values and a URL param carries one:
20915
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20916
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20917
+ // client's page dedupe — never decoded, and never a sort key.
20918
+ id: external_exports.string(),
20904
20919
  /** Empty when the instances carried no repo attribute. */
20905
20920
  repo: external_exports.string(),
20921
+ // Empty when the instances carried no file path (a prompt, or a tool call
20922
+ // with no file attribution). Both halves empty is a real location — usually
20923
+ // the largest one in a store — and is selectable like any other.
20924
+ file: external_exports.string(),
20906
20925
  instanceCount: external_exports.number().int().nonnegative(),
20926
+ // The WORST severity present, not the first row's. It is this list's primary
20927
+ // sort key, so it is also what explains why a row is where it is, and it is
20928
+ // how a reader decides what to open without opening everything.
20907
20929
  maxSeverity: Severity,
20908
20930
  latestDetectedAt: external_exports.iso.datetime(),
20931
+ // Folded from the instances' derived statuses with the same open-dominates
20932
+ // precedence a group uses, so it answers "is anything left to do here" and
20933
+ // not much more: a location holding 1 open among 40 resolved reads like one
20934
+ // holding 40 open. That loss is accepted — the panel beside this list
20935
+ // carries each finding's own status, and instanceCount sits next to the
20936
+ // badge.
20909
20937
  status: FindingStatus.optional(),
20910
- files: external_exports.array(FindingLocationFile)
20911
- }).meta({ id: "FindingLocationRepo" });
20938
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20939
+ // tally rather than a sample and a row can say how many there are. Bounded
20940
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20941
+ ruleIds: external_exports.array(external_exports.string())
20942
+ }).meta({ id: "FindingLocationSummary" });
20943
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20944
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20912
20945
  var ListFindingLocationsQuery = external_exports.object({
20913
20946
  severity: external_exports.array(Severity).optional(),
20914
20947
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20921,18 +20954,42 @@ var ListFindingLocationsQuery = external_exports.object({
20921
20954
  q: external_exports.string().optional(),
20922
20955
  sessionId: external_exports.string().optional(),
20923
20956
  from: external_exports.iso.datetime().optional(),
20924
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
20957
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
20958
+ // even when the cursor has already advanced past its sort position — the
20959
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
20960
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
20961
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
20962
+ // into the thousands, a selection sitting off page 0 is the ordinary case
20963
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
20964
+ includeId: external_exports.string().optional(),
20965
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
20966
+ cursor: external_exports.string().optional()
20925
20967
  });
20926
20968
  var ListFindingLocationsResponse = external_exports.object({
20927
20969
  totals: external_exports.object({
20970
+ // Findings matching the filters across the whole scope. Unlike the types
20971
+ // read's same-named field this needs no caveat: the filters here narrow
20972
+ // per finding, so this is the sum of every row's instanceCount.
20928
20973
  findings: external_exports.number().int().nonnegative(),
20929
- repos: external_exports.number().int().nonnegative(),
20930
- files: external_exports.number().int().nonnegative()
20974
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
20975
+ // states. The facets beside it count FINDINGS (see below); a surface
20976
+ // showing both says which is which.
20977
+ locations: external_exports.number().int().nonnegative()
20931
20978
  }),
20932
- /** Sorted by max severity, then most recent. */
20933
- items: external_exports.array(FindingLocationRepo),
20934
- /** Whether `limit` truncated the repo list. */
20935
- hasMore: external_exports.boolean()
20979
+ // Counts in FINDINGS, where the types response counts types, each dimension
20980
+ // still excluding its own filter. Deliberately not locations: counting those
20981
+ // needs a set of location keys per dimension per value — memory tracking the
20982
+ // store times the vocabulary, in a read whose scan promises flat memory —
20983
+ // and the cheap per-location version is not an approximation but WRONG. A
20984
+ // location holding {claudecode, block} and {codex, warn} would survive
20985
+ // provider=claudecode AND action=warn, under which no single finding
20986
+ // matches, so the facet would contradict the instanceCount this whole view
20987
+ // rests on. Findings also keep the toolbar in the same unit as the page
20988
+ // tally and the panel it sits above.
20989
+ facets: FindingFacets,
20990
+ /** Sorted by max severity, then most recent, then (repo, file). */
20991
+ items: external_exports.array(FindingLocationSummary),
20992
+ nextCursor: external_exports.string().nullable()
20936
20993
  }).meta({ id: "ListFindingLocationsResponse" });
20937
20994
 
20938
20995
  // ../../packages/schema/src/zod/meta.ts
@@ -22101,6 +22158,14 @@ var ControlPlaneErrorBody = external_exports.object({
22101
22158
  message: external_exports.string().optional()
22102
22159
  }).optional()
22103
22160
  });
22161
+ var RemoteFailureKind = external_exports.enum([
22162
+ "unauthorized",
22163
+ "forbidden",
22164
+ "route-absent",
22165
+ "invalid-request",
22166
+ "rejected",
22167
+ "unreachable"
22168
+ ]);
22104
22169
  var AttachDeviceRequest = external_exports.object({
22105
22170
  // This machine's own continuity id, so re-attaching ROTATES the credential
22106
22171
  // on one machine record instead of producing a second one. Client-minted
@@ -22794,139 +22859,62 @@ function deriveFindingStatus(row) {
22794
22859
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22795
22860
  return "open";
22796
22861
  }
22797
- function distinctUsers(instances) {
22798
- const seen = /* @__PURE__ */ new Set();
22799
- const users = [];
22800
- for (const i of instances) {
22801
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22802
- seen.add(i.user.id);
22803
- users.push(i.user);
22804
- }
22805
- return users;
22806
- }
22807
22862
  function sortUsers(users) {
22808
22863
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22809
22864
  }
22810
- function buildFindingGroups(rows, opts = {}) {
22811
- const overrides = opts.overrides;
22865
+ function buildFindingTypes(aggregates, opts = {}) {
22812
22866
  const packNames = opts.packNames;
22813
- const aggregates = opts.aggregates;
22814
- const byRuleId = /* @__PURE__ */ new Map();
22815
- for (const row of rows) {
22816
- const existing = byRuleId.get(row.ruleId);
22817
- if (existing) existing.push(row);
22818
- else byRuleId.set(row.ruleId, [row]);
22819
- }
22820
- const groups = [];
22821
- for (const [ruleId, ruleRows] of byRuleId) {
22822
- const instances = ruleRows.map((r) => {
22823
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22824
- return {
22825
- id: r.id,
22826
- provider: toApiProvider(r.sourceTool),
22827
- repo: r.repo,
22828
- file: r.file,
22829
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22830
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22831
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22832
- ...r.user === void 0 ? {} : { user: r.user },
22833
- action: toApiAction(effectiveDbAction),
22834
- detectedAt: r.occurredAt,
22835
- confidence: r.confidence,
22836
- status: r.status
22837
- };
22838
- });
22839
- const agg = aggregates?.get(ruleId);
22840
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22841
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22842
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22843
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22844
- );
22845
- const seenProviders = /* @__PURE__ */ new Set();
22846
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22847
- if (seenProviders.has(p)) return false;
22848
- seenProviders.add(p);
22849
- return true;
22850
- });
22851
- const actionSet = new Set(
22852
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22853
- );
22867
+ const types = [];
22868
+ for (const [ruleId, agg] of aggregates) {
22869
+ const users = sortUsers(agg.users ?? []);
22870
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
22871
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22854
22872
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22855
- const severity = ruleRows[0]?.severity ?? "low";
22856
- const detection = {
22857
- id: ruleId,
22858
- name: packNames?.get(ruleId) ?? null
22859
- };
22860
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22861
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22862
- const match = {
22863
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22864
- contextPrefix: ""
22865
- // empty (pending privacy review)
22866
- };
22867
- const status = foldGroupStatus(
22868
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22869
- );
22870
- const group = {
22873
+ const apiCategory = toApiCategory(agg.category ?? "custom");
22874
+ const type = {
22871
22875
  id: ruleId,
22872
22876
  category: apiCategory,
22873
22877
  subtype: ruleId,
22874
22878
  // human label comes with pack metadata later
22875
- severity,
22876
- match,
22877
- detection,
22878
- policy,
22879
- instanceCount: agg?.instanceCount ?? instances.length,
22879
+ severity: agg.severity ?? "low",
22880
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
22881
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
22882
+ instanceCount: agg.instanceCount,
22880
22883
  providers,
22881
22884
  aggregateAction,
22882
- latestDetectedAt,
22883
- instances,
22884
- status,
22885
+ latestDetectedAt: agg.latestDetectedAt,
22886
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22885
22887
  ...users.length > 0 ? { users } : {}
22886
22888
  };
22887
- if (agg) {
22888
- actionsCache.set(group, [...actionSet]);
22889
- if (agg.searchText !== void 0) {
22890
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22891
- }
22889
+ actionsCache.set(type, [...actionSet]);
22890
+ if (agg.searchText !== void 0) {
22891
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22892
22892
  }
22893
- groups.push(group);
22893
+ types.push(type);
22894
22894
  }
22895
- return groups;
22895
+ return types;
22896
22896
  }
22897
22897
  var haystackCache = /* @__PURE__ */ new WeakMap();
22898
- function buildHaystack(g, extra) {
22898
+ function buildHaystack(t, extra) {
22899
22899
  return [
22900
- g.subtype,
22901
- g.category,
22902
- g.match.maskedValue,
22903
- g.policy.name,
22904
- g.id,
22905
- ...g.instances.map((i) => i.repo),
22906
- ...g.instances.map((i) => i.file),
22907
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22908
- ...g.instances.map((i) => i.id),
22909
- // The people: the whole group's list when the store folded one, plus the
22910
- // preview's own — the two overlap, and a haystack does not mind.
22911
- ...(g.users ?? []).map((u) => u.name),
22912
- ...g.instances.map((i) => i.user?.name ?? ""),
22900
+ t.subtype,
22901
+ t.category,
22902
+ t.policy.name,
22903
+ t.id,
22904
+ ...(t.users ?? []).map((u) => u.name),
22913
22905
  ...extra === void 0 ? [] : [extra]
22914
22906
  ].join(" ").toLowerCase();
22915
22907
  }
22916
- function groupHaystack(g) {
22917
- const cached2 = haystackCache.get(g);
22908
+ function typeHaystack(t) {
22909
+ const cached2 = haystackCache.get(t);
22918
22910
  if (cached2 !== void 0) return cached2;
22919
- const haystack = buildHaystack(g);
22920
- haystackCache.set(g, haystack);
22911
+ const haystack = buildHaystack(t);
22912
+ haystackCache.set(t, haystack);
22921
22913
  return haystack;
22922
22914
  }
22923
22915
  var actionsCache = /* @__PURE__ */ new WeakMap();
22924
- function groupActions(g) {
22925
- const cached2 = actionsCache.get(g);
22926
- if (cached2 !== void 0) return cached2;
22927
- const actions = [...new Set(g.instances.map((i) => i.action))];
22928
- actionsCache.set(g, actions);
22929
- return actions;
22916
+ function typeActions(t) {
22917
+ return actionsCache.get(t) ?? [];
22930
22918
  }
22931
22919
  function countInstancesByStatus(statusInputs, statuses) {
22932
22920
  const statusSet = new Set(statuses);
@@ -22937,8 +22925,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22937
22925
  }
22938
22926
  return sum;
22939
22927
  }
22940
- function applyFindingFilters(groups, opts) {
22941
- let filtered = groups;
22928
+ function applyFindingFilters(types, opts) {
22929
+ let filtered = types;
22942
22930
  if (opts.severity && opts.severity.length > 0) {
22943
22931
  const sevSet = new Set(opts.severity);
22944
22932
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22949,7 +22937,7 @@ function applyFindingFilters(groups, opts) {
22949
22937
  }
22950
22938
  if (opts.actions && opts.actions.length > 0) {
22951
22939
  const actionSet = new Set(opts.actions);
22952
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
22940
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22953
22941
  }
22954
22942
  if (opts.subtype && opts.subtype.length > 0) {
22955
22943
  const subtypeSet = new Set(opts.subtype);
@@ -22961,7 +22949,7 @@ function applyFindingFilters(groups, opts) {
22961
22949
  }
22962
22950
  if (opts.q) {
22963
22951
  const q = opts.q.toLowerCase();
22964
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
22952
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22965
22953
  }
22966
22954
  return filtered;
22967
22955
  }
@@ -22976,11 +22964,11 @@ function compareFindingGroupOrder(a, b) {
22976
22964
  if (recencyDiff !== 0) return recencyDiff;
22977
22965
  return a.id.localeCompare(b.id);
22978
22966
  }
22979
- function sortFindingGroups(groups) {
22980
- return [...groups].sort(compareFindingGroupOrder);
22967
+ function sortFindingTypes(types) {
22968
+ return [...types].sort(compareFindingGroupOrder);
22981
22969
  }
22982
- function computeFindingFacets(allGroups, opts) {
22983
- const forSeverity = applyFindingFilters(allGroups, {
22970
+ function computeFindingFacets(allTypes, opts) {
22971
+ const forSeverity = applyFindingFilters(allTypes, {
22984
22972
  providers: opts.providers,
22985
22973
  actions: opts.actions,
22986
22974
  statuses: opts.statuses,
@@ -22991,7 +22979,7 @@ function computeFindingFacets(allGroups, opts) {
22991
22979
  for (const g of forSeverity) {
22992
22980
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22993
22981
  }
22994
- const forProvider = applyFindingFilters(allGroups, {
22982
+ const forProvider = applyFindingFilters(allTypes, {
22995
22983
  actions: opts.actions,
22996
22984
  statuses: opts.statuses,
22997
22985
  q: opts.q,
@@ -23002,7 +22990,7 @@ function computeFindingFacets(allGroups, opts) {
23002
22990
  for (const g of forProvider) {
23003
22991
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23004
22992
  }
23005
- const forAction = applyFindingFilters(allGroups, {
22993
+ const forAction = applyFindingFilters(allTypes, {
23006
22994
  providers: opts.providers,
23007
22995
  statuses: opts.statuses,
23008
22996
  q: opts.q,
@@ -23011,9 +22999,9 @@ function computeFindingFacets(allGroups, opts) {
23011
22999
  });
23012
23000
  const actionMap = /* @__PURE__ */ new Map();
23013
23001
  for (const g of forAction) {
23014
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23002
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23015
23003
  }
23016
- const forSubtype = applyFindingFilters(allGroups, {
23004
+ const forSubtype = applyFindingFilters(allTypes, {
23017
23005
  providers: opts.providers,
23018
23006
  actions: opts.actions,
23019
23007
  statuses: opts.statuses,
@@ -23022,7 +23010,7 @@ function computeFindingFacets(allGroups, opts) {
23022
23010
  });
23023
23011
  const subtypeMap = /* @__PURE__ */ new Map();
23024
23012
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23025
- const forStatus = applyFindingFilters(allGroups, {
23013
+ const forStatus = applyFindingFilters(allTypes, {
23026
23014
  providers: opts.providers,
23027
23015
  actions: opts.actions,
23028
23016
  q: opts.q,
@@ -23070,10 +23058,20 @@ function matchesDimension(row, opts, dimension) {
23070
23058
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23071
23059
  case "tools":
23072
23060
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23061
+ // An EMPTY value is a real filter here, not an absent one. The location
23062
+ // list buckets a finding whose event recorded no repo — or no file — under
23063
+ // the empty string, and selecting that bucket has to narrow the panel to
23064
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23065
+ // row omits the key, which every call site already does.
23066
+ //
23067
+ // Reading '' as unset is what this replaced, and it failed in the one place
23068
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23069
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23070
+ // — a row reading 3 findings beside a panel listing every finding there is.
23073
23071
  case "repo":
23074
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23072
+ return opts.repo === void 0 || row.repo === opts.repo;
23075
23073
  case "file":
23076
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23074
+ return opts.file === void 0 || row.file === opts.file;
23077
23075
  case "q":
23078
23076
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23079
23077
  }
@@ -23187,6 +23185,23 @@ function addToLocation(acc, row) {
23187
23185
  acc.statuses.push(row.status);
23188
23186
  acc.ruleIds.add(row.ruleId);
23189
23187
  }
23188
+ function compareLocationOrder(a, b) {
23189
+ const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23190
+ const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23191
+ if (rankA !== rankB) return rankA - rankB;
23192
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23193
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23194
+ }
23195
+ if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23196
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23197
+ return 0;
23198
+ }
23199
+ function encodeLocationId(repo, file2) {
23200
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23201
+ }
23202
+ function encodePart(value) {
23203
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23204
+ }
23190
23205
 
23191
23206
  // ../../packages/schema/src/zod/installed-pack.ts
23192
23207
  var InstalledPack = external_exports.object({
@@ -23693,11 +23708,11 @@ var WorkspaceSettings = external_exports.object({
23693
23708
  // covers the current payload and must be re-granted.
23694
23709
  modelJudgeConsent: ModelJudgeConsent.optional(),
23695
23710
  // Records that the user consented to the DEFERRED send — the outbox — along
23696
- // with the payload shape and the endpoint they agreed to. Since payload v2
23697
- // that covers both the pre-attach backlog and undelivered captures (which
23698
- // carry prompt/reply text in `content`); the key name predates the widening.
23699
- // Absent until granted, and a grant for a different endpoint or an older
23700
- // payload no longer counts.
23711
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23712
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23713
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23714
+ // both widenings. Absent until granted, and a grant for a different endpoint
23715
+ // or an older payload no longer counts.
23701
23716
  historySyncConsent: HistorySyncConsent.optional()
23702
23717
  });
23703
23718
  function defaultWorkspaceSettings() {
@@ -23828,6 +23843,9 @@ var ManagedSettingKey = external_exports.enum([
23828
23843
  "dataSharesInPlace",
23829
23844
  "redactFallback"
23830
23845
  ]).meta({ id: "ManagedSettingKey" });
23846
+ function isManagedSettingKey(value) {
23847
+ return ManagedSettingKey.safeParse(value).success;
23848
+ }
23831
23849
  var ManagedSettingsValues = external_exports.object({
23832
23850
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
23833
23851
  controlPlane: external_exports.object({
@@ -23852,7 +23870,27 @@ var ManagedSettings = external_exports.object({
23852
23870
  // Which of those the user may not change. A key here with no matching value
23853
23871
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23854
23872
  // the user may still override. The two are separable on purpose.
23855
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23873
+ //
23874
+ // Parsed as NAMES rather than as the enum, and split below: a name this
23875
+ // build does not know is dropped from the locked set and reported, never a
23876
+ // reason to refuse the file. The same shape reaches an older build whenever
23877
+ // an administrator locks a key a newer build added, and refusing it there
23878
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
23879
+ // the fleets most likely to carry a version skew. A name outside the enum
23880
+ // is still never HONOURED: the lockable set stays explicit above.
23881
+ lockedFields: external_exports.array(external_exports.string()).default([])
23882
+ }).transform(({ lockedFields, ...rest }) => {
23883
+ const known = [];
23884
+ const unknown2 = [];
23885
+ for (const name of lockedFields) {
23886
+ if (isManagedSettingKey(name)) known.push(name);
23887
+ else unknown2.push(name);
23888
+ }
23889
+ return {
23890
+ ...rest,
23891
+ lockedFields: known,
23892
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
23893
+ };
23856
23894
  }).meta({ id: "ManagedSettings" });
23857
23895
 
23858
23896
  // ../../packages/schema/src/zod/project-files.ts
@@ -23976,7 +24014,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23976
24014
  timestamp: external_exports.iso.date(),
23977
24015
  critical: external_exports.number().int().nonnegative(),
23978
24016
  high: external_exports.number().int().nonnegative(),
23979
- medium: external_exports.number().int().nonnegative()
24017
+ medium: external_exports.number().int().nonnegative(),
24018
+ // Optional and additive, so a producer written against the earlier
24019
+ // three-series contract keeps validating. A consumer plotting it resolves the
24020
+ // absent case itself — the chart point requires a number.
24021
+ low: external_exports.number().int().nonnegative().optional()
23980
24022
  }).meta({ id: "FindingsTimeseriesPoint" });
23981
24023
  var FindingsTimeseriesResponse = external_exports.object({
23982
24024
  range: TimeRange,
@@ -24002,6 +24044,10 @@ var ResolvedFeedItem = external_exports.object({
24002
24044
  findingKey: external_exports.string(),
24003
24045
  ruleId: external_exports.string(),
24004
24046
  severity: Severity,
24047
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24048
+ // identifies the file: a bare path matches the same name in every repo.
24049
+ // Optional and additive; empty when the event carried no repo.
24050
+ repo: external_exports.string().optional(),
24005
24051
  path: external_exports.string(),
24006
24052
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24007
24053
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -25575,7 +25621,8 @@ var SqliteActivityRepository = class {
25575
25621
  SELECT 1 FROM audit_events d
25576
25622
  WHERE d.root_session_id = audit_events.id
25577
25623
  AND (d.content LIKE ? ESCAPE '\\'
25578
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
25624
+ OR coalesce(json_extract(d.attributes, '$.detail'),
25625
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25579
25626
  );
25580
25627
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25581
25628
  }
@@ -26913,23 +26960,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26913
26960
  )`;
26914
26961
 
26915
26962
  // ../../packages/persistence/src/repositories/findings.ts
26916
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26917
- var DEFAULT_LOCATIONS_LIMIT = 100;
26918
- var LOCATION_RULE_IDS_CAP = 20;
26919
- function compareLocationOrder(a, b) {
26920
- return compareFindingGroupOrder(
26921
- {
26922
- severity: a.maxSeverity,
26923
- latestDetectedAt: a.latestDetectedAt,
26924
- id: ""
26925
- },
26926
- {
26927
- severity: b.maxSeverity,
26928
- latestDetectedAt: b.latestDetectedAt,
26929
- id: ""
26930
- }
26931
- );
26932
- }
26933
26963
  var CONCAT_SEP = ",";
26934
26964
  var TUPLE_SEP = "|";
26935
26965
  function splitConcat(value) {
@@ -26981,13 +27011,48 @@ function decodeGroupCursor(cursor) {
26981
27011
  return null;
26982
27012
  }
26983
27013
  function firstAfter(sorted, cursor) {
26984
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
27014
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26985
27015
  return index === -1 ? sorted.length : index;
26986
27016
  }
26987
27017
  function findDeepLinked(sorted, page, id) {
26988
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26989
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
27018
+ if (page.some((t) => t.id === id)) return void 0;
27019
+ return sorted.find((t) => t.id === id);
27020
+ }
27021
+ function encodeLocationCursor(location) {
27022
+ const payload = {
27023
+ sev: location.maxSeverity,
27024
+ t: location.latestDetectedAt,
27025
+ r: location.repo,
27026
+ f: location.file
27027
+ };
27028
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
27029
+ }
27030
+ function decodeLocationCursor(cursor) {
27031
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
27032
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
27033
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
27034
+ }
27035
+ return null;
27036
+ }
27037
+ function firstLocationAfter(sorted, cursor) {
27038
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
27039
+ return index === -1 ? sorted.length : index;
27040
+ }
27041
+ function findDeepLinkedLocation(sorted, page, id) {
27042
+ if (page.some((l) => l.id === id)) return void 0;
27043
+ return sorted.find((l) => l.id === id);
26990
27044
  }
27045
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
27046
+ d.severity AS severity, f.masked_match AS masked_match,
27047
+ f.action_taken AS action_taken, f.confidence AS confidence,
27048
+ e.started_at AS occurred_at,
27049
+ e.source_tool AS source_tool,
27050
+ e.repo AS repo,
27051
+ e.file_path AS file,
27052
+ e.tool_name AS tool_name,
27053
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
27054
+ e.event_type AS kind, f.finding_key AS finding_key,
27055
+ ${latestResolutionStatusSql("f")} AS latest_status`;
26991
27056
  var DAY_MS3 = 864e5;
26992
27057
  var SqliteFindingsRepository = class {
26993
27058
  constructor(db) {
@@ -27108,30 +27173,26 @@ var SqliteFindingsRepository = class {
27108
27173
  );
27109
27174
  }
27110
27175
  /**
27111
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27112
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27113
- * attributes bag, rule_id/category/severity from the definition), scoped to
27114
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27115
- * rows this list must never surface), groups by ruleId, computes
27116
- * per-filter-excluded facets, applies the requested filters, and sorts by
27117
- * severity then recency. Filtering
27118
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27119
- * reflect the full filtered set; `items` is the requested
27120
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27121
- * filter, `totals.findings` counts only instances whose derived status was
27122
- * requested, and each item's instance preview is narrowed the same way.
27176
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
27177
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
27178
+ * list must never surface), with per-filter-excluded facets, the requested
27179
+ * filters applied, and sorted by severity then recency. Filtering and faceting
27180
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
27181
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
27182
+ * Under a `status` filter, `totals.findings` counts only findings whose
27183
+ * derived status was requested.
27184
+ *
27185
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
27186
+ * folding EVERY finding into the numbers a type row and the filters need
27187
+ * (count, severity, category, providers, actions, statuses, latest, search
27188
+ * text). The findings OF a type come from listFindingInstances scoped to
27189
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27123
27190
  *
27124
- * Two reads, neither of which materializes a row per finding:
27125
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27126
- * the group and the filters need (count, providers, actions, statuses,
27127
- * latest, search text);
27128
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27129
- * populate `instances` for the table's expanded rows.
27130
27191
  * The aggregates carry raw DB values and are translated by the same
27131
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27132
- * rule is ever restated in SQL.
27192
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
27193
+ * status rule is ever restated in SQL.
27133
27194
  */
27134
- listGroupedFindings(query) {
27195
+ listFindingTypes(query) {
27135
27196
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27136
27197
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27137
27198
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27144,12 +27205,7 @@ var SqliteFindingsRepository = class {
27144
27205
  predicate,
27145
27206
  params: sessionParams
27146
27207
  });
27147
- const rows = this.previewRows(aggregates, {
27148
- sessionId: query.sessionId,
27149
- from: query.from
27150
- });
27151
- const groupable = rows.map(toFlatFindingRow);
27152
- const allGroups = buildFindingGroups(groupable, { aggregates });
27208
+ const allTypes = buildFindingTypes(aggregates);
27153
27209
  const filterOpts = {
27154
27210
  severity: query.severity,
27155
27211
  providers: query.provider,
@@ -27158,30 +27214,25 @@ var SqliteFindingsRepository = class {
27158
27214
  subtype: query.subtype,
27159
27215
  q: query.q
27160
27216
  };
27161
- const facets = computeFindingFacets(allGroups, filterOpts);
27162
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
27217
+ const facets = computeFindingFacets(allTypes, filterOpts);
27218
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27163
27219
  const statusFilter = query.status ?? [];
27164
27220
  const totals = {
27165
- findings: sorted.reduce((acc, g) => {
27166
- if (statusFilter.length === 0) return acc + g.instanceCount;
27167
- const agg = aggregates.get(g.id);
27168
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
27221
+ findings: sorted.reduce((acc, t) => {
27222
+ if (statusFilter.length === 0) return acc + t.instanceCount;
27223
+ const agg = aggregates.get(t.id);
27224
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27169
27225
  }, 0),
27170
- groups: sorted.length
27226
+ types: sorted.length
27171
27227
  };
27172
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
27228
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27173
27229
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27174
27230
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27175
27231
  const page = sorted.slice(start, start + limit);
27176
27232
  const lastOnPage = page.at(-1);
27177
27233
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27178
27234
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27179
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27180
- const narrow = (g) => statusSet ? {
27181
- ...g,
27182
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27183
- } : g;
27184
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
27235
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27185
27236
  return Promise.resolve({
27186
27237
  totals,
27187
27238
  facets,
@@ -27192,7 +27243,7 @@ var SqliteFindingsRepository = class {
27192
27243
  }
27193
27244
  /**
27194
27245
  * One row per rule_id, folding EVERY instance of the group into the values
27195
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
27246
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27196
27247
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27197
27248
  *
27198
27249
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27286,13 +27337,25 @@ var SqliteFindingsRepository = class {
27286
27337
  });
27287
27338
  }
27288
27339
  /**
27289
- * The same findings folded by location: repository, then file within it.
27340
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27290
27341
  *
27291
27342
  * The grouping keys come from the capturing event's attributes, which is what
27292
- * the local store relates a finding to — there is no finding↔asset row to
27293
- * group by instead. A repo or file the event did not record folds into the
27294
- * empty-string bucket, which the view renders but does not link, since no
27295
- * filter can name it.
27343
+ * the local store relates a finding to; there is no finding↔asset row to group
27344
+ * by instead. A repo or file the event did not record folds into the
27345
+ * empty-string bucket, which is a real location like any other: it is listed,
27346
+ * it is selectable, and its `?loc=` token is as good as any other row's.
27347
+ *
27348
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
27349
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
27350
+ * list was rebuilt to remove — and two-level pagination inside an
27351
+ * expand/collapse table is what pushed that view to master/detail in the first
27352
+ * place.
27353
+ *
27354
+ * Every filter narrows the FINDINGS and the locations fall out of what
27355
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
27356
+ * reports for the same filters scoped to that pair. The view depends on it:
27357
+ * one toolbar sits over both panels precisely because a location owns none of
27358
+ * its fields.
27296
27359
  */
27297
27360
  listFindingLocations(query) {
27298
27361
  const opts = {
@@ -27304,13 +27367,16 @@ var SqliteFindingsRepository = class {
27304
27367
  tools: query.tool,
27305
27368
  q: query.q
27306
27369
  };
27307
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
27370
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
27371
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27308
27372
  const byRepo = /* @__PURE__ */ new Map();
27373
+ const accumulator = createInstanceFacetAccumulator(opts);
27309
27374
  let total = 0;
27310
27375
  for (const row of this.scanFindingRows({
27311
27376
  sessionId: query.sessionId,
27312
27377
  from: query.from
27313
27378
  })) {
27379
+ accumulator.add(row);
27314
27380
  if (!matchesInstanceFilters(row, opts)) continue;
27315
27381
  total += 1;
27316
27382
  let files = byRepo.get(row.repo);
@@ -27325,103 +27391,35 @@ var SqliteFindingsRepository = class {
27325
27391
  }
27326
27392
  addToLocation(acc, row);
27327
27393
  }
27328
- let fileCount = 0;
27329
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27330
- fileCount += files.size;
27331
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27332
- file: file2,
27333
- instanceCount: acc.instanceCount,
27334
- maxSeverity: acc.maxSeverity,
27335
- latestDetectedAt: acc.latestDetectedAt,
27336
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27337
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27338
- })).sort(compareLocationOrder);
27339
- const rollup = fileRows.reduce(
27340
- (a, f) => ({
27341
- instanceCount: a.instanceCount + f.instanceCount,
27342
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27343
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27344
- }),
27345
- {
27346
- instanceCount: 0,
27347
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27348
- latestDetectedAt: ""
27349
- }
27350
- );
27351
- const statuses = fileRows.map((f) => f.status);
27352
- const folded = foldGroupStatus(statuses);
27353
- return {
27354
- repo,
27355
- instanceCount: rollup.instanceCount,
27356
- maxSeverity: rollup.maxSeverity,
27357
- latestDetectedAt: rollup.latestDetectedAt,
27358
- ...folded === void 0 ? {} : { status: folded },
27359
- files: fileRows
27360
- };
27361
- });
27362
- repos.sort(compareLocationOrder);
27394
+ const sorted = [];
27395
+ for (const [repo, files] of byRepo) {
27396
+ for (const [file2, acc] of files) {
27397
+ const status = foldGroupStatus(acc.statuses);
27398
+ sorted.push({
27399
+ id: encodeLocationId(repo, file2),
27400
+ repo,
27401
+ file: file2,
27402
+ instanceCount: acc.instanceCount,
27403
+ maxSeverity: acc.maxSeverity,
27404
+ latestDetectedAt: acc.latestDetectedAt,
27405
+ ...status === void 0 ? {} : { status },
27406
+ ruleIds: [...acc.ruleIds]
27407
+ });
27408
+ }
27409
+ }
27410
+ sorted.sort(compareLocationOrder);
27411
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
27412
+ const page = sorted.slice(start, start + limit);
27413
+ const lastOnPage = page.at(-1);
27414
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
27415
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27363
27416
  return Promise.resolve({
27364
- totals: { findings: total, repos: repos.length, files: fileCount },
27365
- items: repos.slice(0, limit),
27366
- hasMore: repos.length > limit
27417
+ totals: { findings: total, locations: sorted.length },
27418
+ facets: accumulator.facets(),
27419
+ items: [...page, ...deepLinked ? [deepLinked] : []],
27420
+ nextCursor
27367
27421
  });
27368
27422
  }
27369
- /**
27370
- * Each group's newest instances, for the table's expanded rows.
27371
- *
27372
- * ONE index-ordered scan with early termination, and the shape is the point.
27373
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27374
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27375
- * through a temp B-tree to keep a bounded preview of each group, and then
27376
- * sorts the survivors again for the page order. Both sorts grow with the
27377
- * store while the answer does not.
27378
- *
27379
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27380
- * (or the session or window index the scope names — see `findingScanSql`),
27381
- * which is already the order the page wants, and keeps rows per rule until
27382
- * each rule has as many as it can show. The aggregate the caller already holds
27383
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27384
- * per rule, summed, is the number of rows this scan has to find, and it stops
27385
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27386
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27387
- * store with many firing rules widens it. The bound that DOES hold
27388
- * unconditionally is the sorted form's floor: this scan visits at most as
27389
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27390
- * sorted, and stops the moment every rule has its cap, where the sorted form
27391
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27392
- * wanted instances sitting at the tail of the scope — is one pass over
27393
- * everything in scope with a block sort of the id tie-break only, never a
27394
- * sort of the scope, which is still that floor.
27395
- *
27396
- * A row whose rule the aggregate did not see is skipped: the two statements
27397
- * run without a shared snapshot, so a capture landing between them can add a
27398
- * rule here that has no counts there, and the counts are what the group is
27399
- * built from.
27400
- */
27401
- previewRows(aggregates, scope) {
27402
- const wanted = /* @__PURE__ */ new Map();
27403
- let remaining = 0;
27404
- for (const [ruleId, agg] of aggregates) {
27405
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27406
- wanted.set(ruleId, n);
27407
- remaining += n;
27408
- }
27409
- const rows = [];
27410
- if (remaining === 0) return rows;
27411
- const { sql, params } = this.findingScanSql(scope);
27412
- const taken = /* @__PURE__ */ new Map();
27413
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27414
- const want = wanted.get(r.rule_id);
27415
- if (want === void 0) continue;
27416
- const have = taken.get(r.rule_id) ?? 0;
27417
- if (have >= want) continue;
27418
- taken.set(r.rule_id, have + 1);
27419
- rows.push(r);
27420
- remaining -= 1;
27421
- if (remaining === 0) break;
27422
- }
27423
- return rows;
27424
- }
27425
27423
  /**
27426
27424
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27427
27425
  *
@@ -27448,6 +27446,33 @@ var SqliteFindingsRepository = class {
27448
27446
  yield toFlatFindingRow(r);
27449
27447
  }
27450
27448
  }
27449
+ /**
27450
+ * One finding by its own id, or null when no such row exists.
27451
+ *
27452
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
27453
+ * the store — and, unlike anything derived from a list page, it resolves a
27454
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
27455
+ * deep link needs: the id it carries may name a finding thousands of rows
27456
+ * older than anything a first page holds.
27457
+ *
27458
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
27459
+ * RESOLVES an id; whether that row would survive the list's current filters is
27460
+ * a different question, and hiding the target because a filter excludes it is
27461
+ * worse than showing it.
27462
+ *
27463
+ * `groupId` on the result IS the rule id, so this one read answers both "which
27464
+ * type should the list select?" and "what does the drawer show?".
27465
+ */
27466
+ findingInstance(id) {
27467
+ const row = this.db.prepare(
27468
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
27469
+ FROM inspection_findings f
27470
+ JOIN audit_events e ON e.id = f.audit_event_id
27471
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27472
+ WHERE f.id = ?`
27473
+ ).get(id);
27474
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
27475
+ }
27451
27476
  /**
27452
27477
  * The one statement both instance-level scans run: every finding in scope,
27453
27478
  * joined to its event and definition, newest first.
@@ -27481,17 +27506,7 @@ var SqliteFindingsRepository = class {
27481
27506
  conditions.push("e.started_at >= ?");
27482
27507
  params.push(isoToEpochMillis(scope.from));
27483
27508
  }
27484
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27485
- d.severity AS severity, f.masked_match AS masked_match,
27486
- f.action_taken AS action_taken, f.confidence AS confidence,
27487
- e.started_at AS occurred_at,
27488
- e.source_tool AS source_tool,
27489
- e.repo AS repo,
27490
- e.file_path AS file,
27491
- e.tool_name AS tool_name,
27492
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27493
- e.event_type AS kind, f.finding_key AS finding_key,
27494
- ${latestResolutionStatusSql("f")} AS latest_status
27509
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27495
27510
  FROM audit_events e
27496
27511
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27497
27512
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27505,6 +27520,26 @@ var SqliteFindingsRepository = class {
27505
27520
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27506
27521
  const rows = this.db.prepare(
27507
27522
  `SELECT rule_id,
27523
+ -- BARE columns beside max(latest_at), which is deliberate and
27524
+ -- is SQLite's documented behaviour: with a single min()/max()
27525
+ -- in an aggregate query, every bare column takes its value from
27526
+ -- the row that produced the extremum. So these are the severity
27527
+ -- and category of the definition whose finding is NEWEST, which
27528
+ -- is what the row-based build they replaced read off its first
27529
+ -- (newest-first) row.
27530
+ --
27531
+ -- min() is WRONG here and was the defect: inspection_definitions
27532
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
27533
+ -- mints a new row), so a rule whose severity moved between
27534
+ -- versions has several, and min() picks the ALPHABETICALLY
27535
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
27536
+ -- That is arbitrary in direction, and it feeds the badge, the
27537
+ -- filter, the facet counts and the primary sort key.
27538
+ --
27539
+ -- Adding a second min()/max() aggregate here would make these
27540
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
27541
+ severity,
27542
+ category,
27508
27543
  sum(tuple_count) AS instance_count,
27509
27544
  max(latest_at) AS latest_at,
27510
27545
  group_concat(source_tools) AS source_tools,
@@ -27515,6 +27550,14 @@ var SqliteFindingsRepository = class {
27515
27550
  group_concat(tool_names) AS tool_names
27516
27551
  FROM (
27517
27552
  SELECT d.rule_id AS rule_id,
27553
+ -- Severity and category are columns of the DEFINITION, and
27554
+ -- a rule can have SEVERAL definitions (one per version), so
27555
+ -- these are grouped on below and resolved to the newest
27556
+ -- firing version by the outer query's bare-column select.
27557
+ -- They ride the aggregate because the type build has no rows
27558
+ -- to read them off \u2014 see buildFindingTypes.
27559
+ d.severity AS severity,
27560
+ d.category AS category,
27518
27561
  e.event_type || '${TUPLE_SEP}' ||
27519
27562
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27520
27563
  coalesce(latest.status, '') AS status_tuple,
@@ -27529,7 +27572,7 @@ var SqliteFindingsRepository = class {
27529
27572
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27530
27573
  ON latest.finding_key = f.finding_key
27531
27574
  ${scope.predicate}
27532
- GROUP BY d.rule_id, status_tuple
27575
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27533
27576
  )
27534
27577
  GROUP BY rule_id`
27535
27578
  ).all(scope.params);
@@ -27538,6 +27581,8 @@ var SqliteFindingsRepository = class {
27538
27581
  r.rule_id,
27539
27582
  {
27540
27583
  instanceCount: r.instance_count,
27584
+ severity: r.severity,
27585
+ category: r.category,
27541
27586
  sourceTools: splitConcat(r.source_tools),
27542
27587
  actionsTaken: splitConcat(r.actions_taken),
27543
27588
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27554,7 +27599,7 @@ var SqliteFindingsRepository = class {
27554
27599
  latestDetectedAt: epochMillisToIso(r.latest_at),
27555
27600
  // Free text only — joined and substring-matched, so group_concat's
27556
27601
  // commas need no unpicking (a repo/path containing one still matches).
27557
- // Left undefined (not '') when unfetched, so buildFindingGroups can
27602
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27558
27603
  // tell "no q this request" from "a group with no repo/file at all"
27559
27604
  // and skip priming a haystack nothing will read.
27560
27605
  ...withSearchText ? {
@@ -27706,6 +27751,12 @@ var SqliteHistorySyncRepository = class {
27706
27751
  this.markOwedStmt = db.prepare(
27707
27752
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27708
27753
  );
27754
+ this.markCaptureBacklogOwedStmt = db.prepare(
27755
+ `UPDATE audit_events SET outbox_owed = 1
27756
+ WHERE synced_at IS NULL
27757
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27758
+ AND started_at < :before`
27759
+ );
27709
27760
  this.stampStmt = db.prepare(
27710
27761
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27711
27762
  );
@@ -27754,7 +27805,9 @@ var SqliteHistorySyncRepository = class {
27754
27805
  );
27755
27806
  this.disownCapturesStmt = db.prepare(
27756
27807
  `UPDATE audit_events SET outbox_owed = NULL
27757
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27808
+ WHERE outbox_owed IS NOT NULL
27809
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27810
+ AND started_at < :attachedAt`
27758
27811
  );
27759
27812
  this.rearmStmt = db.prepare(
27760
27813
  `UPDATE audit_events SET synced_at = NULL
@@ -27830,6 +27883,7 @@ var SqliteHistorySyncRepository = class {
27830
27883
  freezeBoundaryStmt;
27831
27884
  captureRowsStmt;
27832
27885
  markOwedStmt;
27886
+ markCaptureBacklogOwedStmt;
27833
27887
  captureSkipCountStmt;
27834
27888
  disownCapturesStmt;
27835
27889
  partitionStmt;
@@ -27893,6 +27947,23 @@ var SqliteHistorySyncRepository = class {
27893
27947
  markCaptureOwed(id) {
27894
27948
  this.markOwedStmt.run({ id });
27895
27949
  }
27950
+ /**
27951
+ * Mark every capture already on disk as owed, as of `before`.
27952
+ *
27953
+ * The consent-time backfill, called once from `aka attach` when a human
27954
+ * grants existing-history consent — never from an ongoing drain pass, and
27955
+ * never inferred from a boundary that could later move. `before` is the
27956
+ * caller's own "now" at the moment consent was granted, so what this marks
27957
+ * is exactly the backlog the consent prompt already counted, not whatever a
27958
+ * later re-attach or key rotation might widen it to.
27959
+ *
27960
+ * Returns how many rows matched, for the caller to log or test against. Not a
27961
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
27962
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27963
+ */
27964
+ markCaptureBacklogOwed(before) {
27965
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27966
+ }
27896
27967
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27897
27968
  markSynced(ids, atMs) {
27898
27969
  this.stampAll(ids, atMs);
@@ -28009,15 +28080,42 @@ var SqliteHistorySyncRepository = class {
28009
28080
  *
28010
28081
  * Delivery is a fact about ONE recipient: rows sent to the deployment a
28011
28082
  * machine has just left are undelivered as far as the new one is concerned.
28012
- * All three in one transaction, so a crash between them cannot leave stamps
28013
- * attributed to the wrong deployment, or a boundary that belongs to another.
28083
+ * All four in one transaction, so a crash between them cannot leave stamps
28084
+ * attributed to the wrong deployment, a boundary that belongs to another, or
28085
+ * a disown with no re-mark to follow it.
28014
28086
  *
28015
28087
  * The boundary is written HERE and only here, which is what freezes it: a
28016
28088
  * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28017
28089
  * unchanged, so this never runs and the backlog does not widen back over rows
28018
28090
  * the live path has since delivered.
28091
+ *
28092
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28093
+ * granted existing-history consent for the deployment this call is arming —
28094
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28095
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28096
+ * apart. Passed only when that grant is valid, since this method has no way
28097
+ * to check consent itself and must not mark a row owed for a machine that
28098
+ * never agreed to it. Applied AFTER the disown above, in the SAME
28099
+ * transaction: what the disown clears is every marker below `backlogBefore`,
28100
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28101
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28102
+ * on the cleared side of that bound — and the re-mark in the same
28103
+ * transaction is what puts those rows back. A crash between the two cannot
28104
+ * strand the ledger disowned with nothing re-marked — the transaction either
28105
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
28106
+ * committed re-enters this method on the very next pass. Omit it (the
28107
+ * structural-only tests do) to exercise the disown in isolation.
28108
+ *
28109
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
28110
+ * touching a marker the NEW deployment's OWN live path has already set: B's
28111
+ * live path can mark a capture owed from the moment `aka attach` writes the
28112
+ * descriptor, before the drain's first pass ever reaches this method, and
28113
+ * such a row sits at or after the bound rather than below it. What keeps the
28114
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
28115
+ * bound — disown runs first, re-mark second, both inside the one
28116
+ * transaction above.
28019
28117
  */
28020
- rearmFor(fingerprint, backlogBefore) {
28118
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28021
28119
  this.ensureRowStmt.run();
28022
28120
  withTransaction(
28023
28121
  this.db,
@@ -28025,7 +28123,10 @@ var SqliteHistorySyncRepository = class {
28025
28123
  const previous = getRow(this.fingerprintStmt)?.fingerprint;
28026
28124
  this.rearmStmt.run();
28027
28125
  if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28028
- this.disownCapturesStmt.run();
28126
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28127
+ }
28128
+ if (backfillCapturesBefore !== void 0) {
28129
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28029
28130
  }
28030
28131
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28031
28132
  },
@@ -28302,7 +28403,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28302
28403
  }
28303
28404
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28304
28405
  }
28305
- function readManagedSettings(paths = managedSettingsPaths()) {
28406
+ var testOnlyManagedPaths = null;
28407
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28306
28408
  for (const path of paths) {
28307
28409
  let text;
28308
28410
  try {
@@ -30782,7 +30884,7 @@ function toUtcDateString(ms) {
30782
30884
  return new Date(ms).toISOString().slice(0, 10);
30783
30885
  }
30784
30886
  function isTimeseriesSeverity(s) {
30785
- return s === "critical" || s === "high" || s === "medium";
30887
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30786
30888
  }
30787
30889
  var SqliteSecurityRepository = class {
30788
30890
  constructor(db, now = () => Date.now()) {
@@ -30911,12 +31013,16 @@ var SqliteSecurityRepository = class {
30911
31013
  const now = this.now();
30912
31014
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30913
31015
  const rows = this.findingsInRange(windowStart, now);
30914
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30915
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30916
- critical: 0,
30917
- high: 0,
30918
- medium: 0
30919
- }));
31016
+ const points = Array.from(
31017
+ { length: numBuckets },
31018
+ (_, i) => ({
31019
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31020
+ critical: 0,
31021
+ high: 0,
31022
+ medium: 0,
31023
+ low: 0
31024
+ })
31025
+ );
30920
31026
  for (const r of rows) {
30921
31027
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30922
31028
  const bucket = points[idx];
@@ -31134,6 +31240,7 @@ var SqliteSecurityRepository = class {
31134
31240
  `SELECT f.finding_key AS finding_key,
31135
31241
  d.rule_id AS rule_id,
31136
31242
  d.severity AS severity,
31243
+ e.repo AS repo,
31137
31244
  e.file_path AS path,
31138
31245
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31139
31246
  latest.resolved_at AS latest_resolved_at
@@ -31153,6 +31260,7 @@ var SqliteSecurityRepository = class {
31153
31260
  const items = rows.map((r) => ({
31154
31261
  findingKey: r.finding_key,
31155
31262
  ruleId: r.rule_id,
31263
+ repo: r.repo ?? "",
31156
31264
  severity: r.severity,
31157
31265
  path: r.path ?? "",
31158
31266
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31162,13 +31270,66 @@ var SqliteSecurityRepository = class {
31162
31270
  }));
31163
31271
  return Promise.resolve({ items });
31164
31272
  }
31273
+ /**
31274
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31275
+ *
31276
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31277
+ * list: a secret committed three weeks ago and never rotated is still the most
31278
+ * important thing to fix, and any window hides it. It carried a "newest N
31279
+ * findings" cap and then a range; the first meant a different span on every
31280
+ * machine, and the second reported "no recommendations" over live exposure.
31281
+ *
31282
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31283
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31284
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31285
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31286
+ * The two answer different questions and only this one has to match a link.
31287
+ *
31288
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31289
+ * whole-store scope costs a grouped scan rather than a row per finding.
31290
+ */
31291
+ recommendationInputs() {
31292
+ const rows = allRows(
31293
+ this.db.prepare(
31294
+ `SELECT d.rule_id AS rule_id,
31295
+ d.category AS category,
31296
+ d.severity AS severity,
31297
+ COUNT(*) AS count
31298
+ FROM inspection_findings f
31299
+ JOIN audit_events e ON e.id = f.audit_event_id
31300
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31301
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31302
+ ON latest.finding_key = f.finding_key
31303
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31304
+ AND e.event_type = 'code_change'
31305
+ AND (
31306
+ f.finding_key IS NULL
31307
+ OR latest.status IS NULL
31308
+ OR latest.status NOT IN ('resolved', 'dismissed')
31309
+ )
31310
+ GROUP BY d.rule_id, d.category, d.severity`
31311
+ )
31312
+ );
31313
+ return Promise.resolve(
31314
+ rows.map((r) => ({
31315
+ ruleId: r.rule_id,
31316
+ category: r.category,
31317
+ severity: r.severity,
31318
+ count: r.count
31319
+ }))
31320
+ );
31321
+ }
31165
31322
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31166
31323
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31167
31324
  // numeric and the JS aggregations bucket/split on ms directly.
31168
31325
  findingsInRange(fromMs, toMs) {
31169
31326
  const rows = allRows(
31170
31327
  this.db.prepare(
31171
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31328
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31329
+ // joined for `severity`, so they are two more columns off a row this read
31330
+ // already fetches. They feed the recommended-actions rollup.
31331
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31332
+ d.rule_id AS rule_id, d.category AS category
31172
31333
  FROM inspection_findings f
31173
31334
  JOIN audit_events e ON e.id = f.audit_event_id
31174
31335
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -31181,7 +31342,9 @@ var SqliteSecurityRepository = class {
31181
31342
  return rows.map((r) => ({
31182
31343
  occurredAt: r.occurred_at,
31183
31344
  severity: r.severity,
31184
- actionTaken: r.action_taken
31345
+ actionTaken: r.action_taken,
31346
+ ruleId: r.rule_id,
31347
+ category: r.category
31185
31348
  }));
31186
31349
  }
31187
31350
  };
@@ -32351,14 +32514,51 @@ function openLocalDatabase(dir) {
32351
32514
  };
32352
32515
  }
32353
32516
 
32354
- // ../../packages/persistence/src/finding-key.ts
32517
+ // ../../packages/persistence/src/egress-wire.ts
32355
32518
  import { createHash as createHash3 } from "crypto";
32519
+ function hashProjectKey(projectKey) {
32520
+ return createHash3("sha256").update(projectKey, "utf8").digest("hex");
32521
+ }
32522
+ function toIngestHit(hit) {
32523
+ return {
32524
+ host: hit.host,
32525
+ kind: hit.kind,
32526
+ name: hit.name,
32527
+ category: hit.category,
32528
+ trust: hit.trust,
32529
+ network: hit.network,
32530
+ method: hit.method,
32531
+ transport: hit.transport,
32532
+ url: hit.url,
32533
+ template: hit.template,
32534
+ dataClass: hit.dataClass,
32535
+ site: {
32536
+ file: hit.site.file,
32537
+ line: hit.site.line,
32538
+ dynamic: hit.site.dynamic,
32539
+ vendored: hit.site.vendored
32540
+ }
32541
+ };
32542
+ }
32543
+ function toEgressIngestRequest(input2) {
32544
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32545
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32546
+ return {
32547
+ projectKey: hashProjectKey(input2.projectKey),
32548
+ project: input2.project,
32549
+ reconcile,
32550
+ hits: hits.map(toIngestHit)
32551
+ };
32552
+ }
32553
+
32554
+ // ../../packages/persistence/src/finding-key.ts
32555
+ import { createHash as createHash4 } from "crypto";
32356
32556
  function normalizeFilePath(filePath) {
32357
32557
  return filePath.replaceAll("\\", "/");
32358
32558
  }
32359
32559
  function computeFindingKey(input2) {
32360
32560
  const normalizedPath = normalizeFilePath(input2.filePath);
32361
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32561
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32362
32562
  }
32363
32563
 
32364
32564
  // ../../packages/persistence/src/fingerprint.ts
@@ -32484,14 +32684,18 @@ function fingerprintValue(key, raw) {
32484
32684
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32485
32685
  }
32486
32686
 
32487
- // ../../packages/persistence/src/history-preview.ts
32687
+ // ../../packages/persistence/src/history-backfill.ts
32488
32688
  import { existsSync as existsSync4 } from "fs";
32489
32689
  import { join as join9 } from "path";
32690
+
32691
+ // ../../packages/persistence/src/history-preview.ts
32692
+ import { existsSync as existsSync5 } from "fs";
32693
+ import { join as join10 } from "path";
32490
32694
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32491
32695
 
32492
32696
  // ../../packages/persistence/src/store-symlinks.ts
32493
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32494
- import { dirname as dirname3, join as join10, resolve } from "path";
32697
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32698
+ import { dirname as dirname3, join as join11, resolve } from "path";
32495
32699
 
32496
32700
  // ../../packages/persistence/src/vault/crypto.ts
32497
32701
  import {
@@ -32506,19 +32710,19 @@ import {
32506
32710
  import { execFileSync } from "child_process";
32507
32711
  import { randomBytes as randomBytes2 } from "crypto";
32508
32712
  import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32509
- import { join as join11 } from "path";
32713
+ import { join as join12 } from "path";
32510
32714
 
32511
32715
  // ../../packages/persistence/src/vault/vault.ts
32512
32716
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32513
32717
 
32514
32718
  // ../../packages/persistence/src/warn-era-cap.ts
32515
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32516
- import { join as join12 } from "path";
32719
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32720
+ import { join as join13 } from "path";
32517
32721
  var MARKER = "warn-era-capped";
32518
32722
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32519
32723
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32520
- const marker = join12(dataDir2, MARKER);
32521
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32724
+ const marker = join13(dataDir2, MARKER);
32725
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32522
32726
  const capped = db.policies.capCategoryActions();
32523
32727
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32524
32728
  `, { mode: DATA_FILE_MODE });
@@ -32577,8 +32781,8 @@ function resolveProvider() {
32577
32781
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32578
32782
  try {
32579
32783
  ensureLayoutDirSync(base);
32580
- const settingsFile = join13(settingsDir(base), "settings.json");
32581
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
32784
+ const settingsFile = join14(settingsDir(base), "settings.json");
32785
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
32582
32786
  } catch {
32583
32787
  }
32584
32788
  migrateLegacyLayout(base);
@@ -32603,7 +32807,7 @@ function resolveProviderSafe(resolveProviderFn) {
32603
32807
  // ../../packages/plugin-sdk/src/config-inventory.ts
32604
32808
  import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32605
32809
  import { homedir as homedir2 } from "os";
32606
- import { basename as basename3, join as join15 } from "path";
32810
+ import { basename as basename3, join as join16 } from "path";
32607
32811
 
32608
32812
  // ../../packages/detections/src/egress/registry.ts
32609
32813
  var EXTRACTOR_VERSION = "1";
@@ -36527,8 +36731,8 @@ function bundledDetections() {
36527
36731
  }
36528
36732
 
36529
36733
  // ../../packages/plugin-sdk/src/repo.ts
36530
- import { existsSync as existsSync8, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36531
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join14, sep as sep2 } from "path";
36734
+ import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
36735
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36532
36736
  function resolveRepoIdentity(cwd) {
36533
36737
  try {
36534
36738
  const root = findGitRoot(cwd);
@@ -36557,32 +36761,32 @@ function resolveWorktreeRoot(cwd) {
36557
36761
  function findGitRoot(start) {
36558
36762
  let dir = start;
36559
36763
  for (; ; ) {
36560
- if (existsSync8(join14(dir, ".git"))) return dir;
36764
+ if (existsSync9(join15(dir, ".git"))) return dir;
36561
36765
  const parent = dirname4(dir);
36562
36766
  if (parent === dir) return void 0;
36563
36767
  dir = parent;
36564
36768
  }
36565
36769
  }
36566
36770
  function resolveGitContext(root) {
36567
- const dotGit = join14(root, ".git");
36771
+ const dotGit = join15(root, ".git");
36568
36772
  try {
36569
36773
  if (statSync6(dotGit).isDirectory()) {
36570
- return { configPath: join14(dotGit, "config"), headRoot: root };
36774
+ return { configPath: join15(dotGit, "config"), headRoot: root };
36571
36775
  }
36572
36776
  } catch {
36573
36777
  return void 0;
36574
36778
  }
36575
36779
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36576
36780
  if (!target) return void 0;
36577
- const gitdir = isAbsolute(target) ? target : join14(root, target);
36578
- if (existsSync8(join14(gitdir, "config"))) {
36579
- return { configPath: join14(gitdir, "config"), headRoot: root };
36781
+ const gitdir = isAbsolute(target) ? target : join15(root, target);
36782
+ if (existsSync9(join15(gitdir, "config"))) {
36783
+ return { configPath: join15(gitdir, "config"), headRoot: root };
36580
36784
  }
36581
- const commonRaw = safeRead(join14(gitdir, "commondir"))?.trim();
36785
+ const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
36582
36786
  if (!commonRaw) return void 0;
36583
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join14(gitdir, commonRaw);
36787
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
36584
36788
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36585
- return { configPath: join14(commonGitDir, "config"), headRoot };
36789
+ return { configPath: join15(commonGitDir, "config"), headRoot };
36586
36790
  }
36587
36791
  function safeRead(path) {
36588
36792
  try {
@@ -36624,9 +36828,9 @@ function slugFromUrl(url2) {
36624
36828
  }
36625
36829
 
36626
36830
  // ../../packages/plugin-sdk/src/events.ts
36627
- import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
36831
+ import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36628
36832
  function contentHashOf(text) {
36629
- return createHash4("sha256").update(text).digest("hex");
36833
+ return createHash5("sha256").update(text).digest("hex");
36630
36834
  }
36631
36835
  function buildIngestEvent(input2) {
36632
36836
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -36652,7 +36856,7 @@ function buildIngestEvent(input2) {
36652
36856
  }
36653
36857
 
36654
36858
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36655
- import { existsSync as existsSync9 } from "fs";
36859
+ import { existsSync as existsSync10 } from "fs";
36656
36860
  import { fileURLToPath } from "url";
36657
36861
  import { Worker } from "worker_threads";
36658
36862
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -36666,7 +36870,7 @@ function resolveWorkerUrl() {
36666
36870
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
36667
36871
  const candidate = new URL(name, import.meta.url);
36668
36872
  try {
36669
- if (existsSync9(fileURLToPath(candidate))) {
36873
+ if (existsSync10(fileURLToPath(candidate))) {
36670
36874
  resolvedWorkerUrl = candidate;
36671
36875
  return candidate;
36672
36876
  }
@@ -37129,13 +37333,48 @@ function createGuardedScanner(partition, gateway, opts) {
37129
37333
  };
37130
37334
  }
37131
37335
 
37336
+ // ../../packages/plugin-sdk/src/host-floor.ts
37337
+ import { readFileSync as readFileSync11 } from "fs";
37338
+ import { join as join18 } from "path";
37339
+
37340
+ // ../../packages/plugin-sdk/src/model-governance.ts
37341
+ import {
37342
+ closeSync as closeSync2,
37343
+ fstatSync,
37344
+ mkdirSync as mkdirSync2,
37345
+ openSync as openSync2,
37346
+ readFileSync as readFileSync10,
37347
+ readSync,
37348
+ writeFileSync as writeFileSync5
37349
+ } from "fs";
37350
+ import { join as join17 } from "path";
37351
+ var TAIL_BYTES = 256 * 1024;
37352
+
37353
+ // ../../packages/plugin-sdk/src/host-floor.ts
37354
+ var HOST_FEATURE = {
37355
+ ModelSwitch: "model-switch",
37356
+ VaultPointerDisplay: "vault-pointer-display"
37357
+ };
37358
+ var HOST_FLOORS = {
37359
+ [HOST_FEATURE.ModelSwitch]: {
37360
+ label: "model-switch protection",
37361
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37362
+ since: "2.1.251"
37363
+ },
37364
+ [HOST_FEATURE.VaultPointerDisplay]: {
37365
+ label: "vault pointer display",
37366
+ hookEvents: ["MessageDisplay"],
37367
+ since: "2.1.152"
37368
+ }
37369
+ };
37370
+
37132
37371
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37133
37372
  var import_ignore = __toESM(require_ignore(), 1);
37134
- import { readFileSync as readFileSync10 } from "fs";
37135
- import { join as join16 } from "path";
37373
+ import { readFileSync as readFileSync12 } from "fs";
37374
+ import { join as join19 } from "path";
37136
37375
  function readIgnoreLayer(dir, filename, anchorLen) {
37137
37376
  try {
37138
- return { matcher: (0, import_ignore.default)().add(readFileSync10(join16(dir, filename), "utf8")), anchorLen };
37377
+ return { matcher: (0, import_ignore.default)().add(readFileSync12(join19(dir, filename), "utf8")), anchorLen };
37139
37378
  } catch {
37140
37379
  return void 0;
37141
37380
  }
@@ -37165,22 +37404,9 @@ function withLayer(layers, layer) {
37165
37404
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
37166
37405
  import { arch, hostname as hostname4, platform, release } from "os";
37167
37406
 
37168
- // ../../packages/plugin-sdk/src/model-governance.ts
37169
- import {
37170
- closeSync as closeSync2,
37171
- fstatSync,
37172
- mkdirSync as mkdirSync2,
37173
- openSync as openSync2,
37174
- readFileSync as readFileSync11,
37175
- readSync,
37176
- writeFileSync as writeFileSync5
37177
- } from "fs";
37178
- import { join as join17 } from "path";
37179
- var TAIL_BYTES = 256 * 1024;
37180
-
37181
37407
  // ../../packages/plugin-sdk/src/nudge.ts
37182
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
37183
- import { join as join18 } from "path";
37408
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
37409
+ import { join as join20 } from "path";
37184
37410
 
37185
37411
  // ../../packages/plugin-sdk/src/paths.ts
37186
37412
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37252,8 +37478,8 @@ function createPolicyResolver(bundle) {
37252
37478
  }
37253
37479
 
37254
37480
  // ../../packages/plugin-sdk/src/project-files.ts
37255
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
37256
- import { basename as basename5, join as join19 } from "path";
37481
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37482
+ import { basename as basename5, join as join21 } from "path";
37257
37483
 
37258
37484
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37259
37485
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37284,6 +37510,14 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
37284
37510
  // ../../packages/plugin-sdk/src/runtime.ts
37285
37511
  import { randomUUID as randomUUID14 } from "crypto";
37286
37512
  var ENFORCEMENT_CEILING_ENABLED = false;
37513
+ function applyEnforcementCeiling(action, policyMode, enabled) {
37514
+ if (!enabled || policyMode !== "warn") return action;
37515
+ return action === "block" || action === "redact" ? "warn" : action;
37516
+ }
37517
+ function resolveEnforcedAction(action, opts) {
37518
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
37519
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
37520
+ }
37287
37521
  function startTiming() {
37288
37522
  try {
37289
37523
  return performance.now();
@@ -37392,12 +37626,12 @@ function createPluginRuntime(gateway, settings, opts) {
37392
37626
  }
37393
37627
  function actionForFinding(finding, excepted, rewritable = true) {
37394
37628
  if (excepted?.has(finding)) return "allow";
37395
- const action = resolveAction(finding.ruleId, finding.category);
37396
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
37397
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
37398
- return "warn";
37399
- }
37400
- return action;
37629
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
37630
+ policyMode,
37631
+ redactFallback,
37632
+ rewritable,
37633
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
37634
+ });
37401
37635
  }
37402
37636
  function decide(findings, text, excepted, rewritable = true) {
37403
37637
  if (findings.length === 0) return { action: "log", text, findings: [] };
@@ -37646,11 +37880,11 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37646
37880
 
37647
37881
  // ../../packages/plugin-sdk/src/throttle.ts
37648
37882
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37649
- import { join as join20 } from "path";
37883
+ import { join as join22 } from "path";
37650
37884
 
37651
37885
  // ../../packages/scanner/src/discover.ts
37652
37886
  import { readdirSync as readdirSync5 } from "fs";
37653
- import { join as join21 } from "path";
37887
+ import { join as join23 } from "path";
37654
37888
 
37655
37889
  // ../../packages/scanner/src/constants.ts
37656
37890
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -37695,7 +37929,7 @@ function discoverGitRepos(opts) {
37695
37929
  if (!entry.isDirectory()) continue;
37696
37930
  if (DISCOVER_SKIP.has(entry.name)) continue;
37697
37931
  if (entry.name.startsWith(".")) continue;
37698
- visit2(join21(dir, entry.name), depth + 1);
37932
+ visit2(join23(dir, entry.name), depth + 1);
37699
37933
  }
37700
37934
  }
37701
37935
  for (const root of searchRoots) {
@@ -37798,46 +38032,9 @@ function renderMultiRepoSummary(summary, opts = {}) {
37798
38032
  }
37799
38033
 
37800
38034
  // ../../packages/scanner/src/scan.ts
37801
- import { existsSync as existsSync11, readFileSync as readFileSync19 } from "fs";
38035
+ import { existsSync as existsSync12, readFileSync as readFileSync20 } from "fs";
37802
38036
  import { extname as extname2, isAbsolute as isAbsolute2, relative as relative3 } from "path";
37803
38037
 
37804
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
37805
- import { createHash as createHash5 } from "crypto";
37806
- function hashProjectKey(projectKey) {
37807
- return createHash5("sha256").update(projectKey, "utf8").digest("hex");
37808
- }
37809
- function toIngestHit(hit) {
37810
- return {
37811
- host: hit.host,
37812
- kind: hit.kind,
37813
- name: hit.name,
37814
- category: hit.category,
37815
- trust: hit.trust,
37816
- network: hit.network,
37817
- method: hit.method,
37818
- transport: hit.transport,
37819
- url: hit.url,
37820
- template: hit.template,
37821
- dataClass: hit.dataClass,
37822
- site: {
37823
- file: hit.site.file,
37824
- line: hit.site.line,
37825
- dynamic: hit.site.dynamic,
37826
- vendored: hit.site.vendored
37827
- }
37828
- };
37829
- }
37830
- function toEgressIngestRequest(input2) {
37831
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
37832
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
37833
- return {
37834
- projectKey: hashProjectKey(input2.projectKey),
37835
- project: input2.project,
37836
- reconcile,
37837
- hits: hits.map(toIngestHit)
37838
- };
37839
- }
37840
-
37841
38038
  // ../../packages/remote/src/http.ts
37842
38039
  import { request as httpRequest } from "http";
37843
38040
  import { request as httpsRequest } from "https";
@@ -38117,6 +38314,7 @@ function createRemoteClient(options) {
38117
38314
  url: url2(ROUTES.shares),
38118
38315
  body: JSON.stringify(validated.data)
38119
38316
  });
38317
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
38120
38318
  okBody(response);
38121
38319
  },
38122
38320
  async pollCommand() {
@@ -38139,19 +38337,51 @@ function createRemoteClient(options) {
38139
38337
  };
38140
38338
  }
38141
38339
 
38142
- // ../../packages/plugin-runtime/src/attached/failure.ts
38340
+ // ../../packages/remote/src/failure-kind.ts
38143
38341
  function statusOf(err) {
38144
38342
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
38145
38343
  const { status } = err;
38146
38344
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
38147
38345
  return status >= 100 && status <= 599 ? status : null;
38148
38346
  }
38149
- function classifyFailure(err) {
38150
- switch (statusOf(err)) {
38347
+ function nameOf(err) {
38348
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
38349
+ return typeof err.name === "string" ? err.name : null;
38350
+ }
38351
+ function classifyRemoteFailure(err) {
38352
+ switch (nameOf(err)) {
38353
+ case "RemoteRouteAbsent":
38354
+ return "route-absent";
38355
+ case "RemoteRequestInvalid":
38356
+ return "invalid-request";
38357
+ case "RemoteResponseInvalid":
38358
+ return "rejected";
38359
+ default:
38360
+ break;
38361
+ }
38362
+ const status = statusOf(err);
38363
+ if (status === null) return "unreachable";
38364
+ switch (status) {
38151
38365
  case 401:
38152
38366
  return "unauthorized";
38153
38367
  case 403:
38154
38368
  return "forbidden";
38369
+ case 429:
38370
+ return "unreachable";
38371
+ case 404:
38372
+ return "unreachable";
38373
+ default:
38374
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
38375
+ }
38376
+ }
38377
+
38378
+ // ../../packages/plugin-runtime/src/attached/failure.ts
38379
+ function classifyFailure(err) {
38380
+ switch (classifyRemoteFailure(err)) {
38381
+ case "unauthorized":
38382
+ return "unauthorized";
38383
+ case "forbidden":
38384
+ return "forbidden";
38155
38385
  default:
38156
38386
  return "unreachable";
38157
38387
  }
@@ -38173,11 +38403,11 @@ function withTimeout(promise2, ms) {
38173
38403
  }
38174
38404
 
38175
38405
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
38176
- import { readFileSync as readFileSync13 } from "fs";
38177
- import { join as join22 } from "path";
38406
+ import { readFileSync as readFileSync14 } from "fs";
38407
+ import { join as join24 } from "path";
38178
38408
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
38179
38409
  function forwardDropsPath(dataDir2) {
38180
- return join22(dataDir2, FORWARD_DROPS_FILENAME);
38410
+ return join24(dataDir2, FORWARD_DROPS_FILENAME);
38181
38411
  }
38182
38412
  function recordForwardDrops(dataDir2, count, nowMs) {
38183
38413
  if (count <= 0) return;
@@ -38195,7 +38425,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
38195
38425
  }
38196
38426
  function readForwardDrops(dataDir2) {
38197
38427
  try {
38198
- const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
38428
+ const parsed2 = JSON.parse(readFileSync14(forwardDropsPath(dataDir2), "utf8"));
38199
38429
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
38200
38430
  const record2 = parsed2;
38201
38431
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -38213,9 +38443,9 @@ function readForwardDrops(dataDir2) {
38213
38443
 
38214
38444
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
38215
38445
  import { randomUUID as randomUUID15 } from "crypto";
38216
- import { readFileSync as readFileSync14 } from "fs";
38446
+ import { readFileSync as readFileSync15 } from "fs";
38217
38447
  import { readFile, rename, writeFile } from "fs/promises";
38218
- import { join as join23 } from "path";
38448
+ import { join as join25 } from "path";
38219
38449
  function isInvalidRequest(err) {
38220
38450
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
38221
38451
  }
@@ -38253,7 +38483,7 @@ function parseBreakerState(raw, nowMs) {
38253
38483
  }
38254
38484
  function createForwardPolicy(deps) {
38255
38485
  const now = deps.now ?? (() => Date.now());
38256
- const file2 = join23(deps.dir, STATE_FILENAME);
38486
+ const file2 = join25(deps.dir, STATE_FILENAME);
38257
38487
  let state = null;
38258
38488
  let loading = null;
38259
38489
  async function readState() {
@@ -38975,8 +39205,8 @@ function toolAuditEvent(input2) {
38975
39205
  }
38976
39206
 
38977
39207
  // ../../packages/plugin-runtime/src/attached/history-state.ts
38978
- import { readFileSync as readFileSync15 } from "fs";
38979
- import { join as join24 } from "path";
39208
+ import { readFileSync as readFileSync16 } from "fs";
39209
+ import { join as join26 } from "path";
38980
39210
 
38981
39211
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
38982
39212
  import { createHash as createHash6 } from "crypto";
@@ -38993,7 +39223,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
38993
39223
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
38994
39224
 
38995
39225
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
38996
- import { readFileSync as readFileSync16 } from "fs";
39226
+ import { readFileSync as readFileSync17 } from "fs";
38997
39227
  function createPluginBlock(build, policyStore) {
38998
39228
  return async () => {
38999
39229
  const cached2 = await policyStore.read();
@@ -39012,7 +39242,7 @@ function createPluginBlock(build, policyStore) {
39012
39242
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39013
39243
  import { randomUUID as randomUUID16 } from "crypto";
39014
39244
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39015
- import { join as join25 } from "path";
39245
+ import { join as join27 } from "path";
39016
39246
 
39017
39247
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39018
39248
  import { rename as rename2 } from "fs/promises";
@@ -39036,7 +39266,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39036
39266
 
39037
39267
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39038
39268
  function createPolicyStore(dir = dataDir()) {
39039
- const file2 = join25(dir, "policy-cache.json");
39269
+ const file2 = join27(dir, "policy-cache.json");
39040
39270
  async function read() {
39041
39271
  try {
39042
39272
  const raw = await readFile2(file2, "utf8");
@@ -39267,11 +39497,11 @@ function readStorePosture(dbPath2) {
39267
39497
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39268
39498
  import { randomUUID as randomUUID17 } from "crypto";
39269
39499
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39270
- import { join as join26 } from "path";
39500
+ import { join as join28 } from "path";
39271
39501
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39272
39502
  function createPostureStore(dir = settingsDir(), legacyDir) {
39273
- const file2 = join26(dir, "posture-state.json");
39274
- const legacyFile = legacyDir === void 0 ? null : join26(legacyDir, "posture-state.json");
39503
+ const file2 = join28(dir, "posture-state.json");
39504
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
39275
39505
  async function persist(state) {
39276
39506
  await ensureDataDir(dir);
39277
39507
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39339,8 +39569,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39339
39569
  }
39340
39570
 
39341
39571
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39342
- import { readFileSync as readFileSync17 } from "fs";
39343
- import { join as join27 } from "path";
39572
+ import { readFileSync as readFileSync18 } from "fs";
39573
+ import { join as join29 } from "path";
39344
39574
 
39345
39575
  // ../../packages/plugin-runtime/src/attached/status.ts
39346
39576
  var REFUSAL_LINES = {
@@ -39814,8 +40044,8 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
39814
40044
  import { statSync as statSync11 } from "fs";
39815
40045
 
39816
40046
  // ../../packages/scanner/src/walk.ts
39817
- import { readdirSync as readdirSync6, readFileSync as readFileSync18, statSync as statSync10 } from "fs";
39818
- import { extname, join as join28, relative as relative2, sep as sep4 } from "path";
40047
+ import { readdirSync as readdirSync6, readFileSync as readFileSync19, statSync as statSync10 } from "fs";
40048
+ import { extname, join as join30, relative as relative2, sep as sep4 } from "path";
39819
40049
  var import_ignore2 = __toESM(require_ignore(), 1);
39820
40050
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
39821
40051
  ".ts",
@@ -39866,7 +40096,7 @@ function* walkTree(rootDir, opts = {}) {
39866
40096
  );
39867
40097
  for (const entry of dirents) {
39868
40098
  const name = entry.name;
39869
- const fullPath = join28(dir, name);
40099
+ const fullPath = join30(dir, name);
39870
40100
  if (entry.isDirectory()) {
39871
40101
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
39872
40102
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {
@@ -39920,7 +40150,7 @@ function* walkSourceFiles(opts = {}) {
39920
40150
  if (opts.shouldRead && !opts.shouldRead(meta4)) continue;
39921
40151
  let content;
39922
40152
  try {
39923
- content = readFileSync18(file2.path, "utf8");
40153
+ content = readFileSync19(file2.path, "utf8");
39924
40154
  } catch {
39925
40155
  continue;
39926
40156
  }
@@ -40040,7 +40270,7 @@ function isUnderRoot(path, rootDir) {
40040
40270
  async function sweepDeletedFiles(gateway, rootDir, previous) {
40041
40271
  const deleted = [];
40042
40272
  for (const path of previous.keys()) {
40043
- if (!isUnderRoot(path, rootDir) || existsSync11(path)) continue;
40273
+ if (!isUnderRoot(path, rootDir) || existsSync12(path)) continue;
40044
40274
  deleted.push(path);
40045
40275
  await resolveRemovedFindings(gateway, path, [], { deleted: true });
40046
40276
  }
@@ -40147,7 +40377,7 @@ function scanManifests(egress, ledger, updates, rootDir) {
40147
40377
  if (prev?.mtime === manifest.mtime) continue;
40148
40378
  let content;
40149
40379
  try {
40150
- content = readFileSync19(manifest.path, "utf8");
40380
+ content = readFileSync20(manifest.path, "utf8");
40151
40381
  } catch {
40152
40382
  continue;
40153
40383
  }