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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/sync.js CHANGED
@@ -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";
@@ -20743,13 +20740,11 @@ var FindingGroup = external_exports.object({
20743
20740
  latestDetectedAt: external_exports.iso.datetime(),
20744
20741
  instances: external_exports.array(FindingInstance),
20745
20742
  // Derived from instances' statuses with open-dominates precedence (see
20746
- // buildFindingGroups). Undefined only when no instance carries a status.
20743
+ // foldGroupStatus). Undefined only when no instance carries a status.
20747
20744
  status: FindingStatus.optional(),
20748
- // The distinct people across the WHOLE group, not just the `instances`
20749
- // preview — from the store's whole-group aggregate when it supplies one,
20750
- // else folded from the rows (see buildFindingGroups). Undefined when no
20751
- // instance carries a user, or when the store supplied whole-group folds
20752
- // without one.
20745
+ // The distinct people across the WHOLE group, not just the instances
20746
+ // carried here. Undefined when no instance carries a user, or when the
20747
+ // store supplied whole-group folds without one.
20753
20748
  users: external_exports.array(FindingUser).optional()
20754
20749
  }).meta({ id: "FindingGroup" });
20755
20750
  var FindingStats = external_exports.object({
@@ -20778,21 +20773,31 @@ var FindingFacets = external_exports.object({
20778
20773
  // counted under no value.
20779
20774
  status: external_exports.array(FindingFacetItem),
20780
20775
  // Host tool (attributes.tool_name). Present only on the instance-level
20781
- // reads, which can filter by it; the grouped read omits the dimension
20776
+ // reads, which can filter by it; the type-level read omits the dimension
20782
20777
  // because a group spans tools.
20783
20778
  tool: external_exports.array(FindingFacetItem).optional()
20784
20779
  }).meta({ id: "FindingFacets" });
20785
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20786
- var ListGroupedFindingsQuery = external_exports.object({
20780
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20781
+ id: "FindingTypeSummary"
20782
+ });
20783
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20784
+ var MAX_FINDING_TYPES_LIMIT = 100;
20785
+ var ListFindingTypesQuery = external_exports.object({
20787
20786
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20788
- // FindingAction.
20787
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20788
+ // firing version carries, and this list pages types.
20789
+ //
20790
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20791
+ // definition versions at different severities, so a type kept by this filter
20792
+ // can hold findings that individually do not match — see totals.findings on
20793
+ // ListFindingTypesResponse, which counts them all.
20789
20794
  severity: external_exports.array(Severity).optional(),
20790
20795
  subtype: external_exports.array(external_exports.string()).optional(),
20791
20796
  provider: external_exports.array(FindingProvider).optional(),
20792
20797
  action: external_exports.array(FindingAction).optional(),
20793
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20794
- // individual instances' — so a filtered group's Status column always reads
20795
- // one of the requested values.
20798
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20799
+ // individual findings' — so a filtered row's status always reads one of the
20800
+ // requested values.
20796
20801
  status: external_exports.array(FindingStatus).optional(),
20797
20802
  q: external_exports.string().optional(),
20798
20803
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20802,23 +20807,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20802
20807
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20803
20808
  // means all time — this list has no default window.
20804
20809
  from: external_exports.iso.datetime().optional(),
20805
- // A group or instance id that must appear in the page even when the cursor
20806
- // has already advanced past its sort position. This is what keeps the
20807
- // Findings page's one-shot ?finding= deep link resolving once the list
20808
- // paginates: the target group is appended out of sort order rather than
20809
- // scanning forward for it. Never affects totals, facets or the cursor.
20810
+ // A RULE id that must appear in the page even when the cursor has already
20811
+ // advanced past its sort position. This is what keeps the selected type
20812
+ // visible in the list once it paginates: the target is appended out of sort
20813
+ // order rather than scanned forward for. Never affects totals, facets or the
20814
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20815
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20816
+ // and so is not bounded by what any page happens to hold.
20810
20817
  includeId: external_exports.string().optional(),
20811
- groupBy: external_exports.literal("type").optional(),
20812
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20818
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20813
20819
  cursor: external_exports.string().optional()
20814
20820
  });
20815
- var ListGroupedFindingsResponse = external_exports.object({
20821
+ var ListFindingTypesResponse = external_exports.object({
20816
20822
  totals: external_exports.object({
20823
+ // Findings belonging to the matching TYPES — not findings that each match
20824
+ // the filters. The filters here select types, so a type that survives
20825
+ // contributes its whole instanceCount.
20826
+ //
20827
+ // `status` is the one exception, narrowed per finding via
20828
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20829
+ // this can exceed what the instance read reports for the same filters: a
20830
+ // rule whose severity moved between versions is kept on its newest and
20831
+ // still counts its older findings. Narrowing the other three needs
20832
+ // per-dimension counts the aggregate does not carry today.
20817
20833
  findings: external_exports.number().int().nonnegative(),
20818
- groups: external_exports.number().int().nonnegative()
20834
+ // Counts TYPES, which is the unit this read pages. The instance read's
20835
+ // own totals count findings; the two deliberately answer different
20836
+ // questions and are never summed.
20837
+ types: external_exports.number().int().nonnegative()
20819
20838
  }),
20820
20839
  facets: FindingFacets,
20821
- items: external_exports.array(FindingGroup),
20840
+ items: external_exports.array(FindingTypeSummary),
20822
20841
  nextCursor: external_exports.string().nullable(),
20823
20842
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20824
20843
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20826,7 +20845,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20826
20845
  // every firing, so the two numbers legitimately differ — this map lets a
20827
20846
  // session-scoped view show both.
20828
20847
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20829
- }).meta({ id: "ListGroupedFindingsResponse" });
20848
+ }).meta({ id: "ListFindingTypesResponse" });
20830
20849
  var ApplyFindingActionRequest = external_exports.object({
20831
20850
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20832
20851
  // it, so it is excluded from the request contract. The mapping helper
@@ -20856,12 +20875,13 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20856
20875
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20857
20876
  var ListFindingInstancesQuery = external_exports.object({
20858
20877
  severity: external_exports.array(Severity).optional(),
20859
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20878
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20879
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20860
20880
  subtype: external_exports.array(external_exports.string()).optional(),
20861
20881
  provider: external_exports.array(FindingProvider).optional(),
20862
20882
  action: external_exports.array(FindingAction).optional(),
20863
20883
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20864
- // the grouped query's group-level fold.
20884
+ // the types query's type-level fold.
20865
20885
  status: external_exports.array(FindingStatus).optional(),
20866
20886
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20867
20887
  // where the free-text `q` can only match the rendered "via Bash" label.
@@ -20878,37 +20898,47 @@ var ListFindingInstancesQuery = external_exports.object({
20878
20898
  });
20879
20899
  var ListFindingInstancesResponse = external_exports.object({
20880
20900
  // Instances matching the filters across the whole scope, not just this
20881
- // page — cursor-independent, like the grouped list's totals.
20901
+ // page — cursor-independent, like the types list's totals.
20882
20902
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20883
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20903
+ // Counts in INSTANCES here, where the types response counts types. Each
20884
20904
  // dimension still excludes its own filter.
20885
20905
  facets: FindingFacets,
20886
20906
  items: external_exports.array(FindingInstanceDetail),
20887
20907
  nextCursor: external_exports.string().nullable()
20888
20908
  }).meta({ id: "ListFindingInstancesResponse" });
20889
- var FindingLocationFile = external_exports.object({
20890
- // Empty when the instances carried no file path (a prompt or a tool call
20891
- // with no file attribution).
20892
- file: external_exports.string(),
20893
- instanceCount: external_exports.number().int().nonnegative(),
20894
- maxSeverity: Severity,
20895
- latestDetectedAt: external_exports.iso.datetime(),
20896
- // Folded from the instances' derived statuses with the same
20897
- // open-dominates precedence a group uses.
20898
- status: FindingStatus.optional(),
20899
- // Distinct rules seen at this location, capped — the row shows them as
20900
- // chips, and the count is what conveys scale.
20901
- ruleIds: external_exports.array(external_exports.string())
20902
- }).meta({ id: "FindingLocationFile" });
20903
- var FindingLocationRepo = external_exports.object({
20909
+ var FindingLocationSummary = external_exports.object({
20910
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20911
+ // because a location's identity is two values and a URL param carries one:
20912
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20913
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20914
+ // client's page dedupe — never decoded, and never a sort key.
20915
+ id: external_exports.string(),
20904
20916
  /** Empty when the instances carried no repo attribute. */
20905
20917
  repo: external_exports.string(),
20918
+ // Empty when the instances carried no file path (a prompt, or a tool call
20919
+ // with no file attribution). Both halves empty is a real location — usually
20920
+ // the largest one in a store — and is selectable like any other.
20921
+ file: external_exports.string(),
20906
20922
  instanceCount: external_exports.number().int().nonnegative(),
20923
+ // The WORST severity present, not the first row's. It is this list's primary
20924
+ // sort key, so it is also what explains why a row is where it is, and it is
20925
+ // how a reader decides what to open without opening everything.
20907
20926
  maxSeverity: Severity,
20908
20927
  latestDetectedAt: external_exports.iso.datetime(),
20928
+ // Folded from the instances' derived statuses with the same open-dominates
20929
+ // precedence a group uses, so it answers "is anything left to do here" and
20930
+ // not much more: a location holding 1 open among 40 resolved reads like one
20931
+ // holding 40 open. That loss is accepted — the panel beside this list
20932
+ // carries each finding's own status, and instanceCount sits next to the
20933
+ // badge.
20909
20934
  status: FindingStatus.optional(),
20910
- files: external_exports.array(FindingLocationFile)
20911
- }).meta({ id: "FindingLocationRepo" });
20935
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20936
+ // tally rather than a sample and a row can say how many there are. Bounded
20937
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20938
+ ruleIds: external_exports.array(external_exports.string())
20939
+ }).meta({ id: "FindingLocationSummary" });
20940
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20941
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20912
20942
  var ListFindingLocationsQuery = external_exports.object({
20913
20943
  severity: external_exports.array(Severity).optional(),
20914
20944
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20921,18 +20951,42 @@ var ListFindingLocationsQuery = external_exports.object({
20921
20951
  q: external_exports.string().optional(),
20922
20952
  sessionId: external_exports.string().optional(),
20923
20953
  from: external_exports.iso.datetime().optional(),
20924
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
20954
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
20955
+ // even when the cursor has already advanced past its sort position — the
20956
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
20957
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
20958
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
20959
+ // into the thousands, a selection sitting off page 0 is the ordinary case
20960
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
20961
+ includeId: external_exports.string().optional(),
20962
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
20963
+ cursor: external_exports.string().optional()
20925
20964
  });
20926
20965
  var ListFindingLocationsResponse = external_exports.object({
20927
20966
  totals: external_exports.object({
20967
+ // Findings matching the filters across the whole scope. Unlike the types
20968
+ // read's same-named field this needs no caveat: the filters here narrow
20969
+ // per finding, so this is the sum of every row's instanceCount.
20928
20970
  findings: external_exports.number().int().nonnegative(),
20929
- repos: external_exports.number().int().nonnegative(),
20930
- files: external_exports.number().int().nonnegative()
20971
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
20972
+ // states. The facets beside it count FINDINGS (see below); a surface
20973
+ // showing both says which is which.
20974
+ locations: external_exports.number().int().nonnegative()
20931
20975
  }),
20932
- /** Sorted by max severity, then most recent. */
20933
- items: external_exports.array(FindingLocationRepo),
20934
- /** Whether `limit` truncated the repo list. */
20935
- hasMore: external_exports.boolean()
20976
+ // Counts in FINDINGS, where the types response counts types, each dimension
20977
+ // still excluding its own filter. Deliberately not locations: counting those
20978
+ // needs a set of location keys per dimension per value — memory tracking the
20979
+ // store times the vocabulary, in a read whose scan promises flat memory —
20980
+ // and the cheap per-location version is not an approximation but WRONG. A
20981
+ // location holding {claudecode, block} and {codex, warn} would survive
20982
+ // provider=claudecode AND action=warn, under which no single finding
20983
+ // matches, so the facet would contradict the instanceCount this whole view
20984
+ // rests on. Findings also keep the toolbar in the same unit as the page
20985
+ // tally and the panel it sits above.
20986
+ facets: FindingFacets,
20987
+ /** Sorted by max severity, then most recent, then (repo, file). */
20988
+ items: external_exports.array(FindingLocationSummary),
20989
+ nextCursor: external_exports.string().nullable()
20936
20990
  }).meta({ id: "ListFindingLocationsResponse" });
20937
20991
 
20938
20992
  // ../../packages/schema/src/zod/meta.ts
@@ -22101,6 +22155,14 @@ var ControlPlaneErrorBody = external_exports.object({
22101
22155
  message: external_exports.string().optional()
22102
22156
  }).optional()
22103
22157
  });
22158
+ var RemoteFailureKind = external_exports.enum([
22159
+ "unauthorized",
22160
+ "forbidden",
22161
+ "route-absent",
22162
+ "invalid-request",
22163
+ "rejected",
22164
+ "unreachable"
22165
+ ]);
22104
22166
  var AttachDeviceRequest = external_exports.object({
22105
22167
  // This machine's own continuity id, so re-attaching ROTATES the credential
22106
22168
  // on one machine record instead of producing a second one. Client-minted
@@ -22794,139 +22856,62 @@ function deriveFindingStatus(row) {
22794
22856
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22795
22857
  return "open";
22796
22858
  }
22797
- function distinctUsers(instances) {
22798
- const seen = /* @__PURE__ */ new Set();
22799
- const users = [];
22800
- for (const i of instances) {
22801
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22802
- seen.add(i.user.id);
22803
- users.push(i.user);
22804
- }
22805
- return users;
22806
- }
22807
22859
  function sortUsers(users) {
22808
22860
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22809
22861
  }
22810
- function buildFindingGroups(rows, opts = {}) {
22811
- const overrides = opts.overrides;
22862
+ function buildFindingTypes(aggregates, opts = {}) {
22812
22863
  const packNames = opts.packNames;
22813
- const aggregates = opts.aggregates;
22814
- const byRuleId = /* @__PURE__ */ new Map();
22815
- for (const row of rows) {
22816
- const existing = byRuleId.get(row.ruleId);
22817
- if (existing) existing.push(row);
22818
- else byRuleId.set(row.ruleId, [row]);
22819
- }
22820
- const groups = [];
22821
- for (const [ruleId, ruleRows] of byRuleId) {
22822
- const instances = ruleRows.map((r) => {
22823
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22824
- return {
22825
- id: r.id,
22826
- provider: toApiProvider(r.sourceTool),
22827
- repo: r.repo,
22828
- file: r.file,
22829
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22830
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22831
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22832
- ...r.user === void 0 ? {} : { user: r.user },
22833
- action: toApiAction(effectiveDbAction),
22834
- detectedAt: r.occurredAt,
22835
- confidence: r.confidence,
22836
- status: r.status
22837
- };
22838
- });
22839
- const agg = aggregates?.get(ruleId);
22840
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22841
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22842
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22843
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22844
- );
22845
- const seenProviders = /* @__PURE__ */ new Set();
22846
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22847
- if (seenProviders.has(p)) return false;
22848
- seenProviders.add(p);
22849
- return true;
22850
- });
22851
- const actionSet = new Set(
22852
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22853
- );
22864
+ const types = [];
22865
+ for (const [ruleId, agg] of aggregates) {
22866
+ const users = sortUsers(agg.users ?? []);
22867
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
22868
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22854
22869
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22855
- const severity = ruleRows[0]?.severity ?? "low";
22856
- const detection = {
22857
- id: ruleId,
22858
- name: packNames?.get(ruleId) ?? null
22859
- };
22860
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22861
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22862
- const match = {
22863
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22864
- contextPrefix: ""
22865
- // empty (pending privacy review)
22866
- };
22867
- const status = foldGroupStatus(
22868
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22869
- );
22870
- const group = {
22870
+ const apiCategory = toApiCategory(agg.category ?? "custom");
22871
+ const type = {
22871
22872
  id: ruleId,
22872
22873
  category: apiCategory,
22873
22874
  subtype: ruleId,
22874
22875
  // human label comes with pack metadata later
22875
- severity,
22876
- match,
22877
- detection,
22878
- policy,
22879
- instanceCount: agg?.instanceCount ?? instances.length,
22876
+ severity: agg.severity ?? "low",
22877
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
22878
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
22879
+ instanceCount: agg.instanceCount,
22880
22880
  providers,
22881
22881
  aggregateAction,
22882
- latestDetectedAt,
22883
- instances,
22884
- status,
22882
+ latestDetectedAt: agg.latestDetectedAt,
22883
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
22885
22884
  ...users.length > 0 ? { users } : {}
22886
22885
  };
22887
- if (agg) {
22888
- actionsCache.set(group, [...actionSet]);
22889
- if (agg.searchText !== void 0) {
22890
- haystackCache.set(group, buildHaystack(group, agg.searchText));
22891
- }
22886
+ actionsCache.set(type, [...actionSet]);
22887
+ if (agg.searchText !== void 0) {
22888
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
22892
22889
  }
22893
- groups.push(group);
22890
+ types.push(type);
22894
22891
  }
22895
- return groups;
22892
+ return types;
22896
22893
  }
22897
22894
  var haystackCache = /* @__PURE__ */ new WeakMap();
22898
- function buildHaystack(g, extra) {
22895
+ function buildHaystack(t, extra) {
22899
22896
  return [
22900
- g.subtype,
22901
- g.category,
22902
- g.match.maskedValue,
22903
- g.policy.name,
22904
- g.id,
22905
- ...g.instances.map((i) => i.repo),
22906
- ...g.instances.map((i) => i.file),
22907
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
22908
- ...g.instances.map((i) => i.id),
22909
- // The people: the whole group's list when the store folded one, plus the
22910
- // preview's own — the two overlap, and a haystack does not mind.
22911
- ...(g.users ?? []).map((u) => u.name),
22912
- ...g.instances.map((i) => i.user?.name ?? ""),
22897
+ t.subtype,
22898
+ t.category,
22899
+ t.policy.name,
22900
+ t.id,
22901
+ ...(t.users ?? []).map((u) => u.name),
22913
22902
  ...extra === void 0 ? [] : [extra]
22914
22903
  ].join(" ").toLowerCase();
22915
22904
  }
22916
- function groupHaystack(g) {
22917
- const cached2 = haystackCache.get(g);
22905
+ function typeHaystack(t) {
22906
+ const cached2 = haystackCache.get(t);
22918
22907
  if (cached2 !== void 0) return cached2;
22919
- const haystack = buildHaystack(g);
22920
- haystackCache.set(g, haystack);
22908
+ const haystack = buildHaystack(t);
22909
+ haystackCache.set(t, haystack);
22921
22910
  return haystack;
22922
22911
  }
22923
22912
  var actionsCache = /* @__PURE__ */ new WeakMap();
22924
- function groupActions(g) {
22925
- const cached2 = actionsCache.get(g);
22926
- if (cached2 !== void 0) return cached2;
22927
- const actions = [...new Set(g.instances.map((i) => i.action))];
22928
- actionsCache.set(g, actions);
22929
- return actions;
22913
+ function typeActions(t) {
22914
+ return actionsCache.get(t) ?? [];
22930
22915
  }
22931
22916
  function countInstancesByStatus(statusInputs, statuses) {
22932
22917
  const statusSet = new Set(statuses);
@@ -22937,8 +22922,8 @@ function countInstancesByStatus(statusInputs, statuses) {
22937
22922
  }
22938
22923
  return sum;
22939
22924
  }
22940
- function applyFindingFilters(groups, opts) {
22941
- let filtered = groups;
22925
+ function applyFindingFilters(types, opts) {
22926
+ let filtered = types;
22942
22927
  if (opts.severity && opts.severity.length > 0) {
22943
22928
  const sevSet = new Set(opts.severity);
22944
22929
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -22949,7 +22934,7 @@ function applyFindingFilters(groups, opts) {
22949
22934
  }
22950
22935
  if (opts.actions && opts.actions.length > 0) {
22951
22936
  const actionSet = new Set(opts.actions);
22952
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
22937
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
22953
22938
  }
22954
22939
  if (opts.subtype && opts.subtype.length > 0) {
22955
22940
  const subtypeSet = new Set(opts.subtype);
@@ -22961,7 +22946,7 @@ function applyFindingFilters(groups, opts) {
22961
22946
  }
22962
22947
  if (opts.q) {
22963
22948
  const q = opts.q.toLowerCase();
22964
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
22949
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
22965
22950
  }
22966
22951
  return filtered;
22967
22952
  }
@@ -22976,11 +22961,11 @@ function compareFindingGroupOrder(a, b) {
22976
22961
  if (recencyDiff !== 0) return recencyDiff;
22977
22962
  return a.id.localeCompare(b.id);
22978
22963
  }
22979
- function sortFindingGroups(groups) {
22980
- return [...groups].sort(compareFindingGroupOrder);
22964
+ function sortFindingTypes(types) {
22965
+ return [...types].sort(compareFindingGroupOrder);
22981
22966
  }
22982
- function computeFindingFacets(allGroups, opts) {
22983
- const forSeverity = applyFindingFilters(allGroups, {
22967
+ function computeFindingFacets(allTypes, opts) {
22968
+ const forSeverity = applyFindingFilters(allTypes, {
22984
22969
  providers: opts.providers,
22985
22970
  actions: opts.actions,
22986
22971
  statuses: opts.statuses,
@@ -22991,7 +22976,7 @@ function computeFindingFacets(allGroups, opts) {
22991
22976
  for (const g of forSeverity) {
22992
22977
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
22993
22978
  }
22994
- const forProvider = applyFindingFilters(allGroups, {
22979
+ const forProvider = applyFindingFilters(allTypes, {
22995
22980
  actions: opts.actions,
22996
22981
  statuses: opts.statuses,
22997
22982
  q: opts.q,
@@ -23002,7 +22987,7 @@ function computeFindingFacets(allGroups, opts) {
23002
22987
  for (const g of forProvider) {
23003
22988
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23004
22989
  }
23005
- const forAction = applyFindingFilters(allGroups, {
22990
+ const forAction = applyFindingFilters(allTypes, {
23006
22991
  providers: opts.providers,
23007
22992
  statuses: opts.statuses,
23008
22993
  q: opts.q,
@@ -23011,9 +22996,9 @@ function computeFindingFacets(allGroups, opts) {
23011
22996
  });
23012
22997
  const actionMap = /* @__PURE__ */ new Map();
23013
22998
  for (const g of forAction) {
23014
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
22999
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23015
23000
  }
23016
- const forSubtype = applyFindingFilters(allGroups, {
23001
+ const forSubtype = applyFindingFilters(allTypes, {
23017
23002
  providers: opts.providers,
23018
23003
  actions: opts.actions,
23019
23004
  statuses: opts.statuses,
@@ -23022,7 +23007,7 @@ function computeFindingFacets(allGroups, opts) {
23022
23007
  });
23023
23008
  const subtypeMap = /* @__PURE__ */ new Map();
23024
23009
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23025
- const forStatus = applyFindingFilters(allGroups, {
23010
+ const forStatus = applyFindingFilters(allTypes, {
23026
23011
  providers: opts.providers,
23027
23012
  actions: opts.actions,
23028
23013
  q: opts.q,
@@ -23070,10 +23055,20 @@ function matchesDimension(row, opts, dimension) {
23070
23055
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23071
23056
  case "tools":
23072
23057
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23058
+ // An EMPTY value is a real filter here, not an absent one. The location
23059
+ // list buckets a finding whose event recorded no repo — or no file — under
23060
+ // the empty string, and selecting that bucket has to narrow the panel to
23061
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23062
+ // row omits the key, which every call site already does.
23063
+ //
23064
+ // Reading '' as unset is what this replaced, and it failed in the one place
23065
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23066
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23067
+ // — a row reading 3 findings beside a panel listing every finding there is.
23073
23068
  case "repo":
23074
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23069
+ return opts.repo === void 0 || row.repo === opts.repo;
23075
23070
  case "file":
23076
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23071
+ return opts.file === void 0 || row.file === opts.file;
23077
23072
  case "q":
23078
23073
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23079
23074
  }
@@ -23187,6 +23182,23 @@ function addToLocation(acc, row) {
23187
23182
  acc.statuses.push(row.status);
23188
23183
  acc.ruleIds.add(row.ruleId);
23189
23184
  }
23185
+ function compareLocationOrder(a, b) {
23186
+ const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23187
+ const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23188
+ if (rankA !== rankB) return rankA - rankB;
23189
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23190
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23191
+ }
23192
+ if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23193
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23194
+ return 0;
23195
+ }
23196
+ function encodeLocationId(repo, file2) {
23197
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23198
+ }
23199
+ function encodePart(value) {
23200
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23201
+ }
23190
23202
 
23191
23203
  // ../../packages/schema/src/zod/installed-pack.ts
23192
23204
  var InstalledPack = external_exports.object({
@@ -23693,11 +23705,11 @@ var WorkspaceSettings = external_exports.object({
23693
23705
  // covers the current payload and must be re-granted.
23694
23706
  modelJudgeConsent: ModelJudgeConsent.optional(),
23695
23707
  // Records that the user consented to the DEFERRED send — the outbox — along
23696
- // with the payload shape and the endpoint they agreed to. Since payload v2
23697
- // that covers both the pre-attach backlog and undelivered captures (which
23698
- // carry prompt/reply text in `content`); the key name predates the widening.
23699
- // Absent until granted, and a grant for a different endpoint or an older
23700
- // payload no longer counts.
23708
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23709
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23710
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23711
+ // both widenings. Absent until granted, and a grant for a different endpoint
23712
+ // or an older payload no longer counts.
23701
23713
  historySyncConsent: HistorySyncConsent.optional()
23702
23714
  });
23703
23715
  function defaultWorkspaceSettings() {
@@ -23828,6 +23840,9 @@ var ManagedSettingKey = external_exports.enum([
23828
23840
  "dataSharesInPlace",
23829
23841
  "redactFallback"
23830
23842
  ]).meta({ id: "ManagedSettingKey" });
23843
+ function isManagedSettingKey(value) {
23844
+ return ManagedSettingKey.safeParse(value).success;
23845
+ }
23831
23846
  var ManagedSettingsValues = external_exports.object({
23832
23847
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
23833
23848
  controlPlane: external_exports.object({
@@ -23852,7 +23867,27 @@ var ManagedSettings = external_exports.object({
23852
23867
  // Which of those the user may not change. A key here with no matching value
23853
23868
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23854
23869
  // the user may still override. The two are separable on purpose.
23855
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23870
+ //
23871
+ // Parsed as NAMES rather than as the enum, and split below: a name this
23872
+ // build does not know is dropped from the locked set and reported, never a
23873
+ // reason to refuse the file. The same shape reaches an older build whenever
23874
+ // an administrator locks a key a newer build added, and refusing it there
23875
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
23876
+ // the fleets most likely to carry a version skew. A name outside the enum
23877
+ // is still never HONOURED: the lockable set stays explicit above.
23878
+ lockedFields: external_exports.array(external_exports.string()).default([])
23879
+ }).transform(({ lockedFields, ...rest }) => {
23880
+ const known = [];
23881
+ const unknown2 = [];
23882
+ for (const name of lockedFields) {
23883
+ if (isManagedSettingKey(name)) known.push(name);
23884
+ else unknown2.push(name);
23885
+ }
23886
+ return {
23887
+ ...rest,
23888
+ lockedFields: known,
23889
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
23890
+ };
23856
23891
  }).meta({ id: "ManagedSettings" });
23857
23892
 
23858
23893
  // ../../packages/schema/src/zod/project-files.ts
@@ -23976,7 +24011,11 @@ var FindingsTimeseriesPoint = external_exports.object({
23976
24011
  timestamp: external_exports.iso.date(),
23977
24012
  critical: external_exports.number().int().nonnegative(),
23978
24013
  high: external_exports.number().int().nonnegative(),
23979
- medium: external_exports.number().int().nonnegative()
24014
+ medium: external_exports.number().int().nonnegative(),
24015
+ // Optional and additive, so a producer written against the earlier
24016
+ // three-series contract keeps validating. A consumer plotting it resolves the
24017
+ // absent case itself — the chart point requires a number.
24018
+ low: external_exports.number().int().nonnegative().optional()
23980
24019
  }).meta({ id: "FindingsTimeseriesPoint" });
23981
24020
  var FindingsTimeseriesResponse = external_exports.object({
23982
24021
  range: TimeRange,
@@ -24002,6 +24041,10 @@ var ResolvedFeedItem = external_exports.object({
24002
24041
  findingKey: external_exports.string(),
24003
24042
  ruleId: external_exports.string(),
24004
24043
  severity: Severity,
24044
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24045
+ // identifies the file: a bare path matches the same name in every repo.
24046
+ // Optional and additive; empty when the event carried no repo.
24047
+ repo: external_exports.string().optional(),
24005
24048
  path: external_exports.string(),
24006
24049
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24007
24050
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -25575,7 +25618,8 @@ var SqliteActivityRepository = class {
25575
25618
  SELECT 1 FROM audit_events d
25576
25619
  WHERE d.root_session_id = audit_events.id
25577
25620
  AND (d.content LIKE ? ESCAPE '\\'
25578
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
25621
+ OR coalesce(json_extract(d.attributes, '$.detail'),
25622
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25579
25623
  );
25580
25624
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25581
25625
  }
@@ -26913,23 +26957,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
26913
26957
  )`;
26914
26958
 
26915
26959
  // ../../packages/persistence/src/repositories/findings.ts
26916
- var PREVIEW_INSTANCES_PER_GROUP = 200;
26917
- var DEFAULT_LOCATIONS_LIMIT = 100;
26918
- var LOCATION_RULE_IDS_CAP = 20;
26919
- function compareLocationOrder(a, b) {
26920
- return compareFindingGroupOrder(
26921
- {
26922
- severity: a.maxSeverity,
26923
- latestDetectedAt: a.latestDetectedAt,
26924
- id: ""
26925
- },
26926
- {
26927
- severity: b.maxSeverity,
26928
- latestDetectedAt: b.latestDetectedAt,
26929
- id: ""
26930
- }
26931
- );
26932
- }
26933
26960
  var CONCAT_SEP = ",";
26934
26961
  var TUPLE_SEP = "|";
26935
26962
  function splitConcat(value) {
@@ -26981,13 +27008,48 @@ function decodeGroupCursor(cursor) {
26981
27008
  return null;
26982
27009
  }
26983
27010
  function firstAfter(sorted, cursor) {
26984
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
27011
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
26985
27012
  return index === -1 ? sorted.length : index;
26986
27013
  }
26987
27014
  function findDeepLinked(sorted, page, id) {
26988
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
26989
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
27015
+ if (page.some((t) => t.id === id)) return void 0;
27016
+ return sorted.find((t) => t.id === id);
26990
27017
  }
27018
+ function encodeLocationCursor(location) {
27019
+ const payload = {
27020
+ sev: location.maxSeverity,
27021
+ t: location.latestDetectedAt,
27022
+ r: location.repo,
27023
+ f: location.file
27024
+ };
27025
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
27026
+ }
27027
+ function decodeLocationCursor(cursor) {
27028
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
27029
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
27030
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
27031
+ }
27032
+ return null;
27033
+ }
27034
+ function firstLocationAfter(sorted, cursor) {
27035
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
27036
+ return index === -1 ? sorted.length : index;
27037
+ }
27038
+ function findDeepLinkedLocation(sorted, page, id) {
27039
+ if (page.some((l) => l.id === id)) return void 0;
27040
+ return sorted.find((l) => l.id === id);
27041
+ }
27042
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
27043
+ d.severity AS severity, f.masked_match AS masked_match,
27044
+ f.action_taken AS action_taken, f.confidence AS confidence,
27045
+ e.started_at AS occurred_at,
27046
+ e.source_tool AS source_tool,
27047
+ e.repo AS repo,
27048
+ e.file_path AS file,
27049
+ e.tool_name AS tool_name,
27050
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
27051
+ e.event_type AS kind, f.finding_key AS finding_key,
27052
+ ${latestResolutionStatusSql("f")} AS latest_status`;
26991
27053
  var DAY_MS3 = 864e5;
26992
27054
  var SqliteFindingsRepository = class {
26993
27055
  constructor(db) {
@@ -27108,30 +27170,26 @@ var SqliteFindingsRepository = class {
27108
27170
  );
27109
27171
  }
27110
27172
  /**
27111
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27112
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27113
- * attributes bag, rule_id/category/severity from the definition), scoped to
27114
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27115
- * rows this list must never surface), groups by ruleId, computes
27116
- * per-filter-excluded facets, applies the requested filters, and sorts by
27117
- * severity then recency. Filtering
27118
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27119
- * reflect the full filtered set; `items` is the requested
27120
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27121
- * filter, `totals.findings` counts only instances whose derived status was
27122
- * requested, and each item's instance preview is narrowed the same way.
27173
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
27174
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
27175
+ * list must never surface), with per-filter-excluded facets, the requested
27176
+ * filters applied, and sorted by severity then recency. Filtering and faceting
27177
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
27178
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
27179
+ * Under a `status` filter, `totals.findings` counts only findings whose
27180
+ * derived status was requested.
27181
+ *
27182
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
27183
+ * folding EVERY finding into the numbers a type row and the filters need
27184
+ * (count, severity, category, providers, actions, statuses, latest, search
27185
+ * text). The findings OF a type come from listFindingInstances scoped to
27186
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27123
27187
  *
27124
- * Two reads, neither of which materializes a row per finding:
27125
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27126
- * the group and the filters need (count, providers, actions, statuses,
27127
- * latest, search text);
27128
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27129
- * populate `instances` for the table's expanded rows.
27130
27188
  * The aggregates carry raw DB values and are translated by the same
27131
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27132
- * rule is ever restated in SQL.
27189
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
27190
+ * status rule is ever restated in SQL.
27133
27191
  */
27134
- listGroupedFindings(query) {
27192
+ listFindingTypes(query) {
27135
27193
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27136
27194
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27137
27195
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27144,12 +27202,7 @@ var SqliteFindingsRepository = class {
27144
27202
  predicate,
27145
27203
  params: sessionParams
27146
27204
  });
27147
- const rows = this.previewRows(aggregates, {
27148
- sessionId: query.sessionId,
27149
- from: query.from
27150
- });
27151
- const groupable = rows.map(toFlatFindingRow);
27152
- const allGroups = buildFindingGroups(groupable, { aggregates });
27205
+ const allTypes = buildFindingTypes(aggregates);
27153
27206
  const filterOpts = {
27154
27207
  severity: query.severity,
27155
27208
  providers: query.provider,
@@ -27158,30 +27211,25 @@ var SqliteFindingsRepository = class {
27158
27211
  subtype: query.subtype,
27159
27212
  q: query.q
27160
27213
  };
27161
- const facets = computeFindingFacets(allGroups, filterOpts);
27162
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
27214
+ const facets = computeFindingFacets(allTypes, filterOpts);
27215
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27163
27216
  const statusFilter = query.status ?? [];
27164
27217
  const totals = {
27165
- findings: sorted.reduce((acc, g) => {
27166
- if (statusFilter.length === 0) return acc + g.instanceCount;
27167
- const agg = aggregates.get(g.id);
27168
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
27218
+ findings: sorted.reduce((acc, t) => {
27219
+ if (statusFilter.length === 0) return acc + t.instanceCount;
27220
+ const agg = aggregates.get(t.id);
27221
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27169
27222
  }, 0),
27170
- groups: sorted.length
27223
+ types: sorted.length
27171
27224
  };
27172
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
27225
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27173
27226
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27174
27227
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27175
27228
  const page = sorted.slice(start, start + limit);
27176
27229
  const lastOnPage = page.at(-1);
27177
27230
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27178
27231
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27179
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27180
- const narrow = (g) => statusSet ? {
27181
- ...g,
27182
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27183
- } : g;
27184
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
27232
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27185
27233
  return Promise.resolve({
27186
27234
  totals,
27187
27235
  facets,
@@ -27192,7 +27240,7 @@ var SqliteFindingsRepository = class {
27192
27240
  }
27193
27241
  /**
27194
27242
  * One row per rule_id, folding EVERY instance of the group into the values
27195
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
27243
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27196
27244
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27197
27245
  *
27198
27246
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27286,13 +27334,25 @@ var SqliteFindingsRepository = class {
27286
27334
  });
27287
27335
  }
27288
27336
  /**
27289
- * The same findings folded by location: repository, then file within it.
27337
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27290
27338
  *
27291
27339
  * The grouping keys come from the capturing event's attributes, which is what
27292
- * the local store relates a finding to — there is no finding↔asset row to
27293
- * group by instead. A repo or file the event did not record folds into the
27294
- * empty-string bucket, which the view renders but does not link, since no
27295
- * filter can name it.
27340
+ * the local store relates a finding to; there is no finding↔asset row to group
27341
+ * by instead. A repo or file the event did not record folds into the
27342
+ * empty-string bucket, which is a real location like any other: it is listed,
27343
+ * it is selectable, and its `?loc=` token is as good as any other row's.
27344
+ *
27345
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
27346
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
27347
+ * list was rebuilt to remove — and two-level pagination inside an
27348
+ * expand/collapse table is what pushed that view to master/detail in the first
27349
+ * place.
27350
+ *
27351
+ * Every filter narrows the FINDINGS and the locations fall out of what
27352
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
27353
+ * reports for the same filters scoped to that pair. The view depends on it:
27354
+ * one toolbar sits over both panels precisely because a location owns none of
27355
+ * its fields.
27296
27356
  */
27297
27357
  listFindingLocations(query) {
27298
27358
  const opts = {
@@ -27304,13 +27364,16 @@ var SqliteFindingsRepository = class {
27304
27364
  tools: query.tool,
27305
27365
  q: query.q
27306
27366
  };
27307
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
27367
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
27368
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27308
27369
  const byRepo = /* @__PURE__ */ new Map();
27370
+ const accumulator = createInstanceFacetAccumulator(opts);
27309
27371
  let total = 0;
27310
27372
  for (const row of this.scanFindingRows({
27311
27373
  sessionId: query.sessionId,
27312
27374
  from: query.from
27313
27375
  })) {
27376
+ accumulator.add(row);
27314
27377
  if (!matchesInstanceFilters(row, opts)) continue;
27315
27378
  total += 1;
27316
27379
  let files = byRepo.get(row.repo);
@@ -27325,103 +27388,35 @@ var SqliteFindingsRepository = class {
27325
27388
  }
27326
27389
  addToLocation(acc, row);
27327
27390
  }
27328
- let fileCount = 0;
27329
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27330
- fileCount += files.size;
27331
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27332
- file: file2,
27333
- instanceCount: acc.instanceCount,
27334
- maxSeverity: acc.maxSeverity,
27335
- latestDetectedAt: acc.latestDetectedAt,
27336
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27337
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27338
- })).sort(compareLocationOrder);
27339
- const rollup = fileRows.reduce(
27340
- (a, f) => ({
27341
- instanceCount: a.instanceCount + f.instanceCount,
27342
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27343
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27344
- }),
27345
- {
27346
- instanceCount: 0,
27347
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27348
- latestDetectedAt: ""
27349
- }
27350
- );
27351
- const statuses = fileRows.map((f) => f.status);
27352
- const folded = foldGroupStatus(statuses);
27353
- return {
27354
- repo,
27355
- instanceCount: rollup.instanceCount,
27356
- maxSeverity: rollup.maxSeverity,
27357
- latestDetectedAt: rollup.latestDetectedAt,
27358
- ...folded === void 0 ? {} : { status: folded },
27359
- files: fileRows
27360
- };
27361
- });
27362
- repos.sort(compareLocationOrder);
27391
+ const sorted = [];
27392
+ for (const [repo, files] of byRepo) {
27393
+ for (const [file2, acc] of files) {
27394
+ const status = foldGroupStatus(acc.statuses);
27395
+ sorted.push({
27396
+ id: encodeLocationId(repo, file2),
27397
+ repo,
27398
+ file: file2,
27399
+ instanceCount: acc.instanceCount,
27400
+ maxSeverity: acc.maxSeverity,
27401
+ latestDetectedAt: acc.latestDetectedAt,
27402
+ ...status === void 0 ? {} : { status },
27403
+ ruleIds: [...acc.ruleIds]
27404
+ });
27405
+ }
27406
+ }
27407
+ sorted.sort(compareLocationOrder);
27408
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
27409
+ const page = sorted.slice(start, start + limit);
27410
+ const lastOnPage = page.at(-1);
27411
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
27412
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27363
27413
  return Promise.resolve({
27364
- totals: { findings: total, repos: repos.length, files: fileCount },
27365
- items: repos.slice(0, limit),
27366
- hasMore: repos.length > limit
27414
+ totals: { findings: total, locations: sorted.length },
27415
+ facets: accumulator.facets(),
27416
+ items: [...page, ...deepLinked ? [deepLinked] : []],
27417
+ nextCursor
27367
27418
  });
27368
27419
  }
27369
- /**
27370
- * Each group's newest instances, for the table's expanded rows.
27371
- *
27372
- * ONE index-ordered scan with early termination, and the shape is the point.
27373
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27374
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27375
- * through a temp B-tree to keep a bounded preview of each group, and then
27376
- * sorts the survivors again for the page order. Both sorts grow with the
27377
- * store while the answer does not.
27378
- *
27379
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27380
- * (or the session or window index the scope names — see `findingScanSql`),
27381
- * which is already the order the page wants, and keeps rows per rule until
27382
- * each rule has as many as it can show. The aggregate the caller already holds
27383
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27384
- * per rule, summed, is the number of rows this scan has to find, and it stops
27385
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27386
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27387
- * store with many firing rules widens it. The bound that DOES hold
27388
- * unconditionally is the sorted form's floor: this scan visits at most as
27389
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27390
- * sorted, and stops the moment every rule has its cap, where the sorted form
27391
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27392
- * wanted instances sitting at the tail of the scope — is one pass over
27393
- * everything in scope with a block sort of the id tie-break only, never a
27394
- * sort of the scope, which is still that floor.
27395
- *
27396
- * A row whose rule the aggregate did not see is skipped: the two statements
27397
- * run without a shared snapshot, so a capture landing between them can add a
27398
- * rule here that has no counts there, and the counts are what the group is
27399
- * built from.
27400
- */
27401
- previewRows(aggregates, scope) {
27402
- const wanted = /* @__PURE__ */ new Map();
27403
- let remaining = 0;
27404
- for (const [ruleId, agg] of aggregates) {
27405
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27406
- wanted.set(ruleId, n);
27407
- remaining += n;
27408
- }
27409
- const rows = [];
27410
- if (remaining === 0) return rows;
27411
- const { sql, params } = this.findingScanSql(scope);
27412
- const taken = /* @__PURE__ */ new Map();
27413
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27414
- const want = wanted.get(r.rule_id);
27415
- if (want === void 0) continue;
27416
- const have = taken.get(r.rule_id) ?? 0;
27417
- if (have >= want) continue;
27418
- taken.set(r.rule_id, have + 1);
27419
- rows.push(r);
27420
- remaining -= 1;
27421
- if (remaining === 0) break;
27422
- }
27423
- return rows;
27424
- }
27425
27420
  /**
27426
27421
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27427
27422
  *
@@ -27448,6 +27443,33 @@ var SqliteFindingsRepository = class {
27448
27443
  yield toFlatFindingRow(r);
27449
27444
  }
27450
27445
  }
27446
+ /**
27447
+ * One finding by its own id, or null when no such row exists.
27448
+ *
27449
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
27450
+ * the store — and, unlike anything derived from a list page, it resolves a
27451
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
27452
+ * deep link needs: the id it carries may name a finding thousands of rows
27453
+ * older than anything a first page holds.
27454
+ *
27455
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
27456
+ * RESOLVES an id; whether that row would survive the list's current filters is
27457
+ * a different question, and hiding the target because a filter excludes it is
27458
+ * worse than showing it.
27459
+ *
27460
+ * `groupId` on the result IS the rule id, so this one read answers both "which
27461
+ * type should the list select?" and "what does the drawer show?".
27462
+ */
27463
+ findingInstance(id) {
27464
+ const row = this.db.prepare(
27465
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
27466
+ FROM inspection_findings f
27467
+ JOIN audit_events e ON e.id = f.audit_event_id
27468
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27469
+ WHERE f.id = ?`
27470
+ ).get(id);
27471
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
27472
+ }
27451
27473
  /**
27452
27474
  * The one statement both instance-level scans run: every finding in scope,
27453
27475
  * joined to its event and definition, newest first.
@@ -27481,17 +27503,7 @@ var SqliteFindingsRepository = class {
27481
27503
  conditions.push("e.started_at >= ?");
27482
27504
  params.push(isoToEpochMillis(scope.from));
27483
27505
  }
27484
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27485
- d.severity AS severity, f.masked_match AS masked_match,
27486
- f.action_taken AS action_taken, f.confidence AS confidence,
27487
- e.started_at AS occurred_at,
27488
- e.source_tool AS source_tool,
27489
- e.repo AS repo,
27490
- e.file_path AS file,
27491
- e.tool_name AS tool_name,
27492
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27493
- e.event_type AS kind, f.finding_key AS finding_key,
27494
- ${latestResolutionStatusSql("f")} AS latest_status
27506
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27495
27507
  FROM audit_events e
27496
27508
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27497
27509
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27505,6 +27517,26 @@ var SqliteFindingsRepository = class {
27505
27517
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27506
27518
  const rows = this.db.prepare(
27507
27519
  `SELECT rule_id,
27520
+ -- BARE columns beside max(latest_at), which is deliberate and
27521
+ -- is SQLite's documented behaviour: with a single min()/max()
27522
+ -- in an aggregate query, every bare column takes its value from
27523
+ -- the row that produced the extremum. So these are the severity
27524
+ -- and category of the definition whose finding is NEWEST, which
27525
+ -- is what the row-based build they replaced read off its first
27526
+ -- (newest-first) row.
27527
+ --
27528
+ -- min() is WRONG here and was the defect: inspection_definitions
27529
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
27530
+ -- mints a new row), so a rule whose severity moved between
27531
+ -- versions has several, and min() picks the ALPHABETICALLY
27532
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
27533
+ -- That is arbitrary in direction, and it feeds the badge, the
27534
+ -- filter, the facet counts and the primary sort key.
27535
+ --
27536
+ -- Adding a second min()/max() aggregate here would make these
27537
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
27538
+ severity,
27539
+ category,
27508
27540
  sum(tuple_count) AS instance_count,
27509
27541
  max(latest_at) AS latest_at,
27510
27542
  group_concat(source_tools) AS source_tools,
@@ -27515,6 +27547,14 @@ var SqliteFindingsRepository = class {
27515
27547
  group_concat(tool_names) AS tool_names
27516
27548
  FROM (
27517
27549
  SELECT d.rule_id AS rule_id,
27550
+ -- Severity and category are columns of the DEFINITION, and
27551
+ -- a rule can have SEVERAL definitions (one per version), so
27552
+ -- these are grouped on below and resolved to the newest
27553
+ -- firing version by the outer query's bare-column select.
27554
+ -- They ride the aggregate because the type build has no rows
27555
+ -- to read them off \u2014 see buildFindingTypes.
27556
+ d.severity AS severity,
27557
+ d.category AS category,
27518
27558
  e.event_type || '${TUPLE_SEP}' ||
27519
27559
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27520
27560
  coalesce(latest.status, '') AS status_tuple,
@@ -27529,7 +27569,7 @@ var SqliteFindingsRepository = class {
27529
27569
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27530
27570
  ON latest.finding_key = f.finding_key
27531
27571
  ${scope.predicate}
27532
- GROUP BY d.rule_id, status_tuple
27572
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27533
27573
  )
27534
27574
  GROUP BY rule_id`
27535
27575
  ).all(scope.params);
@@ -27538,6 +27578,8 @@ var SqliteFindingsRepository = class {
27538
27578
  r.rule_id,
27539
27579
  {
27540
27580
  instanceCount: r.instance_count,
27581
+ severity: r.severity,
27582
+ category: r.category,
27541
27583
  sourceTools: splitConcat(r.source_tools),
27542
27584
  actionsTaken: splitConcat(r.actions_taken),
27543
27585
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27554,7 +27596,7 @@ var SqliteFindingsRepository = class {
27554
27596
  latestDetectedAt: epochMillisToIso(r.latest_at),
27555
27597
  // Free text only — joined and substring-matched, so group_concat's
27556
27598
  // commas need no unpicking (a repo/path containing one still matches).
27557
- // Left undefined (not '') when unfetched, so buildFindingGroups can
27599
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27558
27600
  // tell "no q this request" from "a group with no repo/file at all"
27559
27601
  // and skip priming a haystack nothing will read.
27560
27602
  ...withSearchText ? {
@@ -27706,6 +27748,12 @@ var SqliteHistorySyncRepository = class {
27706
27748
  this.markOwedStmt = db.prepare(
27707
27749
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27708
27750
  );
27751
+ this.markCaptureBacklogOwedStmt = db.prepare(
27752
+ `UPDATE audit_events SET outbox_owed = 1
27753
+ WHERE synced_at IS NULL
27754
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27755
+ AND started_at < :before`
27756
+ );
27709
27757
  this.stampStmt = db.prepare(
27710
27758
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27711
27759
  );
@@ -27754,7 +27802,9 @@ var SqliteHistorySyncRepository = class {
27754
27802
  );
27755
27803
  this.disownCapturesStmt = db.prepare(
27756
27804
  `UPDATE audit_events SET outbox_owed = NULL
27757
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27805
+ WHERE outbox_owed IS NOT NULL
27806
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27807
+ AND started_at < :attachedAt`
27758
27808
  );
27759
27809
  this.rearmStmt = db.prepare(
27760
27810
  `UPDATE audit_events SET synced_at = NULL
@@ -27830,6 +27880,7 @@ var SqliteHistorySyncRepository = class {
27830
27880
  freezeBoundaryStmt;
27831
27881
  captureRowsStmt;
27832
27882
  markOwedStmt;
27883
+ markCaptureBacklogOwedStmt;
27833
27884
  captureSkipCountStmt;
27834
27885
  disownCapturesStmt;
27835
27886
  partitionStmt;
@@ -27893,6 +27944,23 @@ var SqliteHistorySyncRepository = class {
27893
27944
  markCaptureOwed(id) {
27894
27945
  this.markOwedStmt.run({ id });
27895
27946
  }
27947
+ /**
27948
+ * Mark every capture already on disk as owed, as of `before`.
27949
+ *
27950
+ * The consent-time backfill, called once from `aka attach` when a human
27951
+ * grants existing-history consent — never from an ongoing drain pass, and
27952
+ * never inferred from a boundary that could later move. `before` is the
27953
+ * caller's own "now" at the moment consent was granted, so what this marks
27954
+ * is exactly the backlog the consent prompt already counted, not whatever a
27955
+ * later re-attach or key rotation might widen it to.
27956
+ *
27957
+ * Returns how many rows matched, for the caller to log or test against. Not a
27958
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
27959
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27960
+ */
27961
+ markCaptureBacklogOwed(before) {
27962
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27963
+ }
27896
27964
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27897
27965
  markSynced(ids, atMs) {
27898
27966
  this.stampAll(ids, atMs);
@@ -28009,15 +28077,42 @@ var SqliteHistorySyncRepository = class {
28009
28077
  *
28010
28078
  * Delivery is a fact about ONE recipient: rows sent to the deployment a
28011
28079
  * machine has just left are undelivered as far as the new one is concerned.
28012
- * All three in one transaction, so a crash between them cannot leave stamps
28013
- * attributed to the wrong deployment, or a boundary that belongs to another.
28080
+ * All four in one transaction, so a crash between them cannot leave stamps
28081
+ * attributed to the wrong deployment, a boundary that belongs to another, or
28082
+ * a disown with no re-mark to follow it.
28014
28083
  *
28015
28084
  * The boundary is written HERE and only here, which is what freezes it: a
28016
28085
  * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28017
28086
  * unchanged, so this never runs and the backlog does not widen back over rows
28018
28087
  * the live path has since delivered.
28088
+ *
28089
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28090
+ * granted existing-history consent for the deployment this call is arming —
28091
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28092
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28093
+ * apart. Passed only when that grant is valid, since this method has no way
28094
+ * to check consent itself and must not mark a row owed for a machine that
28095
+ * never agreed to it. Applied AFTER the disown above, in the SAME
28096
+ * transaction: what the disown clears is every marker below `backlogBefore`,
28097
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28098
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28099
+ * on the cleared side of that bound — and the re-mark in the same
28100
+ * transaction is what puts those rows back. A crash between the two cannot
28101
+ * strand the ledger disowned with nothing re-marked — the transaction either
28102
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
28103
+ * committed re-enters this method on the very next pass. Omit it (the
28104
+ * structural-only tests do) to exercise the disown in isolation.
28105
+ *
28106
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
28107
+ * touching a marker the NEW deployment's OWN live path has already set: B's
28108
+ * live path can mark a capture owed from the moment `aka attach` writes the
28109
+ * descriptor, before the drain's first pass ever reaches this method, and
28110
+ * such a row sits at or after the bound rather than below it. What keeps the
28111
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
28112
+ * bound — disown runs first, re-mark second, both inside the one
28113
+ * transaction above.
28019
28114
  */
28020
- rearmFor(fingerprint, backlogBefore) {
28115
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28021
28116
  this.ensureRowStmt.run();
28022
28117
  withTransaction(
28023
28118
  this.db,
@@ -28025,7 +28120,10 @@ var SqliteHistorySyncRepository = class {
28025
28120
  const previous = getRow(this.fingerprintStmt)?.fingerprint;
28026
28121
  this.rearmStmt.run();
28027
28122
  if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28028
- this.disownCapturesStmt.run();
28123
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28124
+ }
28125
+ if (backfillCapturesBefore !== void 0) {
28126
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28029
28127
  }
28030
28128
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28031
28129
  },
@@ -28302,7 +28400,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28302
28400
  }
28303
28401
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28304
28402
  }
28305
- function readManagedSettings(paths = managedSettingsPaths()) {
28403
+ var testOnlyManagedPaths = null;
28404
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28306
28405
  for (const path of paths) {
28307
28406
  let text;
28308
28407
  try {
@@ -30782,7 +30881,7 @@ function toUtcDateString(ms) {
30782
30881
  return new Date(ms).toISOString().slice(0, 10);
30783
30882
  }
30784
30883
  function isTimeseriesSeverity(s) {
30785
- return s === "critical" || s === "high" || s === "medium";
30884
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30786
30885
  }
30787
30886
  var SqliteSecurityRepository = class {
30788
30887
  constructor(db, now = () => Date.now()) {
@@ -30911,12 +31010,16 @@ var SqliteSecurityRepository = class {
30911
31010
  const now = this.now();
30912
31011
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
30913
31012
  const rows = this.findingsInRange(windowStart, now);
30914
- const points = Array.from({ length: numBuckets }, (_, i) => ({
30915
- timestamp: toUtcDateString(windowStart + i * bucketMs),
30916
- critical: 0,
30917
- high: 0,
30918
- medium: 0
30919
- }));
31013
+ const points = Array.from(
31014
+ { length: numBuckets },
31015
+ (_, i) => ({
31016
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31017
+ critical: 0,
31018
+ high: 0,
31019
+ medium: 0,
31020
+ low: 0
31021
+ })
31022
+ );
30920
31023
  for (const r of rows) {
30921
31024
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
30922
31025
  const bucket = points[idx];
@@ -31134,6 +31237,7 @@ var SqliteSecurityRepository = class {
31134
31237
  `SELECT f.finding_key AS finding_key,
31135
31238
  d.rule_id AS rule_id,
31136
31239
  d.severity AS severity,
31240
+ e.repo AS repo,
31137
31241
  e.file_path AS path,
31138
31242
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31139
31243
  latest.resolved_at AS latest_resolved_at
@@ -31153,6 +31257,7 @@ var SqliteSecurityRepository = class {
31153
31257
  const items = rows.map((r) => ({
31154
31258
  findingKey: r.finding_key,
31155
31259
  ruleId: r.rule_id,
31260
+ repo: r.repo ?? "",
31156
31261
  severity: r.severity,
31157
31262
  path: r.path ?? "",
31158
31263
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31162,13 +31267,66 @@ var SqliteSecurityRepository = class {
31162
31267
  }));
31163
31268
  return Promise.resolve({ items });
31164
31269
  }
31270
+ /**
31271
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31272
+ *
31273
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31274
+ * list: a secret committed three weeks ago and never rotated is still the most
31275
+ * important thing to fix, and any window hides it. It carried a "newest N
31276
+ * findings" cap and then a range; the first meant a different span on every
31277
+ * machine, and the second reported "no recommendations" over live exposure.
31278
+ *
31279
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31280
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31281
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31282
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31283
+ * The two answer different questions and only this one has to match a link.
31284
+ *
31285
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31286
+ * whole-store scope costs a grouped scan rather than a row per finding.
31287
+ */
31288
+ recommendationInputs() {
31289
+ const rows = allRows(
31290
+ this.db.prepare(
31291
+ `SELECT d.rule_id AS rule_id,
31292
+ d.category AS category,
31293
+ d.severity AS severity,
31294
+ COUNT(*) AS count
31295
+ FROM inspection_findings f
31296
+ JOIN audit_events e ON e.id = f.audit_event_id
31297
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31298
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31299
+ ON latest.finding_key = f.finding_key
31300
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31301
+ AND e.event_type = 'code_change'
31302
+ AND (
31303
+ f.finding_key IS NULL
31304
+ OR latest.status IS NULL
31305
+ OR latest.status NOT IN ('resolved', 'dismissed')
31306
+ )
31307
+ GROUP BY d.rule_id, d.category, d.severity`
31308
+ )
31309
+ );
31310
+ return Promise.resolve(
31311
+ rows.map((r) => ({
31312
+ ruleId: r.rule_id,
31313
+ category: r.category,
31314
+ severity: r.severity,
31315
+ count: r.count
31316
+ }))
31317
+ );
31318
+ }
31165
31319
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31166
31320
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31167
31321
  // numeric and the JS aggregations bucket/split on ms directly.
31168
31322
  findingsInRange(fromMs, toMs) {
31169
31323
  const rows = allRows(
31170
31324
  this.db.prepare(
31171
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31325
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31326
+ // joined for `severity`, so they are two more columns off a row this read
31327
+ // already fetches. They feed the recommended-actions rollup.
31328
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31329
+ d.rule_id AS rule_id, d.category AS category
31172
31330
  FROM inspection_findings f
31173
31331
  JOIN audit_events e ON e.id = f.audit_event_id
31174
31332
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -31181,7 +31339,9 @@ var SqliteSecurityRepository = class {
31181
31339
  return rows.map((r) => ({
31182
31340
  occurredAt: r.occurred_at,
31183
31341
  severity: r.severity,
31184
- actionTaken: r.action_taken
31342
+ actionTaken: r.action_taken,
31343
+ ruleId: r.rule_id,
31344
+ category: r.category
31185
31345
  }));
31186
31346
  }
31187
31347
  };
@@ -32351,14 +32511,51 @@ function openLocalDatabase(dir) {
32351
32511
  };
32352
32512
  }
32353
32513
 
32354
- // ../../packages/persistence/src/finding-key.ts
32514
+ // ../../packages/persistence/src/egress-wire.ts
32355
32515
  import { createHash as createHash3 } from "crypto";
32516
+ function hashProjectKey(projectKey) {
32517
+ return createHash3("sha256").update(projectKey, "utf8").digest("hex");
32518
+ }
32519
+ function toIngestHit(hit) {
32520
+ return {
32521
+ host: hit.host,
32522
+ kind: hit.kind,
32523
+ name: hit.name,
32524
+ category: hit.category,
32525
+ trust: hit.trust,
32526
+ network: hit.network,
32527
+ method: hit.method,
32528
+ transport: hit.transport,
32529
+ url: hit.url,
32530
+ template: hit.template,
32531
+ dataClass: hit.dataClass,
32532
+ site: {
32533
+ file: hit.site.file,
32534
+ line: hit.site.line,
32535
+ dynamic: hit.site.dynamic,
32536
+ vendored: hit.site.vendored
32537
+ }
32538
+ };
32539
+ }
32540
+ function toEgressIngestRequest(input2) {
32541
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32542
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32543
+ return {
32544
+ projectKey: hashProjectKey(input2.projectKey),
32545
+ project: input2.project,
32546
+ reconcile,
32547
+ hits: hits.map(toIngestHit)
32548
+ };
32549
+ }
32550
+
32551
+ // ../../packages/persistence/src/finding-key.ts
32552
+ import { createHash as createHash4 } from "crypto";
32356
32553
  function normalizeFilePath(filePath) {
32357
32554
  return filePath.replaceAll("\\", "/");
32358
32555
  }
32359
32556
  function computeFindingKey(input2) {
32360
32557
  const normalizedPath = normalizeFilePath(input2.filePath);
32361
- return createHash3("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32558
+ return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
32362
32559
  }
32363
32560
 
32364
32561
  // ../../packages/persistence/src/fingerprint.ts
@@ -32484,14 +32681,18 @@ function fingerprintValue(key, raw) {
32484
32681
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32485
32682
  }
32486
32683
 
32487
- // ../../packages/persistence/src/history-preview.ts
32684
+ // ../../packages/persistence/src/history-backfill.ts
32488
32685
  import { existsSync as existsSync4 } from "fs";
32489
32686
  import { join as join9 } from "path";
32687
+
32688
+ // ../../packages/persistence/src/history-preview.ts
32689
+ import { existsSync as existsSync5 } from "fs";
32690
+ import { join as join10 } from "path";
32490
32691
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32491
32692
 
32492
32693
  // ../../packages/persistence/src/store-symlinks.ts
32493
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32494
- import { dirname as dirname3, join as join10, resolve } from "path";
32694
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32695
+ import { dirname as dirname3, join as join11, resolve } from "path";
32495
32696
 
32496
32697
  // ../../packages/persistence/src/vault/crypto.ts
32497
32698
  import {
@@ -32506,61 +32707,25 @@ import {
32506
32707
  import { execFileSync } from "child_process";
32507
32708
  import { randomBytes as randomBytes2 } from "crypto";
32508
32709
  import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32509
- import { join as join11 } from "path";
32710
+ import { join as join12 } from "path";
32510
32711
 
32511
32712
  // ../../packages/persistence/src/vault/vault.ts
32512
32713
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32513
32714
 
32514
32715
  // ../../packages/persistence/src/warn-era-cap.ts
32515
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32516
- import { join as join12 } from "path";
32716
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32717
+ import { join as join13 } from "path";
32517
32718
  var MARKER = "warn-era-capped";
32518
32719
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32519
32720
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32520
- const marker = join12(dataDir2, MARKER);
32521
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32721
+ const marker = join13(dataDir2, MARKER);
32722
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32522
32723
  const capped = db.policies.capCategoryActions();
32523
32724
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32524
32725
  `, { mode: DATA_FILE_MODE });
32525
32726
  return { capped };
32526
32727
  }
32527
32728
 
32528
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32529
- function hashProjectKey(projectKey) {
32530
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32531
- }
32532
- function toIngestHit(hit) {
32533
- return {
32534
- host: hit.host,
32535
- kind: hit.kind,
32536
- name: hit.name,
32537
- category: hit.category,
32538
- trust: hit.trust,
32539
- network: hit.network,
32540
- method: hit.method,
32541
- transport: hit.transport,
32542
- url: hit.url,
32543
- template: hit.template,
32544
- dataClass: hit.dataClass,
32545
- site: {
32546
- file: hit.site.file,
32547
- line: hit.site.line,
32548
- dynamic: hit.site.dynamic,
32549
- vendored: hit.site.vendored
32550
- }
32551
- };
32552
- }
32553
- function toEgressIngestRequest(input2) {
32554
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32555
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32556
- return {
32557
- projectKey: hashProjectKey(input2.projectKey),
32558
- project: input2.project,
32559
- reconcile,
32560
- hits: hits.map(toIngestHit)
32561
- };
32562
- }
32563
-
32564
32729
  // ../../packages/remote/src/http.ts
32565
32730
  import { request as httpRequest } from "http";
32566
32731
  import { request as httpsRequest } from "https";
@@ -32840,6 +33005,7 @@ function createRemoteClient(options) {
32840
33005
  url: url2(ROUTES.shares),
32841
33006
  body: JSON.stringify(validated.data)
32842
33007
  });
33008
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32843
33009
  okBody(response);
32844
33010
  },
32845
33011
  async pollCommand() {
@@ -32862,19 +33028,51 @@ function createRemoteClient(options) {
32862
33028
  };
32863
33029
  }
32864
33030
 
32865
- // ../../packages/plugin-runtime/src/attached/failure.ts
33031
+ // ../../packages/remote/src/failure-kind.ts
32866
33032
  function statusOf(err) {
32867
33033
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32868
33034
  const { status } = err;
32869
33035
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32870
33036
  return status >= 100 && status <= 599 ? status : null;
32871
33037
  }
32872
- function classifyFailure(err) {
32873
- switch (statusOf(err)) {
33038
+ function nameOf(err) {
33039
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33040
+ return typeof err.name === "string" ? err.name : null;
33041
+ }
33042
+ function classifyRemoteFailure(err) {
33043
+ switch (nameOf(err)) {
33044
+ case "RemoteRouteAbsent":
33045
+ return "route-absent";
33046
+ case "RemoteRequestInvalid":
33047
+ return "invalid-request";
33048
+ case "RemoteResponseInvalid":
33049
+ return "rejected";
33050
+ default:
33051
+ break;
33052
+ }
33053
+ const status = statusOf(err);
33054
+ if (status === null) return "unreachable";
33055
+ switch (status) {
32874
33056
  case 401:
32875
33057
  return "unauthorized";
32876
33058
  case 403:
32877
33059
  return "forbidden";
33060
+ case 429:
33061
+ return "unreachable";
33062
+ case 404:
33063
+ return "unreachable";
33064
+ default:
33065
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33066
+ }
33067
+ }
33068
+
33069
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33070
+ function classifyFailure(err) {
33071
+ switch (classifyRemoteFailure(err)) {
33072
+ case "unauthorized":
33073
+ return "unauthorized";
33074
+ case "forbidden":
33075
+ return "forbidden";
32878
33076
  default:
32879
33077
  return "unreachable";
32880
33078
  }
@@ -32966,10 +33164,10 @@ function commandScanFor(config2, scanWorktree2, sourceTool) {
32966
33164
 
32967
33165
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32968
33166
  import { readFileSync as readFileSync8 } from "fs";
32969
- import { join as join13 } from "path";
33167
+ import { join as join14 } from "path";
32970
33168
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32971
33169
  function forwardDropsPath(dataDir2) {
32972
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33170
+ return join14(dataDir2, FORWARD_DROPS_FILENAME);
32973
33171
  }
32974
33172
  function recordForwardDrops(dataDir2, count, nowMs) {
32975
33173
  if (count <= 0) return;
@@ -33005,13 +33203,13 @@ function readForwardDrops(dataDir2) {
33005
33203
 
33006
33204
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33007
33205
  import { randomUUID as randomUUID15 } from "crypto";
33008
- import { readFileSync as readFileSync14 } from "fs";
33206
+ import { readFileSync as readFileSync15 } from "fs";
33009
33207
  import { readFile, rename, writeFile } from "fs/promises";
33010
- import { join as join22 } from "path";
33208
+ import { join as join24 } from "path";
33011
33209
 
33012
33210
  // ../../packages/plugin-sdk/src/config.ts
33013
- import { existsSync as existsSync7 } from "fs";
33014
- import { join as join14 } from "path";
33211
+ import { existsSync as existsSync8 } from "fs";
33212
+ import { join as join15 } from "path";
33015
33213
 
33016
33214
  // ../../packages/plugin-sdk/src/provider-env.ts
33017
33215
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33065,8 +33263,8 @@ function resolveProvider() {
33065
33263
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33066
33264
  try {
33067
33265
  ensureLayoutDirSync(base);
33068
- const settingsFile = join14(settingsDir(base), "settings.json");
33069
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33266
+ const settingsFile = join15(settingsDir(base), "settings.json");
33267
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33070
33268
  } catch {
33071
33269
  }
33072
33270
  migrateLegacyLayout(base);
@@ -33091,7 +33289,7 @@ function resolveProviderSafe(resolveProviderFn) {
33091
33289
  // ../../packages/plugin-sdk/src/config-inventory.ts
33092
33290
  import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33093
33291
  import { homedir as homedir2 } from "os";
33094
- import { basename as basename3, join as join16 } from "path";
33292
+ import { basename as basename3, join as join17 } from "path";
33095
33293
 
33096
33294
  // ../../packages/detections/src/egress/registry.ts
33097
33295
  var EXTRACTOR_VERSION = "1";
@@ -37015,8 +37213,8 @@ function bundledDetections() {
37015
37213
  }
37016
37214
 
37017
37215
  // ../../packages/plugin-sdk/src/repo.ts
37018
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
37019
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
37216
+ import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
37217
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
37020
37218
  function resolveRepoIdentity(cwd) {
37021
37219
  try {
37022
37220
  const root = findGitRoot(cwd);
@@ -37045,32 +37243,32 @@ function resolveWorktreeRoot(cwd) {
37045
37243
  function findGitRoot(start) {
37046
37244
  let dir = start;
37047
37245
  for (; ; ) {
37048
- if (existsSync8(join15(dir, ".git"))) return dir;
37246
+ if (existsSync9(join16(dir, ".git"))) return dir;
37049
37247
  const parent = dirname4(dir);
37050
37248
  if (parent === dir) return void 0;
37051
37249
  dir = parent;
37052
37250
  }
37053
37251
  }
37054
37252
  function resolveGitContext(root) {
37055
- const dotGit = join15(root, ".git");
37253
+ const dotGit = join16(root, ".git");
37056
37254
  try {
37057
37255
  if (statSync6(dotGit).isDirectory()) {
37058
- return { configPath: join15(dotGit, "config"), headRoot: root };
37256
+ return { configPath: join16(dotGit, "config"), headRoot: root };
37059
37257
  }
37060
37258
  } catch {
37061
37259
  return void 0;
37062
37260
  }
37063
37261
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
37064
37262
  if (!target) return void 0;
37065
- const gitdir = isAbsolute(target) ? target : join15(root, target);
37066
- if (existsSync8(join15(gitdir, "config"))) {
37067
- return { configPath: join15(gitdir, "config"), headRoot: root };
37263
+ const gitdir = isAbsolute(target) ? target : join16(root, target);
37264
+ if (existsSync9(join16(gitdir, "config"))) {
37265
+ return { configPath: join16(gitdir, "config"), headRoot: root };
37068
37266
  }
37069
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
37267
+ const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
37070
37268
  if (!commonRaw) return void 0;
37071
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
37269
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
37072
37270
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
37073
- return { configPath: join15(commonGitDir, "config"), headRoot };
37271
+ return { configPath: join16(commonGitDir, "config"), headRoot };
37074
37272
  }
37075
37273
  function safeRead(path) {
37076
37274
  try {
@@ -37140,7 +37338,7 @@ function buildIngestEvent(input2) {
37140
37338
  }
37141
37339
 
37142
37340
  // ../../packages/plugin-sdk/src/isolated-scan.ts
37143
- import { existsSync as existsSync9 } from "fs";
37341
+ import { existsSync as existsSync10 } from "fs";
37144
37342
  import { fileURLToPath } from "url";
37145
37343
  import { Worker } from "worker_threads";
37146
37344
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -37154,7 +37352,7 @@ function resolveWorkerUrl() {
37154
37352
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
37155
37353
  const candidate = new URL(name, import.meta.url);
37156
37354
  try {
37157
- if (existsSync9(fileURLToPath(candidate))) {
37355
+ if (existsSync10(fileURLToPath(candidate))) {
37158
37356
  resolvedWorkerUrl = candidate;
37159
37357
  return candidate;
37160
37358
  }
@@ -37617,13 +37815,48 @@ function createGuardedScanner(partition, gateway, opts) {
37617
37815
  };
37618
37816
  }
37619
37817
 
37818
+ // ../../packages/plugin-sdk/src/host-floor.ts
37819
+ import { readFileSync as readFileSync12 } from "fs";
37820
+ import { join as join19 } from "path";
37821
+
37822
+ // ../../packages/plugin-sdk/src/model-governance.ts
37823
+ import {
37824
+ closeSync as closeSync2,
37825
+ fstatSync,
37826
+ mkdirSync as mkdirSync2,
37827
+ openSync as openSync2,
37828
+ readFileSync as readFileSync11,
37829
+ readSync,
37830
+ writeFileSync as writeFileSync5
37831
+ } from "fs";
37832
+ import { join as join18 } from "path";
37833
+ var TAIL_BYTES = 256 * 1024;
37834
+
37835
+ // ../../packages/plugin-sdk/src/host-floor.ts
37836
+ var HOST_FEATURE = {
37837
+ ModelSwitch: "model-switch",
37838
+ VaultPointerDisplay: "vault-pointer-display"
37839
+ };
37840
+ var HOST_FLOORS = {
37841
+ [HOST_FEATURE.ModelSwitch]: {
37842
+ label: "model-switch protection",
37843
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37844
+ since: "2.1.251"
37845
+ },
37846
+ [HOST_FEATURE.VaultPointerDisplay]: {
37847
+ label: "vault pointer display",
37848
+ hookEvents: ["MessageDisplay"],
37849
+ since: "2.1.152"
37850
+ }
37851
+ };
37852
+
37620
37853
  // ../../packages/plugin-sdk/src/ignore-layers.ts
37621
37854
  var import_ignore = __toESM(require_ignore(), 1);
37622
- import { readFileSync as readFileSync11 } from "fs";
37623
- import { join as join17 } from "path";
37855
+ import { readFileSync as readFileSync13 } from "fs";
37856
+ import { join as join20 } from "path";
37624
37857
  function readIgnoreLayer(dir, filename, anchorLen) {
37625
37858
  try {
37626
- return { matcher: (0, import_ignore.default)().add(readFileSync11(join17(dir, filename), "utf8")), anchorLen };
37859
+ return { matcher: (0, import_ignore.default)().add(readFileSync13(join20(dir, filename), "utf8")), anchorLen };
37627
37860
  } catch {
37628
37861
  return void 0;
37629
37862
  }
@@ -37653,22 +37886,9 @@ function withLayer(layers, layer) {
37653
37886
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
37654
37887
  import { arch, hostname as hostname4, platform, release } from "os";
37655
37888
 
37656
- // ../../packages/plugin-sdk/src/model-governance.ts
37657
- import {
37658
- closeSync as closeSync2,
37659
- fstatSync,
37660
- mkdirSync as mkdirSync2,
37661
- openSync as openSync2,
37662
- readFileSync as readFileSync12,
37663
- readSync,
37664
- writeFileSync as writeFileSync5
37665
- } from "fs";
37666
- import { join as join18 } from "path";
37667
- var TAIL_BYTES = 256 * 1024;
37668
-
37669
37889
  // ../../packages/plugin-sdk/src/nudge.ts
37670
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
37671
- import { join as join19 } from "path";
37890
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
37891
+ import { join as join21 } from "path";
37672
37892
 
37673
37893
  // ../../packages/plugin-sdk/src/paths.ts
37674
37894
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -37740,8 +37960,8 @@ function createPolicyResolver(bundle) {
37740
37960
  }
37741
37961
 
37742
37962
  // ../../packages/plugin-sdk/src/project-files.ts
37743
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
37744
- import { basename as basename5, join as join20 } from "path";
37963
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37964
+ import { basename as basename5, join as join22 } from "path";
37745
37965
 
37746
37966
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
37747
37967
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -37772,6 +37992,14 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
37772
37992
  // ../../packages/plugin-sdk/src/runtime.ts
37773
37993
  import { randomUUID as randomUUID14 } from "crypto";
37774
37994
  var ENFORCEMENT_CEILING_ENABLED = false;
37995
+ function applyEnforcementCeiling(action, policyMode, enabled) {
37996
+ if (!enabled || policyMode !== "warn") return action;
37997
+ return action === "block" || action === "redact" ? "warn" : action;
37998
+ }
37999
+ function resolveEnforcedAction(action, opts) {
38000
+ const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
38001
+ return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
38002
+ }
37775
38003
  function startTiming() {
37776
38004
  try {
37777
38005
  return performance.now();
@@ -37880,12 +38108,12 @@ function createPluginRuntime(gateway, settings, opts) {
37880
38108
  }
37881
38109
  function actionForFinding(finding, excepted, rewritable = true) {
37882
38110
  if (excepted?.has(finding)) return "allow";
37883
- const action = resolveAction(finding.ruleId, finding.category);
37884
- if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
37885
- if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
37886
- return "warn";
37887
- }
37888
- return action;
38111
+ return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
38112
+ policyMode,
38113
+ redactFallback,
38114
+ rewritable,
38115
+ ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
38116
+ });
37889
38117
  }
37890
38118
  function decide(findings, text, excepted, rewritable = true) {
37891
38119
  if (findings.length === 0) return { action: "log", text, findings: [] };
@@ -38134,7 +38362,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38134
38362
 
38135
38363
  // ../../packages/plugin-sdk/src/throttle.ts
38136
38364
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38137
- import { join as join21 } from "path";
38365
+ import { join as join23 } from "path";
38138
38366
 
38139
38367
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
38140
38368
  function isInvalidRequest(err) {
@@ -38174,7 +38402,7 @@ function parseBreakerState(raw, nowMs) {
38174
38402
  }
38175
38403
  function createForwardPolicy(deps) {
38176
38404
  const now = deps.now ?? (() => Date.now());
38177
- const file2 = join22(deps.dir, STATE_FILENAME);
38405
+ const file2 = join24(deps.dir, STATE_FILENAME);
38178
38406
  let state = null;
38179
38407
  let loading = null;
38180
38408
  async function readState() {
@@ -38896,8 +39124,8 @@ function toolAuditEvent(input2) {
38896
39124
  }
38897
39125
 
38898
39126
  // ../../packages/plugin-runtime/src/attached/history-state.ts
38899
- import { readFileSync as readFileSync15 } from "fs";
38900
- import { join as join23 } from "path";
39127
+ import { readFileSync as readFileSync16 } from "fs";
39128
+ import { join as join25 } from "path";
38901
39129
 
38902
39130
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
38903
39131
  import { createHash as createHash6 } from "crypto";
@@ -38914,7 +39142,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
38914
39142
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
38915
39143
 
38916
39144
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
38917
- import { readFileSync as readFileSync16 } from "fs";
39145
+ import { readFileSync as readFileSync17 } from "fs";
38918
39146
  function createPluginBlock(build, policyStore) {
38919
39147
  return async () => {
38920
39148
  const cached2 = await policyStore.read();
@@ -38933,7 +39161,7 @@ function createPluginBlock(build, policyStore) {
38933
39161
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38934
39162
  import { randomUUID as randomUUID16 } from "crypto";
38935
39163
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
38936
- import { join as join24 } from "path";
39164
+ import { join as join26 } from "path";
38937
39165
 
38938
39166
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
38939
39167
  import { rename as rename2 } from "fs/promises";
@@ -38957,7 +39185,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38957
39185
 
38958
39186
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38959
39187
  function createPolicyStore(dir = dataDir()) {
38960
- const file2 = join24(dir, "policy-cache.json");
39188
+ const file2 = join26(dir, "policy-cache.json");
38961
39189
  async function read() {
38962
39190
  try {
38963
39191
  const raw = await readFile2(file2, "utf8");
@@ -39237,11 +39465,11 @@ function readStorePosture(dbPath2) {
39237
39465
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39238
39466
  import { randomUUID as randomUUID17 } from "crypto";
39239
39467
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39240
- import { join as join25 } from "path";
39468
+ import { join as join27 } from "path";
39241
39469
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39242
39470
  function createPostureStore(dir = settingsDir(), legacyDir) {
39243
- const file2 = join25(dir, "posture-state.json");
39244
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
39471
+ const file2 = join27(dir, "posture-state.json");
39472
+ const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
39245
39473
  async function persist(state) {
39246
39474
  await ensureDataDir(dir);
39247
39475
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39309,11 +39537,11 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39309
39537
  }
39310
39538
 
39311
39539
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39312
- import { readFileSync as readFileSync17 } from "fs";
39313
- import { join as join26 } from "path";
39540
+ import { readFileSync as readFileSync18 } from "fs";
39541
+ import { join as join28 } from "path";
39314
39542
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
39315
39543
  function syncStatePath(dataDir2) {
39316
- return join26(dataDir2, SYNC_STATE_FILENAME);
39544
+ return join28(dataDir2, SYNC_STATE_FILENAME);
39317
39545
  }
39318
39546
  function writeSyncState(dataDir2, result) {
39319
39547
  try {
@@ -39817,7 +40045,7 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
39817
40045
 
39818
40046
  // ../../packages/scanner/src/discover.ts
39819
40047
  import { readdirSync as readdirSync5 } from "fs";
39820
- import { join as join27 } from "path";
40048
+ import { join as join29 } from "path";
39821
40049
 
39822
40050
  // ../../packages/scanner/src/constants.ts
39823
40051
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -39841,15 +40069,15 @@ var DISCOVER_SKIP = /* @__PURE__ */ new Set([
39841
40069
  import { basename as basename6, relative } from "path";
39842
40070
 
39843
40071
  // ../../packages/scanner/src/scan.ts
39844
- import { existsSync as existsSync11, readFileSync as readFileSync19 } from "fs";
40072
+ import { existsSync as existsSync12, readFileSync as readFileSync20 } from "fs";
39845
40073
  import { extname as extname2, isAbsolute as isAbsolute2, relative as relative3 } from "path";
39846
40074
 
39847
40075
  // ../../packages/scanner/src/manifests.ts
39848
40076
  import { statSync as statSync11 } from "fs";
39849
40077
 
39850
40078
  // ../../packages/scanner/src/walk.ts
39851
- import { readdirSync as readdirSync6, readFileSync as readFileSync18, statSync as statSync10 } from "fs";
39852
- import { extname, join as join28, relative as relative2, sep as sep4 } from "path";
40079
+ import { readdirSync as readdirSync6, readFileSync as readFileSync19, statSync as statSync10 } from "fs";
40080
+ import { extname, join as join30, relative as relative2, sep as sep4 } from "path";
39853
40081
  var import_ignore2 = __toESM(require_ignore(), 1);
39854
40082
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
39855
40083
  ".ts",
@@ -39900,7 +40128,7 @@ function* walkTree(rootDir, opts = {}) {
39900
40128
  );
39901
40129
  for (const entry of dirents) {
39902
40130
  const name = entry.name;
39903
- const fullPath = join28(dir, name);
40131
+ const fullPath = join30(dir, name);
39904
40132
  if (entry.isDirectory()) {
39905
40133
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
39906
40134
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {
@@ -39954,7 +40182,7 @@ function* walkSourceFiles(opts = {}) {
39954
40182
  if (opts.shouldRead && !opts.shouldRead(meta4)) continue;
39955
40183
  let content;
39956
40184
  try {
39957
- content = readFileSync18(file2.path, "utf8");
40185
+ content = readFileSync19(file2.path, "utf8");
39958
40186
  } catch {
39959
40187
  continue;
39960
40188
  }
@@ -40074,7 +40302,7 @@ function isUnderRoot(path, rootDir) {
40074
40302
  async function sweepDeletedFiles(gateway, rootDir, previous) {
40075
40303
  const deleted = [];
40076
40304
  for (const path of previous.keys()) {
40077
- if (!isUnderRoot(path, rootDir) || existsSync11(path)) continue;
40305
+ if (!isUnderRoot(path, rootDir) || existsSync12(path)) continue;
40078
40306
  deleted.push(path);
40079
40307
  await resolveRemovedFindings(gateway, path, [], { deleted: true });
40080
40308
  }
@@ -40181,7 +40409,7 @@ function scanManifests(egress, ledger, updates, rootDir) {
40181
40409
  if (prev?.mtime === manifest.mtime) continue;
40182
40410
  let content;
40183
40411
  try {
40184
- content = readFileSync19(manifest.path, "utf8");
40412
+ content = readFileSync20(manifest.path, "utf8");
40185
40413
  } catch {
40186
40414
  continue;
40187
40415
  }