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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -492,10 +492,7 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/hooks/session-start.ts
495
- import { readFileSync as readFileSync21 } from "fs";
496
-
497
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
498
- import { createHash as createHash4 } from "crypto";
495
+ import { readFileSync as readFileSync22 } from "fs";
499
496
 
500
497
  // ../../packages/persistence/src/attached-derived.ts
501
498
  import { rmSync } from "fs";
@@ -20748,13 +20745,11 @@ var FindingGroup = external_exports.object({
20748
20745
  latestDetectedAt: external_exports.iso.datetime(),
20749
20746
  instances: external_exports.array(FindingInstance),
20750
20747
  // Derived from instances' statuses with open-dominates precedence (see
20751
- // buildFindingGroups). Undefined only when no instance carries a status.
20748
+ // foldGroupStatus). Undefined only when no instance carries a status.
20752
20749
  status: FindingStatus.optional(),
20753
- // The distinct people across the WHOLE group, not just the `instances`
20754
- // preview — from the store's whole-group aggregate when it supplies one,
20755
- // else folded from the rows (see buildFindingGroups). Undefined when no
20756
- // instance carries a user, or when the store supplied whole-group folds
20757
- // without one.
20750
+ // The distinct people across the WHOLE group, not just the instances
20751
+ // carried here. Undefined when no instance carries a user, or when the
20752
+ // store supplied whole-group folds without one.
20758
20753
  users: external_exports.array(FindingUser).optional()
20759
20754
  }).meta({ id: "FindingGroup" });
20760
20755
  var FindingStats = external_exports.object({
@@ -20783,21 +20778,31 @@ var FindingFacets = external_exports.object({
20783
20778
  // counted under no value.
20784
20779
  status: external_exports.array(FindingFacetItem),
20785
20780
  // Host tool (attributes.tool_name). Present only on the instance-level
20786
- // reads, which can filter by it; the grouped read omits the dimension
20781
+ // reads, which can filter by it; the type-level read omits the dimension
20787
20782
  // because a group spans tools.
20788
20783
  tool: external_exports.array(FindingFacetItem).optional()
20789
20784
  }).meta({ id: "FindingFacets" });
20790
- var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
20791
- var ListGroupedFindingsQuery = external_exports.object({
20785
+ var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20786
+ id: "FindingTypeSummary"
20787
+ });
20788
+ var DEFAULT_FINDING_TYPES_LIMIT = 50;
20789
+ var MAX_FINDING_TYPES_LIMIT = 100;
20790
+ var ListFindingTypesQuery = external_exports.object({
20792
20791
  // NOTE: severity filters by Severity (critical/high/medium/low), not by
20793
- // FindingAction.
20792
+ // FindingAction. It narrows TYPES: a type's severity is the one its newest
20793
+ // firing version carries, and this list pages types.
20794
+ //
20795
+ // That is NOT a claim the findings of a type share it. A rule can hold several
20796
+ // definition versions at different severities, so a type kept by this filter
20797
+ // can hold findings that individually do not match — see totals.findings on
20798
+ // ListFindingTypesResponse, which counts them all.
20794
20799
  severity: external_exports.array(Severity).optional(),
20795
20800
  subtype: external_exports.array(external_exports.string()).optional(),
20796
20801
  provider: external_exports.array(FindingProvider).optional(),
20797
20802
  action: external_exports.array(FindingAction).optional(),
20798
- // Matches a group's DERIVED status (see FindingGroup.status), not its
20799
- // individual instances' — so a filtered group's Status column always reads
20800
- // one of the requested values.
20803
+ // Matches a type's DERIVED status (see FindingGroup.status), not its
20804
+ // individual findings' — so a filtered row's status always reads one of the
20805
+ // requested values.
20801
20806
  status: external_exports.array(FindingStatus).optional(),
20802
20807
  q: external_exports.string().optional(),
20803
20808
  // Scope to findings whose event carries this session id (the Activity page's
@@ -20807,23 +20812,37 @@ var ListGroupedFindingsQuery = external_exports.object({
20807
20812
  // from a time-scoped page (Activity's range) can carry that scope. Absent
20808
20813
  // means all time — this list has no default window.
20809
20814
  from: external_exports.iso.datetime().optional(),
20810
- // A group or instance id that must appear in the page even when the cursor
20811
- // has already advanced past its sort position. This is what keeps the
20812
- // Findings page's one-shot ?finding= deep link resolving once the list
20813
- // paginates: the target group is appended out of sort order rather than
20814
- // scanning forward for it. Never affects totals, facets or the cursor.
20815
+ // A RULE id that must appear in the page even when the cursor has already
20816
+ // advanced past its sort position. This is what keeps the selected type
20817
+ // visible in the list once it paginates: the target is appended out of sort
20818
+ // order rather than scanned forward for. Never affects totals, facets or the
20819
+ // cursor. Unlike the grouped read this replaces, it names a rule only — an
20820
+ // instance id is resolved by `findingInstance`, which is a primary-key seek
20821
+ // and so is not bounded by what any page happens to hold.
20815
20822
  includeId: external_exports.string().optional(),
20816
- groupBy: external_exports.literal("type").optional(),
20817
- limit: external_exports.coerce.number().int().min(1).max(100).optional(),
20823
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
20818
20824
  cursor: external_exports.string().optional()
20819
20825
  });
20820
- var ListGroupedFindingsResponse = external_exports.object({
20826
+ var ListFindingTypesResponse = external_exports.object({
20821
20827
  totals: external_exports.object({
20828
+ // Findings belonging to the matching TYPES — not findings that each match
20829
+ // the filters. The filters here select types, so a type that survives
20830
+ // contributes its whole instanceCount.
20831
+ //
20832
+ // `status` is the one exception, narrowed per finding via
20833
+ // countInstancesByStatus. `severity`, `provider` and `action` are not, so
20834
+ // this can exceed what the instance read reports for the same filters: a
20835
+ // rule whose severity moved between versions is kept on its newest and
20836
+ // still counts its older findings. Narrowing the other three needs
20837
+ // per-dimension counts the aggregate does not carry today.
20822
20838
  findings: external_exports.number().int().nonnegative(),
20823
- groups: external_exports.number().int().nonnegative()
20839
+ // Counts TYPES, which is the unit this read pages. The instance read's
20840
+ // own totals count findings; the two deliberately answer different
20841
+ // questions and are never summed.
20842
+ types: external_exports.number().int().nonnegative()
20824
20843
  }),
20825
20844
  facets: FindingFacets,
20826
- items: external_exports.array(FindingGroup),
20845
+ items: external_exports.array(FindingTypeSummary),
20827
20846
  nextCursor: external_exports.string().nullable(),
20828
20847
  // Present only on session-scoped queries (`sessionId` set): per ruleId, how
20829
20848
  // many times that rule fired in the session's persisted transcript. Findings
@@ -20831,7 +20850,7 @@ var ListGroupedFindingsResponse = external_exports.object({
20831
20850
  // every firing, so the two numbers legitimately differ — this map lets a
20832
20851
  // session-scoped view show both.
20833
20852
  sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
20834
- }).meta({ id: "ListGroupedFindingsResponse" });
20853
+ }).meta({ id: "ListFindingTypesResponse" });
20835
20854
  var ApplyFindingActionRequest = external_exports.object({
20836
20855
  // 'quarantined' is system-assigned (see FindingAction) — clients may not set
20837
20856
  // it, so it is excluded from the request contract. The mapping helper
@@ -20861,12 +20880,13 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
20861
20880
  var MAX_FLAT_FINDINGS_LIMIT = 200;
20862
20881
  var ListFindingInstancesQuery = external_exports.object({
20863
20882
  severity: external_exports.array(Severity).optional(),
20864
- // Rule ids, the same vocabulary the grouped list's `subtype` carries.
20883
+ // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
20884
+ // ONE of them is how the master/detail view scopes its right-hand panel.
20865
20885
  subtype: external_exports.array(external_exports.string()).optional(),
20866
20886
  provider: external_exports.array(FindingProvider).optional(),
20867
20887
  action: external_exports.array(FindingAction).optional(),
20868
20888
  // Matches each instance's OWN derived status (deriveFindingStatus), unlike
20869
- // the grouped query's group-level fold.
20889
+ // the types query's type-level fold.
20870
20890
  status: external_exports.array(FindingStatus).optional(),
20871
20891
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20872
20892
  // where the free-text `q` can only match the rendered "via Bash" label.
@@ -20883,37 +20903,47 @@ var ListFindingInstancesQuery = external_exports.object({
20883
20903
  });
20884
20904
  var ListFindingInstancesResponse = external_exports.object({
20885
20905
  // Instances matching the filters across the whole scope, not just this
20886
- // page — cursor-independent, like the grouped list's totals.
20906
+ // page — cursor-independent, like the types list's totals.
20887
20907
  totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
20888
- // Counts in INSTANCES here, where the grouped response counts groups. Each
20908
+ // Counts in INSTANCES here, where the types response counts types. Each
20889
20909
  // dimension still excludes its own filter.
20890
20910
  facets: FindingFacets,
20891
20911
  items: external_exports.array(FindingInstanceDetail),
20892
20912
  nextCursor: external_exports.string().nullable()
20893
20913
  }).meta({ id: "ListFindingInstancesResponse" });
20894
- var FindingLocationFile = external_exports.object({
20895
- // Empty when the instances carried no file path (a prompt or a tool call
20896
- // with no file attribution).
20897
- file: external_exports.string(),
20898
- instanceCount: external_exports.number().int().nonnegative(),
20899
- maxSeverity: Severity,
20900
- latestDetectedAt: external_exports.iso.datetime(),
20901
- // Folded from the instances' derived statuses with the same
20902
- // open-dominates precedence a group uses.
20903
- status: FindingStatus.optional(),
20904
- // Distinct rules seen at this location, capped — the row shows them as
20905
- // chips, and the count is what conveys scale.
20906
- ruleIds: external_exports.array(external_exports.string())
20907
- }).meta({ id: "FindingLocationFile" });
20908
- var FindingLocationRepo = external_exports.object({
20914
+ var FindingLocationSummary = external_exports.object({
20915
+ // Opaque, stable, minted from the pair by encodeLocationId. It exists
20916
+ // because a location's identity is two values and a URL param carries one:
20917
+ // `?loc=` names a location the way `?rule=` names a type. Only ever compared
20918
+ // for EQUALITY — the page's selection check, this read's `includeId`, the
20919
+ // client's page dedupe — never decoded, and never a sort key.
20920
+ id: external_exports.string(),
20909
20921
  /** Empty when the instances carried no repo attribute. */
20910
20922
  repo: external_exports.string(),
20923
+ // Empty when the instances carried no file path (a prompt, or a tool call
20924
+ // with no file attribution). Both halves empty is a real location — usually
20925
+ // the largest one in a store — and is selectable like any other.
20926
+ file: external_exports.string(),
20911
20927
  instanceCount: external_exports.number().int().nonnegative(),
20928
+ // The WORST severity present, not the first row's. It is this list's primary
20929
+ // sort key, so it is also what explains why a row is where it is, and it is
20930
+ // how a reader decides what to open without opening everything.
20912
20931
  maxSeverity: Severity,
20913
20932
  latestDetectedAt: external_exports.iso.datetime(),
20933
+ // Folded from the instances' derived statuses with the same open-dominates
20934
+ // precedence a group uses, so it answers "is anything left to do here" and
20935
+ // not much more: a location holding 1 open among 40 resolved reads like one
20936
+ // holding 40 open. That loss is accepted — the panel beside this list
20937
+ // carries each finding's own status, and instanceCount sits next to the
20938
+ // badge.
20914
20939
  status: FindingStatus.optional(),
20915
- files: external_exports.array(FindingLocationFile)
20916
- }).meta({ id: "FindingLocationRepo" });
20940
+ // Every distinct rule seen at this location, UNCAPPED — so the length is a
20941
+ // tally rather than a sample and a row can say how many there are. Bounded
20942
+ // by the ruleset, not by the store. The view bounds what it DISPLAYS.
20943
+ ruleIds: external_exports.array(external_exports.string())
20944
+ }).meta({ id: "FindingLocationSummary" });
20945
+ var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
20946
+ var MAX_FINDING_LOCATIONS_LIMIT = 100;
20917
20947
  var ListFindingLocationsQuery = external_exports.object({
20918
20948
  severity: external_exports.array(Severity).optional(),
20919
20949
  subtype: external_exports.array(external_exports.string()).optional(),
@@ -20926,18 +20956,42 @@ var ListFindingLocationsQuery = external_exports.object({
20926
20956
  q: external_exports.string().optional(),
20927
20957
  sessionId: external_exports.string().optional(),
20928
20958
  from: external_exports.iso.datetime().optional(),
20929
- limit: external_exports.coerce.number().int().min(1).max(500).optional()
20959
+ // A LOCATION id (see FindingLocationSummary.id) that must appear in the page
20960
+ // even when the cursor has already advanced past its sort position — the
20961
+ // counterpart of ListFindingTypesQuery.includeId, and needed far more often
20962
+ // here. Selecting a row pushes the URL, which re-renders the server and resets
20963
+ // the client's page cache to page 0; with distinct (repo, file) pairs running
20964
+ // into the thousands, a selection sitting off page 0 is the ordinary case
20965
+ // rather than a deep-link corner. Never affects totals, facets or the cursor.
20966
+ includeId: external_exports.string().optional(),
20967
+ limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
20968
+ cursor: external_exports.string().optional()
20930
20969
  });
20931
20970
  var ListFindingLocationsResponse = external_exports.object({
20932
20971
  totals: external_exports.object({
20972
+ // Findings matching the filters across the whole scope. Unlike the types
20973
+ // read's same-named field this needs no caveat: the filters here narrow
20974
+ // per finding, so this is the sum of every row's instanceCount.
20933
20975
  findings: external_exports.number().int().nonnegative(),
20934
- repos: external_exports.number().int().nonnegative(),
20935
- files: external_exports.number().int().nonnegative()
20976
+ // Counts LOCATIONS, the unit this read pages — the number the paginator
20977
+ // states. The facets beside it count FINDINGS (see below); a surface
20978
+ // showing both says which is which.
20979
+ locations: external_exports.number().int().nonnegative()
20936
20980
  }),
20937
- /** Sorted by max severity, then most recent. */
20938
- items: external_exports.array(FindingLocationRepo),
20939
- /** Whether `limit` truncated the repo list. */
20940
- hasMore: external_exports.boolean()
20981
+ // Counts in FINDINGS, where the types response counts types, each dimension
20982
+ // still excluding its own filter. Deliberately not locations: counting those
20983
+ // needs a set of location keys per dimension per value — memory tracking the
20984
+ // store times the vocabulary, in a read whose scan promises flat memory —
20985
+ // and the cheap per-location version is not an approximation but WRONG. A
20986
+ // location holding {claudecode, block} and {codex, warn} would survive
20987
+ // provider=claudecode AND action=warn, under which no single finding
20988
+ // matches, so the facet would contradict the instanceCount this whole view
20989
+ // rests on. Findings also keep the toolbar in the same unit as the page
20990
+ // tally and the panel it sits above.
20991
+ facets: FindingFacets,
20992
+ /** Sorted by max severity, then most recent, then (repo, file). */
20993
+ items: external_exports.array(FindingLocationSummary),
20994
+ nextCursor: external_exports.string().nullable()
20941
20995
  }).meta({ id: "ListFindingLocationsResponse" });
20942
20996
 
20943
20997
  // ../../packages/schema/src/zod/meta.ts
@@ -22220,6 +22274,14 @@ var ControlPlaneErrorBody = external_exports.object({
22220
22274
  message: external_exports.string().optional()
22221
22275
  }).optional()
22222
22276
  });
22277
+ var RemoteFailureKind = external_exports.enum([
22278
+ "unauthorized",
22279
+ "forbidden",
22280
+ "route-absent",
22281
+ "invalid-request",
22282
+ "rejected",
22283
+ "unreachable"
22284
+ ]);
22223
22285
  var AttachDeviceRequest = external_exports.object({
22224
22286
  // This machine's own continuity id, so re-attaching ROTATES the credential
22225
22287
  // on one machine record instead of producing a second one. Client-minted
@@ -22913,139 +22975,62 @@ function deriveFindingStatus(row) {
22913
22975
  if (row.latestResolutionStatus === "dismissed") return "dismissed";
22914
22976
  return "open";
22915
22977
  }
22916
- function distinctUsers(instances) {
22917
- const seen = /* @__PURE__ */ new Set();
22918
- const users = [];
22919
- for (const i of instances) {
22920
- if (i.user === void 0 || seen.has(i.user.id)) continue;
22921
- seen.add(i.user.id);
22922
- users.push(i.user);
22923
- }
22924
- return users;
22925
- }
22926
22978
  function sortUsers(users) {
22927
22979
  return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
22928
22980
  }
22929
- function buildFindingGroups(rows, opts = {}) {
22930
- const overrides = opts.overrides;
22981
+ function buildFindingTypes(aggregates, opts = {}) {
22931
22982
  const packNames = opts.packNames;
22932
- const aggregates = opts.aggregates;
22933
- const byRuleId = /* @__PURE__ */ new Map();
22934
- for (const row of rows) {
22935
- const existing = byRuleId.get(row.ruleId);
22936
- if (existing) existing.push(row);
22937
- else byRuleId.set(row.ruleId, [row]);
22938
- }
22939
- const groups = [];
22940
- for (const [ruleId, ruleRows] of byRuleId) {
22941
- const instances = ruleRows.map((r) => {
22942
- const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
22943
- return {
22944
- id: r.id,
22945
- provider: toApiProvider(r.sourceTool),
22946
- repo: r.repo,
22947
- file: r.file,
22948
- ...r.toolName === void 0 ? {} : { toolName: r.toolName },
22949
- ...r.eventId === void 0 ? {} : { eventId: r.eventId },
22950
- ...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
22951
- ...r.user === void 0 ? {} : { user: r.user },
22952
- action: toApiAction(effectiveDbAction),
22953
- detectedAt: r.occurredAt,
22954
- confidence: r.confidence,
22955
- status: r.status
22956
- };
22957
- });
22958
- const agg = aggregates?.get(ruleId);
22959
- const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
22960
- const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
22961
- (max, r) => r.occurredAt > max ? r.occurredAt : max,
22962
- ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
22963
- );
22964
- const seenProviders = /* @__PURE__ */ new Set();
22965
- const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
22966
- if (seenProviders.has(p)) return false;
22967
- seenProviders.add(p);
22968
- return true;
22969
- });
22970
- const actionSet = new Set(
22971
- agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
22972
- );
22983
+ const types = [];
22984
+ for (const [ruleId, agg] of aggregates) {
22985
+ const users = sortUsers(agg.users ?? []);
22986
+ const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
22987
+ const actionSet = new Set(agg.actionsTaken.map(toApiAction));
22973
22988
  const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
22974
- const severity = ruleRows[0]?.severity ?? "low";
22975
- const detection = {
22976
- id: ruleId,
22977
- name: packNames?.get(ruleId) ?? null
22978
- };
22979
- const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
22980
- const policy = { id: `category:${apiCategory}`, name: apiCategory };
22981
- const match = {
22982
- maskedValue: ruleRows[0]?.maskedMatch ?? "",
22983
- contextPrefix: ""
22984
- // empty (pending privacy review)
22985
- };
22986
- const status = foldGroupStatus(
22987
- agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
22988
- );
22989
- const group = {
22989
+ const apiCategory = toApiCategory(agg.category ?? "custom");
22990
+ const type = {
22990
22991
  id: ruleId,
22991
22992
  category: apiCategory,
22992
22993
  subtype: ruleId,
22993
22994
  // human label comes with pack metadata later
22994
- severity,
22995
- match,
22996
- detection,
22997
- policy,
22998
- instanceCount: agg?.instanceCount ?? instances.length,
22995
+ severity: agg.severity ?? "low",
22996
+ detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
22997
+ policy: { id: `category:${apiCategory}`, name: apiCategory },
22998
+ instanceCount: agg.instanceCount,
22999
22999
  providers,
23000
23000
  aggregateAction,
23001
- latestDetectedAt,
23002
- instances,
23003
- status,
23001
+ latestDetectedAt: agg.latestDetectedAt,
23002
+ status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
23004
23003
  ...users.length > 0 ? { users } : {}
23005
23004
  };
23006
- if (agg) {
23007
- actionsCache.set(group, [...actionSet]);
23008
- if (agg.searchText !== void 0) {
23009
- haystackCache.set(group, buildHaystack(group, agg.searchText));
23010
- }
23005
+ actionsCache.set(type, [...actionSet]);
23006
+ if (agg.searchText !== void 0) {
23007
+ haystackCache.set(type, buildHaystack(type, agg.searchText));
23011
23008
  }
23012
- groups.push(group);
23009
+ types.push(type);
23013
23010
  }
23014
- return groups;
23011
+ return types;
23015
23012
  }
23016
23013
  var haystackCache = /* @__PURE__ */ new WeakMap();
23017
- function buildHaystack(g, extra) {
23014
+ function buildHaystack(t, extra) {
23018
23015
  return [
23019
- g.subtype,
23020
- g.category,
23021
- g.match.maskedValue,
23022
- g.policy.name,
23023
- g.id,
23024
- ...g.instances.map((i) => i.repo),
23025
- ...g.instances.map((i) => i.file),
23026
- ...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
23027
- ...g.instances.map((i) => i.id),
23028
- // The people: the whole group's list when the store folded one, plus the
23029
- // preview's own — the two overlap, and a haystack does not mind.
23030
- ...(g.users ?? []).map((u) => u.name),
23031
- ...g.instances.map((i) => i.user?.name ?? ""),
23016
+ t.subtype,
23017
+ t.category,
23018
+ t.policy.name,
23019
+ t.id,
23020
+ ...(t.users ?? []).map((u) => u.name),
23032
23021
  ...extra === void 0 ? [] : [extra]
23033
23022
  ].join(" ").toLowerCase();
23034
23023
  }
23035
- function groupHaystack(g) {
23036
- const cached2 = haystackCache.get(g);
23024
+ function typeHaystack(t) {
23025
+ const cached2 = haystackCache.get(t);
23037
23026
  if (cached2 !== void 0) return cached2;
23038
- const haystack = buildHaystack(g);
23039
- haystackCache.set(g, haystack);
23027
+ const haystack = buildHaystack(t);
23028
+ haystackCache.set(t, haystack);
23040
23029
  return haystack;
23041
23030
  }
23042
23031
  var actionsCache = /* @__PURE__ */ new WeakMap();
23043
- function groupActions(g) {
23044
- const cached2 = actionsCache.get(g);
23045
- if (cached2 !== void 0) return cached2;
23046
- const actions = [...new Set(g.instances.map((i) => i.action))];
23047
- actionsCache.set(g, actions);
23048
- return actions;
23032
+ function typeActions(t) {
23033
+ return actionsCache.get(t) ?? [];
23049
23034
  }
23050
23035
  function countInstancesByStatus(statusInputs, statuses) {
23051
23036
  const statusSet = new Set(statuses);
@@ -23056,8 +23041,8 @@ function countInstancesByStatus(statusInputs, statuses) {
23056
23041
  }
23057
23042
  return sum;
23058
23043
  }
23059
- function applyFindingFilters(groups, opts) {
23060
- let filtered = groups;
23044
+ function applyFindingFilters(types, opts) {
23045
+ let filtered = types;
23061
23046
  if (opts.severity && opts.severity.length > 0) {
23062
23047
  const sevSet = new Set(opts.severity);
23063
23048
  filtered = filtered.filter((g) => sevSet.has(g.severity));
@@ -23068,7 +23053,7 @@ function applyFindingFilters(groups, opts) {
23068
23053
  }
23069
23054
  if (opts.actions && opts.actions.length > 0) {
23070
23055
  const actionSet = new Set(opts.actions);
23071
- filtered = filtered.filter((g) => groupActions(g).some((a) => actionSet.has(a)));
23056
+ filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
23072
23057
  }
23073
23058
  if (opts.subtype && opts.subtype.length > 0) {
23074
23059
  const subtypeSet = new Set(opts.subtype);
@@ -23080,7 +23065,7 @@ function applyFindingFilters(groups, opts) {
23080
23065
  }
23081
23066
  if (opts.q) {
23082
23067
  const q = opts.q.toLowerCase();
23083
- filtered = filtered.filter((g) => groupHaystack(g).includes(q));
23068
+ filtered = filtered.filter((t) => typeHaystack(t).includes(q));
23084
23069
  }
23085
23070
  return filtered;
23086
23071
  }
@@ -23095,11 +23080,11 @@ function compareFindingGroupOrder(a, b) {
23095
23080
  if (recencyDiff !== 0) return recencyDiff;
23096
23081
  return a.id.localeCompare(b.id);
23097
23082
  }
23098
- function sortFindingGroups(groups) {
23099
- return [...groups].sort(compareFindingGroupOrder);
23083
+ function sortFindingTypes(types) {
23084
+ return [...types].sort(compareFindingGroupOrder);
23100
23085
  }
23101
- function computeFindingFacets(allGroups, opts) {
23102
- const forSeverity = applyFindingFilters(allGroups, {
23086
+ function computeFindingFacets(allTypes, opts) {
23087
+ const forSeverity = applyFindingFilters(allTypes, {
23103
23088
  providers: opts.providers,
23104
23089
  actions: opts.actions,
23105
23090
  statuses: opts.statuses,
@@ -23110,7 +23095,7 @@ function computeFindingFacets(allGroups, opts) {
23110
23095
  for (const g of forSeverity) {
23111
23096
  severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
23112
23097
  }
23113
- const forProvider = applyFindingFilters(allGroups, {
23098
+ const forProvider = applyFindingFilters(allTypes, {
23114
23099
  actions: opts.actions,
23115
23100
  statuses: opts.statuses,
23116
23101
  q: opts.q,
@@ -23121,7 +23106,7 @@ function computeFindingFacets(allGroups, opts) {
23121
23106
  for (const g of forProvider) {
23122
23107
  for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
23123
23108
  }
23124
- const forAction = applyFindingFilters(allGroups, {
23109
+ const forAction = applyFindingFilters(allTypes, {
23125
23110
  providers: opts.providers,
23126
23111
  statuses: opts.statuses,
23127
23112
  q: opts.q,
@@ -23130,9 +23115,9 @@ function computeFindingFacets(allGroups, opts) {
23130
23115
  });
23131
23116
  const actionMap = /* @__PURE__ */ new Map();
23132
23117
  for (const g of forAction) {
23133
- for (const a of groupActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23118
+ for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
23134
23119
  }
23135
- const forSubtype = applyFindingFilters(allGroups, {
23120
+ const forSubtype = applyFindingFilters(allTypes, {
23136
23121
  providers: opts.providers,
23137
23122
  actions: opts.actions,
23138
23123
  statuses: opts.statuses,
@@ -23141,7 +23126,7 @@ function computeFindingFacets(allGroups, opts) {
23141
23126
  });
23142
23127
  const subtypeMap = /* @__PURE__ */ new Map();
23143
23128
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
23144
- const forStatus = applyFindingFilters(allGroups, {
23129
+ const forStatus = applyFindingFilters(allTypes, {
23145
23130
  providers: opts.providers,
23146
23131
  actions: opts.actions,
23147
23132
  q: opts.q,
@@ -23189,10 +23174,20 @@ function matchesDimension(row, opts, dimension) {
23189
23174
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23190
23175
  case "tools":
23191
23176
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23177
+ // An EMPTY value is a real filter here, not an absent one. The location
23178
+ // list buckets a finding whose event recorded no repo — or no file — under
23179
+ // the empty string, and selecting that bucket has to narrow the panel to
23180
+ // exactly it. Only `undefined` means "no filter"; a caller that wants every
23181
+ // row omits the key, which every call site already does.
23182
+ //
23183
+ // Reading '' as unset is what this replaced, and it failed in the one place
23184
+ // it mattered: the no-repo/no-file bucket is often the largest in a real
23185
+ // store, and its panel dropped both predicates and returned the WHOLE scope
23186
+ // — a row reading 3 findings beside a panel listing every finding there is.
23192
23187
  case "repo":
23193
- return opts.repo === void 0 || opts.repo === "" || row.repo === opts.repo;
23188
+ return opts.repo === void 0 || row.repo === opts.repo;
23194
23189
  case "file":
23195
- return opts.file === void 0 || opts.file === "" || row.file === opts.file;
23190
+ return opts.file === void 0 || row.file === opts.file;
23196
23191
  case "q":
23197
23192
  return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
23198
23193
  }
@@ -23306,6 +23301,23 @@ function addToLocation(acc, row) {
23306
23301
  acc.statuses.push(row.status);
23307
23302
  acc.ruleIds.add(row.ruleId);
23308
23303
  }
23304
+ function compareLocationOrder(a, b) {
23305
+ const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23306
+ const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23307
+ if (rankA !== rankB) return rankA - rankB;
23308
+ if (a.latestDetectedAt !== b.latestDetectedAt) {
23309
+ return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23310
+ }
23311
+ if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23312
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23313
+ return 0;
23314
+ }
23315
+ function encodeLocationId(repo, file2) {
23316
+ return `${encodePart(repo)}/${encodePart(file2)}`;
23317
+ }
23318
+ function encodePart(value) {
23319
+ return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
23320
+ }
23309
23321
 
23310
23322
  // ../../packages/schema/src/zod/installed-pack.ts
23311
23323
  var InstalledPack = external_exports.object({
@@ -23754,7 +23766,7 @@ function isVaultConsentValid(consent) {
23754
23766
  // ../../packages/schema/src/zod/local.ts
23755
23767
  var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23756
23768
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23757
- var HISTORY_SYNC_PAYLOAD_VERSION = 2;
23769
+ var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23758
23770
  var RunMode = external_exports.enum(["standalone", "attached"]);
23759
23771
  var ControlPlaneConnection = external_exports.object({
23760
23772
  endpoint: external_exports.string().min(1),
@@ -23820,11 +23832,11 @@ var WorkspaceSettings = external_exports.object({
23820
23832
  // covers the current payload and must be re-granted.
23821
23833
  modelJudgeConsent: ModelJudgeConsent.optional(),
23822
23834
  // Records that the user consented to the DEFERRED send — the outbox — along
23823
- // with the payload shape and the endpoint they agreed to. Since payload v2
23824
- // that covers both the pre-attach backlog and undelivered captures (which
23825
- // carry prompt/reply text in `content`); the key name predates the widening.
23826
- // Absent until granted, and a grant for a different endpoint or an older
23827
- // payload no longer counts.
23835
+ // with the payload shape and the endpoint they agreed to. Since payload v3
23836
+ // that covers the pre-attach backlog AND undelivered captures alike, and both
23837
+ // carry prompt/reply/tool-output text in `content`; the key name predates
23838
+ // both widenings. Absent until granted, and a grant for a different endpoint
23839
+ // or an older payload no longer counts.
23828
23840
  historySyncConsent: HistorySyncConsent.optional()
23829
23841
  });
23830
23842
  function defaultWorkspaceSettings() {
@@ -23955,6 +23967,9 @@ var ManagedSettingKey = external_exports.enum([
23955
23967
  "dataSharesInPlace",
23956
23968
  "redactFallback"
23957
23969
  ]).meta({ id: "ManagedSettingKey" });
23970
+ function isManagedSettingKey(value) {
23971
+ return ManagedSettingKey.safeParse(value).success;
23972
+ }
23958
23973
  var ManagedSettingsValues = external_exports.object({
23959
23974
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
23960
23975
  controlPlane: external_exports.object({
@@ -23979,7 +23994,27 @@ var ManagedSettings = external_exports.object({
23979
23994
  // Which of those the user may not change. A key here with no matching value
23980
23995
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23981
23996
  // the user may still override. The two are separable on purpose.
23982
- lockedFields: external_exports.array(ManagedSettingKey).default([])
23997
+ //
23998
+ // Parsed as NAMES rather than as the enum, and split below: a name this
23999
+ // build does not know is dropped from the locked set and reported, never a
24000
+ // reason to refuse the file. The same shape reaches an older build whenever
24001
+ // an administrator locks a key a newer build added, and refusing it there
24002
+ // ran that build entirely unmanaged — every pin and lock gone — on exactly
24003
+ // the fleets most likely to carry a version skew. A name outside the enum
24004
+ // is still never HONOURED: the lockable set stays explicit above.
24005
+ lockedFields: external_exports.array(external_exports.string()).default([])
24006
+ }).transform(({ lockedFields, ...rest }) => {
24007
+ const known = [];
24008
+ const unknown2 = [];
24009
+ for (const name of lockedFields) {
24010
+ if (isManagedSettingKey(name)) known.push(name);
24011
+ else unknown2.push(name);
24012
+ }
24013
+ return {
24014
+ ...rest,
24015
+ lockedFields: known,
24016
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24017
+ };
23983
24018
  }).meta({ id: "ManagedSettings" });
23984
24019
 
23985
24020
  // ../../packages/schema/src/zod/project-files.ts
@@ -24103,7 +24138,11 @@ var FindingsTimeseriesPoint = external_exports.object({
24103
24138
  timestamp: external_exports.iso.date(),
24104
24139
  critical: external_exports.number().int().nonnegative(),
24105
24140
  high: external_exports.number().int().nonnegative(),
24106
- medium: external_exports.number().int().nonnegative()
24141
+ medium: external_exports.number().int().nonnegative(),
24142
+ // Optional and additive, so a producer written against the earlier
24143
+ // three-series contract keeps validating. A consumer plotting it resolves the
24144
+ // absent case itself — the chart point requires a number.
24145
+ low: external_exports.number().int().nonnegative().optional()
24107
24146
  }).meta({ id: "FindingsTimeseriesPoint" });
24108
24147
  var FindingsTimeseriesResponse = external_exports.object({
24109
24148
  range: TimeRange,
@@ -24129,6 +24168,10 @@ var ResolvedFeedItem = external_exports.object({
24129
24168
  findingKey: external_exports.string(),
24130
24169
  ruleId: external_exports.string(),
24131
24170
  severity: Severity,
24171
+ // Repository slug, and the file path RELATIVE to it. The pair is what
24172
+ // identifies the file: a bare path matches the same name in every repo.
24173
+ // Optional and additive; empty when the event carried no repo.
24174
+ repo: external_exports.string().optional(),
24132
24175
  path: external_exports.string(),
24133
24176
  // ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
24134
24177
  // findings domain). The reader `.toISOString()`s the DB epoch-ms values.
@@ -25676,7 +25719,8 @@ var SqliteActivityRepository = class {
25676
25719
  SELECT 1 FROM audit_events d
25677
25720
  WHERE d.root_session_id = audit_events.id
25678
25721
  AND (d.content LIKE ? ESCAPE '\\'
25679
- OR json_extract(d.attributes, '$.detail') LIKE ? ESCAPE '\\')))`
25722
+ OR coalesce(json_extract(d.attributes, '$.detail'),
25723
+ json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
25680
25724
  );
25681
25725
  params.push(pattern, pattern, pattern, pattern, pattern, pattern);
25682
25726
  }
@@ -27014,23 +27058,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
27014
27058
  )`;
27015
27059
 
27016
27060
  // ../../packages/persistence/src/repositories/findings.ts
27017
- var PREVIEW_INSTANCES_PER_GROUP = 200;
27018
- var DEFAULT_LOCATIONS_LIMIT = 100;
27019
- var LOCATION_RULE_IDS_CAP = 20;
27020
- function compareLocationOrder(a, b) {
27021
- return compareFindingGroupOrder(
27022
- {
27023
- severity: a.maxSeverity,
27024
- latestDetectedAt: a.latestDetectedAt,
27025
- id: ""
27026
- },
27027
- {
27028
- severity: b.maxSeverity,
27029
- latestDetectedAt: b.latestDetectedAt,
27030
- id: ""
27031
- }
27032
- );
27033
- }
27034
27061
  var CONCAT_SEP = ",";
27035
27062
  var TUPLE_SEP = "|";
27036
27063
  function splitConcat(value) {
@@ -27082,13 +27109,48 @@ function decodeGroupCursor(cursor) {
27082
27109
  return null;
27083
27110
  }
27084
27111
  function firstAfter(sorted, cursor) {
27085
- const index = sorted.findIndex((g) => compareFindingGroupOrder(g, cursor) > 0);
27112
+ const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
27086
27113
  return index === -1 ? sorted.length : index;
27087
27114
  }
27088
27115
  function findDeepLinked(sorted, page, id) {
27089
- if (page.some((g) => g.id === id || g.instances.some((i) => i.id === id))) return void 0;
27090
- return sorted.find((g) => g.id === id || g.instances.some((i) => i.id === id));
27116
+ if (page.some((t) => t.id === id)) return void 0;
27117
+ return sorted.find((t) => t.id === id);
27118
+ }
27119
+ function encodeLocationCursor(location) {
27120
+ const payload = {
27121
+ sev: location.maxSeverity,
27122
+ t: location.latestDetectedAt,
27123
+ r: location.repo,
27124
+ f: location.file
27125
+ };
27126
+ return Buffer.from(JSON.stringify(payload)).toString("base64url");
27127
+ }
27128
+ function decodeLocationCursor(cursor) {
27129
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
27130
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
27131
+ return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
27132
+ }
27133
+ return null;
27134
+ }
27135
+ function firstLocationAfter(sorted, cursor) {
27136
+ const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
27137
+ return index === -1 ? sorted.length : index;
27138
+ }
27139
+ function findDeepLinkedLocation(sorted, page, id) {
27140
+ if (page.some((l) => l.id === id)) return void 0;
27141
+ return sorted.find((l) => l.id === id);
27091
27142
  }
27143
+ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
27144
+ d.severity AS severity, f.masked_match AS masked_match,
27145
+ f.action_taken AS action_taken, f.confidence AS confidence,
27146
+ e.started_at AS occurred_at,
27147
+ e.source_tool AS source_tool,
27148
+ e.repo AS repo,
27149
+ e.file_path AS file,
27150
+ e.tool_name AS tool_name,
27151
+ f.audit_event_id AS event_id, e.root_session_id AS session_id,
27152
+ e.event_type AS kind, f.finding_key AS finding_key,
27153
+ ${latestResolutionStatusSql("f")} AS latest_status`;
27092
27154
  var DAY_MS3 = 864e5;
27093
27155
  var SqliteFindingsRepository = class {
27094
27156
  constructor(db) {
@@ -27209,30 +27271,26 @@ var SqliteFindingsRepository = class {
27209
27271
  );
27210
27272
  }
27211
27273
  /**
27212
- * Grouped findings for the dashboard — joins inspection_findings⋈audit_events
27213
- * ⋈inspection_definitions (repo/file/toolName from the audit event's
27214
- * attributes bag, rule_id/category/severity from the definition), scoped to
27215
- * the four capture kinds (audit_events also holds structural/reconciler/scan
27216
- * rows this list must never surface), groups by ruleId, computes
27217
- * per-filter-excluded facets, applies the requested filters, and sorts by
27218
- * severity then recency. Filtering
27219
- * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
27220
- * reflect the full filtered set; `items` is the requested
27221
- * page (default 50); no cursor (nextCursor is always null). Under a `status`
27222
- * filter, `totals.findings` counts only instances whose derived status was
27223
- * requested, and each item's instance preview is narrowed the same way.
27274
+ * Finding TYPES for the dashboard — one row per rule, scoped to the four
27275
+ * capture kinds (audit_events also holds structural/reconciler/scan rows this
27276
+ * list must never surface), with per-filter-excluded facets, the requested
27277
+ * filters applied, and sorted by severity then recency. Filtering and faceting
27278
+ * run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
27279
+ * full filtered set; `items` is the requested page (default 50), keyset-paged.
27280
+ * Under a `status` filter, `totals.findings` counts only findings whose
27281
+ * derived status was requested.
27282
+ *
27283
+ * ONE read, which materializes no findings: a single aggregate per rule_id,
27284
+ * folding EVERY finding into the numbers a type row and the filters need
27285
+ * (count, severity, category, providers, actions, statuses, latest, search
27286
+ * text). The findings OF a type come from listFindingInstances scoped to
27287
+ * `subtype`, so neither list bounds the other and no per-type cap exists.
27224
27288
  *
27225
- * Two reads, neither of which materializes a row per finding:
27226
- * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
27227
- * the group and the filters need (count, providers, actions, statuses,
27228
- * latest, search text);
27229
- * 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
27230
- * populate `instances` for the table's expanded rows.
27231
27289
  * The aggregates carry raw DB values and are translated by the same
27232
- * @akasecurity/schema mappers the row path uses, so no enum mapping or status
27233
- * rule is ever restated in SQL.
27290
+ * @akasecurity/schema mappers every other path uses, so no enum mapping or
27291
+ * status rule is ever restated in SQL.
27234
27292
  */
27235
- listGroupedFindings(query) {
27293
+ listFindingTypes(query) {
27236
27294
  const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
27237
27295
  const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
27238
27296
  const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
@@ -27245,12 +27303,7 @@ var SqliteFindingsRepository = class {
27245
27303
  predicate,
27246
27304
  params: sessionParams
27247
27305
  });
27248
- const rows = this.previewRows(aggregates, {
27249
- sessionId: query.sessionId,
27250
- from: query.from
27251
- });
27252
- const groupable = rows.map(toFlatFindingRow);
27253
- const allGroups = buildFindingGroups(groupable, { aggregates });
27306
+ const allTypes = buildFindingTypes(aggregates);
27254
27307
  const filterOpts = {
27255
27308
  severity: query.severity,
27256
27309
  providers: query.provider,
@@ -27259,30 +27312,25 @@ var SqliteFindingsRepository = class {
27259
27312
  subtype: query.subtype,
27260
27313
  q: query.q
27261
27314
  };
27262
- const facets = computeFindingFacets(allGroups, filterOpts);
27263
- const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
27315
+ const facets = computeFindingFacets(allTypes, filterOpts);
27316
+ const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
27264
27317
  const statusFilter = query.status ?? [];
27265
27318
  const totals = {
27266
- findings: sorted.reduce((acc, g) => {
27267
- if (statusFilter.length === 0) return acc + g.instanceCount;
27268
- const agg = aggregates.get(g.id);
27269
- return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
27319
+ findings: sorted.reduce((acc, t) => {
27320
+ if (statusFilter.length === 0) return acc + t.instanceCount;
27321
+ const agg = aggregates.get(t.id);
27322
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
27270
27323
  }, 0),
27271
- groups: sorted.length
27324
+ types: sorted.length
27272
27325
  };
27273
- const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
27326
+ const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
27274
27327
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
27275
27328
  const start = cursor === null ? 0 : firstAfter(sorted, cursor);
27276
27329
  const page = sorted.slice(start, start + limit);
27277
27330
  const lastOnPage = page.at(-1);
27278
27331
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
27279
27332
  const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
27280
- const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
27281
- const narrow = (g) => statusSet ? {
27282
- ...g,
27283
- instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
27284
- } : g;
27285
- const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
27333
+ const items = [...page, ...deepLinked ? [deepLinked] : []];
27286
27334
  return Promise.resolve({
27287
27335
  totals,
27288
27336
  facets,
@@ -27293,7 +27341,7 @@ var SqliteFindingsRepository = class {
27293
27341
  }
27294
27342
  /**
27295
27343
  * One row per rule_id, folding EVERY instance of the group into the values
27296
- * buildFindingGroups cannot recover from a preview. Bounded by the number of
27344
+ * buildFindingTypes cannot recover from an aggregate. Bounded by the number of
27297
27345
  * distinct rule_ids (the installed packs' rules), not by the store's size.
27298
27346
  *
27299
27347
  * A single scan, folded in two levels: the inner SELECT groups by
@@ -27387,13 +27435,25 @@ var SqliteFindingsRepository = class {
27387
27435
  });
27388
27436
  }
27389
27437
  /**
27390
- * The same findings folded by location: repository, then file within it.
27438
+ * The same findings folded by WHERE they live — one row per (repo, file) pair.
27391
27439
  *
27392
27440
  * The grouping keys come from the capturing event's attributes, which is what
27393
- * the local store relates a finding to — there is no finding↔asset row to
27394
- * group by instead. A repo or file the event did not record folds into the
27395
- * empty-string bucket, which the view renders but does not link, since no
27396
- * filter can name it.
27441
+ * the local store relates a finding to; there is no finding↔asset row to group
27442
+ * by instead. A repo or file the event did not record folds into the
27443
+ * empty-string bucket, which is a real location like any other: it is listed,
27444
+ * it is selectable, and its `?loc=` token is as good as any other row's.
27445
+ *
27446
+ * ONE flat list rather than repos nesting files. A rollup can only be paged by
27447
+ * repo, which leaves the file list inside it unbounded — the shape the by-type
27448
+ * list was rebuilt to remove — and two-level pagination inside an
27449
+ * expand/collapse table is what pushed that view to master/detail in the first
27450
+ * place.
27451
+ *
27452
+ * Every filter narrows the FINDINGS and the locations fall out of what
27453
+ * survives, so each row's `instanceCount` is exactly what listFindingInstances
27454
+ * reports for the same filters scoped to that pair. The view depends on it:
27455
+ * one toolbar sits over both panels precisely because a location owns none of
27456
+ * its fields.
27397
27457
  */
27398
27458
  listFindingLocations(query) {
27399
27459
  const opts = {
@@ -27405,13 +27465,16 @@ var SqliteFindingsRepository = class {
27405
27465
  tools: query.tool,
27406
27466
  q: query.q
27407
27467
  };
27408
- const limit = query.limit ?? DEFAULT_LOCATIONS_LIMIT;
27468
+ const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
27469
+ const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
27409
27470
  const byRepo = /* @__PURE__ */ new Map();
27471
+ const accumulator = createInstanceFacetAccumulator(opts);
27410
27472
  let total = 0;
27411
27473
  for (const row of this.scanFindingRows({
27412
27474
  sessionId: query.sessionId,
27413
27475
  from: query.from
27414
27476
  })) {
27477
+ accumulator.add(row);
27415
27478
  if (!matchesInstanceFilters(row, opts)) continue;
27416
27479
  total += 1;
27417
27480
  let files = byRepo.get(row.repo);
@@ -27426,103 +27489,35 @@ var SqliteFindingsRepository = class {
27426
27489
  }
27427
27490
  addToLocation(acc, row);
27428
27491
  }
27429
- let fileCount = 0;
27430
- const repos = [...byRepo.entries()].map(([repo, files]) => {
27431
- fileCount += files.size;
27432
- const fileRows = [...files.entries()].map(([file2, acc]) => ({
27433
- file: file2,
27434
- instanceCount: acc.instanceCount,
27435
- maxSeverity: acc.maxSeverity,
27436
- latestDetectedAt: acc.latestDetectedAt,
27437
- ...foldGroupStatus(acc.statuses) === void 0 ? {} : { status: foldGroupStatus(acc.statuses) },
27438
- ruleIds: [...acc.ruleIds].slice(0, LOCATION_RULE_IDS_CAP)
27439
- })).sort(compareLocationOrder);
27440
- const rollup = fileRows.reduce(
27441
- (a, f) => ({
27442
- instanceCount: a.instanceCount + f.instanceCount,
27443
- maxSeverity: compareLocationOrder(f, a) < 0 ? f.maxSeverity : a.maxSeverity,
27444
- latestDetectedAt: f.latestDetectedAt > a.latestDetectedAt ? f.latestDetectedAt : a.latestDetectedAt
27445
- }),
27446
- {
27447
- instanceCount: 0,
27448
- maxSeverity: fileRows[0]?.maxSeverity ?? "low",
27449
- latestDetectedAt: ""
27450
- }
27451
- );
27452
- const statuses = fileRows.map((f) => f.status);
27453
- const folded = foldGroupStatus(statuses);
27454
- return {
27455
- repo,
27456
- instanceCount: rollup.instanceCount,
27457
- maxSeverity: rollup.maxSeverity,
27458
- latestDetectedAt: rollup.latestDetectedAt,
27459
- ...folded === void 0 ? {} : { status: folded },
27460
- files: fileRows
27461
- };
27462
- });
27463
- repos.sort(compareLocationOrder);
27492
+ const sorted = [];
27493
+ for (const [repo, files] of byRepo) {
27494
+ for (const [file2, acc] of files) {
27495
+ const status = foldGroupStatus(acc.statuses);
27496
+ sorted.push({
27497
+ id: encodeLocationId(repo, file2),
27498
+ repo,
27499
+ file: file2,
27500
+ instanceCount: acc.instanceCount,
27501
+ maxSeverity: acc.maxSeverity,
27502
+ latestDetectedAt: acc.latestDetectedAt,
27503
+ ...status === void 0 ? {} : { status },
27504
+ ruleIds: [...acc.ruleIds]
27505
+ });
27506
+ }
27507
+ }
27508
+ sorted.sort(compareLocationOrder);
27509
+ const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
27510
+ const page = sorted.slice(start, start + limit);
27511
+ const lastOnPage = page.at(-1);
27512
+ const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
27513
+ const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
27464
27514
  return Promise.resolve({
27465
- totals: { findings: total, repos: repos.length, files: fileCount },
27466
- items: repos.slice(0, limit),
27467
- hasMore: repos.length > limit
27515
+ totals: { findings: total, locations: sorted.length },
27516
+ facets: accumulator.facets(),
27517
+ items: [...page, ...deepLinked ? [deepLinked] : []],
27518
+ nextCursor
27468
27519
  });
27469
27520
  }
27470
- /**
27471
- * Each group's newest instances, for the table's expanded rows.
27472
- *
27473
- * ONE index-ordered scan with early termination, and the shape is the point.
27474
- * The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
27475
- * started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
27476
- * through a temp B-tree to keep a bounded preview of each group, and then
27477
- * sorts the survivors again for the page order. Both sorts grow with the
27478
- * store while the answer does not.
27479
- *
27480
- * Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
27481
- * (or the session or window index the scope names — see `findingScanSql`),
27482
- * which is already the order the page wants, and keeps rows per rule until
27483
- * each rule has as many as it can show. The aggregate the caller already holds
27484
- * says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
27485
- * per rule, summed, is the number of rows this scan has to find, and it stops
27486
- * on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
27487
- * (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
27488
- * store with many firing rules widens it. The bound that DOES hold
27489
- * unconditionally is the sorted form's floor: this scan visits at most as
27490
- * many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
27491
- * sorted, and stops the moment every rule has its cap, where the sorted form
27492
- * sorts the whole scope regardless. The true worst case — the rarest rule's
27493
- * wanted instances sitting at the tail of the scope — is one pass over
27494
- * everything in scope with a block sort of the id tie-break only, never a
27495
- * sort of the scope, which is still that floor.
27496
- *
27497
- * A row whose rule the aggregate did not see is skipped: the two statements
27498
- * run without a shared snapshot, so a capture landing between them can add a
27499
- * rule here that has no counts there, and the counts are what the group is
27500
- * built from.
27501
- */
27502
- previewRows(aggregates, scope) {
27503
- const wanted = /* @__PURE__ */ new Map();
27504
- let remaining = 0;
27505
- for (const [ruleId, agg] of aggregates) {
27506
- const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
27507
- wanted.set(ruleId, n);
27508
- remaining += n;
27509
- }
27510
- const rows = [];
27511
- if (remaining === 0) return rows;
27512
- const { sql, params } = this.findingScanSql(scope);
27513
- const taken = /* @__PURE__ */ new Map();
27514
- for (const r of iterateRows(this.db.prepare(sql), params)) {
27515
- const want = wanted.get(r.rule_id);
27516
- if (want === void 0) continue;
27517
- const have = taken.get(r.rule_id) ?? 0;
27518
- if (have >= want) continue;
27519
- taken.set(r.rule_id, have + 1);
27520
- rows.push(r);
27521
- remaining -= 1;
27522
- if (remaining === 0) break;
27523
- }
27524
- return rows;
27525
- }
27526
27521
  /**
27527
27522
  * Every finding in scope as a FlatFindingRow, newest first, streamed.
27528
27523
  *
@@ -27549,6 +27544,33 @@ var SqliteFindingsRepository = class {
27549
27544
  yield toFlatFindingRow(r);
27550
27545
  }
27551
27546
  }
27547
+ /**
27548
+ * One finding by its own id, or null when no such row exists.
27549
+ *
27550
+ * A primary-key seek on `inspection_findings`, so its cost does not grow with
27551
+ * the store — and, unlike anything derived from a list page, it resolves a
27552
+ * finding of ANY age. That is what the Findings page's one-shot `?finding=`
27553
+ * deep link needs: the id it carries may name a finding thousands of rows
27554
+ * older than anything a first page holds.
27555
+ *
27556
+ * Deliberately UNFILTERED — no capture-kind, session or time predicate. It
27557
+ * RESOLVES an id; whether that row would survive the list's current filters is
27558
+ * a different question, and hiding the target because a filter excludes it is
27559
+ * worse than showing it.
27560
+ *
27561
+ * `groupId` on the result IS the rule id, so this one read answers both "which
27562
+ * type should the list select?" and "what does the drawer show?".
27563
+ */
27564
+ findingInstance(id) {
27565
+ const row = this.db.prepare(
27566
+ `SELECT ${FINDING_ROW_COLUMNS_SQL}
27567
+ FROM inspection_findings f
27568
+ JOIN audit_events e ON e.id = f.audit_event_id
27569
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27570
+ WHERE f.id = ?`
27571
+ ).get(id);
27572
+ return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
27573
+ }
27552
27574
  /**
27553
27575
  * The one statement both instance-level scans run: every finding in scope,
27554
27576
  * joined to its event and definition, newest first.
@@ -27582,17 +27604,7 @@ var SqliteFindingsRepository = class {
27582
27604
  conditions.push("e.started_at >= ?");
27583
27605
  params.push(isoToEpochMillis(scope.from));
27584
27606
  }
27585
- const sql = `SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
27586
- d.severity AS severity, f.masked_match AS masked_match,
27587
- f.action_taken AS action_taken, f.confidence AS confidence,
27588
- e.started_at AS occurred_at,
27589
- e.source_tool AS source_tool,
27590
- e.repo AS repo,
27591
- e.file_path AS file,
27592
- e.tool_name AS tool_name,
27593
- f.audit_event_id AS event_id, e.root_session_id AS session_id,
27594
- e.event_type AS kind, f.finding_key AS finding_key,
27595
- ${latestResolutionStatusSql("f")} AS latest_status
27607
+ const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
27596
27608
  FROM audit_events e
27597
27609
  CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
27598
27610
  CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -27606,6 +27618,26 @@ var SqliteFindingsRepository = class {
27606
27618
  group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
27607
27619
  const rows = this.db.prepare(
27608
27620
  `SELECT rule_id,
27621
+ -- BARE columns beside max(latest_at), which is deliberate and
27622
+ -- is SQLite's documented behaviour: with a single min()/max()
27623
+ -- in an aggregate query, every bare column takes its value from
27624
+ -- the row that produced the extremum. So these are the severity
27625
+ -- and category of the definition whose finding is NEWEST, which
27626
+ -- is what the row-based build they replaced read off its first
27627
+ -- (newest-first) row.
27628
+ --
27629
+ -- min() is WRONG here and was the defect: inspection_definitions
27630
+ -- holds one row per rule VERSION (see its writer \u2014 a version bump
27631
+ -- mints a new row), so a rule whose severity moved between
27632
+ -- versions has several, and min() picks the ALPHABETICALLY
27633
+ -- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
27634
+ -- That is arbitrary in direction, and it feeds the badge, the
27635
+ -- filter, the facet counts and the primary sort key.
27636
+ --
27637
+ -- Adding a second min()/max() aggregate here would make these
27638
+ -- bare columns ambiguous again; keep max(latest_at) the only one.
27639
+ severity,
27640
+ category,
27609
27641
  sum(tuple_count) AS instance_count,
27610
27642
  max(latest_at) AS latest_at,
27611
27643
  group_concat(source_tools) AS source_tools,
@@ -27616,6 +27648,14 @@ var SqliteFindingsRepository = class {
27616
27648
  group_concat(tool_names) AS tool_names
27617
27649
  FROM (
27618
27650
  SELECT d.rule_id AS rule_id,
27651
+ -- Severity and category are columns of the DEFINITION, and
27652
+ -- a rule can have SEVERAL definitions (one per version), so
27653
+ -- these are grouped on below and resolved to the newest
27654
+ -- firing version by the outer query's bare-column select.
27655
+ -- They ride the aggregate because the type build has no rows
27656
+ -- to read them off \u2014 see buildFindingTypes.
27657
+ d.severity AS severity,
27658
+ d.category AS category,
27619
27659
  e.event_type || '${TUPLE_SEP}' ||
27620
27660
  (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
27621
27661
  coalesce(latest.status, '') AS status_tuple,
@@ -27630,7 +27670,7 @@ var SqliteFindingsRepository = class {
27630
27670
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
27631
27671
  ON latest.finding_key = f.finding_key
27632
27672
  ${scope.predicate}
27633
- GROUP BY d.rule_id, status_tuple
27673
+ GROUP BY d.rule_id, d.severity, d.category, status_tuple
27634
27674
  )
27635
27675
  GROUP BY rule_id`
27636
27676
  ).all(scope.params);
@@ -27639,6 +27679,8 @@ var SqliteFindingsRepository = class {
27639
27679
  r.rule_id,
27640
27680
  {
27641
27681
  instanceCount: r.instance_count,
27682
+ severity: r.severity,
27683
+ category: r.category,
27642
27684
  sourceTools: splitConcat(r.source_tools),
27643
27685
  actionsTaken: splitConcat(r.actions_taken),
27644
27686
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
@@ -27655,7 +27697,7 @@ var SqliteFindingsRepository = class {
27655
27697
  latestDetectedAt: epochMillisToIso(r.latest_at),
27656
27698
  // Free text only — joined and substring-matched, so group_concat's
27657
27699
  // commas need no unpicking (a repo/path containing one still matches).
27658
- // Left undefined (not '') when unfetched, so buildFindingGroups can
27700
+ // Left undefined (not '') when unfetched, so buildFindingTypes can
27659
27701
  // tell "no q this request" from "a group with no repo/file at all"
27660
27702
  // and skip priming a haystack nothing will read.
27661
27703
  ...withSearchText ? {
@@ -27807,6 +27849,12 @@ var SqliteHistorySyncRepository = class {
27807
27849
  this.markOwedStmt = db.prepare(
27808
27850
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27809
27851
  );
27852
+ this.markCaptureBacklogOwedStmt = db.prepare(
27853
+ `UPDATE audit_events SET outbox_owed = 1
27854
+ WHERE synced_at IS NULL
27855
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27856
+ AND started_at < :before`
27857
+ );
27810
27858
  this.stampStmt = db.prepare(
27811
27859
  `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27812
27860
  );
@@ -27855,7 +27903,9 @@ var SqliteHistorySyncRepository = class {
27855
27903
  );
27856
27904
  this.disownCapturesStmt = db.prepare(
27857
27905
  `UPDATE audit_events SET outbox_owed = NULL
27858
- WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
27906
+ WHERE outbox_owed IS NOT NULL
27907
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27908
+ AND started_at < :attachedAt`
27859
27909
  );
27860
27910
  this.rearmStmt = db.prepare(
27861
27911
  `UPDATE audit_events SET synced_at = NULL
@@ -27931,6 +27981,7 @@ var SqliteHistorySyncRepository = class {
27931
27981
  freezeBoundaryStmt;
27932
27982
  captureRowsStmt;
27933
27983
  markOwedStmt;
27984
+ markCaptureBacklogOwedStmt;
27934
27985
  captureSkipCountStmt;
27935
27986
  disownCapturesStmt;
27936
27987
  partitionStmt;
@@ -27994,6 +28045,23 @@ var SqliteHistorySyncRepository = class {
27994
28045
  markCaptureOwed(id) {
27995
28046
  this.markOwedStmt.run({ id });
27996
28047
  }
28048
+ /**
28049
+ * Mark every capture already on disk as owed, as of `before`.
28050
+ *
28051
+ * The consent-time backfill, called once from `aka attach` when a human
28052
+ * grants existing-history consent — never from an ongoing drain pass, and
28053
+ * never inferred from a boundary that could later move. `before` is the
28054
+ * caller's own "now" at the moment consent was granted, so what this marks
28055
+ * is exactly the backlog the consent prompt already counted, not whatever a
28056
+ * later re-attach or key rotation might widen it to.
28057
+ *
28058
+ * Returns how many rows matched, for the caller to log or test against. Not a
28059
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
28060
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
28061
+ */
28062
+ markCaptureBacklogOwed(before) {
28063
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
28064
+ }
27997
28065
  /** Record delivery. Called only AFTER the far side has accepted the rows. */
27998
28066
  markSynced(ids, atMs) {
27999
28067
  this.stampAll(ids, atMs);
@@ -28110,15 +28178,42 @@ var SqliteHistorySyncRepository = class {
28110
28178
  *
28111
28179
  * Delivery is a fact about ONE recipient: rows sent to the deployment a
28112
28180
  * machine has just left are undelivered as far as the new one is concerned.
28113
- * All three in one transaction, so a crash between them cannot leave stamps
28114
- * attributed to the wrong deployment, or a boundary that belongs to another.
28181
+ * All four in one transaction, so a crash between them cannot leave stamps
28182
+ * attributed to the wrong deployment, a boundary that belongs to another, or
28183
+ * a disown with no re-mark to follow it.
28115
28184
  *
28116
28185
  * The boundary is written HERE and only here, which is what freezes it: a
28117
28186
  * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28118
28187
  * unchanged, so this never runs and the backlog does not widen back over rows
28119
28188
  * the live path has since delivered.
28189
+ *
28190
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28191
+ * granted existing-history consent for the deployment this call is arming —
28192
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28193
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28194
+ * apart. Passed only when that grant is valid, since this method has no way
28195
+ * to check consent itself and must not mark a row owed for a machine that
28196
+ * never agreed to it. Applied AFTER the disown above, in the SAME
28197
+ * transaction: what the disown clears is every marker below `backlogBefore`,
28198
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28199
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28200
+ * on the cleared side of that bound — and the re-mark in the same
28201
+ * transaction is what puts those rows back. A crash between the two cannot
28202
+ * strand the ledger disowned with nothing re-marked — the transaction either
28203
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
28204
+ * committed re-enters this method on the very next pass. Omit it (the
28205
+ * structural-only tests do) to exercise the disown in isolation.
28206
+ *
28207
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
28208
+ * touching a marker the NEW deployment's OWN live path has already set: B's
28209
+ * live path can mark a capture owed from the moment `aka attach` writes the
28210
+ * descriptor, before the drain's first pass ever reaches this method, and
28211
+ * such a row sits at or after the bound rather than below it. What keeps the
28212
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
28213
+ * bound — disown runs first, re-mark second, both inside the one
28214
+ * transaction above.
28120
28215
  */
28121
- rearmFor(fingerprint, backlogBefore) {
28216
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28122
28217
  this.ensureRowStmt.run();
28123
28218
  withTransaction(
28124
28219
  this.db,
@@ -28126,7 +28221,10 @@ var SqliteHistorySyncRepository = class {
28126
28221
  const previous = getRow(this.fingerprintStmt)?.fingerprint;
28127
28222
  this.rearmStmt.run();
28128
28223
  if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28129
- this.disownCapturesStmt.run();
28224
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28225
+ }
28226
+ if (backfillCapturesBefore !== void 0) {
28227
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28130
28228
  }
28131
28229
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28132
28230
  },
@@ -28406,7 +28504,8 @@ function managedSettingsPaths(platform2 = process.platform) {
28406
28504
  }
28407
28505
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
28408
28506
  }
28409
- function readManagedSettings(paths = managedSettingsPaths()) {
28507
+ var testOnlyManagedPaths = null;
28508
+ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
28410
28509
  for (const path of paths) {
28411
28510
  let text;
28412
28511
  try {
@@ -30886,7 +30985,7 @@ function toUtcDateString(ms) {
30886
30985
  return new Date(ms).toISOString().slice(0, 10);
30887
30986
  }
30888
30987
  function isTimeseriesSeverity(s) {
30889
- return s === "critical" || s === "high" || s === "medium";
30988
+ return s === "critical" || s === "high" || s === "medium" || s === "low";
30890
30989
  }
30891
30990
  var SqliteSecurityRepository = class {
30892
30991
  constructor(db, now = () => Date.now()) {
@@ -31015,12 +31114,16 @@ var SqliteSecurityRepository = class {
31015
31114
  const now = this.now();
31016
31115
  const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
31017
31116
  const rows = this.findingsInRange(windowStart, now);
31018
- const points = Array.from({ length: numBuckets }, (_, i) => ({
31019
- timestamp: toUtcDateString(windowStart + i * bucketMs),
31020
- critical: 0,
31021
- high: 0,
31022
- medium: 0
31023
- }));
31117
+ const points = Array.from(
31118
+ { length: numBuckets },
31119
+ (_, i) => ({
31120
+ timestamp: toUtcDateString(windowStart + i * bucketMs),
31121
+ critical: 0,
31122
+ high: 0,
31123
+ medium: 0,
31124
+ low: 0
31125
+ })
31126
+ );
31024
31127
  for (const r of rows) {
31025
31128
  const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
31026
31129
  const bucket = points[idx];
@@ -31238,6 +31341,7 @@ var SqliteSecurityRepository = class {
31238
31341
  `SELECT f.finding_key AS finding_key,
31239
31342
  d.rule_id AS rule_id,
31240
31343
  d.severity AS severity,
31344
+ e.repo AS repo,
31241
31345
  e.file_path AS path,
31242
31346
  COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
31243
31347
  latest.resolved_at AS latest_resolved_at
@@ -31257,6 +31361,7 @@ var SqliteSecurityRepository = class {
31257
31361
  const items = rows.map((r) => ({
31258
31362
  findingKey: r.finding_key,
31259
31363
  ruleId: r.rule_id,
31364
+ repo: r.repo ?? "",
31260
31365
  severity: r.severity,
31261
31366
  path: r.path ?? "",
31262
31367
  resolvedAt: new Date(r.latest_resolved_at).toISOString(),
@@ -31266,13 +31371,66 @@ var SqliteSecurityRepository = class {
31266
31371
  }));
31267
31372
  return Promise.resolve({ items });
31268
31373
  }
31374
+ /**
31375
+ * Per-rule tallies of the findings that are still OPEN, whole-store.
31376
+ *
31377
+ * Scoped by status rather than by time, because the card this feeds is a to-do
31378
+ * list: a secret committed three weeks ago and never rotated is still the most
31379
+ * important thing to fix, and any window hides it. It carried a "newest N
31380
+ * findings" cap and then a range; the first meant a different span on every
31381
+ * machine, and the second reported "no recommendations" over live exposure.
31382
+ *
31383
+ * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
31384
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
31385
+ * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
31386
+ * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
31387
+ * The two answer different questions and only this one has to match a link.
31388
+ *
31389
+ * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
31390
+ * whole-store scope costs a grouped scan rather than a row per finding.
31391
+ */
31392
+ recommendationInputs() {
31393
+ const rows = allRows(
31394
+ this.db.prepare(
31395
+ `SELECT d.rule_id AS rule_id,
31396
+ d.category AS category,
31397
+ d.severity AS severity,
31398
+ COUNT(*) AS count
31399
+ FROM inspection_findings f
31400
+ JOIN audit_events e ON e.id = f.audit_event_id
31401
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31402
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31403
+ ON latest.finding_key = f.finding_key
31404
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31405
+ AND e.event_type = 'code_change'
31406
+ AND (
31407
+ f.finding_key IS NULL
31408
+ OR latest.status IS NULL
31409
+ OR latest.status NOT IN ('resolved', 'dismissed')
31410
+ )
31411
+ GROUP BY d.rule_id, d.category, d.severity`
31412
+ )
31413
+ );
31414
+ return Promise.resolve(
31415
+ rows.map((r) => ({
31416
+ ruleId: r.rule_id,
31417
+ category: r.category,
31418
+ severity: r.severity,
31419
+ count: r.count
31420
+ }))
31421
+ );
31422
+ }
31269
31423
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
31270
31424
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
31271
31425
  // numeric and the JS aggregations bucket/split on ms directly.
31272
31426
  findingsInRange(fromMs, toMs) {
31273
31427
  const rows = allRows(
31274
31428
  this.db.prepare(
31275
- `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
31429
+ // `rule_id`/`category` cost nothing extra: inspection_definitions is already
31430
+ // joined for `severity`, so they are two more columns off a row this read
31431
+ // already fetches. They feed the recommended-actions rollup.
31432
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31433
+ d.rule_id AS rule_id, d.category AS category
31276
31434
  FROM inspection_findings f
31277
31435
  JOIN audit_events e ON e.id = f.audit_event_id
31278
31436
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -31285,7 +31443,9 @@ var SqliteSecurityRepository = class {
31285
31443
  return rows.map((r) => ({
31286
31444
  occurredAt: r.occurred_at,
31287
31445
  severity: r.severity,
31288
- actionTaken: r.action_taken
31446
+ actionTaken: r.action_taken,
31447
+ ruleId: r.rule_id,
31448
+ category: r.category
31289
31449
  }));
31290
31450
  }
31291
31451
  };
@@ -32455,8 +32615,45 @@ function openLocalDatabase(dir) {
32455
32615
  };
32456
32616
  }
32457
32617
 
32458
- // ../../packages/persistence/src/finding-key.ts
32618
+ // ../../packages/persistence/src/egress-wire.ts
32459
32619
  import { createHash as createHash3 } from "crypto";
32620
+ function hashProjectKey(projectKey) {
32621
+ return createHash3("sha256").update(projectKey, "utf8").digest("hex");
32622
+ }
32623
+ function toIngestHit(hit) {
32624
+ return {
32625
+ host: hit.host,
32626
+ kind: hit.kind,
32627
+ name: hit.name,
32628
+ category: hit.category,
32629
+ trust: hit.trust,
32630
+ network: hit.network,
32631
+ method: hit.method,
32632
+ transport: hit.transport,
32633
+ url: hit.url,
32634
+ template: hit.template,
32635
+ dataClass: hit.dataClass,
32636
+ site: {
32637
+ file: hit.site.file,
32638
+ line: hit.site.line,
32639
+ dynamic: hit.site.dynamic,
32640
+ vendored: hit.site.vendored
32641
+ }
32642
+ };
32643
+ }
32644
+ function toEgressIngestRequest(input2) {
32645
+ const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32646
+ const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32647
+ return {
32648
+ projectKey: hashProjectKey(input2.projectKey),
32649
+ project: input2.project,
32650
+ reconcile,
32651
+ hits: hits.map(toIngestHit)
32652
+ };
32653
+ }
32654
+
32655
+ // ../../packages/persistence/src/finding-key.ts
32656
+ import { createHash as createHash4 } from "crypto";
32460
32657
 
32461
32658
  // ../../packages/persistence/src/fingerprint.ts
32462
32659
  import { createHmac, randomBytes } from "crypto";
@@ -32497,14 +32694,18 @@ function readFingerprintKey(dataDir2) {
32497
32694
  return parseKeyFile(raw);
32498
32695
  }
32499
32696
 
32500
- // ../../packages/persistence/src/history-preview.ts
32697
+ // ../../packages/persistence/src/history-backfill.ts
32501
32698
  import { existsSync as existsSync4 } from "fs";
32502
32699
  import { join as join9 } from "path";
32700
+
32701
+ // ../../packages/persistence/src/history-preview.ts
32702
+ import { existsSync as existsSync5 } from "fs";
32703
+ import { join as join10 } from "path";
32503
32704
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32504
32705
 
32505
32706
  // ../../packages/persistence/src/store-symlinks.ts
32506
- import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32507
- import { dirname as dirname3, join as join10, resolve } from "path";
32707
+ import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32708
+ import { dirname as dirname3, join as join11, resolve } from "path";
32508
32709
  var STORE_DB = "the store database (including the prompt corpus)";
32509
32710
  var STORE_SETTINGS = "your settings file";
32510
32711
  function storeContents(home) {
@@ -32513,7 +32714,7 @@ function storeContents(home) {
32513
32714
  [settingsDir(home), STORE_SETTINGS],
32514
32715
  [dataDir(home), STORE_DB],
32515
32716
  [keysDir(home), "the vault key"],
32516
- [join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
32717
+ [join11(settingsDir(home), "settings.json"), STORE_SETTINGS],
32517
32718
  [dbPath(home), STORE_DB]
32518
32719
  ]);
32519
32720
  }
@@ -32528,7 +32729,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
32528
32729
  holds,
32529
32730
  // existsSync follows the link, so a target that is gone reads as
32530
32731
  // absent here while lstat above still sees the link itself.
32531
- missing: !existsSync5(path),
32732
+ missing: !existsSync6(path),
32532
32733
  mode: targetMode(path, platform2)
32533
32734
  }
32534
32735
  ];
@@ -32566,61 +32767,25 @@ import {
32566
32767
  import { execFileSync } from "child_process";
32567
32768
  import { randomBytes as randomBytes2 } from "crypto";
32568
32769
  import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32569
- import { join as join11 } from "path";
32770
+ import { join as join12 } from "path";
32570
32771
 
32571
32772
  // ../../packages/persistence/src/vault/vault.ts
32572
32773
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32573
32774
 
32574
32775
  // ../../packages/persistence/src/warn-era-cap.ts
32575
- import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
32576
- import { join as join12 } from "path";
32776
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32777
+ import { join as join13 } from "path";
32577
32778
  var MARKER = "warn-era-capped";
32578
32779
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32579
32780
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32580
- const marker = join12(dataDir2, MARKER);
32581
- if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
32781
+ const marker = join13(dataDir2, MARKER);
32782
+ if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32582
32783
  const capped = db.policies.capCategoryActions();
32583
32784
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
32584
32785
  `, { mode: DATA_FILE_MODE });
32585
32786
  return { capped };
32586
32787
  }
32587
32788
 
32588
- // ../../packages/plugin-runtime/src/attached/egress-wire.ts
32589
- function hashProjectKey(projectKey) {
32590
- return createHash4("sha256").update(projectKey, "utf8").digest("hex");
32591
- }
32592
- function toIngestHit(hit) {
32593
- return {
32594
- host: hit.host,
32595
- kind: hit.kind,
32596
- name: hit.name,
32597
- category: hit.category,
32598
- trust: hit.trust,
32599
- network: hit.network,
32600
- method: hit.method,
32601
- transport: hit.transport,
32602
- url: hit.url,
32603
- template: hit.template,
32604
- dataClass: hit.dataClass,
32605
- site: {
32606
- file: hit.site.file,
32607
- line: hit.site.line,
32608
- dynamic: hit.site.dynamic,
32609
- vendored: hit.site.vendored
32610
- }
32611
- };
32612
- }
32613
- function toEgressIngestRequest(input2) {
32614
- const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
32615
- const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
32616
- return {
32617
- projectKey: hashProjectKey(input2.projectKey),
32618
- project: input2.project,
32619
- reconcile,
32620
- hits: hits.map(toIngestHit)
32621
- };
32622
- }
32623
-
32624
32789
  // ../../packages/remote/src/http.ts
32625
32790
  import { request as httpRequest } from "http";
32626
32791
  import { request as httpsRequest } from "https";
@@ -32900,6 +33065,7 @@ function createRemoteClient(options) {
32900
33065
  url: url2(ROUTES.shares),
32901
33066
  body: JSON.stringify(validated.data)
32902
33067
  });
33068
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
32903
33069
  okBody(response);
32904
33070
  },
32905
33071
  async pollCommand() {
@@ -32922,19 +33088,51 @@ function createRemoteClient(options) {
32922
33088
  };
32923
33089
  }
32924
33090
 
32925
- // ../../packages/plugin-runtime/src/attached/failure.ts
33091
+ // ../../packages/remote/src/failure-kind.ts
32926
33092
  function statusOf(err) {
32927
33093
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
32928
33094
  const { status } = err;
32929
33095
  if (typeof status !== "number" || !Number.isInteger(status)) return null;
32930
33096
  return status >= 100 && status <= 599 ? status : null;
32931
33097
  }
32932
- function classifyFailure(err) {
32933
- switch (statusOf(err)) {
33098
+ function nameOf(err) {
33099
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
33100
+ return typeof err.name === "string" ? err.name : null;
33101
+ }
33102
+ function classifyRemoteFailure(err) {
33103
+ switch (nameOf(err)) {
33104
+ case "RemoteRouteAbsent":
33105
+ return "route-absent";
33106
+ case "RemoteRequestInvalid":
33107
+ return "invalid-request";
33108
+ case "RemoteResponseInvalid":
33109
+ return "rejected";
33110
+ default:
33111
+ break;
33112
+ }
33113
+ const status = statusOf(err);
33114
+ if (status === null) return "unreachable";
33115
+ switch (status) {
32934
33116
  case 401:
32935
33117
  return "unauthorized";
32936
33118
  case 403:
32937
33119
  return "forbidden";
33120
+ case 429:
33121
+ return "unreachable";
33122
+ case 404:
33123
+ return "unreachable";
33124
+ default:
33125
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
33126
+ }
33127
+ }
33128
+
33129
+ // ../../packages/plugin-runtime/src/attached/failure.ts
33130
+ function classifyFailure(err) {
33131
+ switch (classifyRemoteFailure(err)) {
33132
+ case "unauthorized":
33133
+ return "unauthorized";
33134
+ case "forbidden":
33135
+ return "forbidden";
32938
33136
  default:
32939
33137
  return "unreachable";
32940
33138
  }
@@ -32957,10 +33155,10 @@ function withTimeout(promise2, ms) {
32957
33155
 
32958
33156
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32959
33157
  import { readFileSync as readFileSync8 } from "fs";
32960
- import { join as join13 } from "path";
33158
+ import { join as join14 } from "path";
32961
33159
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
32962
33160
  function forwardDropsPath(dataDir2) {
32963
- return join13(dataDir2, FORWARD_DROPS_FILENAME);
33161
+ return join14(dataDir2, FORWARD_DROPS_FILENAME);
32964
33162
  }
32965
33163
  function recordForwardDrops(dataDir2, count, nowMs) {
32966
33164
  if (count <= 0) return;
@@ -32996,13 +33194,13 @@ function readForwardDrops(dataDir2) {
32996
33194
 
32997
33195
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32998
33196
  import { randomUUID as randomUUID15 } from "crypto";
32999
- import { readFileSync as readFileSync14 } from "fs";
33197
+ import { readFileSync as readFileSync15 } from "fs";
33000
33198
  import { readFile, rename, writeFile } from "fs/promises";
33001
- import { join as join22 } from "path";
33199
+ import { join as join24 } from "path";
33002
33200
 
33003
33201
  // ../../packages/plugin-sdk/src/config.ts
33004
- import { existsSync as existsSync7 } from "fs";
33005
- import { join as join14 } from "path";
33202
+ import { existsSync as existsSync8 } from "fs";
33203
+ import { join as join15 } from "path";
33006
33204
 
33007
33205
  // ../../packages/plugin-sdk/src/provider-env.ts
33008
33206
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33056,8 +33254,8 @@ function resolveProvider() {
33056
33254
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33057
33255
  try {
33058
33256
  ensureLayoutDirSync(base);
33059
- const settingsFile = join14(settingsDir(base), "settings.json");
33060
- if (existsSync7(settingsFile)) tightenFile(settingsFile);
33257
+ const settingsFile = join15(settingsDir(base), "settings.json");
33258
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
33061
33259
  } catch {
33062
33260
  }
33063
33261
  migrateLegacyLayout(base);
@@ -33082,7 +33280,7 @@ function resolveProviderSafe(resolveProviderFn) {
33082
33280
  // ../../packages/plugin-sdk/src/config-inventory.ts
33083
33281
  import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33084
33282
  import { homedir as homedir2 } from "os";
33085
- import { basename as basename4, join as join16 } from "path";
33283
+ import { basename as basename4, join as join17 } from "path";
33086
33284
 
33087
33285
  // ../../packages/detections/src/egress/registry.ts
33088
33286
  var EXTRACTOR_VERSION = "1";
@@ -36211,8 +36409,8 @@ function maskText(text) {
36211
36409
  }
36212
36410
 
36213
36411
  // ../../packages/plugin-sdk/src/repo.ts
36214
- import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36215
- import { basename as basename3, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36412
+ import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
36413
+ import { basename as basename3, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
36216
36414
  function resolveRepoIdentity(cwd) {
36217
36415
  try {
36218
36416
  const root = findGitRoot(cwd);
@@ -36262,7 +36460,7 @@ function resolveGitBranch(cwd) {
36262
36460
  try {
36263
36461
  const root = findGitRoot(cwd);
36264
36462
  if (!root) return void 0;
36265
- const dotGit = join15(root, ".git");
36463
+ const dotGit = join16(root, ".git");
36266
36464
  let gitdir;
36267
36465
  try {
36268
36466
  gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
@@ -36270,7 +36468,7 @@ function resolveGitBranch(cwd) {
36270
36468
  return void 0;
36271
36469
  }
36272
36470
  if (gitdir === void 0) return void 0;
36273
- const head = safeRead(join15(gitdir, "HEAD"));
36471
+ const head = safeRead(join16(gitdir, "HEAD"));
36274
36472
  if (!head) return void 0;
36275
36473
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
36276
36474
  } catch {
@@ -36280,37 +36478,37 @@ function resolveGitBranch(cwd) {
36280
36478
  function resolveWorktreeGitdir(root, dotGitFile) {
36281
36479
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
36282
36480
  if (!target) return void 0;
36283
- return isAbsolute(target) ? target : join15(root, target);
36481
+ return isAbsolute(target) ? target : join16(root, target);
36284
36482
  }
36285
36483
  function findGitRoot(start) {
36286
36484
  let dir = start;
36287
36485
  for (; ; ) {
36288
- if (existsSync8(join15(dir, ".git"))) return dir;
36486
+ if (existsSync9(join16(dir, ".git"))) return dir;
36289
36487
  const parent = dirname4(dir);
36290
36488
  if (parent === dir) return void 0;
36291
36489
  dir = parent;
36292
36490
  }
36293
36491
  }
36294
36492
  function resolveGitContext(root) {
36295
- const dotGit = join15(root, ".git");
36493
+ const dotGit = join16(root, ".git");
36296
36494
  try {
36297
36495
  if (statSync6(dotGit).isDirectory()) {
36298
- return { configPath: join15(dotGit, "config"), headRoot: root };
36496
+ return { configPath: join16(dotGit, "config"), headRoot: root };
36299
36497
  }
36300
36498
  } catch {
36301
36499
  return void 0;
36302
36500
  }
36303
36501
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
36304
36502
  if (!target) return void 0;
36305
- const gitdir = isAbsolute(target) ? target : join15(root, target);
36306
- if (existsSync8(join15(gitdir, "config"))) {
36307
- return { configPath: join15(gitdir, "config"), headRoot: root };
36503
+ const gitdir = isAbsolute(target) ? target : join16(root, target);
36504
+ if (existsSync9(join16(gitdir, "config"))) {
36505
+ return { configPath: join16(gitdir, "config"), headRoot: root };
36308
36506
  }
36309
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
36507
+ const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
36310
36508
  if (!commonRaw) return void 0;
36311
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
36509
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
36312
36510
  const headRoot = basename3(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
36313
- return { configPath: join15(commonGitDir, "config"), headRoot };
36511
+ return { configPath: join16(commonGitDir, "config"), headRoot };
36314
36512
  }
36315
36513
  function safeRead(path) {
36316
36514
  try {
@@ -36376,31 +36574,31 @@ function resolveConfigInventory(input2) {
36376
36574
  };
36377
36575
  try {
36378
36576
  const home = input2.homeDir ?? homedir2();
36379
- const claudeDir = join16(home, ".claude");
36577
+ const claudeDir = join17(home, ".claude");
36380
36578
  const repo = resolveRepoIdentity(input2.cwd);
36381
36579
  const repoIdentity = repo?.url ?? input2.cwd;
36382
36580
  const projectSource = `project:${repoIdentity}`;
36383
- collectSettingsHooks(scan2, join16(claudeDir, "settings.json"), "user");
36384
- collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.json"), "project");
36385
- collectSettingsHooks(scan2, join16(input2.cwd, ".claude", "settings.local.json"), "local");
36581
+ collectSettingsHooks(scan2, join17(claudeDir, "settings.json"), "user");
36582
+ collectSettingsHooks(scan2, join17(input2.cwd, ".claude", "settings.json"), "project");
36583
+ collectSettingsHooks(scan2, join17(input2.cwd, ".claude", "settings.local.json"), "local");
36386
36584
  const projectOrigin = { scope: "project", project: repoIdentity };
36387
- collectMcpFile(scan2, join16(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
36388
- collectUserClaudeJson(scan2, join16(home, ".claude.json"), input2.cwd, repoIdentity);
36389
- collectMcpFile(scan2, join16(claudeDir, "settings.json"), { scope: "user" });
36390
- collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.json"), projectOrigin);
36391
- collectMcpFile(scan2, join16(input2.cwd, ".claude", "settings.local.json"), {
36585
+ collectMcpFile(scan2, join17(input2.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
36586
+ collectUserClaudeJson(scan2, join17(home, ".claude.json"), input2.cwd, repoIdentity);
36587
+ collectMcpFile(scan2, join17(claudeDir, "settings.json"), { scope: "user" });
36588
+ collectMcpFile(scan2, join17(input2.cwd, ".claude", "settings.json"), projectOrigin);
36589
+ collectMcpFile(scan2, join17(input2.cwd, ".claude", "settings.local.json"), {
36392
36590
  scope: "local",
36393
36591
  project: repoIdentity
36394
36592
  });
36395
36593
  collectConfigFiles(scan2, claudeDir, input2.cwd);
36396
- collectSkillsDir(scan2, join16(claudeDir, "skills"), { source: "local", scope: "user" });
36397
- collectSkillsDir(scan2, join16(input2.cwd, ".claude", "skills"), {
36594
+ collectSkillsDir(scan2, join17(claudeDir, "skills"), { source: "local", scope: "user" });
36595
+ collectSkillsDir(scan2, join17(input2.cwd, ".claude", "skills"), {
36398
36596
  source: projectSource,
36399
36597
  scope: "project"
36400
36598
  });
36401
36599
  collectInstalledPlugins(scan2, claudeDir);
36402
36600
  collectMarketplaceSkills(scan2, claudeDir);
36403
- collectSkillsDir(scan2, join16(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36601
+ collectSkillsDir(scan2, join17(input2.cwd, "skills"), { source: projectSource, scope: "project" });
36404
36602
  scan2.skills = dedupeSkills(scan2.skills);
36405
36603
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
36406
36604
  } catch (err) {
@@ -36529,7 +36727,7 @@ function projectEntryFor(projects, cwd) {
36529
36727
  return void 0;
36530
36728
  }
36531
36729
  function collectPluginManifestMcp(scan2, installPath, origin) {
36532
- const manifestPath = join16(installPath, ".claude-plugin", "plugin.json");
36730
+ const manifestPath = join17(installPath, ".claude-plugin", "plugin.json");
36533
36731
  const raw = readOptional(manifestPath);
36534
36732
  if (raw === void 0) return;
36535
36733
  try {
@@ -36537,7 +36735,7 @@ function collectPluginManifestMcp(scan2, installPath, origin) {
36537
36735
  if (typeof parsed2 !== "object" || parsed2 === null) return;
36538
36736
  const declared = parsed2.mcpServers;
36539
36737
  if (typeof declared === "string" && declared.length > 0) {
36540
- collectMcpFile(scan2, join16(installPath, declared), origin, { recordErrors: true });
36738
+ collectMcpFile(scan2, join17(installPath, declared), origin, { recordErrors: true });
36541
36739
  } else {
36542
36740
  collectMcpObject(scan2, declared, manifestPath, origin);
36543
36741
  }
@@ -36554,14 +36752,14 @@ var SETTINGS_KEY_LABELS = [
36554
36752
  ["statusLine", "status line"]
36555
36753
  ];
36556
36754
  function collectConfigFiles(scan2, claudeDir, cwd) {
36557
- settingsConfigFile(scan2, join16(claudeDir, "settings.json"), "user", "User settings");
36558
- settingsConfigFile(scan2, join16(cwd, ".claude", "settings.json"), "project", "Project settings");
36559
- settingsConfigFile(scan2, join16(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
36560
- memoryConfigFile(scan2, join16(claudeDir, "CLAUDE.md"), "user", "User memory");
36561
- memoryConfigFile(scan2, join16(cwd, "CLAUDE.md"), "project", "Project memory");
36562
- mcpJsonConfigFile(scan2, join16(cwd, ".mcp.json"));
36563
- dirConfigFile(scan2, join16(cwd, ".claude", "commands"), "Slash commands", "command");
36564
- dirConfigFile(scan2, join16(cwd, ".claude", "agents"), "Subagents", "subagent");
36755
+ settingsConfigFile(scan2, join17(claudeDir, "settings.json"), "user", "User settings");
36756
+ settingsConfigFile(scan2, join17(cwd, ".claude", "settings.json"), "project", "Project settings");
36757
+ settingsConfigFile(scan2, join17(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
36758
+ memoryConfigFile(scan2, join17(claudeDir, "CLAUDE.md"), "user", "User memory");
36759
+ memoryConfigFile(scan2, join17(cwd, "CLAUDE.md"), "project", "Project memory");
36760
+ mcpJsonConfigFile(scan2, join17(cwd, ".mcp.json"));
36761
+ dirConfigFile(scan2, join17(cwd, ".claude", "commands"), "Slash commands", "command");
36762
+ dirConfigFile(scan2, join17(cwd, ".claude", "agents"), "Subagents", "subagent");
36565
36763
  }
36566
36764
  function configFileEntry(path, scope, kind) {
36567
36765
  try {
@@ -36636,7 +36834,7 @@ function countMarkdownFiles(dir, depth) {
36636
36834
  let count = 0;
36637
36835
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
36638
36836
  if (dirent.name.startsWith(".")) continue;
36639
- if (dirent.isDirectory()) count += countMarkdownFiles(join16(dir, dirent.name), depth + 1);
36837
+ if (dirent.isDirectory()) count += countMarkdownFiles(join17(dir, dirent.name), depth + 1);
36640
36838
  else if (dirent.name.endsWith(".md")) count += 1;
36641
36839
  }
36642
36840
  return count;
@@ -36649,7 +36847,7 @@ function collectSkillsDir(scan2, dir, origin) {
36649
36847
  return;
36650
36848
  }
36651
36849
  for (const name of names) {
36652
- const skillFile = join16(dir, name, "SKILL.md");
36850
+ const skillFile = join17(dir, name, "SKILL.md");
36653
36851
  try {
36654
36852
  const raw = readOptional(skillFile);
36655
36853
  if (raw === void 0) continue;
@@ -36658,7 +36856,7 @@ function collectSkillsDir(scan2, dir, origin) {
36658
36856
  name: front.name ?? name,
36659
36857
  source: origin.source,
36660
36858
  scope: origin.scope,
36661
- location: join16(dir, name),
36859
+ location: join17(dir, name),
36662
36860
  updatedAt: statSync7(skillFile).mtime.toISOString()
36663
36861
  };
36664
36862
  const version2 = front.version ?? origin.defaultVersion;
@@ -36689,7 +36887,7 @@ function parseFrontmatter(raw) {
36689
36887
  return out;
36690
36888
  }
36691
36889
  function collectInstalledPlugins(scan2, claudeDir) {
36692
- const manifestPath = join16(claudeDir, "plugins", "installed_plugins.json");
36890
+ const manifestPath = join17(claudeDir, "plugins", "installed_plugins.json");
36693
36891
  const raw = readOptional(manifestPath);
36694
36892
  if (raw === void 0) return;
36695
36893
  let plugins;
@@ -36714,7 +36912,7 @@ function collectInstalledPlugins(scan2, claudeDir) {
36714
36912
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
36715
36913
  seen.add(installPath);
36716
36914
  const version2 = install.version;
36717
- const hooksPath = join16(installPath, "hooks", "hooks.json");
36915
+ const hooksPath = join17(installPath, "hooks", "hooks.json");
36718
36916
  const hooksRaw = readOptional(hooksPath);
36719
36917
  if (hooksRaw !== void 0) {
36720
36918
  try {
@@ -36734,22 +36932,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
36734
36932
  }
36735
36933
  const origin = { source: marketplace, scope: "plugin", pluginName };
36736
36934
  if (typeof version2 === "string") origin.defaultVersion = version2;
36737
- collectSkillsDir(scan2, join16(installPath, "skills"), origin);
36935
+ collectSkillsDir(scan2, join17(installPath, "skills"), origin);
36738
36936
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
36739
- collectMcpFile(scan2, join16(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
36937
+ collectMcpFile(scan2, join17(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
36740
36938
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
36741
36939
  }
36742
36940
  }
36743
36941
  }
36744
36942
  function collectMarketplaceSkills(scan2, claudeDir) {
36745
- for (const mp of readMarketplaces(join16(claudeDir, "plugins", "known_marketplaces.json"))) {
36943
+ for (const mp of readMarketplaces(join17(claudeDir, "plugins", "known_marketplaces.json"))) {
36746
36944
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
36747
- collectSkillsDir(scan2, join16(mp.installLocation, "skills"), {
36945
+ collectSkillsDir(scan2, join17(mp.installLocation, "skills"), {
36748
36946
  source: mp.name,
36749
36947
  scope: "plugin"
36750
36948
  });
36751
- collectPluginSkillDirs(scan2, join16(mp.installLocation, "plugins"), mp.name);
36752
- collectPluginSkillDirs(scan2, join16(mp.installLocation, "external_plugins"), mp.name);
36949
+ collectPluginSkillDirs(scan2, join17(mp.installLocation, "plugins"), mp.name);
36950
+ collectPluginSkillDirs(scan2, join17(mp.installLocation, "external_plugins"), mp.name);
36753
36951
  }
36754
36952
  }
36755
36953
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -36760,7 +36958,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
36760
36958
  return;
36761
36959
  }
36762
36960
  for (const plugin of plugins) {
36763
- collectSkillsDir(scan2, join16(pluginsDir, plugin, "skills"), {
36961
+ collectSkillsDir(scan2, join17(pluginsDir, plugin, "skills"), {
36764
36962
  source: marketplace,
36765
36963
  scope: "plugin",
36766
36964
  pluginName: plugin
@@ -36842,17 +37040,65 @@ function offersMaintenance(gateway, member) {
36842
37040
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36843
37041
 
36844
37042
  // ../../packages/plugin-sdk/src/isolated-scan.ts
36845
- import { existsSync as existsSync9 } from "fs";
37043
+ import { existsSync as existsSync10 } from "fs";
36846
37044
  import { fileURLToPath } from "url";
36847
37045
  import { Worker } from "worker_threads";
36848
37046
 
37047
+ // ../../packages/plugin-sdk/src/host-floor.ts
37048
+ import { readFileSync as readFileSync12 } from "fs";
37049
+ import { join as join19 } from "path";
37050
+
37051
+ // ../../packages/plugin-sdk/src/model-governance.ts
37052
+ import {
37053
+ closeSync as closeSync2,
37054
+ fstatSync,
37055
+ mkdirSync as mkdirSync2,
37056
+ openSync as openSync2,
37057
+ readFileSync as readFileSync11,
37058
+ readSync,
37059
+ writeFileSync as writeFileSync5
37060
+ } from "fs";
37061
+ import { join as join18 } from "path";
37062
+ var SESSION_MODEL_MARKER = "session-model";
37063
+ function recordSessionModel(dataDir2, sessionId, model) {
37064
+ if (sessionId === void 0 || sessionId === "") return;
37065
+ if (model === void 0 || model === "") return;
37066
+ try {
37067
+ mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
37068
+ writeFileSync5(join18(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
37069
+ encoding: "utf8",
37070
+ mode: DATA_FILE_MODE
37071
+ });
37072
+ } catch {
37073
+ }
37074
+ }
37075
+ var TAIL_BYTES = 256 * 1024;
37076
+
37077
+ // ../../packages/plugin-sdk/src/host-floor.ts
37078
+ var HOST_FEATURE = {
37079
+ ModelSwitch: "model-switch",
37080
+ VaultPointerDisplay: "vault-pointer-display"
37081
+ };
37082
+ var HOST_FLOORS = {
37083
+ [HOST_FEATURE.ModelSwitch]: {
37084
+ label: "model-switch protection",
37085
+ hookEvents: ["PreModelSwitch", "PostModelSwitch"],
37086
+ since: "2.1.251"
37087
+ },
37088
+ [HOST_FEATURE.VaultPointerDisplay]: {
37089
+ label: "vault pointer display",
37090
+ hookEvents: ["MessageDisplay"],
37091
+ since: "2.1.152"
37092
+ }
37093
+ };
37094
+
36849
37095
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36850
37096
  var import_ignore = __toESM(require_ignore(), 1);
36851
- import { readFileSync as readFileSync11 } from "fs";
36852
- import { join as join17 } from "path";
37097
+ import { readFileSync as readFileSync13 } from "fs";
37098
+ import { join as join20 } from "path";
36853
37099
  function readIgnoreLayer(dir, filename, anchorLen) {
36854
37100
  try {
36855
- return { matcher: (0, import_ignore.default)().add(readFileSync11(join17(dir, filename), "utf8")), anchorLen };
37101
+ return { matcher: (0, import_ignore.default)().add(readFileSync13(join20(dir, filename), "utf8")), anchorLen };
36856
37102
  } catch {
36857
37103
  return void 0;
36858
37104
  }
@@ -36908,44 +37154,18 @@ function resolveInventoryContext(input2) {
36908
37154
  return ctx;
36909
37155
  }
36910
37156
 
36911
- // ../../packages/plugin-sdk/src/model-governance.ts
36912
- import {
36913
- closeSync as closeSync2,
36914
- fstatSync,
36915
- mkdirSync as mkdirSync2,
36916
- openSync as openSync2,
36917
- readFileSync as readFileSync12,
36918
- readSync,
36919
- writeFileSync as writeFileSync5
36920
- } from "fs";
36921
- import { join as join18 } from "path";
36922
- var SESSION_MODEL_MARKER = "session-model";
36923
- function recordSessionModel(dataDir2, sessionId, model) {
36924
- if (sessionId === void 0 || sessionId === "") return;
36925
- if (model === void 0 || model === "") return;
36926
- try {
36927
- mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
36928
- writeFileSync5(join18(dataDir2, SESSION_MODEL_MARKER), JSON.stringify({ sessionId, model }), {
36929
- encoding: "utf8",
36930
- mode: DATA_FILE_MODE
36931
- });
36932
- } catch {
36933
- }
36934
- }
36935
- var TAIL_BYTES = 256 * 1024;
36936
-
36937
37157
  // ../../packages/plugin-sdk/src/nudge.ts
36938
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
36939
- import { join as join19 } from "path";
37158
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
37159
+ import { join as join21 } from "path";
36940
37160
  var SESSION_START_MARKER = "session-start-last";
36941
37161
  function claimSessionStart(dataDir2, sessionId) {
36942
37162
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
36943
37163
  }
36944
37164
  function claimOncePerSession(dataDir2, marker, sessionId) {
36945
37165
  if (!sessionId) return true;
36946
- const path = join19(dataDir2, marker);
37166
+ const path = join21(dataDir2, marker);
36947
37167
  try {
36948
- if (readFileSync13(path, "utf8") === sessionId) return false;
37168
+ if (readFileSync14(path, "utf8") === sessionId) return false;
36949
37169
  } catch {
36950
37170
  }
36951
37171
  try {
@@ -36961,8 +37181,8 @@ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
36961
37181
  import { basename as basename5, dirname as dirname5, sep as sep3 } from "path";
36962
37182
 
36963
37183
  // ../../packages/plugin-sdk/src/project-files.ts
36964
- import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
36965
- import { basename as basename6, join as join20 } from "path";
37184
+ import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
37185
+ import { basename as basename6, join as join22 } from "path";
36966
37186
  var SKIP_DIRS = /* @__PURE__ */ new Set([
36967
37187
  ".git",
36968
37188
  "node_modules",
@@ -37059,8 +37279,8 @@ function resolveProjectFiles(cwd, opts = {}) {
37059
37279
  }
37060
37280
  if (entry.isDirectory()) {
37061
37281
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
37062
- const fullPath = join20(dir, entry.name);
37063
- if (existsSync10(join20(fullPath, ".git"))) continue;
37282
+ const fullPath = join22(dir, entry.name);
37283
+ if (existsSync11(join22(fullPath, ".git"))) continue;
37064
37284
  if (depth >= bounds.maxDepth) {
37065
37285
  walk.omitted = true;
37066
37286
  continue;
@@ -37133,9 +37353,9 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
37133
37353
 
37134
37354
  // ../../packages/plugin-sdk/src/throttle.ts
37135
37355
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
37136
- import { join as join21 } from "path";
37356
+ import { join as join23 } from "path";
37137
37357
  function throttled(dataDir2, markerName, windowMs) {
37138
- const marker = join21(dataDir2, markerName);
37358
+ const marker = join23(dataDir2, markerName);
37139
37359
  try {
37140
37360
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
37141
37361
  } catch {
@@ -37186,7 +37406,7 @@ function parseBreakerState(raw, nowMs) {
37186
37406
  }
37187
37407
  function createForwardPolicy(deps) {
37188
37408
  const now = deps.now ?? (() => Date.now());
37189
- const file2 = join22(deps.dir, STATE_FILENAME);
37409
+ const file2 = join24(deps.dir, STATE_FILENAME);
37190
37410
  let state = null;
37191
37411
  let loading = null;
37192
37412
  async function readState() {
@@ -37908,8 +38128,8 @@ function toolAuditEvent(input2) {
37908
38128
  }
37909
38129
 
37910
38130
  // ../../packages/plugin-runtime/src/attached/history-state.ts
37911
- import { readFileSync as readFileSync15 } from "fs";
37912
- import { join as join23 } from "path";
38131
+ import { readFileSync as readFileSync16 } from "fs";
38132
+ import { join as join25 } from "path";
37913
38133
 
37914
38134
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37915
38135
  import { createHash as createHash6 } from "crypto";
@@ -37950,14 +38170,14 @@ function spawnDetached(scriptPath) {
37950
38170
  }
37951
38171
 
37952
38172
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37953
- import { readFileSync as readFileSync16 } from "fs";
38173
+ import { readFileSync as readFileSync17 } from "fs";
37954
38174
  var manifestBuildCache = /* @__PURE__ */ new Map();
37955
38175
  function readManifestBuild(manifestUrl, packageName) {
37956
38176
  const key = manifestUrl.href;
37957
38177
  if (!manifestBuildCache.has(key)) {
37958
38178
  let build;
37959
38179
  try {
37960
- const manifest = JSON.parse(readFileSync16(manifestUrl, "utf8"));
38180
+ const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
37961
38181
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
37962
38182
  } catch {
37963
38183
  build = void 0;
@@ -37984,7 +38204,7 @@ function createPluginBlock(build, policyStore) {
37984
38204
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37985
38205
  import { randomUUID as randomUUID16 } from "crypto";
37986
38206
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
37987
- import { join as join24 } from "path";
38207
+ import { join as join26 } from "path";
37988
38208
 
37989
38209
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37990
38210
  import { rename as rename2 } from "fs/promises";
@@ -38008,7 +38228,7 @@ async function publishByRename(tmp, file2, move = rename2) {
38008
38228
 
38009
38229
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
38010
38230
  function createPolicyStore(dir = dataDir()) {
38011
- const file2 = join24(dir, "policy-cache.json");
38231
+ const file2 = join26(dir, "policy-cache.json");
38012
38232
  async function read() {
38013
38233
  try {
38014
38234
  const raw = await readFile2(file2, "utf8");
@@ -38239,11 +38459,11 @@ function readStorePosture(dbPath2) {
38239
38459
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
38240
38460
  import { randomUUID as randomUUID17 } from "crypto";
38241
38461
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
38242
- import { join as join25 } from "path";
38462
+ import { join as join27 } from "path";
38243
38463
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
38244
38464
  function createPostureStore(dir = settingsDir(), legacyDir) {
38245
- const file2 = join25(dir, "posture-state.json");
38246
- const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
38465
+ const file2 = join27(dir, "posture-state.json");
38466
+ const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
38247
38467
  async function persist(state) {
38248
38468
  await ensureDataDir(dir);
38249
38469
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -38311,8 +38531,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38311
38531
  }
38312
38532
 
38313
38533
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38314
- import { readFileSync as readFileSync17 } from "fs";
38315
- import { join as join26 } from "path";
38534
+ import { readFileSync as readFileSync18 } from "fs";
38535
+ import { join as join28 } from "path";
38316
38536
 
38317
38537
  // ../../packages/plugin-runtime/src/attached/status.ts
38318
38538
  var REFUSAL_LINES = {
@@ -38916,10 +39136,10 @@ function buildSessionRoot(sessionId, input2, ctx, resolved, provider, branch) {
38916
39136
  const attributes = {};
38917
39137
  const osVersion = ctx.host?.attributes.os_version;
38918
39138
  const harnessVersion2 = ctx.harness?.attributes.harness_version;
38919
- const harnessInterface = ctx.harness?.attributes.interface;
39139
+ const harnessInterface2 = ctx.harness?.attributes.interface;
38920
39140
  if (typeof osVersion === "string") attributes.os_version = osVersion;
38921
39141
  if (typeof harnessVersion2 === "string") attributes.harness_version = harnessVersion2;
38922
- if (typeof harnessInterface === "string") attributes.harness_interface = harnessInterface;
39142
+ if (typeof harnessInterface2 === "string") attributes.harness_interface = harnessInterface2;
38923
39143
  attributes.provider = provider.provider;
38924
39144
  if (provider.gatewayHost !== void 0) attributes.gateway_host = provider.gatewayHost;
38925
39145
  attributes.harness = harnessFromTool(input2.tool);
@@ -38952,7 +39172,7 @@ function pluginBuild() {
38952
39172
 
38953
39173
  // src/history/reconcile-trigger.ts
38954
39174
  import { spawn as spawn3 } from "child_process";
38955
- import { dirname as dirname6, join as join28 } from "path";
39175
+ import { dirname as dirname6, join as join30 } from "path";
38956
39176
  import { fileURLToPath as fileURLToPath4 } from "url";
38957
39177
 
38958
39178
  // src/history/tail.ts
@@ -38962,11 +39182,11 @@ import {
38962
39182
  fstatSync as fstatSync2,
38963
39183
  mkdirSync as mkdirSync5,
38964
39184
  openSync as openSync3,
38965
- readFileSync as readFileSync18,
39185
+ readFileSync as readFileSync19,
38966
39186
  readSync as readSync2,
38967
39187
  writeFileSync as writeFileSync8
38968
39188
  } from "fs";
38969
- import { join as join27 } from "path";
39189
+ import { join as join29 } from "path";
38970
39190
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
38971
39191
  function safeSessionId(sessionId) {
38972
39192
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
@@ -38983,7 +39203,7 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
38983
39203
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
38984
39204
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
38985
39205
  const here = dirname6(fileURLToPath4(import.meta.url));
38986
- const child = spawn3(process.execPath, [join28(here, "reconcile.js"), sessionId, transcriptPath], {
39206
+ const child = spawn3(process.execPath, [join30(here, "reconcile.js"), sessionId, transcriptPath], {
38987
39207
  detached: true,
38988
39208
  stdio: "ignore"
38989
39209
  });
@@ -38994,17 +39214,17 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
38994
39214
 
38995
39215
  // src/protocol/marker.ts
38996
39216
  import { randomBytes as randomBytes4 } from "crypto";
38997
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync19, renameSync as renameSync5, writeFileSync as writeFileSync9 } from "fs";
38998
- import { join as join29 } from "path";
39217
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync20, renameSync as renameSync5, writeFileSync as writeFileSync9 } from "fs";
39218
+ import { join as join31 } from "path";
38999
39219
  var MARKER_FILE = "protocol-marker";
39000
39220
  function mintMarker() {
39001
39221
  return randomBytes4(8).toString("hex");
39002
39222
  }
39003
39223
  function sessionProtocolMarker(dataDir2, sessionId) {
39004
39224
  if (!sessionId) return mintMarker();
39005
- const path = join29(dataDir2, MARKER_FILE);
39225
+ const path = join31(dataDir2, MARKER_FILE);
39006
39226
  try {
39007
- const stored = JSON.parse(readFileSync19(path, "utf8"));
39227
+ const stored = JSON.parse(readFileSync20(path, "utf8"));
39008
39228
  if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
39009
39229
  return stored.marker;
39010
39230
  }
@@ -39013,7 +39233,7 @@ function sessionProtocolMarker(dataDir2, sessionId) {
39013
39233
  const marker = mintMarker();
39014
39234
  try {
39015
39235
  mkdirSync6(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
39016
- const tmp = join29(dataDir2, `${MARKER_FILE}.tmp`);
39236
+ const tmp = join31(dataDir2, `${MARKER_FILE}.tmp`);
39017
39237
  writeFileSync9(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
39018
39238
  renameSync5(tmp, path);
39019
39239
  } catch {
@@ -39076,8 +39296,8 @@ function emit(output2) {
39076
39296
  }
39077
39297
 
39078
39298
  // src/hooks/store-health.ts
39079
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync20, writeFileSync as writeFileSync10 } from "fs";
39080
- import { dirname as dirname7, join as join30 } from "path";
39299
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync21, writeFileSync as writeFileSync10 } from "fs";
39300
+ import { dirname as dirname7, join as join32 } from "path";
39081
39301
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
39082
39302
  function markerDirs(dataDir2) {
39083
39303
  return [dataDir2, dirname7(dataDir2)];
@@ -39085,7 +39305,7 @@ function markerDirs(dataDir2) {
39085
39305
  function alreadyClaimed(dirs, marker, sessionId) {
39086
39306
  return dirs.some((dir) => {
39087
39307
  try {
39088
- return readFileSync20(join30(dir, marker), "utf8") === sessionId;
39308
+ return readFileSync21(join32(dir, marker), "utf8") === sessionId;
39089
39309
  } catch {
39090
39310
  return false;
39091
39311
  }
@@ -39095,7 +39315,7 @@ function recordClaim(dirs, marker, sessionId) {
39095
39315
  for (const dir of dirs) {
39096
39316
  try {
39097
39317
  mkdirSync7(dir, { recursive: true, mode: DATA_DIR_MODE });
39098
- writeFileSync10(join30(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39318
+ writeFileSync10(join32(dir, marker), sessionId, { mode: DATA_FILE_MODE });
39099
39319
  return;
39100
39320
  } catch {
39101
39321
  }
@@ -39135,11 +39355,15 @@ function warnIfStoreRedirected(config2, sessionId, write = (message2) => void pr
39135
39355
  }
39136
39356
 
39137
39357
  // src/hooks/session-start.ts
39358
+ function harnessInterface() {
39359
+ const value = process.env.CLAUDE_CODE_ENTRYPOINT;
39360
+ return value === void 0 || value === "" ? void 0 : value;
39361
+ }
39138
39362
  function harnessVersion() {
39139
39363
  const manifestPath = process.argv[2];
39140
39364
  if (!manifestPath) return void 0;
39141
39365
  try {
39142
- const manifest = JSON.parse(readFileSync21(manifestPath, "utf8"));
39366
+ const manifest = JSON.parse(readFileSync22(manifestPath, "utf8"));
39143
39367
  return typeof manifest.version === "string" ? manifest.version : void 0;
39144
39368
  } catch {
39145
39369
  return void 0;
@@ -39157,11 +39381,12 @@ async function main() {
39157
39381
  cwd,
39158
39382
  tool: SOURCE_TOOL.ClaudeCode,
39159
39383
  harnessVersion: version2,
39160
- pluginBuild: version2 === void 0 ? void 0 : { package: PLUGIN_PACKAGE, version: version2 }
39161
- // harnessInterface is intentionally omitted: Claude Code's SessionStart hook
39162
- // exposes no meaningful interface discriminator (terminal vs IDE vs web) yet.
39163
- // The resolver already folds it into the harness bag, so pass it here once
39164
- // the harness surfaces one — no schema change needed.
39384
+ pluginBuild: version2 === void 0 ? void 0 : { package: PLUGIN_PACKAGE, version: version2 },
39385
+ // The surface this session is running on, when the host says. Folded into
39386
+ // the harness bag by the resolver and snapshotted as `harness_interface`;
39387
+ // absent when the host stamps nothing, which reads as unknown rather than
39388
+ // as a terminal session.
39389
+ harnessInterface: harnessInterface()
39165
39390
  });
39166
39391
  if (result.staleBinaryNotice !== null) {
39167
39392
  process.stderr.write(`[aka] ${result.staleBinaryNotice}