@akasecurity/ai-tc-codex 0.9.10 → 0.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -491,9 +491,6 @@ var require_ignore = __commonJS({
491
491
  }
492
492
  });
493
493
 
494
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
495
- import { createHash as createHash4 } from "crypto";
496
-
497
494
  // ../../packages/persistence/src/attached-derived.ts
498
495
  import { rmSync } from "fs";
499
496
  import { join } from "path";
@@ -20742,13 +20739,11 @@ var FindingGroup = external_exports.object({
20742
20739
  latestDetectedAt: external_exports.iso.datetime(),
20743
20740
  instances: external_exports.array(FindingInstance),
20744
20741
  // Derived from instances' statuses with open-dominates precedence (see
20745
- // buildFindingGroups). Undefined only when no instance carries a status.
20742
+ // foldGroupStatus). Undefined only when no instance carries a status.
20746
20743
  status: FindingStatus.optional(),
20747
- // The distinct people across the WHOLE group, not just the `instances`
20748
- // preview — from the store's whole-group aggregate when it supplies one,
20749
- // else folded from the rows (see buildFindingGroups). Undefined when no
20750
- // instance carries a user, or when the store supplied whole-group folds
20751
- // without one.
20744
+ // The distinct people across the WHOLE group, not just the instances
20745
+ // carried here. Undefined when no instance carries a user, or when the
20746
+ // store supplied whole-group folds without one.
20752
20747
  users: external_exports.array(FindingUser).optional()
20753
20748
  }).meta({ id: "FindingGroup" });
20754
20749
  var FindingStats = external_exports.object({
@@ -20777,21 +20772,31 @@ var FindingFacets = external_exports.object({
20777
20772
  // counted under no value.
20778
20773
  status: external_exports.array(FindingFacetItem),
20779
20774
  // Host tool (attributes.tool_name). Present only on the instance-level
20780
- // reads, which can filter by it; the grouped read omits the dimension
20775
+ // reads, which can filter by it; the type-level read omits the dimension
20781
20776
  // because a group spans tools.
20782
20777
  tool: external_exports.array(FindingFacetItem).optional()
20783
20778
  }).meta({ id: "FindingFacets" });
20784
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20785
- var ListGroupedFindingsQuery = external_exports.object({
20779
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20780
+ id: "FindingTypeSummary"
20781
+ });
20782
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20783
+ var MAX_FINDING_TYPES_LIMIT = 100;
20784
+ var ListFindingTypesQuery = external_exports.object({
20786
20785
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20787
- // FindingAction.
20786
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20787
+ // firing version carries, and this list pages types.
20788
+ //
20789
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20790
+ // definition versions at different severities, so a type kept by this filter
20791
+ // can hold findings that individually do not match — see totals.findings on
20792
+ // ListFindingTypesResponse, which counts them all.
20788
20793
  severity: external_exports.array(Severity).optional(),
20789
20794
  subtype: external_exports.array(external_exports.string()).optional(),
20790
20795
  provider: external_exports.array(FindingProvider).optional(),
20791
20796
  action: external_exports.array(FindingAction).optional(),
20792
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20793
- // individual instances' — so a filtered group's Status column always reads
20794
- // one of the requested values.
20797
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20798
+ // individual findings' — so a filtered row's status always reads one of the
20799
+ // requested values.
20795
20800
  status: external_exports.array(FindingStatus).optional(),
20796
20801
  q: external_exports.string().optional(),
20797
20802
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20801,23 +20806,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20801
20806
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20802
20807
  // means all time — this list has no default window.
20803
20808
  from: external_exports.iso.datetime().optional(),
20804
- // A group or instance id that must appear in the page even when the cursor
20805
- // has already advanced past its sort position. This is what keeps the
20806
- // Findings page's one-shot ?finding= deep link resolving once the list
20807
- // paginates: the target group is appended out of sort order rather than
20808
- // scanning forward for it. Never affects totals, facets or the cursor.
20809
+ // A RULE id that must appear in the page even when the cursor has already
20810
+ // advanced past its sort position. This is what keeps the selected type
20811
+ // visible in the list once it paginates: the target is appended out of sort
20812
+ // order rather than scanned forward for. Never affects totals, facets or the
20813
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20814
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20815
+ // and so is not bounded by what any page happens to hold.
20809
20816
  includeId: external_exports.string().optional(),
20810
- groupBy: external_exports.literal("type").optional(),
20811
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20817
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20812
20818
  cursor: external_exports.string().optional()
20813
20819
  });
20814
- var ListGroupedFindingsResponse = external_exports.object({
20820
+ var ListFindingTypesResponse = external_exports.object({
20815
20821
  totals: external_exports.object({
20822
+ // Findings belonging to the matching TYPES — not findings that each match
20823
+ // the filters. The filters here select types, so a type that survives
20824
+ // contributes its whole instanceCount.
20825
+ //
20826
+ // `status` is the one exception, narrowed per finding via
20827
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20828
+ // this can exceed what the instance read reports for the same filters: a
20829
+ // rule whose severity moved between versions is kept on its newest and
20830
+ // still counts its older findings. Narrowing the other three needs
20831
+ // per-dimension counts the aggregate does not carry today.
20816
20832
  findings: external_exports.number().int().nonnegative(),
20817
- groups: external_exports.number().int().nonnegative()
20833
+ // Counts TYPES, which is the unit this read pages. The instance read's
20834
+ // own totals count findings; the two deliberately answer different
20835
+ // questions and are never summed.
20836
+ types: external_exports.number().int().nonnegative()
20818
20837
  }),
20819
20838
  facets: FindingFacets,
20820
- items: external_exports.array(FindingGroup),
20839
+ items: external_exports.array(FindingTypeSummary),
20821
20840
  nextCursor: external_exports.string().nullable(),
20822
20841
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20823
20842
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20825,7 +20844,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20825
20844
  // every firing, so the two numbers legitimately differ — this map lets a
20826
20845
  // session-scoped view show both.
20827
20846
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20828
- }).meta({ id: "ListGroupedFindingsResponse" });
20847
+ }).meta({ id: "ListFindingTypesResponse" });
20829
20848
  var ApplyFindingActionRequest = external_exports.object({
20830
20849
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20831
20850
  // it, so it is excluded from the request contract. The mapping helper
@@ -20855,12 +20874,13 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20855
20874
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20856
20875
  var ListFindingInstancesQuery = external_exports.object({
20857
20876
  severity: external_exports.array(Severity).optional(),
20858
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20877
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20878
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20859
20879
  subtype: external_exports.array(external_exports.string()).optional(),
20860
20880
  provider: external_exports.array(FindingProvider).optional(),
20861
20881
  action: external_exports.array(FindingAction).optional(),
20862
20882
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20863
- // the grouped query's group-level fold.
20883
+ // the types query's type-level fold.
20864
20884
  status: external_exports.array(FindingStatus).optional(),
20865
20885
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20866
20886
  // where the free-text `q` can only match the rendered "via Bash" label.
@@ -20877,37 +20897,47 @@ var ListFindingInstancesQuery = external_exports.object({
20877
20897
  });
20878
20898
  var ListFindingInstancesResponse = external_exports.object({
20879
20899
  // Instances matching the filters across the whole scope, not just this
20880
- // page — cursor-independent, like the grouped list's totals.
20900
+ // page — cursor-independent, like the types list's totals.
20881
20901
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20882
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20902
+ // Counts in INSTANCES here, where the types response counts types. Each
20883
20903
  // dimension still excludes its own filter.
20884
20904
  facets: FindingFacets,
20885
20905
  items: external_exports.array(FindingInstanceDetail),
20886
20906
  nextCursor: external_exports.string().nullable()
20887
20907
  }).meta({ id: "ListFindingInstancesResponse" });
20888
- var FindingLocationFile = external_exports.object({
20889
- // Empty when the instances carried no file path (a prompt or a tool call
20890
- // with no file attribution).
20891
- file: external_exports.string(),
20892
- instanceCount: external_exports.number().int().nonnegative(),
20893
- maxSeverity: Severity,
20894
- latestDetectedAt: external_exports.iso.datetime(),
20895
- // Folded from the instances' derived statuses with the same
20896
- // open-dominates precedence a group uses.
20897
- status: FindingStatus.optional(),
20898
- // Distinct rules seen at this location, capped — the row shows them as
20899
- // chips, and the count is what conveys scale.
20900
- ruleIds: external_exports.array(external_exports.string())
20901
- }).meta({ id: "FindingLocationFile" });
20902
- var FindingLocationRepo = external_exports.object({
20908
+ var FindingLocationSummary = external_exports.object({
20909
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20910
+ // because a location's identity is two values and a URL param carries one:
20911
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20912
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20913
+ // client's page dedupe — never decoded, and never a sort key.
20914
+ id: external_exports.string(),
20903
20915
  /** Empty when the instances carried no repo attribute. */
20904
20916
  repo: external_exports.string(),
20917
+ // Empty when the instances carried no file path (a prompt, or a tool call
20918
+ // with no file attribution). Both halves empty is a real location — usually
20919
+ // the largest one in a store — and is selectable like any other.
20920
+ file: external_exports.string(),
20905
20921
  instanceCount: external_exports.number().int().nonnegative(),
20922
+ // The WORST severity present, not the first row's. It is this list's primary
20923
+ // sort key, so it is also what explains why a row is where it is, and it is
20924
+ // how a reader decides what to open without opening everything.
20906
20925
  maxSeverity: Severity,
20907
20926
  latestDetectedAt: external_exports.iso.datetime(),
20927
+ // Folded from the instances' derived statuses with the same open-dominates
20928
+ // precedence a group uses, so it answers "is anything left to do here" and
20929
+ // not much more: a location holding 1 open among 40 resolved reads like one
20930
+ // holding 40 open. That loss is accepted — the panel beside this list
20931
+ // carries each finding's own status, and instanceCount sits next to the
20932
+ // badge.
20908
20933
  status: FindingStatus.optional(),
20909
- files: external_exports.array(FindingLocationFile)
20910
- }).meta({ id: "FindingLocationRepo" });
20934
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20935
+ // tally rather than a sample and a row can say how many there are. Bounded
20936
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20937
+ ruleIds: external_exports.array(external_exports.string())
20938
+ }).meta({ id: "FindingLocationSummary" });
20939
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20940
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20911
20941
  var ListFindingLocationsQuery = external_exports.object({
20912
20942
  severity: external_exports.array(Severity).optional(),
20913
20943
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20920,18 +20950,42 @@ var ListFindingLocationsQuery = external_exports.object({
20920
20950
  q: external_exports.string().optional(),
20921
20951
  sessionId: external_exports.string().optional(),
20922
20952
  from: external_exports.iso.datetime().optional(),
20923
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
20953
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
20954
+ // even when the cursor has already advanced past its sort position — the
20955
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
20956
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
20957
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
20958
+ // into the thousands, a selection sitting off page 0 is the ordinary case
20959
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
20960
+ includeId: external_exports.string().optional(),
20961
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
20962
+ cursor: external_exports.string().optional()
20924
20963
  });
20925
20964
  var ListFindingLocationsResponse = external_exports.object({
20926
20965
  totals: external_exports.object({
20966
+ // Findings matching the filters across the whole scope. Unlike the types
20967
+ // read's same-named field this needs no caveat: the filters here narrow
20968
+ // per finding, so this is the sum of every row's instanceCount.
20927
20969
  findings: external_exports.number().int().nonnegative(),
20928
- repos: external_exports.number().int().nonnegative(),
20929
- files: external_exports.number().int().nonnegative()
20970
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
20971
+ // states. The facets beside it count FINDINGS (see below); a surface
20972
+ // showing both says which is which.
20973
+ locations: external_exports.number().int().nonnegative()
20930
20974
  }),
20931
- /** Sorted by max severity, then most recent. */
20932
- items: external_exports.array(FindingLocationRepo),
20933
- /** Whether `limit` truncated the repo list. */
20934
- hasMore: external_exports.boolean()
20975
+ // Counts in FINDINGS, where the types response counts types, each dimension
20976
+ // still excluding its own filter. Deliberately not locations: counting those
20977
+ // needs a set of location keys per dimension per value — memory tracking the
20978
+ // store times the vocabulary, in a read whose scan promises flat memory —
20979
+ // and the cheap per-location version is not an approximation but WRONG. A
20980
+ // location holding {claudecode, block} and {codex, warn} would survive
20981
+ // provider=claudecode AND action=warn, under which no single finding
20982
+ // matches, so the facet would contradict the instanceCount this whole view
20983
+ // rests on. Findings also keep the toolbar in the same unit as the page
20984
+ // tally and the panel it sits above.
20985
+ facets: FindingFacets,
20986
+ /** Sorted by max severity, then most recent, then (repo, file). */
20987
+ items: external_exports.array(FindingLocationSummary),
20988
+ nextCursor: external_exports.string().nullable()
20935
20989
  }).meta({ id: "ListFindingLocationsResponse" });
20936
20990
 
20937
20991
  // ../../packages/schema/src/zod/meta.ts
@@ -22100,6 +22154,14 @@ var ControlPlaneErrorBody = external_exports.object({
22100
22154
  message: external_exports.string().optional()
22101
22155
  }).optional()
22102
22156
  });
22157
+ var RemoteFailureKind = external_exports.enum([
22158
+ "unauthorized",
22159
+ "forbidden",
22160
+ "route-absent",
22161
+ "invalid-request",
22162
+ "rejected",
22163
+ "unreachable"
22164
+ ]);
22103
22165
  var AttachDeviceRequest = external_exports.object({
22104
22166
  // This machine's own continuity id, so re-attaching ROTATES the credential
22105
22167
  // on one machine record instead of producing a second one. Client-minted
@@ -22793,139 +22855,62 @@ function deriveFindingStatus(row) {
22793
22855
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22794
22856
  return "open";
22795
22857
  }
22796
- function distinctUsers(instances) {
22797
- const seen = /* @__PURE__ */ new Set();
22798
- const users = [];
22799
- for (const i of instances) {
22800
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22801
- seen.add(i.user.id);
22802
- users.push(i.user);
22803
- }
22804
- return users;
22805
- }
22806
22858
  function sortUsers(users) {
22807
22859
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22808
22860
  }
22809
- function buildFindingGroups(rows, opts = {}) {
22810
- const overrides = opts.overrides;
22861
+ function buildFindingTypes(aggregates, opts = {}) {
22811
22862
  const packNames = opts.packNames;
22812
- const aggregates = opts.aggregates;
22813
- const byRuleId = /* @__PURE__ */ new Map();
22814
- for (const row of rows) {
22815
- const existing = byRuleId.get(row.ruleId);
22816
- if (existing) existing.push(row);
22817
- else byRuleId.set(row.ruleId, [row]);
22818
- }
22819
- const groups = [];
22820
- for (const [ruleId, ruleRows] of byRuleId) {
22821
- const instances = ruleRows.map((r) => {
22822
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22823
- return {
22824
- id: r.id,
22825
- provider: toApiProvider(r.sourceTool),
22826
- repo: r.repo,
22827
- file: r.file,
22828
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22829
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22830
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22831
- ...r.user === void 0 ? {} : { user: r.user },
22832
- action: toApiAction(effectiveDbAction),
22833
- detectedAt: r.occurredAt,
22834
- confidence: r.confidence,
22835
- status: r.status
22836
- };
22837
- });
22838
- const agg = aggregates?.get(ruleId);
22839
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22840
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22841
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22842
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22843
- );
22844
- const seenProviders = /* @__PURE__ */ new Set();
22845
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22846
- if (seenProviders.has(p)) return false;
22847
- seenProviders.add(p);
22848
- return true;
22849
- });
22850
- const actionSet = new Set(
22851
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22852
- );
22863
+ const types = [];
22864
+ for (const [ruleId, agg] of aggregates) {
22865
+ const users = sortUsers(agg.users ?? []);
22866
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
22867
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22853
22868
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22854
- const severity = ruleRows[0]?.severity ?? "low";
22855
- const detection = {
22856
- id: ruleId,
22857
- name: packNames?.get(ruleId) ?? null
22858
- };
22859
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22860
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22861
- const match = {
22862
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22863
- contextPrefix: ""
22864
- // empty (pending privacy review)
22865
- };
22866
- const status = foldGroupStatus(
22867
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22868
- );
22869
- const group = {
22869
+ const apiCategory = toApiCategory(agg.category ?? "custom");
22870
+ const type = {
22870
22871
  id: ruleId,
22871
22872
  category: apiCategory,
22872
22873
  subtype: ruleId,
22873
22874
  // human label comes with pack metadata later
22874
- severity,
22875
- match,
22876
- detection,
22877
- policy,
22878
- instanceCount: agg?.instanceCount ?? instances.length,
22875
+ severity: agg.severity ?? "low",
22876
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
22877
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
22878
+ instanceCount: agg.instanceCount,
22879
22879
  providers,
22880
22880
  aggregateAction,
22881
- latestDetectedAt,
22882
- instances,
22883
- status,
22881
+ latestDetectedAt: agg.latestDetectedAt,
22882
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22884
22883
  ...users.length > 0 ? { users } : {}
22885
22884
  };
22886
- if (agg) {
22887
- actionsCache.set(group, [...actionSet]);
22888
- if (agg.searchText !== void 0) {
22889
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22890
- }
22885
+ actionsCache.set(type, [...actionSet]);
22886
+ if (agg.searchText !== void 0) {
22887
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22891
22888
  }
22892
- groups.push(group);
22889
+ types.push(type);
22893
22890
  }
22894
- return groups;
22891
+ return types;
22895
22892
  }
22896
22893
  var haystackCache = /* @__PURE__ */ new WeakMap();
22897
- function buildHaystack(g, extra) {
22894
+ function buildHaystack(t, extra) {
22898
22895
  return [
22899
- g.subtype,
22900
- g.category,
22901
- g.match.maskedValue,
22902
- g.policy.name,
22903
- g.id,
22904
- ...g.instances.map((i) => i.repo),
22905
- ...g.instances.map((i) => i.file),
22906
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22907
- ...g.instances.map((i) => i.id),
22908
- // The people: the whole group's list when the store folded one, plus the
22909
- // preview's own — the two overlap, and a haystack does not mind.
22910
- ...(g.users ?? []).map((u) => u.name),
22911
- ...g.instances.map((i) => i.user?.name ?? ""),
22896
+ t.subtype,
22897
+ t.category,
22898
+ t.policy.name,
22899
+ t.id,
22900
+ ...(t.users ?? []).map((u) => u.name),
22912
22901
  ...extra === void 0 ? [] : [extra]
22913
22902
  ].join(" ").toLowerCase();
22914
22903
  }
22915
- function groupHaystack(g) {
22916
- const cached2 = haystackCache.get(g);
22904
+ function typeHaystack(t) {
22905
+ const cached2 = haystackCache.get(t);
22917
22906
  if (cached2 !== void 0) return cached2;
22918
- const haystack = buildHaystack(g);
22919
- haystackCache.set(g, haystack);
22907
+ const haystack = buildHaystack(t);
22908
+ haystackCache.set(t, haystack);
22920
22909
  return haystack;
22921
22910
  }
22922
22911
  var actionsCache = /* @__PURE__ */ new WeakMap();
22923
- function groupActions(g) {
22924
- const cached2 = actionsCache.get(g);
22925
- if (cached2 !== void 0) return cached2;
22926
- const actions = [...new Set(g.instances.map((i) => i.action))];
22927
- actionsCache.set(g, actions);
22928
- return actions;
22912
+ function typeActions(t) {
22913
+ return actionsCache.get(t) ?? [];
22929
22914
  }
22930
22915
  function countInstancesByStatus(statusInputs, statuses) {
22931
22916
  const statusSet = new Set(statuses);
@@ -22936,8 +22921,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22936
22921
  }
22937
22922
  return sum;
22938
22923
  }
22939
- function applyFindingFilters(groups, opts) {
22940
- let filtered = groups;
22924
+ function applyFindingFilters(types, opts) {
22925
+ let filtered = types;
22941
22926
  if (opts.severity && opts.severity.length > 0) {
22942
22927
  const sevSet = new Set(opts.severity);
22943
22928
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22948,7 +22933,7 @@ function applyFindingFilters(groups, opts) {
22948
22933
  }
22949
22934
  if (opts.actions && opts.actions.length > 0) {
22950
22935
  const actionSet = new Set(opts.actions);
22951
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
22936
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22952
22937
  }
22953
22938
  if (opts.subtype && opts.subtype.length > 0) {
22954
22939
  const subtypeSet = new Set(opts.subtype);
@@ -22960,7 +22945,7 @@ function applyFindingFilters(groups, opts) {
22960
22945
  }
22961
22946
  if (opts.q) {
22962
22947
  const q = opts.q.toLowerCase();
22963
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
22948
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22964
22949
  }
22965
22950
  return filtered;
22966
22951
  }
@@ -22975,11 +22960,11 @@ function compareFindingGroupOrder(a, b) {
22975
22960
  if (recencyDiff !== 0) return recencyDiff;
22976
22961
  return a.id.localeCompare(b.id);
22977
22962
  }
22978
- function sortFindingGroups(groups) {
22979
- return [...groups].sort(compareFindingGroupOrder);
22963
+ function sortFindingTypes(types) {
22964
+ return [...types].sort(compareFindingGroupOrder);
22980
22965
  }
22981
- function computeFindingFacets(allGroups, opts) {
22982
- const forSeverity = applyFindingFilters(allGroups, {
22966
+ function computeFindingFacets(allTypes, opts) {
22967
+ const forSeverity = applyFindingFilters(allTypes, {
22983
22968
  providers: opts.providers,
22984
22969
  actions: opts.actions,
22985
22970
  statuses: opts.statuses,
@@ -22990,7 +22975,7 @@ function computeFindingFacets(allGroups, opts) {
22990
22975
  for (const g of forSeverity) {
22991
22976
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22992
22977
  }
22993
- const forProvider = applyFindingFilters(allGroups, {
22978
+ const forProvider = applyFindingFilters(allTypes, {
22994
22979
  actions: opts.actions,
22995
22980
  statuses: opts.statuses,
22996
22981
  q: opts.q,
@@ -23001,7 +22986,7 @@ function computeFindingFacets(allGroups, opts) {
23001
22986
  for (const g of forProvider) {
23002
22987
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23003
22988
  }
23004
- const forAction = applyFindingFilters(allGroups, {
22989
+ const forAction = applyFindingFilters(allTypes, {
23005
22990
  providers: opts.providers,
23006
22991
  statuses: opts.statuses,
23007
22992
  q: opts.q,
@@ -23010,9 +22995,9 @@ function computeFindingFacets(allGroups, opts) {
23010
22995
  });
23011
22996
  const actionMap = /* @__PURE__ */ new Map();
23012
22997
  for (const g of forAction) {
23013
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
22998
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23014
22999
  }
23015
- const forSubtype = applyFindingFilters(allGroups, {
23000
+ const forSubtype = applyFindingFilters(allTypes, {
23016
23001
  providers: opts.providers,
23017
23002
  actions: opts.actions,
23018
23003
  statuses: opts.statuses,
@@ -23021,7 +23006,7 @@ function computeFindingFacets(allGroups, opts) {
23021
23006
  });
23022
23007
  const subtypeMap = /* @__PURE__ */ new Map();
23023
23008
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23024
- const forStatus = applyFindingFilters(allGroups, {
23009
+ const forStatus = applyFindingFilters(allTypes, {
23025
23010
  providers: opts.providers,
23026
23011
  actions: opts.actions,
23027
23012
  q: opts.q,
@@ -23069,10 +23054,20 @@ function matchesDimension(row, opts, dimension) {
23069
23054
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23070
23055
  case "tools":
23071
23056
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23057
+ // An EMPTY value is a real filter here, not an absent one. The location
23058
+ // list buckets a finding whose event recorded no repo — or no file — under
23059
+ // the empty string, and selecting that bucket has to narrow the panel to
23060
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23061
+ // row omits the key, which every call site already does.
23062
+ //
23063
+ // Reading '' as unset is what this replaced, and it failed in the one place
23064
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23065
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23066
+ // — a row reading 3 findings beside a panel listing every finding there is.
23072
23067
  case "repo":
23073
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23068
+ return opts.repo === void 0 || row.repo === opts.repo;
23074
23069
  case "file":
23075
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23070
+ return opts.file === void 0 || row.file === opts.file;
23076
23071
  case "q":
23077
23072
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23078
23073
  }
@@ -23186,6 +23181,23 @@ function addToLocation(acc, row) {
23186
23181
  acc.statuses.push(row.status);
23187
23182
  acc.ruleIds.add(row.ruleId);
23188
23183
  }
23184
+ function compareLocationOrder(a, b) {
23185
+ const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23186
+ const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23187
+ if (rankA !== rankB) return rankA - rankB;
23188
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23189
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23190
+ }
23191
+ if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23192
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23193
+ return 0;
23194
+ }
23195
+ function encodeLocationId(repo, file2) {
23196
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23197
+ }
23198
+ function encodePart(value) {
23199
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23200
+ }
23189
23201
 
23190
23202
  // ../../packages/schema/src/zod/installed-pack.ts
23191
23203
  var InstalledPack = external_exports.object({
@@ -23692,11 +23704,11 @@ var WorkspaceSettings = external_exports.object({
23692
23704
  // covers the current payload and must be re-granted.
23693
23705
  modelJudgeConsent: ModelJudgeConsent.optional(),
23694
23706
  // Records that the user consented to the DEFERRED send — the outbox — along
23695
- // with the payload shape and the endpoint they agreed to. Since payload v2
23696
- // that covers both the pre-attach backlog and undelivered captures (which
23697
- // carry prompt/reply text in `content`); the key name predates the widening.
23698
- // Absent until granted, and a grant for a different endpoint or an older
23699
- // payload no longer counts.
23707
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23708
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23709
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23710
+ // both widenings. Absent until granted, and a grant for a different endpoint
23711
+ // or an older payload no longer counts.
23700
23712
  historySyncConsent: HistorySyncConsent.optional()
23701
23713
  });
23702
23714
  function defaultWorkspaceSettings() {
@@ -23827,6 +23839,9 @@ var ManagedSettingKey = external_exports.enum([
23827
23839
  "dataSharesInPlace",
23828
23840
  "redactFallback"
23829
23841
  ]).meta({ id: "ManagedSettingKey" });
23842
+ function isManagedSettingKey(value) {
23843
+ return ManagedSettingKey.safeParse(value).success;
23844
+ }
23830
23845
  var ManagedSettingsValues = external_exports.object({
23831
23846
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
23832
23847
  controlPlane: external_exports.object({
@@ -23851,7 +23866,27 @@ var ManagedSettings = external_exports.object({
23851
23866
  // Which of those the user may not change. A key here with no matching value
23852
23867
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23853
23868
  // the user may still override. The two are separable on purpose.
23854
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23869
+ //
23870
+ // Parsed as NAMES rather than as the enum, and split below: a name this
23871
+ // build does not know is dropped from the locked set and reported, never a
23872
+ // reason to refuse the file. The same shape reaches an older build whenever
23873
+ // an administrator locks a key a newer build added, and refusing it there
23874
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
23875
+ // the fleets most likely to carry a version skew. A name outside the enum
23876
+ // is still never HONOURED: the lockable set stays explicit above.
23877
+ lockedFields: external_exports.array(external_exports.string()).default([])
23878
+ }).transform(({ lockedFields, ...rest }) => {
23879
+ const known = [];
23880
+ const unknown2 = [];
23881
+ for (const name of lockedFields) {
23882
+ if (isManagedSettingKey(name)) known.push(name);
23883
+ else unknown2.push(name);
23884
+ }
23885
+ return {
23886
+ ...rest,
23887
+ lockedFields: known,
23888
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
23889
+ };
23855
23890
  }).meta({ id: "ManagedSettings" });
23856
23891
 
23857
23892
  // ../../packages/schema/src/zod/project-files.ts
@@ -23975,7 +24010,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23975
24010
  timestamp: external_exports.iso.date(),
23976
24011
  critical: external_exports.number().int().nonnegative(),
23977
24012
  high: external_exports.number().int().nonnegative(),
23978
- medium: external_exports.number().int().nonnegative()
24013
+ medium: external_exports.number().int().nonnegative(),
24014
+ // Optional and additive, so a producer written against the earlier
24015
+ // three-series contract keeps validating. A consumer plotting it resolves the
24016
+ // absent case itself — the chart point requires a number.
24017
+ low: external_exports.number().int().nonnegative().optional()
23979
24018
  }).meta({ id: "FindingsTimeseriesPoint" });
23980
24019
  var FindingsTimeseriesResponse = external_exports.object({
23981
24020
  range: TimeRange,
@@ -24001,6 +24040,10 @@ var ResolvedFeedItem = external_exports.object({
24001
24040
  findingKey: external_exports.string(),
24002
24041
  ruleId: external_exports.string(),
24003
24042
  severity: Severity,
24043
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24044
+ // identifies the file: a bare path matches the same name in every repo.
24045
+ // Optional and additive; empty when the event carried no repo.
24046
+ repo: external_exports.string().optional(),
24004
24047
  path: external_exports.string(),
24005
24048
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24006
24049
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -25574,7 +25617,8 @@ var SqliteActivityRepository = class {
25574
25617
  SELECT 1 FROM audit_events d
25575
25618
  WHERE d.root_session_id = audit_events.id
25576
25619
  AND (d.content LIKE ? ESCAPE '\\'
25577
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
25620
+ OR coalesce(json_extract(d.attributes, '$.detail'),
25621
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25578
25622
  );
25579
25623
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25580
25624
  }
@@ -26912,23 +26956,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26912
26956
  )`;
26913
26957
 
26914
26958
  // ../../packages/persistence/src/repositories/findings.ts
26915
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26916
- var DEFAULT_LOCATIONS_LIMIT = 100;
26917
- var LOCATION_RULE_IDS_CAP = 20;
26918
- function compareLocationOrder(a, b) {
26919
- return compareFindingGroupOrder(
26920
- {
26921
- severity: a.maxSeverity,
26922
- latestDetectedAt: a.latestDetectedAt,
26923
- id: ""
26924
- },
26925
- {
26926
- severity: b.maxSeverity,
26927
- latestDetectedAt: b.latestDetectedAt,
26928
- id: ""
26929
- }
26930
- );
26931
- }
26932
26959
  var CONCAT_SEP = ",";
26933
26960
  var TUPLE_SEP = "|";
26934
26961
  function splitConcat(value) {
@@ -26980,13 +27007,48 @@ function decodeGroupCursor(cursor) {
26980
27007
  return null;
26981
27008
  }
26982
27009
  function firstAfter(sorted, cursor) {
26983
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
27010
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26984
27011
  return index === -1 ? sorted.length : index;
26985
27012
  }
26986
27013
  function findDeepLinked(sorted, page, id) {
26987
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26988
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
27014
+ if (page.some((t) => t.id === id)) return void 0;
27015
+ return sorted.find((t) => t.id === id);
27016
+ }
27017
+ function encodeLocationCursor(location) {
27018
+ const payload = {
27019
+ sev: location.maxSeverity,
27020
+ t: location.latestDetectedAt,
27021
+ r: location.repo,
27022
+ f: location.file
27023
+ };
27024
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
27025
+ }
27026
+ function decodeLocationCursor(cursor) {
27027
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
27028
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
27029
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
27030
+ }
27031
+ return null;
26989
27032
  }
27033
+ function firstLocationAfter(sorted, cursor) {
27034
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
27035
+ return index === -1 ? sorted.length : index;
27036
+ }
27037
+ function findDeepLinkedLocation(sorted, page, id) {
27038
+ if (page.some((l) => l.id === id)) return void 0;
27039
+ return sorted.find((l) => l.id === id);
27040
+ }
27041
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
27042
+ d.severity AS severity, f.masked_match AS masked_match,
27043
+ f.action_taken AS action_taken, f.confidence AS confidence,
27044
+ e.started_at AS occurred_at,
27045
+ e.source_tool AS source_tool,
27046
+ e.repo AS repo,
27047
+ e.file_path AS file,
27048
+ e.tool_name AS tool_name,
27049
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
27050
+ e.event_type AS kind, f.finding_key AS finding_key,
27051
+ ${latestResolutionStatusSql("f")} AS latest_status`;
26990
27052
  var DAY_MS3 = 864e5;
26991
27053
  var SqliteFindingsRepository = class {
26992
27054
  constructor(db) {
@@ -27107,30 +27169,26 @@ var SqliteFindingsRepository = class {
27107
27169
  );
27108
27170
  }
27109
27171
  /**
27110
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27111
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27112
- * attributes bag, rule_id/category/severity from the definition), scoped to
27113
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27114
- * rows this list must never surface), groups by ruleId, computes
27115
- * per-filter-excluded facets, applies the requested filters, and sorts by
27116
- * severity then recency. Filtering
27117
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27118
- * reflect the full filtered set; `items` is the requested
27119
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27120
- * filter, `totals.findings` counts only instances whose derived status was
27121
- * requested, and each item's instance preview is narrowed the same way.
27172
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
27173
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
27174
+ * list must never surface), with per-filter-excluded facets, the requested
27175
+ * filters applied, and sorted by severity then recency. Filtering and faceting
27176
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
27177
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
27178
+ * Under a `status` filter, `totals.findings` counts only findings whose
27179
+ * derived status was requested.
27180
+ *
27181
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
27182
+ * folding EVERY finding into the numbers a type row and the filters need
27183
+ * (count, severity, category, providers, actions, statuses, latest, search
27184
+ * text). The findings OF a type come from listFindingInstances scoped to
27185
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27122
27186
  *
27123
- * Two reads, neither of which materializes a row per finding:
27124
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27125
- * the group and the filters need (count, providers, actions, statuses,
27126
- * latest, search text);
27127
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27128
- * populate `instances` for the table's expanded rows.
27129
27187
  * The aggregates carry raw DB values and are translated by the same
27130
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27131
- * rule is ever restated in SQL.
27188
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
27189
+ * status rule is ever restated in SQL.
27132
27190
  */
27133
- listGroupedFindings(query) {
27191
+ listFindingTypes(query) {
27134
27192
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27135
27193
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27136
27194
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27143,12 +27201,7 @@ var SqliteFindingsRepository = class {
27143
27201
  predicate,
27144
27202
  params: sessionParams
27145
27203
  });
27146
- const rows = this.previewRows(aggregates, {
27147
- sessionId: query.sessionId,
27148
- from: query.from
27149
- });
27150
- const groupable = rows.map(toFlatFindingRow);
27151
- const allGroups = buildFindingGroups(groupable, { aggregates });
27204
+ const allTypes = buildFindingTypes(aggregates);
27152
27205
  const filterOpts = {
27153
27206
  severity: query.severity,
27154
27207
  providers: query.provider,
@@ -27157,30 +27210,25 @@ var SqliteFindingsRepository = class {
27157
27210
  subtype: query.subtype,
27158
27211
  q: query.q
27159
27212
  };
27160
- const facets = computeFindingFacets(allGroups, filterOpts);
27161
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
27213
+ const facets = computeFindingFacets(allTypes, filterOpts);
27214
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27162
27215
  const statusFilter = query.status ?? [];
27163
27216
  const totals = {
27164
- findings: sorted.reduce((acc, g) => {
27165
- if (statusFilter.length === 0) return acc + g.instanceCount;
27166
- const agg = aggregates.get(g.id);
27167
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
27217
+ findings: sorted.reduce((acc, t) => {
27218
+ if (statusFilter.length === 0) return acc + t.instanceCount;
27219
+ const agg = aggregates.get(t.id);
27220
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27168
27221
  }, 0),
27169
- groups: sorted.length
27222
+ types: sorted.length
27170
27223
  };
27171
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
27224
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27172
27225
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27173
27226
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27174
27227
  const page = sorted.slice(start, start + limit);
27175
27228
  const lastOnPage = page.at(-1);
27176
27229
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27177
27230
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27178
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27179
- const narrow = (g) => statusSet ? {
27180
- ...g,
27181
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27182
- } : g;
27183
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
27231
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27184
27232
  return Promise.resolve({
27185
27233
  totals,
27186
27234
  facets,
@@ -27191,7 +27239,7 @@ var SqliteFindingsRepository = class {
27191
27239
  }
27192
27240
  /**
27193
27241
  * One row per rule_id, folding EVERY instance of the group into the values
27194
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
27242
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27195
27243
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27196
27244
  *
27197
27245
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27285,13 +27333,25 @@ var SqliteFindingsRepository = class {
27285
27333
  });
27286
27334
  }
27287
27335
  /**
27288
- * The same findings folded by location: repository, then file within it.
27336
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27289
27337
  *
27290
27338
  * The grouping keys come from the capturing event's attributes, which is what
27291
- * the local store relates a finding to — there is no finding↔asset row to
27292
- * group by instead. A repo or file the event did not record folds into the
27293
- * empty-string bucket, which the view renders but does not link, since no
27294
- * filter can name it.
27339
+ * the local store relates a finding to; there is no finding↔asset row to group
27340
+ * by instead. A repo or file the event did not record folds into the
27341
+ * empty-string bucket, which is a real location like any other: it is listed,
27342
+ * it is selectable, and its `?loc=` token is as good as any other row's.
27343
+ *
27344
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
27345
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
27346
+ * list was rebuilt to remove — and two-level pagination inside an
27347
+ * expand/collapse table is what pushed that view to master/detail in the first
27348
+ * place.
27349
+ *
27350
+ * Every filter narrows the FINDINGS and the locations fall out of what
27351
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
27352
+ * reports for the same filters scoped to that pair. The view depends on it:
27353
+ * one toolbar sits over both panels precisely because a location owns none of
27354
+ * its fields.
27295
27355
  */
27296
27356
  listFindingLocations(query) {
27297
27357
  const opts = {
@@ -27303,13 +27363,16 @@ var SqliteFindingsRepository = class {
27303
27363
  tools: query.tool,
27304
27364
  q: query.q
27305
27365
  };
27306
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
27366
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
27367
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27307
27368
  const byRepo = /* @__PURE__ */ new Map();
27369
+ const accumulator = createInstanceFacetAccumulator(opts);
27308
27370
  let total = 0;
27309
27371
  for (const row of this.scanFindingRows({
27310
27372
  sessionId: query.sessionId,
27311
27373
  from: query.from
27312
27374
  })) {
27375
+ accumulator.add(row);
27313
27376
  if (!matchesInstanceFilters(row, opts)) continue;
27314
27377
  total += 1;
27315
27378
  let files = byRepo.get(row.repo);
@@ -27324,103 +27387,35 @@ var SqliteFindingsRepository = class {
27324
27387
  }
27325
27388
  addToLocation(acc, row);
27326
27389
  }
27327
- let fileCount = 0;
27328
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27329
- fileCount += files.size;
27330
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27331
- file: file2,
27332
- instanceCount: acc.instanceCount,
27333
- maxSeverity: acc.maxSeverity,
27334
- latestDetectedAt: acc.latestDetectedAt,
27335
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27336
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27337
- })).sort(compareLocationOrder);
27338
- const rollup = fileRows.reduce(
27339
- (a, f) => ({
27340
- instanceCount: a.instanceCount + f.instanceCount,
27341
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27342
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27343
- }),
27344
- {
27345
- instanceCount: 0,
27346
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27347
- latestDetectedAt: ""
27348
- }
27349
- );
27350
- const statuses = fileRows.map((f) => f.status);
27351
- const folded = foldGroupStatus(statuses);
27352
- return {
27353
- repo,
27354
- instanceCount: rollup.instanceCount,
27355
- maxSeverity: rollup.maxSeverity,
27356
- latestDetectedAt: rollup.latestDetectedAt,
27357
- ...folded === void 0 ? {} : { status: folded },
27358
- files: fileRows
27359
- };
27360
- });
27361
- repos.sort(compareLocationOrder);
27390
+ const sorted = [];
27391
+ for (const [repo, files] of byRepo) {
27392
+ for (const [file2, acc] of files) {
27393
+ const status = foldGroupStatus(acc.statuses);
27394
+ sorted.push({
27395
+ id: encodeLocationId(repo, file2),
27396
+ repo,
27397
+ file: file2,
27398
+ instanceCount: acc.instanceCount,
27399
+ maxSeverity: acc.maxSeverity,
27400
+ latestDetectedAt: acc.latestDetectedAt,
27401
+ ...status === void 0 ? {} : { status },
27402
+ ruleIds: [...acc.ruleIds]
27403
+ });
27404
+ }
27405
+ }
27406
+ sorted.sort(compareLocationOrder);
27407
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
27408
+ const page = sorted.slice(start, start + limit);
27409
+ const lastOnPage = page.at(-1);
27410
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
27411
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27362
27412
  return Promise.resolve({
27363
- totals: { findings: total, repos: repos.length, files: fileCount },
27364
- items: repos.slice(0, limit),
27365
- hasMore: repos.length > limit
27413
+ totals: { findings: total, locations: sorted.length },
27414
+ facets: accumulator.facets(),
27415
+ items: [...page, ...deepLinked ? [deepLinked] : []],
27416
+ nextCursor
27366
27417
  });
27367
27418
  }
27368
- /**
27369
- * Each group's newest instances, for the table's expanded rows.
27370
- *
27371
- * ONE index-ordered scan with early termination, and the shape is the point.
27372
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27373
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27374
- * through a temp B-tree to keep a bounded preview of each group, and then
27375
- * sorts the survivors again for the page order. Both sorts grow with the
27376
- * store while the answer does not.
27377
- *
27378
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27379
- * (or the session or window index the scope names — see `findingScanSql`),
27380
- * which is already the order the page wants, and keeps rows per rule until
27381
- * each rule has as many as it can show. The aggregate the caller already holds
27382
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27383
- * per rule, summed, is the number of rows this scan has to find, and it stops
27384
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27385
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27386
- * store with many firing rules widens it. The bound that DOES hold
27387
- * unconditionally is the sorted form's floor: this scan visits at most as
27388
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27389
- * sorted, and stops the moment every rule has its cap, where the sorted form
27390
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27391
- * wanted instances sitting at the tail of the scope — is one pass over
27392
- * everything in scope with a block sort of the id tie-break only, never a
27393
- * sort of the scope, which is still that floor.
27394
- *
27395
- * A row whose rule the aggregate did not see is skipped: the two statements
27396
- * run without a shared snapshot, so a capture landing between them can add a
27397
- * rule here that has no counts there, and the counts are what the group is
27398
- * built from.
27399
- */
27400
- previewRows(aggregates, scope) {
27401
- const wanted = /* @__PURE__ */ new Map();
27402
- let remaining = 0;
27403
- for (const [ruleId, agg] of aggregates) {
27404
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27405
- wanted.set(ruleId, n);
27406
- remaining += n;
27407
- }
27408
- const rows = [];
27409
- if (remaining === 0) return rows;
27410
- const { sql, params } = this.findingScanSql(scope);
27411
- const taken = /* @__PURE__ */ new Map();
27412
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27413
- const want = wanted.get(r.rule_id);
27414
- if (want === void 0) continue;
27415
- const have = taken.get(r.rule_id) ?? 0;
27416
- if (have >= want) continue;
27417
- taken.set(r.rule_id, have + 1);
27418
- rows.push(r);
27419
- remaining -= 1;
27420
- if (remaining === 0) break;
27421
- }
27422
- return rows;
27423
- }
27424
27419
  /**
27425
27420
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27426
27421
  *
@@ -27447,6 +27442,33 @@ var SqliteFindingsRepository = class {
27447
27442
  yield toFlatFindingRow(r);
27448
27443
  }
27449
27444
  }
27445
+ /**
27446
+ * One finding by its own id, or null when no such row exists.
27447
+ *
27448
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
27449
+ * the store — and, unlike anything derived from a list page, it resolves a
27450
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
27451
+ * deep link needs: the id it carries may name a finding thousands of rows
27452
+ * older than anything a first page holds.
27453
+ *
27454
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
27455
+ * RESOLVES an id; whether that row would survive the list's current filters is
27456
+ * a different question, and hiding the target because a filter excludes it is
27457
+ * worse than showing it.
27458
+ *
27459
+ * `groupId` on the result IS the rule id, so this one read answers both "which
27460
+ * type should the list select?" and "what does the drawer show?".
27461
+ */
27462
+ findingInstance(id) {
27463
+ const row = this.db.prepare(
27464
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
27465
+ FROM inspection_findings f
27466
+ JOIN audit_events e ON e.id = f.audit_event_id
27467
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27468
+ WHERE f.id = ?`
27469
+ ).get(id);
27470
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
27471
+ }
27450
27472
  /**
27451
27473
  * The one statement both instance-level scans run: every finding in scope,
27452
27474
  * joined to its event and definition, newest first.
@@ -27480,17 +27502,7 @@ var SqliteFindingsRepository = class {
27480
27502
  conditions.push("e.started_at >= ?");
27481
27503
  params.push(isoToEpochMillis(scope.from));
27482
27504
  }
27483
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27484
- d.severity AS severity, f.masked_match AS masked_match,
27485
- f.action_taken AS action_taken, f.confidence AS confidence,
27486
- e.started_at AS occurred_at,
27487
- e.source_tool AS source_tool,
27488
- e.repo AS repo,
27489
- e.file_path AS file,
27490
- e.tool_name AS tool_name,
27491
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27492
- e.event_type AS kind, f.finding_key AS finding_key,
27493
- ${latestResolutionStatusSql("f")} AS latest_status
27505
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27494
27506
  FROM audit_events e
27495
27507
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27496
27508
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27504,6 +27516,26 @@ var SqliteFindingsRepository = class {
27504
27516
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27505
27517
  const rows = this.db.prepare(
27506
27518
  `SELECT rule_id,
27519
+ -- BARE columns beside max(latest_at), which is deliberate and
27520
+ -- is SQLite's documented behaviour: with a single min()/max()
27521
+ -- in an aggregate query, every bare column takes its value from
27522
+ -- the row that produced the extremum. So these are the severity
27523
+ -- and category of the definition whose finding is NEWEST, which
27524
+ -- is what the row-based build they replaced read off its first
27525
+ -- (newest-first) row.
27526
+ --
27527
+ -- min() is WRONG here and was the defect: inspection_definitions
27528
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
27529
+ -- mints a new row), so a rule whose severity moved between
27530
+ -- versions has several, and min() picks the ALPHABETICALLY
27531
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
27532
+ -- That is arbitrary in direction, and it feeds the badge, the
27533
+ -- filter, the facet counts and the primary sort key.
27534
+ --
27535
+ -- Adding a second min()/max() aggregate here would make these
27536
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
27537
+ severity,
27538
+ category,
27507
27539
  sum(tuple_count) AS instance_count,
27508
27540
  max(latest_at) AS latest_at,
27509
27541
  group_concat(source_tools) AS source_tools,
@@ -27514,6 +27546,14 @@ var SqliteFindingsRepository = class {
27514
27546
  group_concat(tool_names) AS tool_names
27515
27547
  FROM (
27516
27548
  SELECT d.rule_id AS rule_id,
27549
+ -- Severity and category are columns of the DEFINITION, and
27550
+ -- a rule can have SEVERAL definitions (one per version), so
27551
+ -- these are grouped on below and resolved to the newest
27552
+ -- firing version by the outer query's bare-column select.
27553
+ -- They ride the aggregate because the type build has no rows
27554
+ -- to read them off \u2014 see buildFindingTypes.
27555
+ d.severity AS severity,
27556
+ d.category AS category,
27517
27557
  e.event_type || '${TUPLE_SEP}' ||
27518
27558
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27519
27559
  coalesce(latest.status, '') AS status_tuple,
@@ -27528,7 +27568,7 @@ var SqliteFindingsRepository = class {
27528
27568
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27529
27569
  ON latest.finding_key = f.finding_key
27530
27570
  ${scope.predicate}
27531
- GROUP BY d.rule_id, status_tuple
27571
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27532
27572
  )
27533
27573
  GROUP BY rule_id`
27534
27574
  ).all(scope.params);
@@ -27537,6 +27577,8 @@ var SqliteFindingsRepository = class {
27537
27577
  r.rule_id,
27538
27578
  {
27539
27579
  instanceCount: r.instance_count,
27580
+ severity: r.severity,
27581
+ category: r.category,
27540
27582
  sourceTools: splitConcat(r.source_tools),
27541
27583
  actionsTaken: splitConcat(r.actions_taken),
27542
27584
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27553,7 +27595,7 @@ var SqliteFindingsRepository = class {
27553
27595
  latestDetectedAt: epochMillisToIso(r.latest_at),
27554
27596
  // Free text only — joined and substring-matched, so group_concat's
27555
27597
  // commas need no unpicking (a repo/path containing one still matches).
27556
- // Left undefined (not '') when unfetched, so buildFindingGroups can
27598
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27557
27599
  // tell "no q this request" from "a group with no repo/file at all"
27558
27600
  // and skip priming a haystack nothing will read.
27559
27601
  ...withSearchText ? {
@@ -27705,6 +27747,12 @@ var SqliteHistorySyncRepository = class {
27705
27747
  this.markOwedStmt = db.prepare(
27706
27748
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27707
27749
  );
27750
+ this.markCaptureBacklogOwedStmt = db.prepare(
27751
+ `UPDATE audit_events SET outbox_owed = 1
27752
+ WHERE synced_at IS NULL
27753
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27754
+ AND started_at < :before`
27755
+ );
27708
27756
  this.stampStmt = db.prepare(
27709
27757
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27710
27758
  );
@@ -27753,7 +27801,9 @@ var SqliteHistorySyncRepository = class {
27753
27801
  );
27754
27802
  this.disownCapturesStmt = db.prepare(
27755
27803
  `UPDATE audit_events SET outbox_owed = NULL
27756
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27804
+ WHERE outbox_owed IS NOT NULL
27805
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27806
+ AND started_at < :attachedAt`
27757
27807
  );
27758
27808
  this.rearmStmt = db.prepare(
27759
27809
  `UPDATE audit_events SET synced_at = NULL
@@ -27829,6 +27879,7 @@ var SqliteHistorySyncRepository = class {
27829
27879
  freezeBoundaryStmt;
27830
27880
  captureRowsStmt;
27831
27881
  markOwedStmt;
27882
+ markCaptureBacklogOwedStmt;
27832
27883
  captureSkipCountStmt;
27833
27884
  disownCapturesStmt;
27834
27885
  partitionStmt;
@@ -27892,6 +27943,23 @@ var SqliteHistorySyncRepository = class {
27892
27943
  markCaptureOwed(id) {
27893
27944
  this.markOwedStmt.run({ id });
27894
27945
  }
27946
+ /**
27947
+ * Mark every capture already on disk as owed, as of `before`.
27948
+ *
27949
+ * The consent-time backfill, called once from `aka attach` when a human
27950
+ * grants existing-history consent — never from an ongoing drain pass, and
27951
+ * never inferred from a boundary that could later move. `before` is the
27952
+ * caller's own "now" at the moment consent was granted, so what this marks
27953
+ * is exactly the backlog the consent prompt already counted, not whatever a
27954
+ * later re-attach or key rotation might widen it to.
27955
+ *
27956
+ * Returns how many rows matched, for the caller to log or test against. Not a
27957
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
27958
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27959
+ */
27960
+ markCaptureBacklogOwed(before) {
27961
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27962
+ }
27895
27963
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27896
27964
  markSynced(ids, atMs) {
27897
27965
  this.stampAll(ids, atMs);
@@ -28008,15 +28076,42 @@ var SqliteHistorySyncRepository = class {
28008
28076
  *
28009
28077
  * Delivery is a fact about ONE recipient: rows sent to the deployment a
28010
28078
  * machine has just left are undelivered as far as the new one is concerned.
28011
- * All three in one transaction, so a crash between them cannot leave stamps
28012
- * attributed to the wrong deployment, or a boundary that belongs to another.
28079
+ * All four in one transaction, so a crash between them cannot leave stamps
28080
+ * attributed to the wrong deployment, a boundary that belongs to another, or
28081
+ * a disown with no re-mark to follow it.
28013
28082
  *
28014
28083
  * The boundary is written HERE and only here, which is what freezes it: a
28015
28084
  * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28016
28085
  * unchanged, so this never runs and the backlog does not widen back over rows
28017
28086
  * the live path has since delivered.
28087
+ *
28088
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28089
+ * granted existing-history consent for the deployment this call is arming —
28090
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28091
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28092
+ * apart. Passed only when that grant is valid, since this method has no way
28093
+ * to check consent itself and must not mark a row owed for a machine that
28094
+ * never agreed to it. Applied AFTER the disown above, in the SAME
28095
+ * transaction: what the disown clears is every marker below `backlogBefore`,
28096
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28097
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28098
+ * on the cleared side of that bound — and the re-mark in the same
28099
+ * transaction is what puts those rows back. A crash between the two cannot
28100
+ * strand the ledger disowned with nothing re-marked — the transaction either
28101
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
28102
+ * committed re-enters this method on the very next pass. Omit it (the
28103
+ * structural-only tests do) to exercise the disown in isolation.
28104
+ *
28105
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
28106
+ * touching a marker the NEW deployment's OWN live path has already set: B's
28107
+ * live path can mark a capture owed from the moment `aka attach` writes the
28108
+ * descriptor, before the drain's first pass ever reaches this method, and
28109
+ * such a row sits at or after the bound rather than below it. What keeps the
28110
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
28111
+ * bound — disown runs first, re-mark second, both inside the one
28112
+ * transaction above.
28018
28113
  */
28019
- rearmFor(fingerprint, backlogBefore) {
28114
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28020
28115
  this.ensureRowStmt.run();
28021
28116
  withTransaction(
28022
28117
  this.db,
@@ -28024,7 +28119,10 @@ var SqliteHistorySyncRepository = class {
28024
28119
  const previous = getRow(this.fingerprintStmt)?.fingerprint;
28025
28120
  this.rearmStmt.run();
28026
28121
  if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28027
- this.disownCapturesStmt.run();
28122
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28123
+ }
28124
+ if (backfillCapturesBefore !== void 0) {
28125
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28028
28126
  }
28029
28127
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28030
28128
  },
@@ -28304,7 +28402,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28304
28402
  }
28305
28403
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28306
28404
  }
28307
- function readManagedSettings(paths = managedSettingsPaths()) {
28405
+ var testOnlyManagedPaths = null;
28406
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28308
28407
  for (const path of paths) {
28309
28408
  let text;
28310
28409
  try {
@@ -30784,7 +30883,7 @@ function toUtcDateString(ms) {
30784
30883
  return new Date(ms).toISOString().slice(0, 10);
30785
30884
  }
30786
30885
  function isTimeseriesSeverity(s) {
30787
- return s === "critical" || s === "high" || s === "medium";
30886
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30788
30887
  }
30789
30888
  var SqliteSecurityRepository = class {
30790
30889
  constructor(db, now = () => Date.now()) {
@@ -30913,12 +31012,16 @@ var SqliteSecurityRepository = class {
30913
31012
  const now = this.now();
30914
31013
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30915
31014
  const rows = this.findingsInRange(windowStart, now);
30916
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30917
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30918
- critical: 0,
30919
- high: 0,
30920
- medium: 0
30921
- }));
31015
+ const points = Array.from(
31016
+ { length: numBuckets },
31017
+ (_, i) => ({
31018
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31019
+ critical: 0,
31020
+ high: 0,
31021
+ medium: 0,
31022
+ low: 0
31023
+ })
31024
+ );
30922
31025
  for (const r of rows) {
30923
31026
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30924
31027
  const bucket = points[idx];
@@ -31136,6 +31239,7 @@ var SqliteSecurityRepository = class {
31136
31239
  `SELECT f.finding_key AS finding_key,
31137
31240
  d.rule_id AS rule_id,
31138
31241
  d.severity AS severity,
31242
+ e.repo AS repo,
31139
31243
  e.file_path AS path,
31140
31244
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31141
31245
  latest.resolved_at AS latest_resolved_at
@@ -31155,6 +31259,7 @@ var SqliteSecurityRepository = class {
31155
31259
  const items = rows.map((r) => ({
31156
31260
  findingKey: r.finding_key,
31157
31261
  ruleId: r.rule_id,
31262
+ repo: r.repo ?? "",
31158
31263
  severity: r.severity,
31159
31264
  path: r.path ?? "",
31160
31265
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31164,13 +31269,66 @@ var SqliteSecurityRepository = class {
31164
31269
  }));
31165
31270
  return Promise.resolve({ items });
31166
31271
  }
31272
+ /**
31273
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31274
+ *
31275
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31276
+ * list: a secret committed three weeks ago and never rotated is still the most
31277
+ * important thing to fix, and any window hides it. It carried a "newest N
31278
+ * findings" cap and then a range; the first meant a different span on every
31279
+ * machine, and the second reported "no recommendations" over live exposure.
31280
+ *
31281
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31282
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31283
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31284
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31285
+ * The two answer different questions and only this one has to match a link.
31286
+ *
31287
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31288
+ * whole-store scope costs a grouped scan rather than a row per finding.
31289
+ */
31290
+ recommendationInputs() {
31291
+ const rows = allRows(
31292
+ this.db.prepare(
31293
+ `SELECT d.rule_id AS rule_id,
31294
+ d.category AS category,
31295
+ d.severity AS severity,
31296
+ COUNT(*) AS count
31297
+ FROM inspection_findings f
31298
+ JOIN audit_events e ON e.id = f.audit_event_id
31299
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31300
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31301
+ ON latest.finding_key = f.finding_key
31302
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31303
+ AND e.event_type = 'code_change'
31304
+ AND (
31305
+ f.finding_key IS NULL
31306
+ OR latest.status IS NULL
31307
+ OR latest.status NOT IN ('resolved', 'dismissed')
31308
+ )
31309
+ GROUP BY d.rule_id, d.category, d.severity`
31310
+ )
31311
+ );
31312
+ return Promise.resolve(
31313
+ rows.map((r) => ({
31314
+ ruleId: r.rule_id,
31315
+ category: r.category,
31316
+ severity: r.severity,
31317
+ count: r.count
31318
+ }))
31319
+ );
31320
+ }
31167
31321
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31168
31322
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31169
31323
  // numeric and the JS aggregations bucket/split on ms directly.
31170
31324
  findingsInRange(fromMs, toMs) {
31171
31325
  const rows = allRows(
31172
31326
  this.db.prepare(
31173
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31327
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31328
+ // joined for `severity`, so they are two more columns off a row this read
31329
+ // already fetches. They feed the recommended-actions rollup.
31330
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31331
+ d.rule_id AS rule_id, d.category AS category
31174
31332
  FROM inspection_findings f
31175
31333
  JOIN audit_events e ON e.id = f.audit_event_id
31176
31334
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -31183,7 +31341,9 @@ var SqliteSecurityRepository = class {
31183
31341
  return rows.map((r) => ({
31184
31342
  occurredAt: r.occurred_at,
31185
31343
  severity: r.severity,
31186
- actionTaken: r.action_taken
31344
+ actionTaken: r.action_taken,
31345
+ ruleId: r.rule_id,
31346
+ category: r.category
31187
31347
  }));
31188
31348
  }
31189
31349
  };
@@ -32353,14 +32513,51 @@ function openLocalDatabase(dir) {
32353
32513
  };
32354
32514
  }
32355
32515
 
32356
- // ../../packages/persistence/src/finding-key.ts
32516
+ // ../../packages/persistence/src/egress-wire.ts
32357
32517
  import { createHash as createHash3 } from "crypto";
32518
+ function hashProjectKey(projectKey) {
32519
+ return createHash3("sha256").update(projectKey, "utf8").digest("hex");
32520
+ }
32521
+ function toIngestHit(hit) {
32522
+ return {
32523
+ host: hit.host,
32524
+ kind: hit.kind,
32525
+ name: hit.name,
32526
+ category: hit.category,
32527
+ trust: hit.trust,
32528
+ network: hit.network,
32529
+ method: hit.method,
32530
+ transport: hit.transport,
32531
+ url: hit.url,
32532
+ template: hit.template,
32533
+ dataClass: hit.dataClass,
32534
+ site: {
32535
+ file: hit.site.file,
32536
+ line: hit.site.line,
32537
+ dynamic: hit.site.dynamic,
32538
+ vendored: hit.site.vendored
32539
+ }
32540
+ };
32541
+ }
32542
+ function toEgressIngestRequest(input2) {
32543
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32544
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32545
+ return {
32546
+ projectKey: hashProjectKey(input2.projectKey),
32547
+ project: input2.project,
32548
+ reconcile,
32549
+ hits: hits.map(toIngestHit)
32550
+ };
32551
+ }
32552
+
32553
+ // ../../packages/persistence/src/finding-key.ts
32554
+ import { createHash as createHash4 } from "crypto";
32358
32555
  function normalizeFilePath(filePath) {
32359
32556
  return filePath.replaceAll("\\", "/");
32360
32557
  }
32361
32558
  function computeFindingKey(input2) {
32362
32559
  const normalizedPath = normalizeFilePath(input2.filePath);
32363
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32560
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32364
32561
  }
32365
32562
 
32366
32563
  // ../../packages/persistence/src/fingerprint.ts
@@ -32486,14 +32683,18 @@ function fingerprintValue(key, raw) {
32486
32683
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32487
32684
  }
32488
32685
 
32489
- // ../../packages/persistence/src/history-preview.ts
32686
+ // ../../packages/persistence/src/history-backfill.ts
32490
32687
  import { existsSync as existsSync4 } from "fs";
32491
32688
  import { join as join9 } from "path";
32689
+
32690
+ // ../../packages/persistence/src/history-preview.ts
32691
+ import { existsSync as existsSync5 } from "fs";
32692
+ import { join as join10 } from "path";
32492
32693
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32493
32694
 
32494
32695
  // ../../packages/persistence/src/store-symlinks.ts
32495
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32496
- import { dirname as dirname3, join as join10, resolve } from "path";
32696
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32697
+ import { dirname as dirname3, join as join11, resolve } from "path";
32497
32698
  var STORE_DB = "the store database (including the prompt corpus)";
32498
32699
  var STORE_SETTINGS = "your settings file";
32499
32700
  function storeContents(home) {
@@ -32502,7 +32703,7 @@ function storeContents(home) {
32502
32703
  [settingsDir(home), STORE_SETTINGS],
32503
32704
  [dataDir(home), STORE_DB],
32504
32705
  [keysDir(home), "the vault key"],
32505
- [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
32706
+ [join11(settingsDir(home), "settings.json"), STORE_SETTINGS],
32506
32707
  [dbPath(home), STORE_DB]
32507
32708
  ]);
32508
32709
  }
@@ -32517,7 +32718,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
32517
32718
  holds,
32518
32719
  // existsSync follows the link, so a target that is gone reads as
32519
32720
  // absent here while lstat above still sees the link itself.
32520
- missing: !existsSync5(path),
32721
+ missing: !existsSync6(path),
32521
32722
  mode: targetMode(path, platform2)
32522
32723
  }
32523
32724
  ];
@@ -32555,61 +32756,25 @@ import {
32555
32756
  import { execFileSync } from "child_process";
32556
32757
  import { randomBytes as randomBytes2 } from "crypto";
32557
32758
  import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32558
- import { join as join11 } from "path";
32759
+ import { join as join12 } from "path";
32559
32760
 
32560
32761
  // ../../packages/persistence/src/vault/vault.ts
32561
32762
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32562
32763
 
32563
32764
  // ../../packages/persistence/src/warn-era-cap.ts
32564
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32565
- import { join as join12 } from "path";
32765
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32766
+ import { join as join13 } from "path";
32566
32767
  var MARKER = "warn-era-capped";
32567
32768
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32568
32769
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32569
- const marker = join12(dataDir2, MARKER);
32570
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32770
+ const marker = join13(dataDir2, MARKER);
32771
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32571
32772
  const capped = db.policies.capCategoryActions();
32572
32773
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32573
32774
  `, { mode: DATA_FILE_MODE });
32574
32775
  return { capped };
32575
32776
  }
32576
32777
 
32577
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32578
- function hashProjectKey(projectKey) {
32579
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32580
- }
32581
- function toIngestHit(hit) {
32582
- return {
32583
- host: hit.host,
32584
- kind: hit.kind,
32585
- name: hit.name,
32586
- category: hit.category,
32587
- trust: hit.trust,
32588
- network: hit.network,
32589
- method: hit.method,
32590
- transport: hit.transport,
32591
- url: hit.url,
32592
- template: hit.template,
32593
- dataClass: hit.dataClass,
32594
- site: {
32595
- file: hit.site.file,
32596
- line: hit.site.line,
32597
- dynamic: hit.site.dynamic,
32598
- vendored: hit.site.vendored
32599
- }
32600
- };
32601
- }
32602
- function toEgressIngestRequest(input2) {
32603
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32604
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32605
- return {
32606
- projectKey: hashProjectKey(input2.projectKey),
32607
- project: input2.project,
32608
- reconcile,
32609
- hits: hits.map(toIngestHit)
32610
- };
32611
- }
32612
-
32613
32778
  // ../../packages/remote/src/http.ts
32614
32779
  import { request as httpRequest } from "http";
32615
32780
  import { request as httpsRequest } from "https";
@@ -32889,6 +33054,7 @@ function createRemoteClient(options) {
32889
33054
  url: url2(ROUTES.shares),
32890
33055
  body: JSON.stringify(validated.data)
32891
33056
  });
33057
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32892
33058
  okBody(response);
32893
33059
  },
32894
33060
  async pollCommand() {
@@ -32911,19 +33077,51 @@ function createRemoteClient(options) {
32911
33077
  };
32912
33078
  }
32913
33079
 
32914
- // ../../packages/plugin-runtime/src/attached/failure.ts
33080
+ // ../../packages/remote/src/failure-kind.ts
32915
33081
  function statusOf(err) {
32916
33082
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32917
33083
  const { status } = err;
32918
33084
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32919
33085
  return status >= 100 && status <= 599 ? status : null;
32920
33086
  }
32921
- function classifyFailure(err) {
32922
- switch (statusOf(err)) {
33087
+ function nameOf(err) {
33088
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33089
+ return typeof err.name === "string" ? err.name : null;
33090
+ }
33091
+ function classifyRemoteFailure(err) {
33092
+ switch (nameOf(err)) {
33093
+ case "RemoteRouteAbsent":
33094
+ return "route-absent";
33095
+ case "RemoteRequestInvalid":
33096
+ return "invalid-request";
33097
+ case "RemoteResponseInvalid":
33098
+ return "rejected";
33099
+ default:
33100
+ break;
33101
+ }
33102
+ const status = statusOf(err);
33103
+ if (status === null) return "unreachable";
33104
+ switch (status) {
32923
33105
  case 401:
32924
33106
  return "unauthorized";
32925
33107
  case 403:
32926
33108
  return "forbidden";
33109
+ case 429:
33110
+ return "unreachable";
33111
+ case 404:
33112
+ return "unreachable";
33113
+ default:
33114
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33115
+ }
33116
+ }
33117
+
33118
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33119
+ function classifyFailure(err) {
33120
+ switch (classifyRemoteFailure(err)) {
33121
+ case "unauthorized":
33122
+ return "unauthorized";
33123
+ case "forbidden":
33124
+ return "forbidden";
32927
33125
  default:
32928
33126
  return "unreachable";
32929
33127
  }
@@ -32946,10 +33144,10 @@ function withTimeout(promise2, ms) {
32946
33144
 
32947
33145
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32948
33146
  import { readFileSync as readFileSync8 } from "fs";
32949
- import { join as join13 } from "path";
33147
+ import { join as join14 } from "path";
32950
33148
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32951
33149
  function forwardDropsPath(dataDir2) {
32952
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33150
+ return join14(dataDir2, FORWARD_DROPS_FILENAME);
32953
33151
  }
32954
33152
  function recordForwardDrops(dataDir2, count, nowMs) {
32955
33153
  if (count <= 0) return;
@@ -32985,13 +33183,13 @@ function readForwardDrops(dataDir2) {
32985
33183
 
32986
33184
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32987
33185
  import { randomUUID as randomUUID15 } from "crypto";
32988
- import { readFileSync as readFileSync14 } from "fs";
33186
+ import { readFileSync as readFileSync15 } from "fs";
32989
33187
  import { readFile, rename, writeFile } from "fs/promises";
32990
- import { join as join22 } from "path";
33188
+ import { join as join24 } from "path";
32991
33189
 
32992
33190
  // ../../packages/plugin-sdk/src/config.ts
32993
- import { existsSync as existsSync7 } from "fs";
32994
- import { join as join14 } from "path";
33191
+ import { existsSync as existsSync8 } from "fs";
33192
+ import { join as join15 } from "path";
32995
33193
 
32996
33194
  // ../../packages/plugin-sdk/src/provider-env.ts
32997
33195
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33045,8 +33243,8 @@ function resolveProvider() {
33045
33243
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33046
33244
  try {
33047
33245
  ensureLayoutDirSync(base);
33048
- const settingsFile = join14(settingsDir(base), "settings.json");
33049
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33246
+ const settingsFile = join15(settingsDir(base), "settings.json");
33247
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33050
33248
  } catch {
33051
33249
  }
33052
33250
  migrateLegacyLayout(base);
@@ -33071,7 +33269,7 @@ function resolveProviderSafe(resolveProviderFn) {
33071
33269
  // ../../packages/plugin-sdk/src/config-inventory.ts
33072
33270
  import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33073
33271
  import { homedir as homedir2 } from "os";
33074
- import { basename as basename3, join as join16 } from "path";
33272
+ import { basename as basename3, join as join17 } from "path";
33075
33273
 
33076
33274
  // ../../packages/detections/src/egress/registry.ts
33077
33275
  var EXTRACTOR_VERSION = "1";
@@ -36163,8 +36361,8 @@ function uniqueRuleIds(findings) {
36163
36361
  }
36164
36362
 
36165
36363
  // ../../packages/plugin-sdk/src/repo.ts
36166
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36167
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36364
+ import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36365
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
36168
36366
  function resolveRepo(cwd) {
36169
36367
  try {
36170
36368
  const root = findGitRoot(cwd);
@@ -36179,32 +36377,32 @@ function resolveRepo(cwd) {
36179
36377
  function findGitRoot(start) {
36180
36378
  let dir = start;
36181
36379
  for (; ; ) {
36182
- if (existsSync8(join15(dir, ".git"))) return dir;
36380
+ if (existsSync9(join16(dir, ".git"))) return dir;
36183
36381
  const parent = dirname4(dir);
36184
36382
  if (parent === dir) return void 0;
36185
36383
  dir = parent;
36186
36384
  }
36187
36385
  }
36188
36386
  function resolveGitContext(root) {
36189
- const dotGit = join15(root, ".git");
36387
+ const dotGit = join16(root, ".git");
36190
36388
  try {
36191
36389
  if (statSync6(dotGit).isDirectory()) {
36192
- return { configPath: join15(dotGit, "config"), headRoot: root };
36390
+ return { configPath: join16(dotGit, "config"), headRoot: root };
36193
36391
  }
36194
36392
  } catch {
36195
36393
  return void 0;
36196
36394
  }
36197
36395
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36198
36396
  if (!target) return void 0;
36199
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36200
- if (existsSync8(join15(gitdir, "config"))) {
36201
- return { configPath: join15(gitdir, "config"), headRoot: root };
36397
+ const gitdir = isAbsolute(target) ? target : join16(root, target);
36398
+ if (existsSync9(join16(gitdir, "config"))) {
36399
+ return { configPath: join16(gitdir, "config"), headRoot: root };
36202
36400
  }
36203
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
36401
+ const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
36204
36402
  if (!commonRaw) return void 0;
36205
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
36403
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
36206
36404
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36207
- return { configPath: join15(commonGitDir, "config"), headRoot };
36405
+ return { configPath: join16(commonGitDir, "config"), headRoot };
36208
36406
  }
36209
36407
  function safeRead(path) {
36210
36408
  try {
@@ -36274,7 +36472,7 @@ function buildIngestEvent(input2) {
36274
36472
  }
36275
36473
 
36276
36474
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36277
- import { existsSync as existsSync9 } from "fs";
36475
+ import { existsSync as existsSync10 } from "fs";
36278
36476
  import { fileURLToPath } from "url";
36279
36477
  import { Worker } from "worker_threads";
36280
36478
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -36288,7 +36486,7 @@ function resolveWorkerUrl() {
36288
36486
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
36289
36487
  const candidate = new URL(name, import.meta.url);
36290
36488
  try {
36291
- if (existsSync9(fileURLToPath(candidate))) {
36489
+ if (existsSync10(fileURLToPath(candidate))) {
36292
36490
  resolvedWorkerUrl = candidate;
36293
36491
  return candidate;
36294
36492
  }
@@ -36751,13 +36949,9 @@ function createGuardedScanner(partition, gateway, opts) {
36751
36949
  };
36752
36950
  }
36753
36951
 
36754
- // ../../packages/plugin-sdk/src/ignore-layers.ts
36755
- var import_ignore = __toESM(require_ignore(), 1);
36756
- import { readFileSync as readFileSync11 } from "fs";
36757
- import { join as join17 } from "path";
36758
-
36759
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
36760
- import { arch, hostname as hostname4, platform, release } from "os";
36952
+ // ../../packages/plugin-sdk/src/host-floor.ts
36953
+ import { readFileSync as readFileSync12 } from "fs";
36954
+ import { join as join19 } from "path";
36761
36955
 
36762
36956
  // ../../packages/plugin-sdk/src/model-governance.ts
36763
36957
  import {
@@ -36765,16 +36959,42 @@ import {
36765
36959
  fstatSync,
36766
36960
  mkdirSync as mkdirSync2,
36767
36961
  openSync as openSync2,
36768
- readFileSync as readFileSync12,
36962
+ readFileSync as readFileSync11,
36769
36963
  readSync,
36770
36964
  writeFileSync as writeFileSync5
36771
36965
  } from "fs";
36772
36966
  import { join as join18 } from "path";
36773
36967
  var TAIL_BYTES = 256 * 1024;
36774
36968
 
36969
+ // ../../packages/plugin-sdk/src/host-floor.ts
36970
+ var HOST_FEATURE = {
36971
+ ModelSwitch: "model-switch",
36972
+ VaultPointerDisplay: "vault-pointer-display"
36973
+ };
36974
+ var HOST_FLOORS = {
36975
+ [HOST_FEATURE.ModelSwitch]: {
36976
+ label: "model-switch protection",
36977
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
36978
+ since: "2.1.251"
36979
+ },
36980
+ [HOST_FEATURE.VaultPointerDisplay]: {
36981
+ label: "vault pointer display",
36982
+ hookEvents: ["MessageDisplay"],
36983
+ since: "2.1.152"
36984
+ }
36985
+ };
36986
+
36987
+ // ../../packages/plugin-sdk/src/ignore-layers.ts
36988
+ var import_ignore = __toESM(require_ignore(), 1);
36989
+ import { readFileSync as readFileSync13 } from "fs";
36990
+ import { join as join20 } from "path";
36991
+
36992
+ // ../../packages/plugin-sdk/src/inventory-resolver.ts
36993
+ import { arch, hostname as hostname4, platform, release } from "os";
36994
+
36775
36995
  // ../../packages/plugin-sdk/src/nudge.ts
36776
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36777
- import { join as join19 } from "path";
36996
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
36997
+ import { join as join21 } from "path";
36778
36998
 
36779
36999
  // ../../packages/plugin-sdk/src/paths.ts
36780
37000
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -36816,8 +37036,8 @@ function createPolicyResolver(bundle) {
36816
37036
  }
36817
37037
 
36818
37038
  // ../../packages/plugin-sdk/src/project-files.ts
36819
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36820
- import { basename as basename5, join as join20 } from "path";
37039
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37040
+ import { basename as basename5, join as join22 } from "path";
36821
37041
 
36822
37042
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36823
37043
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -36848,6 +37068,14 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
36848
37068
  // ../../packages/plugin-sdk/src/runtime.ts
36849
37069
  import { randomUUID as randomUUID14 } from "crypto";
36850
37070
  var ENFORCEMENT_CEILING_ENABLED = false;
37071
+ function applyEnforcementCeiling(action, policyMode, enabled) {
37072
+ if (!enabled || policyMode !== "warn") return action;
37073
+ return action === "block" || action === "redact" ? "warn" : action;
37074
+ }
37075
+ function resolveEnforcedAction(action, opts) {
37076
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
37077
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
37078
+ }
36851
37079
  function startTiming() {
36852
37080
  try {
36853
37081
  return performance.now();
@@ -36956,12 +37184,12 @@ function createPluginRuntime(gateway, settings, opts) {
36956
37184
  }
36957
37185
  function actionForFinding(finding, excepted, rewritable = true) {
36958
37186
  if (excepted?.has(finding)) return "allow";
36959
- const action = resolveAction(finding.ruleId, finding.category);
36960
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
36961
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
36962
- return "warn";
36963
- }
36964
- return action;
37187
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
37188
+ policyMode,
37189
+ redactFallback,
37190
+ rewritable,
37191
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
37192
+ });
36965
37193
  }
36966
37194
  function decide(findings, text, excepted, rewritable = true) {
36967
37195
  if (findings.length === 0) return { action: "log", text, findings: [] };
@@ -37210,7 +37438,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37210
37438
 
37211
37439
  // ../../packages/plugin-sdk/src/throttle.ts
37212
37440
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37213
- import { join as join21 } from "path";
37441
+ import { join as join23 } from "path";
37214
37442
 
37215
37443
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
37216
37444
  function isInvalidRequest(err) {
@@ -37250,7 +37478,7 @@ function parseBreakerState(raw, nowMs) {
37250
37478
  }
37251
37479
  function createForwardPolicy(deps) {
37252
37480
  const now = deps.now ?? (() => Date.now());
37253
- const file2 = join22(deps.dir, STATE_FILENAME);
37481
+ const file2 = join24(deps.dir, STATE_FILENAME);
37254
37482
  let state = null;
37255
37483
  let loading = null;
37256
37484
  async function readState() {
@@ -37972,8 +38200,8 @@ function toolAuditEvent(input2) {
37972
38200
  }
37973
38201
 
37974
38202
  // ../../packages/plugin-runtime/src/attached/history-state.ts
37975
- import { readFileSync as readFileSync15 } from "fs";
37976
- import { join as join23 } from "path";
38203
+ import { readFileSync as readFileSync16 } from "fs";
38204
+ import { join as join25 } from "path";
37977
38205
 
37978
38206
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37979
38207
  import { createHash as createHash6 } from "crypto";
@@ -37990,7 +38218,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
37990
38218
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
37991
38219
 
37992
38220
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37993
- import { readFileSync as readFileSync16 } from "fs";
38221
+ import { readFileSync as readFileSync17 } from "fs";
37994
38222
  function createPluginBlock(build, policyStore) {
37995
38223
  return async () => {
37996
38224
  const cached2 = await policyStore.read();
@@ -38009,7 +38237,7 @@ function createPluginBlock(build, policyStore) {
38009
38237
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38010
38238
  import { randomUUID as randomUUID16 } from "crypto";
38011
38239
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38012
- import { join as join24 } from "path";
38240
+ import { join as join26 } from "path";
38013
38241
 
38014
38242
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38015
38243
  import { rename as rename2 } from "fs/promises";
@@ -38033,7 +38261,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38033
38261
 
38034
38262
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38035
38263
  function createPolicyStore(dir = dataDir()) {
38036
- const file2 = join24(dir, "policy-cache.json");
38264
+ const file2 = join26(dir, "policy-cache.json");
38037
38265
  async function read() {
38038
38266
  try {
38039
38267
  const raw = await readFile2(file2, "utf8");
@@ -38264,11 +38492,11 @@ function readStorePosture(dbPath2) {
38264
38492
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38265
38493
  import { randomUUID as randomUUID17 } from "crypto";
38266
38494
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38267
- import { join as join25 } from "path";
38495
+ import { join as join27 } from "path";
38268
38496
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38269
38497
  function createPostureStore(dir = settingsDir(), legacyDir) {
38270
- const file2 = join25(dir, "posture-state.json");
38271
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
38498
+ const file2 = join27(dir, "posture-state.json");
38499
+ const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
38272
38500
  async function persist(state) {
38273
38501
  await ensureDataDir(dir);
38274
38502
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38336,8 +38564,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38336
38564
  }
38337
38565
 
38338
38566
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38339
- import { readFileSync as readFileSync17 } from "fs";
38340
- import { join as join26 } from "path";
38567
+ import { readFileSync as readFileSync18 } from "fs";
38568
+ import { join as join28 } from "path";
38341
38569
 
38342
38570
  // ../../packages/plugin-runtime/src/attached/status.ts
38343
38571
  var REFUSAL_LINES = {
@@ -38969,8 +39197,8 @@ function baseMetadata(input2) {
38969
39197
  }
38970
39198
 
38971
39199
  // src/hooks/store-health.ts
38972
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "fs";
38973
- import { dirname as dirname6, join as join27 } from "path";
39200
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync19, writeFileSync as writeFileSync8 } from "fs";
39201
+ import { dirname as dirname6, join as join29 } from "path";
38974
39202
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
38975
39203
  function markerDirs(dataDir2) {
38976
39204
  return [dataDir2, dirname6(dataDir2)];
@@ -38978,7 +39206,7 @@ function markerDirs(dataDir2) {
38978
39206
  function alreadyClaimed(dirs, marker, sessionId) {
38979
39207
  return dirs.some((dir) => {
38980
39208
  try {
38981
- return readFileSync18(join27(dir, marker), "utf8") === sessionId;
39209
+ return readFileSync19(join29(dir, marker), "utf8") === sessionId;
38982
39210
  } catch {
38983
39211
  return false;
38984
39212
  }
@@ -38988,7 +39216,7 @@ function recordClaim(dirs, marker, sessionId) {
38988
39216
  for (const dir of dirs) {
38989
39217
  try {
38990
39218
  mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
38991
- writeFileSync8(join27(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39219
+ writeFileSync8(join29(dir, marker), sessionId, { mode: DATA_FILE_MODE });
38992
39220
  return;
38993
39221
  } catch {
38994
39222
  }