@akasecurity/ai-tc-codex 0.9.16 → 0.9.17-beta.1

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.
@@ -716,13 +716,13 @@ var require_ignore = __commonJS({
716
716
  const rules = this._rules;
717
717
  const { length } = rules;
718
718
  const shortcut = this._basenameCount * 2 >= length;
719
- const basename8 = shortcut ? basenameOf(path) : path;
719
+ const basename6 = shortcut ? basenameOf(path) : path;
720
720
  for (let index = 0; index < length; index++) {
721
721
  const rule = rules[index];
722
722
  const { negative } = rule;
723
723
  const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
724
724
  if (!skip && rule[mode].test(
725
- shortcut && rule._basenameOnly ? basename8 : path
725
+ shortcut && rule._basenameOnly ? basename6 : path
726
726
  )) {
727
727
  ignored = !negative;
728
728
  unignored = negative;
@@ -874,19 +874,7 @@ var require_ignore = __commonJS({
874
874
 
875
875
  // ../../packages/plugin-sdk/src/config.ts
876
876
  import { existsSync as existsSync8 } from "fs";
877
- import { join as join16 } from "path";
878
-
879
- // ../../packages/persistence/src/attached-derived.ts
880
- import { rmSync } from "fs";
881
- import { join } from "path";
882
- var POLICY_CACHE_FILENAME = "policy-cache.json";
883
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
884
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
885
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
886
-
887
- // ../../packages/persistence/src/control-plane-credential.ts
888
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
889
- import { join as join2 } from "path";
877
+ import { join as join17 } from "path";
890
878
 
891
879
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
892
880
  var DEFERRED_MIGRATION_TAGS = [
@@ -1059,7 +1047,7 @@ var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1059
1047
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1060
1048
 
1061
1049
  // ../../packages/schema/src/invisible-padding.ts
1062
- var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
1050
+ var INVISIBLE_PADDING = /[\u00AD\u061C\u180E\u200B\u200E\u200F\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\uFFF9-\uFFFB\u{E0001}\u{E0020}-\u{E007F}]/gu;
1063
1051
  function stripInvisiblePadding(text) {
1064
1052
  return text.replace(INVISIBLE_PADDING, "");
1065
1053
  }
@@ -3877,9 +3865,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3877
3865
  function stripTabAndNewline(value) {
3878
3866
  return value.replace(asciiTabOrNewline, "");
3879
3867
  }
3880
- function urlHostnameOk(url2, hostname7) {
3881
- hostname7.lastIndex = 0;
3882
- return hostname7.test(url2.hostname);
3868
+ function urlHostnameOk(url2, hostname6) {
3869
+ hostname6.lastIndex = 0;
3870
+ return hostname6.test(url2.hostname);
3883
3871
  }
3884
3872
  function urlProtocolOk(url2, protocol) {
3885
3873
  protocol.lastIndex = 0;
@@ -20799,13 +20787,16 @@ function serviceTierMultiplier(tier) {
20799
20787
  if (tier === void 0) return 1;
20800
20788
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20801
20789
  }
20790
+ function promptTokensOf(usage) {
20791
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
20792
+ }
20802
20793
  function costOf(price, usage) {
20803
20794
  const metered = [
20804
20795
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20805
20796
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20806
20797
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20807
20798
  ];
20808
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
20799
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20809
20800
  if (band !== null && (band.input === null || band.output === null)) return null;
20810
20801
  const inputRate = band?.input ?? price.input;
20811
20802
  const outputRate = band?.output ?? price.output;
@@ -20878,8 +20869,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20878
20869
  ["ollama", "local"],
20879
20870
  ["local", "local"]
20880
20871
  ]);
20881
- function hostingFor(platform2) {
20882
- return PLATFORM_HOSTING.get(platform2) ?? "api";
20872
+ function hostingFor(platform) {
20873
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20883
20874
  }
20884
20875
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20885
20876
  ["anthropic", "anthropic"],
@@ -20893,8 +20884,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20893
20884
  function firstPartyPlatformFor(vendor2) {
20894
20885
  return FIRST_PARTY.get(vendor2) ?? null;
20895
20886
  }
20896
- function isFirstParty(vendor2, platform2) {
20897
- return FIRST_PARTY.get(vendor2) === platform2;
20887
+ function isFirstParty(vendor2, platform) {
20888
+ return FIRST_PARTY.get(vendor2) === platform;
20898
20889
  }
20899
20890
  var PLATFORM_NAMESPACES = Object.freeze([
20900
20891
  "anthropic",
@@ -20955,14 +20946,14 @@ var ModelVendorBuilder = class {
20955
20946
  );
20956
20947
  }
20957
20948
  for (const ref of spec.on ?? []) {
20958
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20959
- const firstParty = isFirstParty(this.vendor, platform2);
20960
- const hosting = hostingFor(platform2);
20949
+ const { platform, price, retention, region } = normalizeRef(ref);
20950
+ const firstParty = isFirstParty(this.vendor, platform);
20951
+ const hosting = hostingFor(platform);
20961
20952
  const isSelfHosted = hosting === "local";
20962
20953
  platforms.set(
20963
- platform2,
20954
+ platform,
20964
20955
  Object.freeze({
20965
- platform: platform2,
20956
+ platform,
20966
20957
  hosting,
20967
20958
  firstParty,
20968
20959
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21015,35 +21006,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21015
21006
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21016
21007
  var BEDROCK_REVISION_RE = /:\d+$/u;
21017
21008
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21018
- var DATED_SUFFIX_RE = /-\d{8}$/u;
21009
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21019
21010
  function stripPlatformDecorations(model) {
21020
21011
  let id = model.trim();
21021
- let platform2 = null;
21012
+ let platform = null;
21022
21013
  if (GEO_PREFIX_RE.test(id)) {
21023
21014
  id = id.replace(GEO_PREFIX_RE, "");
21024
- platform2 = "bedrock";
21015
+ platform = "bedrock";
21025
21016
  }
21026
21017
  if (NAMESPACE_DOT_RE.test(id)) {
21027
21018
  id = id.replace(NAMESPACE_DOT_RE, "");
21028
- platform2 ??= "bedrock";
21019
+ platform ??= "bedrock";
21029
21020
  }
21030
21021
  if (BEDROCK_VERSION_RE.test(id)) {
21031
21022
  id = id.replace(BEDROCK_VERSION_RE, "");
21032
- platform2 ??= "bedrock";
21023
+ platform ??= "bedrock";
21033
21024
  } else if (BEDROCK_REVISION_RE.test(id)) {
21034
21025
  id = id.replace(BEDROCK_REVISION_RE, "");
21035
- platform2 ??= "bedrock";
21026
+ platform ??= "bedrock";
21036
21027
  }
21037
21028
  if (VERTEX_VERSION_RE.test(id)) {
21038
21029
  id = id.replace(VERTEX_VERSION_RE, "");
21039
- platform2 ??= "vertex";
21030
+ platform ??= "vertex";
21040
21031
  }
21041
21032
  if (NAMESPACE_SLASH_RE.test(id)) {
21042
21033
  id = id.replace(NAMESPACE_SLASH_RE, "");
21043
21034
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21044
21035
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21045
21036
  }
21046
- return { id, platform: platform2 };
21037
+ return { id, platform };
21047
21038
  }
21048
21039
  function buildModelIndex(entries) {
21049
21040
  const byId = /* @__PURE__ */ new Map();
@@ -21060,19 +21051,19 @@ function resolveModel(raw, index) {
21060
21051
  if (exact !== void 0) {
21061
21052
  return { entry: exact, canonicalId: raw, platform: null, raw };
21062
21053
  }
21063
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
21054
+ const { id, platform } = stripPlatformDecorations(raw);
21064
21055
  const stripped = index.byId.get(id);
21065
21056
  if (stripped !== void 0) {
21066
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
21057
+ return { entry: stripped, canonicalId: id, platform, raw };
21067
21058
  }
21068
21059
  if (DATED_SUFFIX_RE.test(id)) {
21069
21060
  const undated = id.replace(DATED_SUFFIX_RE, "");
21070
21061
  const byDate = index.byId.get(undated);
21071
21062
  if (byDate !== void 0) {
21072
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
21063
+ return { entry: byDate, canonicalId: undated, platform, raw };
21073
21064
  }
21074
21065
  }
21075
- return { entry: null, canonicalId: raw, platform: platform2, raw };
21066
+ return { entry: null, canonicalId: raw, platform, raw };
21076
21067
  }
21077
21068
 
21078
21069
  // ../../packages/schema/src/model/catalog.ts
@@ -21165,7 +21156,7 @@ anthropic.model("claude-haiku-4-5", {
21165
21156
  name: "Claude Haiku 4.5",
21166
21157
  ctx: 2e5,
21167
21158
  maxOut: 64e3,
21168
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
21159
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21169
21160
  capability: null,
21170
21161
  price: anthropicPrice(1, 5, 0.1),
21171
21162
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21296,6 +21287,11 @@ openai.model("gpt-4o", {
21296
21287
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21297
21288
  on: [...OPENAI_RESELLERS]
21298
21289
  });
21290
+ openai.model("gpt-4o-2024-05-13", {
21291
+ name: "GPT-4o (2024-05-13)",
21292
+ price: tokenPrice(5, 15),
21293
+ on: [...OPENAI_RESELLERS]
21294
+ });
21299
21295
  openai.model("gpt-4o-mini", {
21300
21296
  name: "GPT-4o mini",
21301
21297
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21315,6 +21311,24 @@ openai.model("o3", {
21315
21311
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21316
21312
  on: [...OPENAI_RESELLERS]
21317
21313
  });
21314
+ openai.model("text-embedding-3-small", {
21315
+ name: "text-embedding-3-small",
21316
+ capability: "embedding",
21317
+ price: tokenPrice(0.02, 0),
21318
+ on: [...OPENAI_RESELLERS]
21319
+ });
21320
+ openai.model("text-embedding-3-large", {
21321
+ name: "text-embedding-3-large",
21322
+ capability: "embedding",
21323
+ price: tokenPrice(0.13, 0),
21324
+ on: [...OPENAI_RESELLERS]
21325
+ });
21326
+ openai.model("text-embedding-ada-002", {
21327
+ name: "text-embedding-ada-002",
21328
+ capability: "embedding",
21329
+ price: tokenPrice(0.1, 0),
21330
+ on: [...OPENAI_RESELLERS]
21331
+ });
21318
21332
  openai.model("gpt-oss-120b", {
21319
21333
  name: "GPT-OSS 120B",
21320
21334
  openWeights: true,
@@ -21601,10 +21615,21 @@ var MODEL_ENTRIES = Object.freeze([
21601
21615
  ...alibaba.models(),
21602
21616
  ...amazon.models()
21603
21617
  ]);
21618
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
21619
+ [
21620
+ ...new Set(
21621
+ MODEL_ENTRIES.flatMap(
21622
+ (entry) => [...entry.platforms.values()].flatMap(
21623
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
21624
+ )
21625
+ )
21626
+ )
21627
+ ].sort((a, b) => a - b)
21628
+ );
21604
21629
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21605
21630
 
21606
21631
  // ../../packages/schema/src/model/governance.ts
21607
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
21632
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21608
21633
  var DataRetention = external_exports.enum([
21609
21634
  "zero_retention",
21610
21635
  "no_storage",
@@ -21700,16 +21725,16 @@ function platformForProvider(provider) {
21700
21725
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21701
21726
  }
21702
21727
  function isLocalProvider(provider) {
21703
- const platform2 = platformForProvider(provider);
21704
- return platform2 !== null && hostingFor(platform2) === "local";
21728
+ const platform = platformForProvider(provider);
21729
+ return platform !== null && hostingFor(platform) === "local";
21705
21730
  }
21706
21731
  function priceFor(provider, model) {
21707
21732
  if (isLocalProvider(provider)) return ZERO_PRICE;
21708
21733
  const resolved = resolveModel(model, MODEL_INDEX);
21709
21734
  if (resolved.entry === null) return null;
21710
- const platform2 = resolved.platform ?? platformForProvider(provider);
21711
- if (platform2 === null) return null;
21712
- return resolved.entry.platforms.get(platform2)?.price ?? null;
21735
+ const platform = resolved.platform ?? platformForProvider(provider);
21736
+ if (platform === null) return null;
21737
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21713
21738
  }
21714
21739
  var defaultCostModel = {
21715
21740
  normalizeModelId(provider, model) {
@@ -21735,7 +21760,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21735
21760
 
21736
21761
  // ../../packages/schema/src/token/token-report.ts
21737
21762
  var num = (value) => value ?? 0;
21738
- function costUsageOf(a) {
21763
+ function costUsageOf(a, promptTokens) {
21739
21764
  const usage = {
21740
21765
  inputTokens: num(a.input_tokens),
21741
21766
  outputTokens: num(a.output_tokens),
@@ -21745,11 +21770,12 @@ function costUsageOf(a) {
21745
21770
  webSearchRequests: num(a.web_search_requests)
21746
21771
  };
21747
21772
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
21773
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21748
21774
  return usage;
21749
21775
  }
21750
21776
  function buildTokenReports(leaves, costModel) {
21751
21777
  const bySession = /* @__PURE__ */ new Map();
21752
- for (const { sessionId, attributes } of leaves) {
21778
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21753
21779
  const provider = attributes.provider ?? "unknown";
21754
21780
  const model = attributes.model ?? "unknown";
21755
21781
  const key = `${provider} ${model}`;
@@ -21768,7 +21794,8 @@ function buildTokenReports(leaves, costModel) {
21768
21794
  cacheCreation: 0,
21769
21795
  cacheRead: 0,
21770
21796
  costUsd: 0,
21771
- priced: false
21797
+ priced: false,
21798
+ partial: false
21772
21799
  };
21773
21800
  rollups.set(key, acc);
21774
21801
  }
@@ -21776,8 +21803,14 @@ function buildTokenReports(leaves, costModel) {
21776
21803
  acc.output += num(attributes.output_tokens);
21777
21804
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21778
21805
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21779
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21780
- if (leafCost !== null) {
21806
+ const leafCost = costModel.costFor({
21807
+ provider,
21808
+ model,
21809
+ usage: costUsageOf(attributes, promptTokens)
21810
+ });
21811
+ if (leafCost === null) {
21812
+ acc.partial = true;
21813
+ } else {
21781
21814
  acc.costUsd += leafCost;
21782
21815
  acc.priced = true;
21783
21816
  }
@@ -21793,9 +21826,8 @@ function buildTokenReports(leaves, costModel) {
21793
21826
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21794
21827
  totalTokens += rollupTotal;
21795
21828
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21796
- if (estimatedCostUsd === null) {
21797
- anyUnpriced = true;
21798
- } else {
21829
+ if (acc.partial) anyUnpriced = true;
21830
+ if (estimatedCostUsd !== null) {
21799
21831
  anyPriced = true;
21800
21832
  costUsd += estimatedCostUsd;
21801
21833
  }
@@ -21818,7 +21850,7 @@ function buildTokenReports(leaves, costModel) {
21818
21850
  totalTokens,
21819
21851
  // Σ of the PRICED rollups; null when none had a known price.
21820
21852
  estimatedCostUsd: anyPriced ? costUsd : null,
21821
- // Any unknown (provider, model) means the total understates real spend.
21853
+ // Any call priced to null means the total understates real spend.
21822
21854
  costIsPartial: anyUnpriced
21823
21855
  });
21824
21856
  }
@@ -22697,8 +22729,9 @@ var SessionTokenReport = external_exports.object({
22697
22729
  totalTokens: external_exports.number().int().nonnegative(),
22698
22730
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22699
22731
  estimatedCostUsd: external_exports.number().nullable(),
22700
- // True whenever any rollup has a null cost (unknown provider/model), so the
22701
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
22732
+ // True whenever any call priced to null (an unknown provider/model, or a call
22733
+ // over a long-context threshold whose rate is unpublished), so the total
22734
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22702
22735
  // precise figure rather than silently dropping the unpriced calls.
22703
22736
  costIsPartial: external_exports.boolean()
22704
22737
  });
@@ -23575,7 +23608,15 @@ var StorePostureSnapshot = external_exports.object({
23575
23608
  policyCounts: StorePosturePolicyCounts,
23576
23609
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23577
23610
  // getting its 200 without a payload change.
23578
- plugin: StorePosturePlugin.optional()
23611
+ plugin: StorePosturePlugin.optional(),
23612
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
23613
+ // machine attachment omits it, so its body is byte for byte the one it
23614
+ // sent before this member existed. Absent therefore means machine-wide OR
23615
+ // a reporter older than this member, never "scoped". Both values parse, so
23616
+ // a sender that one day spells `machine` breaks no receiver; any other
23617
+ // value fails the whole snapshot, which is why the reporter sends a
23618
+ // constant and never the raw mode.
23619
+ attachmentMode: AttachmentMode.optional()
23579
23620
  }).meta({ id: "StorePostureSnapshot" });
23580
23621
  var CAPTURE_VERSION_PREFIX = "capture/";
23581
23622
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -24022,7 +24063,7 @@ var Rule = external_exports.strictObject({
24022
24063
  postValidators: external_exports.array(PostValidatorRef).optional(),
24023
24064
  requiresNearby: RequiresNearby.optional(),
24024
24065
  examples: external_exports.array(external_exports.string()).optional(),
24025
- // Whether the matched text is itself sensitive. Absent means 'value'.
24066
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24026
24067
  evidence: RuleEvidence.optional()
24027
24068
  }).meta({ id: "Rule" });
24028
24069
  var Author = external_exports.object({
@@ -24114,7 +24155,13 @@ var DetectionRule = external_exports.object({
24114
24155
  // Representative matching strings the rule author shipped with the rule. The
24115
24156
  // cheapest honest answer to "show me what this rule catches" — every bundled
24116
24157
  // rule has them, and they are already in the stored snapshot.
24117
- examples: external_exports.array(external_exports.string()).optional()
24158
+ examples: external_exports.array(external_exports.string()).optional(),
24159
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
24160
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
24161
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
24162
+ // in a value category (secret/pii/financial/phi) is always 'value',
24163
+ // whatever it declares.
24164
+ evidence: RuleEvidence.optional()
24118
24165
  }).meta({ id: "DetectionRule" });
24119
24166
  var DetectionUpdate = external_exports.object({
24120
24167
  available: external_exports.boolean(),
@@ -24182,8 +24229,10 @@ var ImportDetectionRequest = external_exports.object({
24182
24229
  }).meta({ id: "ImportDetectionRequest" });
24183
24230
 
24184
24231
  // ../../packages/schema/src/zod/detection-build.ts
24185
- function optional2(key, parsed2, raw) {
24186
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
24232
+ function optional2(key, raw, parse4) {
24233
+ if (raw === void 0) return {};
24234
+ const parsed2 = parse4(raw);
24235
+ if (!parsed2.success || parsed2.data === void 0) return {};
24187
24236
  return { [key]: parsed2.data };
24188
24237
  }
24189
24238
  function isStringArray(value) {
@@ -24218,10 +24267,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24218
24267
  category: r.category,
24219
24268
  severity: r.severity,
24220
24269
  matcher: parsed2.data,
24221
- // The rest of what decides whether this rule fires. Carried so a consumer
24222
- // re-running the rule (a preview, a tester) evaluates what the engine
24223
- // evaluates rather than a matcher stripped of its guards — half the
24224
- // bundled catalog carries at least one of these.
24270
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
24271
+ // decides whether this rule fires. Carried so a consumer re-running the
24272
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
24273
+ // than a matcher stripped of its guards — half the bundled catalog
24274
+ // carries at least one of these. `examples` and `evidence` describe the
24275
+ // rule and never gate a match.
24225
24276
  //
24226
24277
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24227
24278
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24231,18 +24282,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24231
24282
  // test should stay exactly what it was, namely a renderable matcher. A
24232
24283
  // field that fails validation is omitted, which reads as "not set" and is
24233
24284
  // the same thing the consumer saw before this change.
24234
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
24285
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24235
24286
  ...optional2(
24236
24287
  "postValidators",
24237
- PostValidatorRef.array().safeParse(r.postValidators),
24238
- r.postValidators
24288
+ r.postValidators,
24289
+ (v) => PostValidatorRef.array().safeParse(v)
24239
24290
  ),
24240
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
24291
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24241
24292
  ...optional2(
24242
24293
  "examples",
24243
- { success: isStringArray(r.examples), data: r.examples },
24244
- r.examples
24245
- )
24294
+ r.examples,
24295
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
24296
+ ),
24297
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24246
24298
  }
24247
24299
  ];
24248
24300
  });
@@ -24935,11 +24987,14 @@ var PolicyBundle = external_exports.object({
24935
24987
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24936
24988
  // Model ids (the raw `model` string a harness reports, e.g.
24937
24989
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24938
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24939
- // one (UserPromptSubmit). Optional so an older backend — and an older
24940
- // on-disk cache — still parses; consumers read `?? []`, which is the
24941
- // unenforced behaviour that predates this field and the safe direction to
24942
- // default.
24990
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24991
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24992
+ // wherever the organization governs the event: everywhere on a
24993
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24994
+ // one (the plugin runtime's `governanceApplies`).
24995
+ // Optional so an older backend — and an older on-disk cache — still
24996
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24997
+ // predates this field and the safe direction to default.
24943
24998
  //
24944
24999
  // Ids, not display names: the governance decision is keyed on the exact
24945
25000
  // string the harness reports (`model_status_override.versionId` in the
@@ -25398,6 +25453,8 @@ var AttachmentScopeEntry = external_exports.object({
25398
25453
  });
25399
25454
  var AttachmentScope = external_exports.object({
25400
25455
  endpoint: external_exports.string().min(1),
25456
+ tenantName: PluginWhoami.shape.tenantName.optional(),
25457
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25401
25458
  entries: external_exports.array(AttachmentScopeEntry)
25402
25459
  });
25403
25460
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25410,7 +25467,13 @@ function parseAttachmentScope(raw) {
25410
25467
  const entry = AttachmentScopeEntry.safeParse(candidate);
25411
25468
  if (entry.success) entries.push(entry.data);
25412
25469
  }
25413
- return { endpoint: envelope.data.endpoint, entries };
25470
+ const { endpoint, tenantName, userEmail } = envelope.data;
25471
+ return {
25472
+ endpoint,
25473
+ ...tenantName === void 0 ? {} : { tenantName },
25474
+ ...userEmail === void 0 ? {} : { userEmail },
25475
+ entries
25476
+ };
25414
25477
  } catch {
25415
25478
  return void 0;
25416
25479
  }
@@ -25775,6 +25838,27 @@ var ManagedSettings = external_exports.object({
25775
25838
  };
25776
25839
  }).meta({ id: "ManagedSettings" });
25777
25840
 
25841
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
25842
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
25843
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
25844
+ var ModPolicySnapshot = external_exports.object({
25845
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
25846
+ generatedAt: external_exports.iso.datetime(),
25847
+ // The complete effective ruleset, as the hook's runtime scans with it: the
25848
+ // user's enabled installed packs (user-modified and custom packs included).
25849
+ // Absent means the store holds no authoritative snapshot, and the reader
25850
+ // scans with the packs it ships — the hook's own fallback.
25851
+ rules: external_exports.array(Rule).optional(),
25852
+ // Rule-targeted actions (first enabled policy per rule wins).
25853
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25854
+ // The resolved action per detection category.
25855
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25856
+ // Rules with an active exception grant. Honouring a grant means matching a
25857
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25858
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25859
+ exceptionRuleIds: external_exports.array(external_exports.string())
25860
+ }).meta({ id: "ModPolicySnapshot" });
25861
+
25778
25862
  // ../../packages/schema/src/zod/project-files.ts
25779
25863
  var ProjectFileInput = external_exports.object({
25780
25864
  path: external_exports.string().min(1),
@@ -26095,7 +26179,16 @@ var AttachInput = external_exports.object({
26095
26179
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26096
26180
  // renders a longer one usefully.
26097
26181
  label: printable(200).optional(),
26098
- accessKey: external_exports.string()
26182
+ accessKey: external_exports.string(),
26183
+ // How much of this machine the attachment is for: everything, or only the
26184
+ // repositories its user enrolls. Optional, so an input without it still
26185
+ // parses; what an absent mode means is for whatever reads it to decide, not
26186
+ // this shape. This member validates the VALUE rather than leaving that to the
26187
+ // call site, a deliberate exception to this module's shape-only rule: a shape
26188
+ // rejection names the field, so a value that is not a mode is refused as a bad
26189
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
26190
+ // it as the mode to attach in.
26191
+ mode: AttachmentMode.optional()
26099
26192
  });
26100
26193
 
26101
26194
  // ../../packages/schema/src/zod/triage.ts
@@ -26381,6 +26474,18 @@ function fromCaptureStatusAttributes(bag) {
26381
26474
  return parsedStatus.success ? parsedStatus.data : null;
26382
26475
  }
26383
26476
 
26477
+ // ../../packages/persistence/src/attached-derived.ts
26478
+ import { rmSync } from "fs";
26479
+ import { join } from "path";
26480
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
26481
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
26482
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
26483
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
26484
+
26485
+ // ../../packages/persistence/src/control-plane-credential.ts
26486
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
26487
+ import { join as join2 } from "path";
26488
+
26384
26489
  // ../../packages/persistence/src/paths.ts
26385
26490
  import {
26386
26491
  chmodSync,
@@ -26527,6 +26632,14 @@ function repairOrRefuseMode(file2) {
26527
26632
  }
26528
26633
  return "ok";
26529
26634
  }
26635
+ function asReadableCredential(value) {
26636
+ const result = AttachedCredentialAny.safeParse(value);
26637
+ if (!result.success) return null;
26638
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
26639
+ return null;
26640
+ }
26641
+ return result.data;
26642
+ }
26530
26643
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26531
26644
  const file2 = controlPlaneCredentialPath(settingsDir2);
26532
26645
  let raw;
@@ -26545,20 +26658,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26545
26658
  } catch {
26546
26659
  return { usable: false, reason: "malformed" };
26547
26660
  }
26548
- const result = AttachedCredential.safeParse(parsed2);
26549
- if (!result.success) return { usable: false, reason: "malformed" };
26550
- if (!isSafeEndpoint(result.data.endpoint)) {
26661
+ const credential = asReadableCredential(parsed2);
26662
+ if (credential === null) return { usable: false, reason: "malformed" };
26663
+ if (!isSafeEndpoint(credential.endpoint)) {
26551
26664
  return { usable: false, reason: "unsafe-endpoint" };
26552
26665
  }
26553
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
26666
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26554
26667
  return {
26555
26668
  usable: false,
26556
26669
  reason: "endpoint-mismatch",
26557
- credentialEndpoint: result.data.endpoint,
26670
+ credentialEndpoint: credential.endpoint,
26558
26671
  settingsEndpoint: connection.endpoint
26559
26672
  };
26560
26673
  }
26561
- return { usable: true, credential: result.data };
26674
+ return { usable: true, credential };
26562
26675
  }
26563
26676
  function readControlPlaneCredential(settingsDir2, connection) {
26564
26677
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26567,7 +26680,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26567
26680
 
26568
26681
  // ../../packages/persistence/src/database.ts
26569
26682
  import { randomUUID as randomUUID11 } from "crypto";
26570
- import { dirname as dirname2, join as join7, sep } from "path";
26683
+ import { dirname as dirname2, join as join8, sep } from "path";
26571
26684
  import { DatabaseSync } from "node:sqlite";
26572
26685
 
26573
26686
  // ../../packages/persistence/src/ids.ts
@@ -26621,6 +26734,7 @@ function uuidFromDigest(digest) {
26621
26734
  function captureWireId(sessionId, contentHash, filePath = null) {
26622
26735
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26623
26736
  }
26737
+ var DOT = ".".charCodeAt(0);
26624
26738
 
26625
26739
  // ../../packages/persistence/src/internal/snapshot.ts
26626
26740
  import { randomUUID } from "crypto";
@@ -26948,6 +27062,25 @@ function scopeKeysParam(scopeKeys) {
26948
27062
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26949
27063
  FROM audit_events AS session_root
26950
27064
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
27065
+ var COUNTED_IN_SCOPE = `
27066
+ AND ${inScope("scope_key")}
27067
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
27068
+ var DRAIN_TOTALS = `SELECT
27069
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27070
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27071
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27072
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27073
+ THEN 1 ELSE 0 END) AS skipped,
27074
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27075
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27076
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27077
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27078
+ FROM audit_events
27079
+ WHERE event_type IN (${TYPE_LIST})`;
27080
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
27081
+ FROM audit_events
27082
+ WHERE synced_at = ${String(SKIPPED)}
27083
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26951
27084
  var ROW_COLUMNS = `id,
26952
27085
  parent_id AS parentId,
26953
27086
  root_session_id AS rootSessionId,
@@ -27023,7 +27156,7 @@ var SqliteHistorySyncRepository = class {
27023
27156
  );
27024
27157
  this.scopedCaptureRowsStmt = db.prepare(
27025
27158
  `SELECT ${ROW_COLUMNS}
27026
- FROM audit_events
27159
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27027
27160
  WHERE synced_at IS NULL
27028
27161
  AND sync_claimed_at IS NULL
27029
27162
  AND outbox_owed = 1
@@ -27076,40 +27209,28 @@ var SqliteHistorySyncRepository = class {
27076
27209
  );
27077
27210
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27078
27211
  FROM audit_events${COUNTED_SCOPE}`);
27212
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27213
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27079
27214
  this.partitionByKindStmt = db.prepare(
27080
27215
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27081
27216
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27082
27217
  GROUP BY event_type`
27083
27218
  );
27084
- this.countsStmt = db.prepare(
27085
- `SELECT
27086
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27087
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27088
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27089
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27090
- THEN 1 ELSE 0 END) AS skipped,
27091
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27092
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27093
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27094
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27095
- FROM audit_events
27096
- WHERE event_type IN (${TYPE_LIST})`
27097
- );
27098
- this.captureSkipCountStmt = db.prepare(
27099
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27100
- // way the structural totals are. The split exists because a refusal is
27101
- // terminal only against the deployment that gave it, and the structural
27102
- // re-arm frees it on a change of deployment. The capture lane has no such
27103
- // escape: re-arming a capture would offer one deployment's undelivered
27104
- // prompts, with their text, to a deployment that never saw them, which is
27105
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27106
- // reasons mean the same thing — this row will not be sent — and splitting
27107
- // them would put refused captures in a bucket nothing reads and nothing
27108
- // frees.
27109
- `SELECT COUNT(*) AS skipped
27110
- FROM audit_events
27111
- WHERE synced_at = ${String(SKIPPED)}
27112
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27219
+ this.scopedPartitionByKindStmt = db.prepare(
27220
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
27221
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
27222
+ GROUP BY event_type`
27223
+ );
27224
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
27225
+ this.scopedCountsStmt = db.prepare(
27226
+ `${DRAIN_TOTALS}
27227
+ AND ${inScope("scope_key")}
27228
+ AND ${inScope(ROOT_SCOPE_KEY)}`
27229
+ );
27230
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
27231
+ this.scopedCaptureSkipCountStmt = db.prepare(
27232
+ `${CAPTURE_SKIPS}
27233
+ AND ${inScope("scope_key")}`
27113
27234
  );
27114
27235
  this.fingerprintStmt = db.prepare(
27115
27236
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27223,6 +27344,10 @@ var SqliteHistorySyncRepository = class {
27223
27344
  scopedCaptureRowsStmt;
27224
27345
  scopedCaptureBacklogOwedStmt;
27225
27346
  markScopeCapturesOwedStmt;
27347
+ scopedPartitionStmt;
27348
+ scopedPartitionByKindStmt;
27349
+ scopedCountsStmt;
27350
+ scopedCaptureSkipCountStmt;
27226
27351
  /**
27227
27352
  * The masked detections recorded against one tool call.
27228
27353
  *
@@ -27444,7 +27569,29 @@ var SqliteHistorySyncRepository = class {
27444
27569
  * in" — and a machine that has never attached has no boundary to pass, so
27445
27570
  * requiring one would force a caller to invent one and report the whole store
27446
27571
  * as queued.
27572
+ *
27573
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
27574
+ * the rows that pass the drain's reachability rule for that scope
27575
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
27576
+ * drain never offers), so a personal repository's rows are in none of them.
27577
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
27578
+ * nothing.
27447
27579
  */
27580
+ partition(scopeKeys) {
27581
+ const row = getRow(
27582
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
27583
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27584
+ );
27585
+ return {
27586
+ queued: row?.queued ?? 0,
27587
+ inProgress: row?.inProgress ?? 0,
27588
+ synced: row?.synced ?? 0,
27589
+ failed: row?.failed ?? 0,
27590
+ refused: row?.refused ?? 0,
27591
+ detached: row?.detached ?? 0,
27592
+ total: row?.total ?? 0
27593
+ };
27594
+ }
27448
27595
  /**
27449
27596
  * The same partition, one row per kind that a lane carries.
27450
27597
  *
@@ -27454,11 +27601,14 @@ var SqliteHistorySyncRepository = class {
27454
27601
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27455
27602
  * rows", never as "zero sent"; the two look identical in a bar and mean
27456
27603
  * different things.
27604
+ *
27605
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
27606
+ * still sum to the scoped aggregate. An empty list returns no rows.
27457
27607
  */
27458
- partitionByKind() {
27608
+ partitionByKind(scopeKeys) {
27459
27609
  return allRows(
27460
- this.partitionByKindStmt,
27461
- {}
27610
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
27611
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27462
27612
  ).map((row) => ({
27463
27613
  kind: row.kind,
27464
27614
  queued: row.queued ?? 0,
@@ -27470,22 +27620,25 @@ var SqliteHistorySyncRepository = class {
27470
27620
  total: row.total ?? 0
27471
27621
  }));
27472
27622
  }
27473
- partition() {
27474
- const row = getRow(this.partitionStmt, {});
27475
- return {
27476
- queued: row?.queued ?? 0,
27477
- inProgress: row?.inProgress ?? 0,
27478
- synced: row?.synced ?? 0,
27479
- failed: row?.failed ?? 0,
27480
- refused: row?.refused ?? 0,
27481
- detached: row?.detached ?? 0,
27482
- total: row?.total ?? 0
27483
- };
27484
- }
27485
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27486
- counts(before) {
27487
- const row = getRow(this.countsStmt, { before });
27488
- const captures = getRow(this.captureSkipCountStmt);
27623
+ /**
27624
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
27625
+ * and skipped are totals.
27626
+ *
27627
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
27628
+ * `capturesSkipped` included: a structural row is counted only when its own
27629
+ * key and its session root's key are among them, a capture when its own key
27630
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
27631
+ * under the same keys and boundary. Omitted, this runs the machine
27632
+ * statements, unchanged; an empty list counts nothing.
27633
+ */
27634
+ counts(before, scopeKeys) {
27635
+ const row = getRow(
27636
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
27637
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
27638
+ );
27639
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
27640
+ scopeKeys: scopeKeysParam(scopeKeys)
27641
+ });
27489
27642
  return {
27490
27643
  pending: row?.pending ?? 0,
27491
27644
  sent: row?.sent ?? 0,
@@ -27737,6 +27890,7 @@ function applyMigrations(db, file2, options = {}) {
27737
27890
  }
27738
27891
  ensureSyncedAtColumn(db, "audit_events");
27739
27892
  ensureScopeKeyColumn(db);
27893
+ ensureScopeOwedIndex(db);
27740
27894
  ensureScanLedgerTable(db);
27741
27895
  ensureHistorySyncTable(db);
27742
27896
  ensureBlockedDetectionsTable(db);
@@ -28177,14 +28331,48 @@ function ensureScopeKeyColumn(db) {
28177
28331
  function hasScopeKeyColumn(db) {
28178
28332
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28179
28333
  }
28334
+ var SCOPE_OWED_INDEX_DDL = "CREATE INDEX IF NOT EXISTS idx_audit_scope_owed ON audit_events (scope_key, event_type, started_at) WHERE outbox_owed = 1 AND synced_at IS NULL";
28335
+ function ensureScopeOwedIndex(db) {
28336
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
28337
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
28338
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
28339
+ if (!complete) return;
28340
+ db.exec(SCOPE_OWED_INDEX_DDL);
28341
+ }
28180
28342
  function ensureScanLedgerTable(db) {
28181
28343
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28182
28344
  path TEXT PRIMARY KEY,
28183
28345
  mtime TEXT NOT NULL,
28184
28346
  content_hash TEXT NOT NULL,
28185
28347
  ruleset_hash TEXT NOT NULL,
28186
- scanned_at INTEGER NOT NULL
28348
+ scanned_at INTEGER NOT NULL,
28349
+ scope_key TEXT,
28350
+ scope_root TEXT
28187
28351
  )`);
28352
+ ensureScanLedgerScopeKeyColumn(db);
28353
+ ensureScanLedgerScopeRootColumn(db);
28354
+ }
28355
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
28356
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
28357
+ function ensureScanLedgerScopeKeyColumn(db) {
28358
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
28359
+ }
28360
+ function ensureScanLedgerScopeRootColumn(db) {
28361
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
28362
+ }
28363
+ function ensureScanLedgerColumn(db, column, ddl) {
28364
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
28365
+ if (hasScanLedgerColumn(db, column)) return;
28366
+ withTransaction(
28367
+ db,
28368
+ () => {
28369
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
28370
+ },
28371
+ "IMMEDIATE"
28372
+ );
28373
+ }
28374
+ function hasScanLedgerColumn(db, column) {
28375
+ return columnNames(db, "scan_ledger").includes(column);
28188
28376
  }
28189
28377
  function ensureHistorySyncTable(db) {
28190
28378
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28235,6 +28423,106 @@ function ensureRuleProbeCacheTable(db) {
28235
28423
  )`);
28236
28424
  }
28237
28425
 
28426
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
28427
+ import { createHash as createHash2 } from "crypto";
28428
+ import { readFileSync as readFileSync2 } from "fs";
28429
+ import { join as join4 } from "path";
28430
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
28431
+ function modPolicySnapshotPath(dataDir2) {
28432
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
28433
+ }
28434
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
28435
+ const byRule = /* @__PURE__ */ new Map();
28436
+ const byCategory = /* @__PURE__ */ new Map();
28437
+ for (const policy of input2.policies) {
28438
+ if (!policy.enabled) continue;
28439
+ if ("ruleId" in policy.target) {
28440
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
28441
+ } else if (!byCategory.has(policy.target.category)) {
28442
+ byCategory.set(policy.target.category, policy.action);
28443
+ }
28444
+ }
28445
+ const categoryActions = {};
28446
+ for (const category of DetectionCategory.options) {
28447
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
28448
+ }
28449
+ return {
28450
+ version: MOD_POLICY_SNAPSHOT_VERSION,
28451
+ generatedAt: generatedAt.toISOString(),
28452
+ // `examples` is documentation the mod never reads, and a custom pack's are
28453
+ // whatever its author pasted in, so they stay behind.
28454
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
28455
+ ruleActions: Object.fromEntries(byRule),
28456
+ categoryActions,
28457
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
28458
+ };
28459
+ }
28460
+ function assignedRuleActionPolicies(installed) {
28461
+ const out = [];
28462
+ for (const [ruleId, action] of installed.ruleActions) {
28463
+ if (installed.assignedRules.has(ruleId))
28464
+ out.push({ target: { ruleId }, action, enabled: true });
28465
+ }
28466
+ return out;
28467
+ }
28468
+ function withoutExamples(rule) {
28469
+ const copy = { ...rule };
28470
+ delete copy.examples;
28471
+ return copy;
28472
+ }
28473
+ function sameContent(a, b) {
28474
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
28475
+ }
28476
+ function readModPolicySnapshot(dataDir2) {
28477
+ try {
28478
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
28479
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
28480
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
28481
+ return parsed2.success ? parsed2.data : null;
28482
+ } catch {
28483
+ return null;
28484
+ }
28485
+ }
28486
+ function writeModPolicySnapshot(dataDir2, snapshot) {
28487
+ const text = JSON.stringify(snapshot);
28488
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
28489
+ const existing = readModPolicySnapshot(dataDir2);
28490
+ if (existing !== null && sameContent(existing, snapshot)) return false;
28491
+ ensureDataDirSync(dataDir2);
28492
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
28493
+ return true;
28494
+ }
28495
+ function regexProbeKey(matcher) {
28496
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
28497
+ }
28498
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28499
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
28500
+ return rules.filter((rule) => {
28501
+ if (rule.matcher.type !== "regex") return true;
28502
+ const key = regexProbeKey(rule.matcher);
28503
+ const verdict = sources.probeVerdict(key);
28504
+ if (verdict === "quarantined") return false;
28505
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
28506
+ });
28507
+ }
28508
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28509
+ const policies = sources.readPolicies();
28510
+ const snapshot = sources.installedRuleset();
28511
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
28512
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
28513
+ return {
28514
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
28515
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
28516
+ exceptionRuleIds: sources.activeExceptionRuleIds()
28517
+ };
28518
+ }
28519
+ function refreshModPolicySnapshot(dataDir2, sources) {
28520
+ try {
28521
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
28522
+ } catch {
28523
+ }
28524
+ }
28525
+
28238
28526
  // ../../packages/persistence/src/internal/json.ts
28239
28527
  function safeJson(s, fallback) {
28240
28528
  if (s == null) return fallback;
@@ -28409,6 +28697,11 @@ var TIMELINE_COLUMNS = `
28409
28697
  json_extract(attributes, '$.targetId') AS target_id,
28410
28698
  json_extract(attributes, '$.internal') AS internal,
28411
28699
  json_extract(attributes, '$.flagged') AS flagged`;
28700
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
28701
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
28702
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
28703
+ " + "
28704
+ );
28412
28705
  var LLM_USAGE_SELECT = `
28413
28706
  SELECT root_session_id AS sessionId,
28414
28707
  provider,
@@ -28420,9 +28713,10 @@ var LLM_USAGE_SELECT = `
28420
28713
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28421
28714
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28422
28715
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28423
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
28716
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
28717
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28424
28718
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28425
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
28719
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28426
28720
  function usageLeaves(rows) {
28427
28721
  return rows.map((row) => {
28428
28722
  const attributes = {
@@ -28437,7 +28731,7 @@ function usageLeaves(rows) {
28437
28731
  if (row.provider !== null) attributes.provider = row.provider;
28438
28732
  if (row.model !== null) attributes.model = row.model;
28439
28733
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28440
- return { sessionId: row.sessionId, attributes };
28734
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28441
28735
  });
28442
28736
  }
28443
28737
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29771,9 +30065,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29771
30065
  AND conditions IS NULL
29772
30066
  AND ${ACTIVE_PREDICATE}`;
29773
30067
  var SqliteExceptionsRepository = class {
29774
- constructor(db, now = () => Date.now()) {
30068
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29775
30069
  this.db = db;
29776
30070
  this.now = now;
30071
+ this.onChange = onChange;
29777
30072
  this.consumeStmt = db.prepare(
29778
30073
  `UPDATE exceptions
29779
30074
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29792,6 +30087,7 @@ var SqliteExceptionsRepository = class {
29792
30087
  }
29793
30088
  db;
29794
30089
  now;
30090
+ onChange;
29795
30091
  consumeStmt;
29796
30092
  insertBlockedStmt;
29797
30093
  sweepBlockedStmt;
@@ -29807,7 +30103,9 @@ var SqliteExceptionsRepository = class {
29807
30103
  */
29808
30104
  create(input2) {
29809
30105
  try {
29810
- return Promise.resolve(this.createSync(input2));
30106
+ const created = this.createSync(input2);
30107
+ this.onChange();
30108
+ return Promise.resolve(created);
29811
30109
  } catch (err) {
29812
30110
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29813
30111
  }
@@ -29938,6 +30236,7 @@ var SqliteExceptionsRepository = class {
29938
30236
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29939
30237
  WHERE id = :id AND revoked_at IS NULL`
29940
30238
  ).run({ id, revokedBy, reason: reason ?? null, now });
30239
+ if (Number(result.changes) === 1) this.onChange();
29941
30240
  return Promise.resolve(Number(result.changes) === 1);
29942
30241
  }
29943
30242
  /**
@@ -29950,6 +30249,15 @@ var SqliteExceptionsRepository = class {
29950
30249
  const result = this.consumeStmt.run({ id, now });
29951
30250
  return Promise.resolve(Number(result.changes) === 1);
29952
30251
  }
30252
+ /** The rule ids with at least one active grant, under any key version. */
30253
+ activeRuleIds(now = this.now()) {
30254
+ return allRows(
30255
+ this.db.prepare(
30256
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
30257
+ ),
30258
+ { now }
30259
+ ).map((row) => row.ruleId);
30260
+ }
29953
30261
  /**
29954
30262
  * The evaluation subset of every active grant under one fingerprint key
29955
30263
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31073,28 +31381,28 @@ var SqliteInspectionFindingsRepository = class {
31073
31381
  };
31074
31382
 
31075
31383
  // ../../packages/persistence/src/repositories/installed-packs.ts
31076
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
31384
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31077
31385
 
31078
31386
  // ../../packages/persistence/src/policy-floor.ts
31079
- import { readFileSync as readFileSync5 } from "fs";
31080
- import { join as join6 } from "path";
31387
+ import { readFileSync as readFileSync6 } from "fs";
31388
+ import { join as join7 } from "path";
31081
31389
 
31082
31390
  // ../../packages/persistence/src/local-layout.ts
31083
31391
  import { renameSync as renameSync3 } from "fs";
31084
31392
  import { mkdir } from "fs/promises";
31085
31393
  import { homedir } from "os";
31086
- import { join as join4 } from "path";
31394
+ import { join as join5 } from "path";
31087
31395
  function defaultDataDir() {
31088
- return join4(homedir(), ".aka");
31396
+ return join5(homedir(), ".aka");
31089
31397
  }
31090
31398
  function settingsDir(base = defaultDataDir()) {
31091
- return join4(base, "settings");
31399
+ return join5(base, "settings");
31092
31400
  }
31093
31401
  function dataDir(base = defaultDataDir()) {
31094
- return join4(base, "data");
31402
+ return join5(base, "data");
31095
31403
  }
31096
31404
  function dbPath(base = defaultDataDir()) {
31097
- return join4(dataDir(base), "aka.db");
31405
+ return join5(dataDir(base), "aka.db");
31098
31406
  }
31099
31407
  async function ensureDataDir(dir = defaultDataDir()) {
31100
31408
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31111,8 +31419,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31111
31419
  for (const { name, dest } of moves) {
31112
31420
  try {
31113
31421
  ensureDataDirSync(dest);
31114
- const moved = join4(dest, name);
31115
- renameSync3(join4(base, name), moved);
31422
+ const moved = join5(dest, name);
31423
+ renameSync3(join5(base, name), moved);
31116
31424
  tightenFile(moved);
31117
31425
  } catch {
31118
31426
  }
@@ -31120,8 +31428,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31120
31428
  }
31121
31429
 
31122
31430
  // ../../packages/persistence/src/settings.ts
31123
- import { readFileSync as readFileSync4 } from "fs";
31124
- import { join as join5 } from "path";
31431
+ import { readFileSync as readFileSync5 } from "fs";
31432
+ import { join as join6 } from "path";
31125
31433
 
31126
31434
  // ../../packages/persistence/src/file-lock.ts
31127
31435
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31129,7 +31437,7 @@ import {
31129
31437
  closeSync,
31130
31438
  existsSync as existsSync2,
31131
31439
  openSync,
31132
- readFileSync as readFileSync2,
31440
+ readFileSync as readFileSync3,
31133
31441
  rmSync as rmSync5,
31134
31442
  statSync as statSync3,
31135
31443
  writeFileSync as writeFileSync2
@@ -31138,16 +31446,16 @@ import { hostname as hostname3 } from "os";
31138
31446
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31139
31447
 
31140
31448
  // ../../packages/persistence/src/managed-settings.ts
31141
- import { readFileSync as readFileSync3 } from "fs";
31449
+ import { readFileSync as readFileSync4 } from "fs";
31142
31450
  import { posix, win32 } from "path";
31143
- function managedSettingsPaths(platform2 = process.platform) {
31144
- if (platform2 === "darwin") {
31451
+ function managedSettingsPaths(platform = process.platform) {
31452
+ if (platform === "darwin") {
31145
31453
  return [
31146
31454
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31147
31455
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31148
31456
  ];
31149
31457
  }
31150
- if (platform2 === "win32") {
31458
+ if (platform === "win32") {
31151
31459
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31152
31460
  }
31153
31461
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -31157,7 +31465,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31157
31465
  for (const path of paths) {
31158
31466
  let text;
31159
31467
  try {
31160
- text = readFileSync3(path, "utf8");
31468
+ text = readFileSync4(path, "utf8");
31161
31469
  } catch {
31162
31470
  continue;
31163
31471
  }
@@ -31211,7 +31519,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31211
31519
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31212
31520
  }
31213
31521
  function readUserSettings(base) {
31214
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
31522
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31215
31523
  if (!record2) return defaultWorkspaceSettings();
31216
31524
  try {
31217
31525
  return WorkspaceSettings.parse(record2);
@@ -31222,7 +31530,7 @@ function readUserSettings(base) {
31222
31530
  function readJson(file2) {
31223
31531
  let text;
31224
31532
  try {
31225
- text = readFileSync4(file2, "utf8");
31533
+ text = readFileSync5(file2, "utf8");
31226
31534
  } catch {
31227
31535
  return null;
31228
31536
  }
@@ -31262,7 +31570,7 @@ var PolicyFloorError = class extends Error {
31262
31570
  };
31263
31571
  function readCachedPolicyBundle(base = defaultDataDir()) {
31264
31572
  try {
31265
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31573
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31266
31574
  const parsed2 = JSON.parse(raw);
31267
31575
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31268
31576
  return PolicyBundle.parse(parsed2.bundle);
@@ -31386,7 +31694,7 @@ function inventorySignature(packs2) {
31386
31694
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31387
31695
  }
31388
31696
  function hashRules(rulesJson) {
31389
- return createHash2("sha256").update(rulesJson).digest("hex");
31697
+ return createHash3("sha256").update(rulesJson).digest("hex");
31390
31698
  }
31391
31699
  function parseVersion(v) {
31392
31700
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31428,9 +31736,10 @@ var SqliteInstalledPacksRepository = class {
31428
31736
  * from `openLocalDatabase`, which is the single construction site that owns a
31429
31737
  * real `~/.aka`.
31430
31738
  */
31431
- constructor(db, baseDir) {
31739
+ constructor(db, baseDir, onChange = () => void 0) {
31432
31740
  this.db = db;
31433
31741
  this.baseDir = baseDir;
31742
+ this.onChange = onChange;
31434
31743
  this.insertMissingStmt = db.prepare(
31435
31744
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31436
31745
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31459,6 +31768,7 @@ var SqliteInstalledPacksRepository = class {
31459
31768
  }
31460
31769
  db;
31461
31770
  baseDir;
31771
+ onChange;
31462
31772
  insertMissingStmt;
31463
31773
  upsertAvailableStmt;
31464
31774
  signatureStmt;
@@ -31531,6 +31841,7 @@ var SqliteInstalledPacksRepository = class {
31531
31841
  },
31532
31842
  "IMMEDIATE"
31533
31843
  );
31844
+ this.onChange();
31534
31845
  } catch {
31535
31846
  }
31536
31847
  }
@@ -31605,6 +31916,7 @@ var SqliteInstalledPacksRepository = class {
31605
31916
  },
31606
31917
  "IMMEDIATE"
31607
31918
  );
31919
+ if (changed) this.onChange();
31608
31920
  return changed;
31609
31921
  }
31610
31922
  /**
@@ -31846,6 +32158,7 @@ var SqliteInstalledPacksRepository = class {
31846
32158
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31847
32159
  WHERE namespace = :namespace AND pack_id = :packId`
31848
32160
  ).run({ policyId, now: Date.now(), namespace, packId });
32161
+ if (Number(res.changes) > 0) this.onChange();
31849
32162
  return Number(res.changes) > 0;
31850
32163
  }
31851
32164
  /**
@@ -31870,6 +32183,7 @@ var SqliteInstalledPacksRepository = class {
31870
32183
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31871
32184
  WHERE namespace = :namespace AND pack_id = :packId`
31872
32185
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
32186
+ if (Number(res.changes) > 0) this.onChange();
31873
32187
  return Number(res.changes) > 0;
31874
32188
  }
31875
32189
  // Fingerprint of the recorded available mirror — compared against the
@@ -32767,13 +33081,19 @@ var SqliteInventoryAssetsRepository = class {
32767
33081
  import { randomUUID as randomUUID6 } from "crypto";
32768
33082
  var SEED_BATCH_WINDOW_MS = 6e4;
32769
33083
  var SqlitePoliciesRepository = class {
32770
- constructor(db) {
33084
+ constructor(db, onChange = () => void 0) {
32771
33085
  this.db = db;
33086
+ this.onChange = onChange;
32772
33087
  }
32773
33088
  db;
33089
+ onChange;
32774
33090
  readPolicies() {
33091
+ return Promise.resolve(this.listPolicies());
33092
+ }
33093
+ /** The synchronous read behind {@link readPolicies}. */
33094
+ listPolicies() {
32775
33095
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32776
- const policies = mapRowsTolerant(rows, (row) => {
33096
+ return mapRowsTolerant(rows, (row) => {
32777
33097
  const target = JSON.parse(row.target);
32778
33098
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32779
33099
  return Policy.parse({
@@ -32785,7 +33105,6 @@ var SqlitePoliciesRepository = class {
32785
33105
  customKeywords
32786
33106
  });
32787
33107
  });
32788
- return Promise.resolve(policies);
32789
33108
  }
32790
33109
  // Seed one policy per bundled category at Monitor so the detection-type config
32791
33110
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32796,7 +33115,7 @@ var SqlitePoliciesRepository = class {
32796
33115
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32797
33116
  if (count > 0) {
32798
33117
  this.markEarlierChoices();
32799
- this.monitorUntouchedSeeds();
33118
+ if (this.monitorUntouchedSeeds()) this.onChange();
32800
33119
  return;
32801
33120
  }
32802
33121
  const stmt = this.db.prepare(
@@ -32813,6 +33132,7 @@ var SqlitePoliciesRepository = class {
32813
33132
  });
32814
33133
  }
32815
33134
  });
33135
+ this.onChange();
32816
33136
  }
32817
33137
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32818
33138
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32878,7 +33198,7 @@ var SqlitePoliciesRepository = class {
32878
33198
  ).filter(
32879
33199
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32880
33200
  );
32881
- if (untouched.length === 0) return;
33201
+ if (untouched.length === 0) return false;
32882
33202
  const stmt = this.db.prepare(
32883
33203
  `UPDATE policies SET action = 'log'
32884
33204
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32889,6 +33209,7 @@ var SqlitePoliciesRepository = class {
32889
33209
  stmt.run({ category: row.category, seeded: row.action });
32890
33210
  }
32891
33211
  });
33212
+ return true;
32892
33213
  }
32893
33214
  // Insert-or-update the single global per-category policy row, keyed on the
32894
33215
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32905,6 +33226,7 @@ var SqlitePoliciesRepository = class {
32905
33226
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32906
33227
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32907
33228
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
33229
+ this.onChange();
32908
33230
  }
32909
33231
  // Caps every global per-category policy currently set to block/redact down
32910
33232
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32915,6 +33237,7 @@ var SqlitePoliciesRepository = class {
32915
33237
  WHERE scope='global' AND action IN ('block','redact')
32916
33238
  AND json_extract(target,'$.category') IS NOT NULL`
32917
33239
  ).run({ now: Date.now() });
33240
+ if (Number(info.changes) > 0) this.onChange();
32918
33241
  return Number(info.changes);
32919
33242
  }
32920
33243
  // Whether the category's row was ever written after it was created — by the
@@ -33234,31 +33557,45 @@ var SqliteScanLedgerRepository = class {
33234
33557
  constructor(db) {
33235
33558
  this.db = db;
33236
33559
  this.upsertStmt = db.prepare(
33237
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33238
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
33560
+ `INSERT INTO scan_ledger
33561
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
33562
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33239
33563
  ON CONFLICT (path) DO UPDATE SET
33240
33564
  mtime = excluded.mtime,
33241
33565
  content_hash = excluded.content_hash,
33242
33566
  ruleset_hash = excluded.ruleset_hash,
33567
+ scope_key = excluded.scope_key,
33568
+ scope_root = excluded.scope_root,
33243
33569
  scanned_at = excluded.scanned_at`
33244
33570
  );
33245
33571
  this.readStmt = db.prepare(
33246
- `SELECT path, mtime, content_hash AS contentHash
33572
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
33573
+ scope_root AS scopeRoot
33247
33574
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33248
33575
  );
33249
33576
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
33577
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33250
33578
  }
33251
33579
  db;
33252
33580
  upsertStmt;
33253
33581
  readStmt;
33254
33582
  pathsStmt;
33583
+ pathKeysStmt;
33255
33584
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33256
33585
  // older ruleset are simply absent, which reads as "never scanned".
33257
33586
  entriesForRuleset(rulesetHash) {
33258
- const rows = allRows(this.readStmt, {
33259
- rulesetHash
33260
- });
33261
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
33587
+ const rows = allRows(this.readStmt, { rulesetHash });
33588
+ return new Map(
33589
+ rows.map((r) => [
33590
+ r.path,
33591
+ {
33592
+ mtime: r.mtime,
33593
+ contentHash: r.contentHash,
33594
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
33595
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
33596
+ }
33597
+ ])
33598
+ );
33262
33599
  }
33263
33600
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33264
33601
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33267,6 +33604,14 @@ var SqliteScanLedgerRepository = class {
33267
33604
  allPaths() {
33268
33605
  return allRows(this.pathsStmt).map((r) => r.path);
33269
33606
  }
33607
+ // Every ledgered path with the repository it was in when it was last read,
33608
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
33609
+ // which repository a vanished file belonged to. `undefined` for a row with no
33610
+ // key, which is every row written before the column existed.
33611
+ pathKeys() {
33612
+ const rows = allRows(this.pathKeysStmt);
33613
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
33614
+ }
33270
33615
  upsertEntries(entries) {
33271
33616
  if (entries.length === 0) return;
33272
33617
  const scannedAt = Date.now();
@@ -33277,6 +33622,8 @@ var SqliteScanLedgerRepository = class {
33277
33622
  mtime: entry.mtime,
33278
33623
  contentHash: entry.contentHash,
33279
33624
  rulesetHash: entry.rulesetHash,
33625
+ scopeKey: entry.scopeKey ?? null,
33626
+ scopeRoot: entry.scopeRoot ?? null,
33280
33627
  scannedAt
33281
33628
  });
33282
33629
  }
@@ -34364,6 +34711,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34364
34711
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34365
34712
  };
34366
34713
  }
34714
+ function withoutTrailingSlashes(path) {
34715
+ let end = path.length;
34716
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
34717
+ return path.slice(0, end);
34718
+ }
34367
34719
  function toEndpointSummary(row) {
34368
34720
  return {
34369
34721
  id: row.id,
@@ -34651,7 +35003,7 @@ var SqliteSharesRepository = class {
34651
35003
  */
34652
35004
  reconcileCallSites(projectKey, reconcile) {
34653
35005
  if (reconcile.mode === "walk") {
34654
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
35006
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34655
35007
  this.db.prepare(
34656
35008
  `DELETE FROM share_call_site
34657
35009
  WHERE project_key = :key
@@ -35219,7 +35571,7 @@ function backupLegacyStore(db, file2) {
35219
35571
  discardStore(file2, backup);
35220
35572
  return backup;
35221
35573
  }
35222
- function openAndInitialize(file2, base, skipTags) {
35574
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35223
35575
  let db = openWithPragmas(file2);
35224
35576
  try {
35225
35577
  if (isForeignSqliteLineage(db)) {
@@ -35231,8 +35583,15 @@ function openAndInitialize(file2, base, skipTags) {
35231
35583
  }
35232
35584
  applyMigrations(db, file2, { skipTags });
35233
35585
  tightenPerms(file2);
35234
- const policies = new SqlitePoliciesRepository(db);
35235
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
35586
+ const modPolicy = {};
35587
+ const onPolicyStateChange = () => {
35588
+ if (modPolicy.current !== void 0)
35589
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
35590
+ };
35591
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
35592
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
35593
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
35594
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35236
35595
  const repositories = {
35237
35596
  events: new SqliteEventsRepository(db),
35238
35597
  findings: new SqliteFindingsRepository(db),
@@ -35241,9 +35600,9 @@ function openAndInitialize(file2, base, skipTags) {
35241
35600
  scanLedger: new SqliteScanLedgerRepository(db),
35242
35601
  historySync: new SqliteHistorySyncRepository(db),
35243
35602
  secretVault: new SqliteSecretVaultRepository(db),
35244
- exceptions: new SqliteExceptionsRepository(db),
35603
+ exceptions,
35245
35604
  resolutions: new SqliteResolutionsRepository(db),
35246
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
35605
+ ruleProbeCache,
35247
35606
  bodyRetention: new SqliteBodyRetentionRepository(db),
35248
35607
  security: new SqliteSecurityRepository(db),
35249
35608
  detections: new SqliteDetectionsRepository(db),
@@ -35261,6 +35620,13 @@ function openAndInitialize(file2, base, skipTags) {
35261
35620
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35262
35621
  configInventory: new SqliteConfigInventoryRepository(db)
35263
35622
  };
35623
+ modPolicy.current = {
35624
+ installedRuleset: () => installedPacks.installedRuleset(),
35625
+ readPolicies: () => policies.listPolicies(),
35626
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
35627
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
35628
+ bundledRegexMatchers: () => shippedRegexMatchers2
35629
+ };
35264
35630
  policies.seedDefaults();
35265
35631
  return { db, ...repositories };
35266
35632
  } catch (err) {
@@ -35272,7 +35638,7 @@ function openAndInitialize(file2, base, skipTags) {
35272
35638
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35273
35639
  function openLocalDatabase(dir, options = {}) {
35274
35640
  ensureDataDirSync(dir);
35275
- const file2 = join7(dir, DB_FILENAME);
35641
+ const file2 = join8(dir, DB_FILENAME);
35276
35642
  reapStalePartials(file2);
35277
35643
  const {
35278
35644
  db,
@@ -35308,7 +35674,8 @@ function openLocalDatabase(dir, options = {}) {
35308
35674
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35309
35675
  // settings/ and data/, and the pack-policy floor needs both halves.
35310
35676
  dirname2(dir),
35311
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
35677
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
35678
+ options.shippedRegexMatchers ?? []
35312
35679
  );
35313
35680
  function captureRowId(event) {
35314
35681
  return captureId(
@@ -35573,7 +35940,7 @@ function openLocalDatabase(dir, options = {}) {
35573
35940
  }
35574
35941
 
35575
35942
  // ../../packages/persistence/src/egress-wire.ts
35576
- import { createHash as createHash3 } from "crypto";
35943
+ import { createHash as createHash4 } from "crypto";
35577
35944
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35578
35945
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35579
35946
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35605,7 +35972,7 @@ function canonicalGitUrl(url2) {
35605
35972
  }
35606
35973
  function hashProjectKey(projectKey) {
35607
35974
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35608
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35975
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35609
35976
  }
35610
35977
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35611
35978
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35670,24 +36037,23 @@ function toEgressIngestRequest(input2) {
35670
36037
  }
35671
36038
 
35672
36039
  // ../../packages/persistence/src/finding-key.ts
35673
- import { createHash as createHash4 } from "crypto";
36040
+ import { createHash as createHash5 } from "crypto";
35674
36041
  function normalizeFilePath(filePath) {
35675
36042
  return filePath.replaceAll("\\", "/");
35676
36043
  }
35677
36044
  function computeFindingKey(input2) {
35678
36045
  const normalizedPath = normalizeFilePath(input2.filePath);
35679
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
36046
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35680
36047
  }
35681
36048
 
35682
36049
  // ../../packages/persistence/src/fingerprint.ts
35683
36050
  import { createHmac, randomBytes } from "crypto";
35684
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35685
- import { join as join8 } from "path";
35686
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
36051
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
36052
+ import { join as join9 } from "path";
35687
36053
  var EXCEPTION_KEY_FILENAME = "exception.key";
35688
36054
  var KEY_MATERIAL_BYTES = 32;
35689
36055
  function keyFilePath(dataDir2) {
35690
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
36056
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35691
36057
  }
35692
36058
  function parseKeyFile(raw) {
35693
36059
  const parsed2 = JSON.parse(raw);
@@ -35714,6 +36080,12 @@ var KEY_VERSION_COLUMNS = {
35714
36080
  };
35715
36081
  var SQLITE_ERROR2 = 1;
35716
36082
  var FLOOR_BUSY_TIMEOUT_MS = 250;
36083
+ function openReadOnly(file2) {
36084
+ const host = process;
36085
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
36086
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
36087
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
36088
+ }
35717
36089
  var FloorUnreadableError = class extends Error {
35718
36090
  code = "floor-unreadable";
35719
36091
  constructor(cause) {
@@ -35725,11 +36097,11 @@ var FloorUnreadableError = class extends Error {
35725
36097
  }
35726
36098
  };
35727
36099
  function storedKeyVersionFloor(dataDir2) {
35728
- const file2 = join8(dataDir2, DB_FILENAME);
36100
+ const file2 = join9(dataDir2, DB_FILENAME);
35729
36101
  if (!existsSync3(file2)) return 0;
35730
36102
  let db;
35731
36103
  try {
35732
- db = new DatabaseSync2(file2, { readOnly: true });
36104
+ db = openReadOnly(file2);
35733
36105
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35734
36106
  let floor = 0;
35735
36107
  for (const [table2, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35780,7 +36152,7 @@ function occupantMessage(file2, kind) {
35780
36152
  function readFingerprintKey(dataDir2) {
35781
36153
  let raw;
35782
36154
  try {
35783
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
36155
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35784
36156
  } catch (err) {
35785
36157
  if (err.code === "ENOENT") return null;
35786
36158
  throw err instanceof Error ? err : new Error(String(err));
@@ -35806,8 +36178,8 @@ function exactFingerprintValue(key, raw) {
35806
36178
  }
35807
36179
 
35808
36180
  // ../../packages/persistence/src/forward-health.ts
35809
- import { readFileSync as readFileSync7 } from "fs";
35810
- import { join as join9 } from "path";
36181
+ import { readFileSync as readFileSync8 } from "fs";
36182
+ import { join as join10 } from "path";
35811
36183
  var BREAKER_COOLDOWN_MS = 3e4;
35812
36184
  function parseForwardHealth(raw, nowMs) {
35813
36185
  try {
@@ -35831,20 +36203,21 @@ function isForwardPaused(health, nowMs) {
35831
36203
 
35832
36204
  // ../../packages/persistence/src/history-backfill.ts
35833
36205
  import { existsSync as existsSync4 } from "fs";
35834
- import { join as join10 } from "path";
36206
+ import { join as join11 } from "path";
35835
36207
 
35836
36208
  // ../../packages/persistence/src/history-preview.ts
35837
36209
  import { existsSync as existsSync5 } from "fs";
35838
- import { join as join11 } from "path";
35839
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36210
+ import { join as join12 } from "path";
36211
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35840
36212
 
35841
36213
  // ../../packages/persistence/src/history-sync-state.ts
35842
- import { readFileSync as readFileSync8 } from "fs";
35843
- import { join as join12 } from "path";
36214
+ import { readFileSync as readFileSync9 } from "fs";
36215
+ import { join as join13 } from "path";
36216
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35844
36217
 
35845
36218
  // ../../packages/persistence/src/store-symlinks.ts
35846
36219
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35847
- import { dirname as dirname3, join as join13, resolve } from "path";
36220
+ import { dirname as dirname3, join as join14, resolve } from "path";
35848
36221
 
35849
36222
  // ../../packages/persistence/src/vault/crypto.ts
35850
36223
  import {
@@ -35858,19 +36231,19 @@ import {
35858
36231
  // ../../packages/persistence/src/vault/key-provider.ts
35859
36232
  import { execFileSync } from "child_process";
35860
36233
  import { randomBytes as randomBytes2 } from "crypto";
35861
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35862
- import { join as join14 } from "path";
36234
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
36235
+ import { join as join15 } from "path";
35863
36236
 
35864
36237
  // ../../packages/persistence/src/vault/vault.ts
35865
36238
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35866
36239
 
35867
36240
  // ../../packages/persistence/src/warn-era-cap.ts
35868
36241
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35869
- import { join as join15 } from "path";
36242
+ import { join as join16 } from "path";
35870
36243
  var MARKER = "warn-era-capped";
35871
36244
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35872
36245
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35873
- const marker = join15(dataDir2, MARKER);
36246
+ const marker = join16(dataDir2, MARKER);
35874
36247
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35875
36248
  const capped = db.policies.capCategoryActions();
35876
36249
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35930,7 +36303,7 @@ function resolveProvider() {
35930
36303
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
35931
36304
  try {
35932
36305
  ensureLayoutDirSync(base);
35933
- const settingsFile = join16(settingsDir(base), "settings.json");
36306
+ const settingsFile = join17(settingsDir(base), "settings.json");
35934
36307
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
35935
36308
  } catch {
35936
36309
  }
@@ -35953,11 +36326,6 @@ function resolveProviderSafe(resolveProviderFn) {
35953
36326
  }
35954
36327
  }
35955
36328
 
35956
- // ../../packages/plugin-sdk/src/config-inventory.ts
35957
- import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
35958
- import { homedir as homedir2 } from "os";
35959
- import { basename as basename3, join as join18 } from "path";
35960
-
35961
36329
  // ../../packages/detections/src/egress/registry.ts
35962
36330
  var EXTRACTOR_VERSION = "3";
35963
36331
  var PROVIDER_REGISTRY = [
@@ -37062,11 +37430,11 @@ var EXACT_KIND_BY_BASENAME = {
37062
37430
  "composer.json": "composer.json",
37063
37431
  "packages.config": "packages.config"
37064
37432
  };
37065
- function manifestKindOf(basename8) {
37066
- if (LOCKFILE_BASENAMES.has(basename8)) return null;
37067
- const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename8) ? EXACT_KIND_BY_BASENAME[basename8] : void 0;
37433
+ function manifestKindOf(basename6) {
37434
+ if (LOCKFILE_BASENAMES.has(basename6)) return null;
37435
+ const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename6) ? EXACT_KIND_BY_BASENAME[basename6] : void 0;
37068
37436
  if (exact !== void 0) return exact;
37069
- if (basename8.endsWith(".csproj")) return "csproj";
37437
+ if (basename6.endsWith(".csproj")) return "csproj";
37070
37438
  return null;
37071
37439
  }
37072
37440
  function extractManifestSdks(text, kind) {
@@ -37694,12 +38062,12 @@ var RegexMatcher2 = class {
37694
38062
  rule.matcher,
37695
38063
  () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
37696
38064
  );
37697
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
38065
+ const scanText = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
37698
38066
  const spans = [];
37699
38067
  let m;
37700
- const maxIterations = scanText2.length + 1;
38068
+ const maxIterations = scanText.length + 1;
37701
38069
  let iterations = 0;
37702
- while ((m = re.exec(scanText2)) !== null) {
38070
+ while ((m = re.exec(scanText)) !== null) {
37703
38071
  if (++iterations > maxIterations) break;
37704
38072
  const group = captureGroup != null ? m[captureGroup] : m[0];
37705
38073
  if (m[0].length === 0) re.lastIndex++;
@@ -38041,17 +38409,18 @@ function ruleEvidence(rule) {
38041
38409
 
38042
38410
  // ../../packages/detections/src/mask.ts
38043
38411
  function maskMatch(raw) {
38044
- if (raw.length <= 5) return "***";
38045
- const atIndex = raw.indexOf("@");
38046
- if (atIndex > 0 && atIndex < raw.length - 1) {
38047
- const domain2 = raw.slice(atIndex + 1);
38412
+ const visible = stripInvisiblePadding(raw);
38413
+ if (visible.length <= 5) return "***";
38414
+ const atIndex = visible.indexOf("@");
38415
+ if (atIndex > 0 && atIndex < visible.length - 1) {
38416
+ const domain2 = visible.slice(atIndex + 1);
38048
38417
  if (domain2.includes(".")) {
38049
- const local = raw.slice(0, atIndex);
38418
+ const local = visible.slice(0, atIndex);
38050
38419
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
38051
38420
  return `${maskedLocal}@${domain2}`;
38052
38421
  }
38053
38422
  }
38054
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
38423
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
38055
38424
  }
38056
38425
 
38057
38426
  // ../../packages/detections/src/pointer-shield.ts
@@ -38313,7 +38682,12 @@ var MIN_RAW_LEN = 4;
38313
38682
  var RAW_RUN_LEN = 8;
38314
38683
  function carriesRawRun(text, rawValues) {
38315
38684
  let windows = null;
38316
- for (const raw of new Set(rawValues)) {
38685
+ const values = /* @__PURE__ */ new Set();
38686
+ for (const raw of rawValues) {
38687
+ values.add(raw);
38688
+ values.add(stripInvisiblePadding(raw));
38689
+ }
38690
+ for (const raw of values) {
38317
38691
  if (raw.length < MIN_RAW_LEN) continue;
38318
38692
  if (raw.length < RAW_RUN_LEN) {
38319
38693
  if (text.includes(raw)) return true;
@@ -38337,11 +38711,16 @@ function carriesRawRun(text, rawValues) {
38337
38711
  return false;
38338
38712
  }
38339
38713
  function safeMaskedMatch(rawMatch) {
38340
- const masked = maskMatch(rawMatch);
38341
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
38342
- return "***";
38714
+ const visible = stripInvisiblePadding(rawMatch);
38715
+ const masked = maskMatch(visible);
38716
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
38717
+ if (!reveals(masked)) return masked;
38718
+ const atIndex = masked.indexOf("@");
38719
+ if (atIndex > 0 && atIndex < masked.length - 1) {
38720
+ const emailFallback = `*${masked.slice(atIndex)}`;
38721
+ if (!reveals(emailFallback)) return emailFallback;
38343
38722
  }
38344
- return masked;
38723
+ return "***";
38345
38724
  }
38346
38725
  function assertRawFree(text, rawValues) {
38347
38726
  if (carriesRawRun(text, rawValues)) {
@@ -40783,6 +41162,11 @@ function bundledDetections() {
40783
41162
  }));
40784
41163
  return cachedDetections;
40785
41164
  }
41165
+ function shippedRegexMatchers() {
41166
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
41167
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
41168
+ );
41169
+ }
40786
41170
 
40787
41171
  // ../../packages/plugin-sdk/src/mask.ts
40788
41172
  var packsReady = false;
@@ -40804,8 +41188,8 @@ function bundledMaskingRules() {
40804
41188
  }
40805
41189
 
40806
41190
  // ../../packages/plugin-sdk/src/repo.ts
40807
- import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
40808
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
41191
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
41192
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
40809
41193
  function resolveRepoIdentity(cwd) {
40810
41194
  try {
40811
41195
  const location = locateRepo(cwd);
@@ -40824,8 +41208,9 @@ function resolveRepoIdentity(cwd) {
40824
41208
  var ATTRIBUTION_MEMO_LIMIT = 64;
40825
41209
  var attributionMemo = /* @__PURE__ */ new Map();
40826
41210
  var NO_ATTRIBUTION = Object.freeze({});
40827
- function resolveRepoAttribution(cwd) {
41211
+ function resolveRepoAttribution(cwd, options) {
40828
41212
  try {
41213
+ if (options?.cache === false) return attributeRepo(cwd);
40829
41214
  const remembered = attributionMemo.get(cwd);
40830
41215
  if (remembered !== void 0) return remembered;
40831
41216
  const attribution = attributeRepo(cwd);
@@ -40856,36 +41241,36 @@ function resolveWorktreeRoot(cwd) {
40856
41241
  function findGitRoot(start) {
40857
41242
  let dir = start;
40858
41243
  for (; ; ) {
40859
- if (existsSync9(join17(dir, ".git"))) return dir;
41244
+ if (existsSync9(join18(dir, ".git"))) return dir;
40860
41245
  const parent = dirname4(dir);
40861
41246
  if (parent === dir) return void 0;
40862
41247
  dir = parent;
40863
41248
  }
40864
41249
  }
40865
41250
  function resolveGitContext(root) {
40866
- const dotGit = join17(root, ".git");
41251
+ const dotGit = join18(root, ".git");
40867
41252
  try {
40868
41253
  if (statSync6(dotGit).isDirectory()) {
40869
- return { configPath: join17(dotGit, "config"), headRoot: root };
41254
+ return { configPath: join18(dotGit, "config"), headRoot: root };
40870
41255
  }
40871
41256
  } catch {
40872
41257
  return void 0;
40873
41258
  }
40874
41259
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
40875
41260
  if (!target) return void 0;
40876
- const gitdir = isAbsolute(target) ? target : join17(root, target);
40877
- if (existsSync9(join17(gitdir, "config"))) {
40878
- return { configPath: join17(gitdir, "config"), headRoot: root };
41261
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
41262
+ if (existsSync9(join18(gitdir, "config"))) {
41263
+ return { configPath: join18(gitdir, "config"), headRoot: root };
40879
41264
  }
40880
- const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
41265
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
40881
41266
  if (!commonRaw) return void 0;
40882
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
41267
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
40883
41268
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
40884
- return { configPath: join17(commonGitDir, "config"), headRoot };
41269
+ return { configPath: join18(commonGitDir, "config"), headRoot };
40885
41270
  }
40886
41271
  function safeRead(path) {
40887
41272
  try {
40888
- return readFileSync10(path, "utf8");
41273
+ return readFileSync11(path, "utf8");
40889
41274
  } catch {
40890
41275
  return void 0;
40891
41276
  }
@@ -40932,9 +41317,9 @@ function slugFromUrl(url2) {
40932
41317
  }
40933
41318
 
40934
41319
  // ../../packages/plugin-sdk/src/events.ts
40935
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
41320
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
40936
41321
  function contentHashOf(text) {
40937
- return createHash5("sha256").update(text).digest("hex");
41322
+ return createHash6("sha256").update(text).digest("hex");
40938
41323
  }
40939
41324
  function buildIngestEvent(input2) {
40940
41325
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -41447,62 +41832,13 @@ function createGuardedScanner(partition, gateway, opts) {
41447
41832
  };
41448
41833
  }
41449
41834
 
41450
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
41451
- import { readFileSync as readFileSync12 } from "fs";
41452
- import { join as join19 } from "path";
41453
-
41454
- // ../../packages/plugin-sdk/src/host-floor.ts
41455
- import { readFileSync as readFileSync14 } from "fs";
41456
- import { join as join21 } from "path";
41457
-
41458
- // ../../packages/plugin-sdk/src/model-governance.ts
41459
- import {
41460
- closeSync as closeSync2,
41461
- fstatSync,
41462
- mkdirSync as mkdirSync2,
41463
- openSync as openSync2,
41464
- readFileSync as readFileSync13,
41465
- readSync,
41466
- writeFileSync as writeFileSync5
41467
- } from "fs";
41468
- import { join as join20 } from "path";
41469
- var TAIL_BYTES = 256 * 1024;
41470
-
41471
- // ../../packages/plugin-sdk/src/host-floor.ts
41472
- var HOST_FEATURE = {
41473
- ModelSwitch: "model-switch",
41474
- VaultPointerDisplay: "vault-pointer-display"
41475
- };
41476
- var HOST_FLOORS = {
41477
- [HOST_FEATURE.ModelSwitch]: {
41478
- label: "model-switch protection",
41479
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
41480
- since: "2.1.251"
41481
- },
41482
- [HOST_FEATURE.VaultPointerDisplay]: {
41483
- label: "vault pointer display",
41484
- hookEvents: ["MessageDisplay"],
41485
- since: "2.1.152"
41486
- }
41487
- };
41488
- var ANTIGRAVITY_HOST_FEATURE = {
41489
- EndOfTurnCapture: "end-of-turn-capture"
41490
- };
41491
- var ANTIGRAVITY_HOST_FLOORS = {
41492
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
41493
- label: "end-of-turn history capture",
41494
- hookEvents: ["Stop"],
41495
- since: "1.1.10"
41496
- }
41497
- };
41498
-
41499
41835
  // ../../packages/plugin-sdk/src/ignore-layers.ts
41500
41836
  var import_ignore = __toESM(require_ignore(), 1);
41501
- import { readFileSync as readFileSync15 } from "fs";
41502
- import { join as join22 } from "path";
41837
+ import { readFileSync as readFileSync12 } from "fs";
41838
+ import { join as join19 } from "path";
41503
41839
  function readIgnoreLayer(dir, filename, anchorLen) {
41504
41840
  try {
41505
- return { matcher: (0, import_ignore.default)().add(readFileSync15(join22(dir, filename), "utf8")), anchorLen };
41841
+ return { matcher: (0, import_ignore.default)().add(readFileSync12(join19(dir, filename), "utf8")), anchorLen };
41506
41842
  } catch {
41507
41843
  return void 0;
41508
41844
  }
@@ -41529,16 +41865,9 @@ function withLayer(layers, layer) {
41529
41865
  return layer ? [...layers, layer] : layers;
41530
41866
  }
41531
41867
 
41532
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
41533
- import { arch, hostname as hostname4, platform, release } from "os";
41534
-
41535
- // ../../packages/plugin-sdk/src/nudge.ts
41536
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
41537
- import { join as join23 } from "path";
41538
-
41539
41868
  // ../../packages/plugin-sdk/src/paths.ts
41540
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
41541
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
41869
+ import { readdirSync as readdirSync2, realpathSync as realpathSync2 } from "fs";
41870
+ import { basename as basename3, dirname as dirname5, sep as sep3 } from "path";
41542
41871
  function toPosix(path) {
41543
41872
  return path.split(sep3).join("/");
41544
41873
  }
@@ -41556,7 +41885,7 @@ function findProjectRoot(startDir, recognizeMarker) {
41556
41885
  }
41557
41886
  function directoryHasMarker(dir, recognizeMarker) {
41558
41887
  try {
41559
- for (const entry of readdirSync3(dir, { withFileTypes: true })) {
41888
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
41560
41889
  if (entry.isFile() && recognizeMarker(entry.name) != null) return true;
41561
41890
  }
41562
41891
  } catch {
@@ -41566,8 +41895,8 @@ function directoryHasMarker(dir, recognizeMarker) {
41566
41895
  }
41567
41896
  function resolveNonGitProject(startDir, recognizeMarker) {
41568
41897
  const projectRoot = findProjectRoot(startDir, recognizeMarker);
41569
- const realRoot = realpathSync3(projectRoot);
41570
- return { root: projectRoot, projectKey: `path:${realRoot}`, project: basename4(realRoot) };
41898
+ const realRoot = realpathSync2(projectRoot);
41899
+ return { root: projectRoot, projectKey: `path:${realRoot}`, project: basename3(realRoot) };
41571
41900
  }
41572
41901
 
41573
41902
  // ../../packages/plugin-sdk/src/policy-resolver.ts
@@ -41614,36 +41943,6 @@ function assignedRulePolicies(installed) {
41614
41943
  return out;
41615
41944
  }
41616
41945
 
41617
- // ../../packages/plugin-sdk/src/project-files.ts
41618
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
41619
- import { basename as basename5, join as join24 } from "path";
41620
-
41621
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
41622
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
41623
- if (typeof v === "string" && v.trim() === "") return void 0;
41624
- return v;
41625
- }, external_exports.string().optional()).catch(void 0);
41626
- var optionalFlag = external_exports.preprocess((v) => {
41627
- if (typeof v !== "string") return false;
41628
- const normalized = v.trim().toLowerCase();
41629
- return normalized !== "" && normalized !== "0" && normalized !== "false";
41630
- }, external_exports.boolean()).catch(false);
41631
- var antigravityProviderEnvShape = {
41632
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
41633
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
41634
- };
41635
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
41636
-
41637
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
41638
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
41639
- if (typeof v === "string" && v.trim() === "") return void 0;
41640
- return v;
41641
- }, external_exports.string().optional()).catch(void 0);
41642
- var codexProviderEnvShape = {
41643
- OPENAI_BASE_URL: optionalBaseUrl3
41644
- };
41645
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
41646
-
41647
41946
  // ../../packages/plugin-sdk/src/runtime.ts
41648
41947
  import { randomUUID as randomUUID15 } from "crypto";
41649
41948
  var ENFORCEMENT_CEILING_ENABLED = false;
@@ -41930,12 +42229,11 @@ function createPluginRuntime(gateway, settings, opts) {
41930
42229
  async function processText(text, context, opts2 = {}) {
41931
42230
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
41932
42231
  }
41933
- async function capture(input2, opts2 = {}) {
42232
+ async function evaluateCapture(input2, opts2) {
41934
42233
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
41935
- const filePath = input2.metadata?.filePath;
41936
42234
  const { decision, excepted, exceptionIds } = await evaluate(
41937
42235
  input2.text,
41938
- { filePath, eventKind: input2.kind },
42236
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
41939
42237
  {
41940
42238
  sourceTool: input2.sourceTool,
41941
42239
  metadata: input2.metadata,
@@ -41943,7 +42241,11 @@ function createPluginRuntime(gateway, settings, opts) {
41943
42241
  },
41944
42242
  opts2.rewritable
41945
42243
  );
41946
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
42244
+ return { decision, excepted, exceptionIds, timingStartedAt };
42245
+ }
42246
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
42247
+ const filePath = input2.metadata?.filePath;
42248
+ if (opts2.persist === "with-findings" && decision.findings.length === 0) return;
41947
42249
  try {
41948
42250
  const contentHash = contentHashOf(input2.text);
41949
42251
  const maskedFindings = decision.findings.filter(
@@ -41986,6 +42288,8 @@ function createPluginRuntime(gateway, settings, opts) {
41986
42288
  // exceptions/blocked_detections when a key is available;
41987
42289
  // falls back to the masked match so at-rest findings still get
41988
42290
  // a stable (if weaker) identity on a workspace with no dataDir.
42291
+ // Both ignore the same invisible padding, so a clean and a
42292
+ // padded occurrence of one secret key alike on either path.
41989
42293
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
41990
42294
  }) : void 0;
41991
42295
  return {
@@ -42013,7 +42317,37 @@ function createPluginRuntime(gateway, settings, opts) {
42013
42317
  }
42014
42318
  } catch {
42015
42319
  }
42016
- return decision;
42320
+ }
42321
+ async function enforcedIn(text, context) {
42322
+ try {
42323
+ await ensureInitialized();
42324
+ if (!scanner) return [];
42325
+ const shielded = shieldPointers(text);
42326
+ const matched = await scanner.scan(shielded.text, context);
42327
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
42328
+ const action = resolveAction(finding.ruleId, finding.category);
42329
+ return action === "block" || action === "redact";
42330
+ });
42331
+ } catch {
42332
+ return [];
42333
+ }
42334
+ }
42335
+ async function capture(input2, opts2 = {}) {
42336
+ const evaluated = await evaluateCapture(input2, opts2);
42337
+ await persistCapture(input2, opts2, evaluated);
42338
+ return evaluated.decision;
42339
+ }
42340
+ async function captureDeferred(input2, opts2 = {}) {
42341
+ const evaluated = await evaluateCapture(input2, opts2);
42342
+ let recorded = false;
42343
+ return {
42344
+ result: evaluated.decision,
42345
+ record: async () => {
42346
+ if (recorded) return;
42347
+ recorded = true;
42348
+ await persistCapture(input2, opts2, evaluated);
42349
+ }
42350
+ };
42017
42351
  }
42018
42352
  async function rulesetFingerprint() {
42019
42353
  try {
@@ -42034,23 +42368,20 @@ function createPluginRuntime(gateway, settings, opts) {
42034
42368
  }
42035
42369
  await gateway.close();
42036
42370
  }
42037
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
42371
+ return {
42372
+ processText,
42373
+ capture,
42374
+ captureDeferred,
42375
+ enforcedIn,
42376
+ rulesetFingerprint,
42377
+ scanIsolationDegraded,
42378
+ close
42379
+ };
42038
42380
  }
42039
42381
 
42040
- // ../../packages/plugin-sdk/src/scope-key.ts
42041
- import { existsSync as existsSync12 } from "fs";
42042
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join25, normalize } from "path";
42043
-
42044
- // ../../packages/plugin-sdk/src/suppressions.ts
42045
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
42046
-
42047
- // ../../packages/plugin-sdk/src/throttle.ts
42048
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
42049
- import { join as join26 } from "path";
42050
-
42051
42382
  // ../../packages/scanner/src/discover.ts
42052
- import { readdirSync as readdirSync5 } from "fs";
42053
- import { join as join27 } from "path";
42383
+ import { readdirSync as readdirSync3 } from "fs";
42384
+ import { join as join20 } from "path";
42054
42385
 
42055
42386
  // ../../packages/scanner/src/constants.ts
42056
42387
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -42079,7 +42410,7 @@ function discoverGitRepos(opts) {
42079
42410
  if (depth > maxDepth || excludePaths.has(dir)) return;
42080
42411
  let entries;
42081
42412
  try {
42082
- entries = readdirSync5(dir, { withFileTypes: true, encoding: "utf8" });
42413
+ entries = readdirSync3(dir, { withFileTypes: true, encoding: "utf8" });
42083
42414
  } catch {
42084
42415
  return;
42085
42416
  }
@@ -42095,7 +42426,7 @@ function discoverGitRepos(opts) {
42095
42426
  if (!entry.isDirectory()) continue;
42096
42427
  if (DISCOVER_SKIP.has(entry.name)) continue;
42097
42428
  if (entry.name.startsWith(".")) continue;
42098
- visit2(join27(dir, entry.name), depth + 1);
42429
+ visit2(join20(dir, entry.name), depth + 1);
42099
42430
  }
42100
42431
  }
42101
42432
  for (const root of searchRoots) {
@@ -42105,7 +42436,7 @@ function discoverGitRepos(opts) {
42105
42436
  }
42106
42437
 
42107
42438
  // ../../packages/scanner/src/render.ts
42108
- import { basename as basename6, relative } from "path";
42439
+ import { basename as basename4, relative } from "path";
42109
42440
  var SEVERITY_ORDER = ["critical", "high", "medium", "low"];
42110
42441
  var SEVERITY_GLYPH = {
42111
42442
  critical: "\u2588",
@@ -42185,7 +42516,7 @@ function renderMultiRepoSummary(summary, opts = {}) {
42185
42516
  "\n"
42186
42517
  );
42187
42518
  }
42188
- const repoRows = summary.repos.filter((r) => r.summary.scanned > 0 || r.summary.findings > 0).map((r) => [basename6(r.rootDir), String(r.summary.scanned), String(r.summary.findings)]);
42519
+ const repoRows = summary.repos.filter((r) => r.summary.scanned > 0 || r.summary.findings > 0).map((r) => [basename4(r.rootDir), String(r.summary.scanned), String(r.summary.findings)]);
42189
42520
  const repoSection = repoRows.length > 0 ? ["", indent(table(["REPO", "SCANNED", "FINDINGS"], repoRows))].join("\n") : "";
42190
42521
  return [
42191
42522
  "\u2713 Multi-repo scan complete",
@@ -42198,8 +42529,8 @@ function renderMultiRepoSummary(summary, opts = {}) {
42198
42529
  }
42199
42530
 
42200
42531
  // ../../packages/scanner/src/scan.ts
42201
- import { existsSync as existsSync14, readFileSync as readFileSync22 } from "fs";
42202
- import { extname as extname2, isAbsolute as isAbsolute3, relative as relative3 } from "path";
42532
+ import { existsSync as existsSync12, readFileSync as readFileSync18 } from "fs";
42533
+ import { extname as extname2, isAbsolute as isAbsolute2, relative as relative3 } from "path";
42203
42534
 
42204
42535
  // ../../packages/remote/src/http.ts
42205
42536
  import { request as httpRequest } from "http";
@@ -42577,11 +42908,11 @@ function withTimeout(promise2, ms) {
42577
42908
  }
42578
42909
 
42579
42910
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
42580
- import { readFileSync as readFileSync17 } from "fs";
42581
- import { join as join28 } from "path";
42911
+ import { readFileSync as readFileSync13 } from "fs";
42912
+ import { join as join21 } from "path";
42582
42913
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
42583
42914
  function forwardDropsPath(dataDir2) {
42584
- return join28(dataDir2, FORWARD_DROPS_FILENAME);
42915
+ return join21(dataDir2, FORWARD_DROPS_FILENAME);
42585
42916
  }
42586
42917
  function recordForwardDrops(dataDir2, count, nowMs) {
42587
42918
  if (count <= 0) return;
@@ -42599,7 +42930,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
42599
42930
  }
42600
42931
  function readForwardDrops(dataDir2) {
42601
42932
  try {
42602
- const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
42933
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
42603
42934
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
42604
42935
  const record2 = parsed2;
42605
42936
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -42618,7 +42949,7 @@ function readForwardDrops(dataDir2) {
42618
42949
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
42619
42950
  import { randomUUID as randomUUID16 } from "crypto";
42620
42951
  import { readFile, rename, writeFile } from "fs/promises";
42621
- import { join as join29 } from "path";
42952
+ import { join as join22 } from "path";
42622
42953
  function isInvalidRequest(err) {
42623
42954
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
42624
42955
  }
@@ -42637,7 +42968,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
42637
42968
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
42638
42969
  function createForwardPolicy(deps) {
42639
42970
  const now = deps.now ?? (() => Date.now());
42640
- const file2 = join29(deps.dir, STATE_FILENAME);
42971
+ const file2 = join22(deps.dir, STATE_FILENAME);
42641
42972
  let state = null;
42642
42973
  let loading = null;
42643
42974
  async function readState() {
@@ -42803,6 +43134,9 @@ var AttachedDataGateway = class {
42803
43134
  *
42804
43135
  * Machine mode answers before any key is read, so a machine attachment pays
42805
43136
  * nothing for scoping and forwards exactly what it always has.
43137
+ *
43138
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
43139
+ * forwarding key for key.
42806
43140
  */
42807
43141
  verdictFor(keyOf) {
42808
43142
  try {
@@ -42819,24 +43153,27 @@ var AttachedDataGateway = class {
42819
43153
  * the key its row holds in the local store, recorded per root (see
42820
43154
  * `rootVerdict`), not the key on the root event just handed in: roots are
42821
43155
  * first-write-wins in the store, so when two producers record a root for one
42822
- * session (the session-start hook, then a reconcile pass) the second leaves
42823
- * the stored row as it was, and the history drain decides that row, not this
42824
- * event. Whether this root EVENT is itself sent takes both keys: the stored
42825
- * one AND its own. The event's attributes (cwd, project, repo) describe where
42826
- * it was recorded from, so a root event keyed to a personal directory is never
42827
- * sent under an enrolled stored root, though the enrolled leaves still forward
42828
- * under it: the instance that wrote the stored root is expected to have
42829
- * forwarded it. If it did not (the root was written while standalone or under
42830
- * another attachment, or its forward failed), the plane refuses those leaves
42831
- * and the history drain ships the root first. Any other row with a root
42832
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
42833
- * is in scope AND this instance recorded an in-scope verdict for that root.
42834
- * The audit-event route has real foreign keys on both columns and stubs no
42835
- * missing root, so a leaf sent after its root was kept local is refused
42836
- * there, and a refused forward counts toward the breaker that guards every
42837
- * other one. A root this instance never recorded is therefore `'local'`: the
42838
- * only answer that cannot orphan a row. A row with no root reference at all
42839
- * has nothing to orphan, and is decided by its own key.
43156
+ * session (the session-start hook, then a reconcile pass) the second leaves the
43157
+ * stored row as it was. That stored row, not this event, is what a history
43158
+ * drain pass would decide, if the root started before the attach; the drain
43159
+ * never offers one that started after it (`started_at < backlogBefore`).
43160
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
43161
+ * its own. The event's attributes (cwd, project, repo) describe where it was
43162
+ * recorded from, so a root event keyed to a personal directory is never sent
43163
+ * under an enrolled stored root, though the enrolled leaves still forward under
43164
+ * it: the instance that wrote the stored root is expected to have forwarded it.
43165
+ * If it did not (the root was written while standalone or under another
43166
+ * attachment, or its forward failed), the plane refuses those leaves. A root
43167
+ * that started before the attach is shipped, ahead of its leaves, by the
43168
+ * history drain; one that started after it is never offered by the drain. Any
43169
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
43170
+ * only when its own key is in scope AND this instance recorded an in-scope
43171
+ * verdict for that root. The audit-event route has real foreign keys on both
43172
+ * columns and stubs no missing root, so a leaf sent after its root was kept
43173
+ * local is refused there, and a refused forward counts toward the breaker that
43174
+ * guards every other one. A root this instance never recorded is therefore
43175
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
43176
+ * reference at all has nothing to orphan, and is decided by its own key.
42840
43177
  *
42841
43178
  * What this costs is stated rather than discovered. A session whose stored
42842
43179
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -42907,6 +43244,87 @@ var AttachedDataGateway = class {
42907
43244
  return [];
42908
43245
  }
42909
43246
  }
43247
+ /**
43248
+ * The verdict for the repositories nested in a scanned project, answered
43249
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
43250
+ *
43251
+ * A walk descends into a nested clone or submodule and folds its files into
43252
+ * the project it is walking, so one register can carry several
43253
+ * repositories' call sites under one project key. Each of them must be in
43254
+ * scope for it to forward. One key out of scope, or a nested repository with
43255
+ * no remote (an `undefined` key), keeps the whole register local.
43256
+ *
43257
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
43258
+ * what is nested in it, and every scan passes the list, empty when nothing
43259
+ * is nested. A register nobody vouched for is not one a scoped attachment
43260
+ * may send.
43261
+ *
43262
+ * Machine mode answers before reading the context, so a machine attachment
43263
+ * forwards exactly what it always has.
43264
+ */
43265
+ nestedVerdict(context) {
43266
+ try {
43267
+ if (this.deps.attachment.mode === "machine") return "forward";
43268
+ const keys = context?.nestedScopeKeys;
43269
+ if (keys === void 0) return "local";
43270
+ for (const key of keys) {
43271
+ if (this.verdictFor(() => key) === "local") return "local";
43272
+ }
43273
+ return "forward";
43274
+ } catch {
43275
+ return "local";
43276
+ }
43277
+ }
43278
+ /**
43279
+ * The register a scoped attachment sends, once the project and the repositories
43280
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
43281
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
43282
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
43283
+ *
43284
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
43285
+ * and the ledger holds every file the scanner ever read under the root, nested
43286
+ * clones' included. So a clone that was removed, or one an ignore file now
43287
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
43288
+ * paths come back as deleted. The scan names the repository of each deleted
43289
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
43290
+ * and each is held to the same verdict as any other key. A path whose key is
43291
+ * absent, or out of scope, is not sent.
43292
+ *
43293
+ * The list is asked for here, and only here: it is an async read of the scan
43294
+ * ledger that the scan makes on being called, so a machine attachment, which
43295
+ * returns before this, and a register already kept local never cause it.
43296
+ *
43297
+ * Anything the scan did not vouch for sends no deleted path, and the register
43298
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
43299
+ * list whose length is not the register's. Deleting is the only thing a dropped
43300
+ * path could have done on the server, so the cost of a refusal is a stored row
43301
+ * that stays, never a path that leaves.
43302
+ *
43303
+ * Machine mode returns `input` itself, the same object and unread, so a machine
43304
+ * attachment's request is exactly what it was. A register that lists no deleted
43305
+ * path, or that is not a ledger register, has nothing to cut and is returned
43306
+ * as it came, with the list unread.
43307
+ */
43308
+ async registerForWire(input2, context) {
43309
+ try {
43310
+ if (this.deps.attachment.mode === "machine") return input2;
43311
+ const { reconcile } = input2;
43312
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
43313
+ const deleted = reconcile.deletedFiles;
43314
+ let kept = [];
43315
+ try {
43316
+ const keys = await context?.deletedFileKeys?.();
43317
+ if (keys?.length === deleted.length) {
43318
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
43319
+ }
43320
+ } catch {
43321
+ kept = [];
43322
+ }
43323
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
43324
+ } catch {
43325
+ return void 0;
43326
+ }
43327
+ }
42910
43328
  /**
42911
43329
  * The event `recordCapture` sends for a capture the verdict let through, or
42912
43330
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -43232,12 +43650,24 @@ var AttachedDataGateway = class {
43232
43650
  * payload onto the wire-boundary-safe shape (no snippet, hashed
43233
43651
  * projectKey), and its result is discarded: `forward.run` never throws or
43234
43652
  * rejects, so there is nothing here to act on.
43653
+ *
43654
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
43655
+ * not say: the key of every repository nested below the scan root, whose
43656
+ * files the walk folded into this register. On a scoped attachment the
43657
+ * register is forwarded only when the project's own key AND every one of
43658
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
43659
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
43660
+ * `registerForWire`). Machine mode never reads either, and the local write
43661
+ * never receives the context and gets the register whole.
43235
43662
  */
43236
- async recordProjectEgress(input2) {
43663
+ async recordProjectEgress(input2, context) {
43237
43664
  const summary = await this.deps.local.recordProjectEgress(input2);
43238
43665
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
43666
+ if (this.nestedVerdict(context) === "local") return summary;
43667
+ const register = await this.registerForWire(input2, context);
43668
+ if (register === void 0) return summary;
43239
43669
  await this.deps.forward.run(
43240
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
43670
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
43241
43671
  );
43242
43672
  return summary;
43243
43673
  }
@@ -43291,6 +43721,11 @@ var AttachedDataGateway = class {
43291
43721
  async scanLedgerPaths() {
43292
43722
  return this.deps.local.scanLedgerPaths();
43293
43723
  }
43724
+ // Delegated, like the path list. An inner gateway that cannot say answers an
43725
+ // empty map, which gives every deleted path no key.
43726
+ async scanLedgerPathKeys() {
43727
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
43728
+ }
43294
43729
  async recordScanned(entries) {
43295
43730
  return this.deps.local.recordScanned(entries);
43296
43731
  }
@@ -43357,6 +43792,12 @@ var AttachedDataGateway = class {
43357
43792
  // and the spread above would otherwise drop the field silently — which is
43358
43793
  // exactly what it did, leaving the whole control inert on every device
43359
43794
  // while every test around it stayed green.
43795
+ //
43796
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
43797
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
43798
+ // reads this bundle once to build detection, so the detections it carries
43799
+ // apply to every event on the machine. Where a prohibition applies is
43800
+ // answered per event by `governanceAppliesTo` below.
43360
43801
  prohibitedModels: cached2.prohibitedModels,
43361
43802
  // NAMED for the same reason as the line above, and it is the same defect
43362
43803
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -43416,6 +43857,30 @@ var AttachedDataGateway = class {
43416
43857
  };
43417
43858
  }
43418
43859
  // ---------------------------------------------------------------------
43860
+ // GovernanceScope — where the organization's model policy applies
43861
+ // ---------------------------------------------------------------------
43862
+ /**
43863
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
43864
+ * the question a model-guard site asks once it has decided to refuse.
43865
+ *
43866
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
43867
+ * with the same key would be forwarded. A machine-wide attachment governs
43868
+ * every event, keyless included, exactly as before. A scoped one governs an
43869
+ * event only when its key names an enrolled repository. An event in a
43870
+ * personal repository, in no repository, with an empty key, or met by a fault
43871
+ * is not governed.
43872
+ *
43873
+ * The event's OWN key, never its session root's. The root rule in
43874
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
43875
+ * this decides whether a refusal applies, which is a question about where the
43876
+ * event happened.
43877
+ *
43878
+ * Answered from memory: no store read, no bundle read, nothing sent.
43879
+ */
43880
+ governanceAppliesTo(scopeKey) {
43881
+ return this.verdictFor(() => scopeKey) === "forward";
43882
+ }
43883
+ // ---------------------------------------------------------------------
43419
43884
  // LocalStoreMaintenance — by delegation (D3).
43420
43885
  //
43421
43886
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -43524,8 +43989,8 @@ function toWireInspection(insp) {
43524
43989
  }
43525
43990
 
43526
43991
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
43527
- import { createHash as createHash6 } from "crypto";
43528
- import { hostname as hostname5 } from "os";
43992
+ import { createHash as createHash7 } from "crypto";
43993
+ import { hostname as hostname4 } from "os";
43529
43994
 
43530
43995
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
43531
43996
  var CORRELATION_ID = EventMetadata.shape.correlationId;
@@ -43543,17 +44008,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
43543
44008
 
43544
44009
  // ../../packages/plugin-runtime/src/attached/install-record.ts
43545
44010
  import { readFile as readFile2, stat } from "fs/promises";
43546
- import { basename as basename7, dirname as dirname7, join as join30, resolve as resolve2 } from "path";
44011
+ import { basename as basename5, dirname as dirname6, join as join23, resolve as resolve2 } from "path";
43547
44012
  async function readInstalledVersion(installRoot) {
43548
44013
  try {
43549
44014
  const versionDir = resolve2(installRoot);
43550
- const pluginDir = dirname7(versionDir);
43551
- const marketplaceDir = dirname7(pluginDir);
43552
- const cacheDir = dirname7(marketplaceDir);
43553
- if (basename7(cacheDir) !== "cache") return null;
43554
- const key = `${basename7(pluginDir)}@${basename7(marketplaceDir)}`;
44015
+ const pluginDir = dirname6(versionDir);
44016
+ const marketplaceDir = dirname6(pluginDir);
44017
+ const cacheDir = dirname6(marketplaceDir);
44018
+ if (basename5(cacheDir) !== "cache") return null;
44019
+ const key = `${basename5(pluginDir)}@${basename5(marketplaceDir)}`;
43555
44020
  const record2 = JSON.parse(
43556
- await readFile2(join30(dirname7(cacheDir), "installed_plugins.json"), "utf8")
44021
+ await readFile2(join23(dirname6(cacheDir), "installed_plugins.json"), "utf8")
43557
44022
  );
43558
44023
  const plugins = record2?.plugins;
43559
44024
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -43585,7 +44050,7 @@ async function exists(path) {
43585
44050
  }
43586
44051
 
43587
44052
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
43588
- import { readFileSync as readFileSync18 } from "fs";
44053
+ import { readFileSync as readFileSync14 } from "fs";
43589
44054
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
43590
44055
  function createPluginBlock(build, policyStore) {
43591
44056
  return async () => {
@@ -43615,7 +44080,7 @@ async function readInstalledVersionBounded(installRoot) {
43615
44080
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
43616
44081
  import { randomUUID as randomUUID17 } from "crypto";
43617
44082
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
43618
- import { join as join31 } from "path";
44083
+ import { join as join24 } from "path";
43619
44084
 
43620
44085
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
43621
44086
  import { rename as rename2 } from "fs/promises";
@@ -43644,7 +44109,7 @@ async function publishByRename(tmp, file2, move = rename2) {
43644
44109
 
43645
44110
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
43646
44111
  function createPolicyStore(dir = dataDir()) {
43647
- const file2 = join31(dir, "policy-cache.json");
44112
+ const file2 = join24(dir, "policy-cache.json");
43648
44113
  async function read() {
43649
44114
  try {
43650
44115
  const raw = await readFile3(file2, "utf8");
@@ -43714,8 +44179,8 @@ function createPolicyStore(dir = dataDir()) {
43714
44179
  }
43715
44180
 
43716
44181
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
43717
- import { readFileSync as readFileSync19 } from "fs";
43718
- import { join as join32 } from "path";
44182
+ import { readFileSync as readFileSync15 } from "fs";
44183
+ import { join as join25 } from "path";
43719
44184
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
43720
44185
  var OUTCOME_KEYS = {
43721
44186
  ok: true,
@@ -43729,7 +44194,7 @@ var OUTCOME_KEYS = {
43729
44194
  };
43730
44195
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
43731
44196
  function postureReportStatePath(dataDir2) {
43732
- return join32(dataDir2, POSTURE_REPORT_STATE_FILENAME);
44197
+ return join25(dataDir2, POSTURE_REPORT_STATE_FILENAME);
43733
44198
  }
43734
44199
  function writePostureReportState(dataDir2, state) {
43735
44200
  try {
@@ -43770,10 +44235,19 @@ function createPostureReporter(deps) {
43770
44235
  hostname: deps.hostname(),
43771
44236
  capturedAt: nowMs,
43772
44237
  ...measurement,
43773
- // Omit the key rather than spread an explicit `undefined` —
43774
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
43775
- // factory.ts keys on presence.
43776
- ...plugin === void 0 ? {} : { plugin }
44238
+ // Omit the key rather than spread an explicit `undefined`. The type
44239
+ // admits `undefined` here (the schema's optional member), and
44240
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
44241
+ // in-memory object free of an explicit `undefined` member, which the
44242
+ // tests pin by key presence.
44243
+ ...plugin === void 0 ? {} : { plugin },
44244
+ // LAST, and only for a scoped attachment. A machine attachment omits
44245
+ // the key the same way, so its body is byte for byte the one it sent
44246
+ // before the member existed. Anything but exactly `machine` reports the
44247
+ // constant `scoped`, never the raw value: that is resolveScope's own
44248
+ // fail direction, and a value outside the wire's vocabulary would fail
44249
+ // the whole snapshot at the receiver, the wipe signal with it.
44250
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
43777
44251
  };
43778
44252
  } catch {
43779
44253
  return null;
@@ -43796,8 +44270,8 @@ function createPostureReporter(deps) {
43796
44270
  }
43797
44271
 
43798
44272
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
43799
- import { statSync as statSync9 } from "fs";
43800
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
44273
+ import { statSync as statSync7 } from "fs";
44274
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
43801
44275
 
43802
44276
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
43803
44277
  function emptyActionCounts() {
@@ -43827,7 +44301,7 @@ function emptyReadout(readError = false) {
43827
44301
  }
43828
44302
  function readStorePosture(dbPath2) {
43829
44303
  try {
43830
- statSync9(dbPath2);
44304
+ statSync7(dbPath2);
43831
44305
  } catch (err) {
43832
44306
  const code = err.code;
43833
44307
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -43855,7 +44329,7 @@ function readStorePosture(dbPath2) {
43855
44329
  readError: false
43856
44330
  });
43857
44331
  try {
43858
- db = new DatabaseSync4(dbPath2, { readOnly: true });
44332
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
43859
44333
  db.exec("PRAGMA busy_timeout = 2000");
43860
44334
  version2 = db.prepare("PRAGMA user_version").get().user_version;
43861
44335
  try {
@@ -43909,11 +44383,11 @@ function readStorePosture(dbPath2) {
43909
44383
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
43910
44384
  import { randomUUID as randomUUID18 } from "crypto";
43911
44385
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
43912
- import { join as join33 } from "path";
44386
+ import { join as join26 } from "path";
43913
44387
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
43914
44388
  function createPostureStore(dir = settingsDir(), legacyDir) {
43915
- const file2 = join33(dir, "posture-state.json");
43916
- const legacyFile = legacyDir === void 0 ? null : join33(legacyDir, "posture-state.json");
44389
+ const file2 = join26(dir, "posture-state.json");
44390
+ const legacyFile = legacyDir === void 0 ? null : join26(legacyDir, "posture-state.json");
43917
44391
  async function persist(state) {
43918
44392
  await ensureDataDir(dir);
43919
44393
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -43981,8 +44455,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
43981
44455
  }
43982
44456
 
43983
44457
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
43984
- import { readFileSync as readFileSync20 } from "fs";
43985
- import { join as join34 } from "path";
44458
+ import { readFileSync as readFileSync16 } from "fs";
44459
+ import { join as join27 } from "path";
43986
44460
 
43987
44461
  // ../../packages/plugin-runtime/src/attached/status.ts
43988
44462
  var REFUSAL_LINES = {
@@ -44012,7 +44486,7 @@ import { fileURLToPath as fileURLToPath4 } from "url";
44012
44486
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
44013
44487
 
44014
44488
  // ../../packages/plugin-runtime/src/attached/factory.ts
44015
- import { hostname as hostname6 } from "os";
44489
+ import { hostname as hostname5 } from "os";
44016
44490
 
44017
44491
  // ../../packages/plugin-runtime/src/recorder.ts
44018
44492
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -44025,7 +44499,7 @@ var StandaloneDataGateway = class {
44025
44499
  // One notice per gateway — see warnRulesetDiscarded.
44026
44500
  warnedRulesetDiscarded = false;
44027
44501
  constructor(dataDir2, detections = [], meta4) {
44028
- this.db = openLocalDatabase(dataDir2);
44502
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
44029
44503
  this.dataDir = dataDir2;
44030
44504
  this.db.installedPacks.recordInventory(detections, meta4);
44031
44505
  }
@@ -44374,6 +44848,9 @@ var StandaloneDataGateway = class {
44374
44848
  scanLedgerPaths() {
44375
44849
  return Promise.resolve(this.db.scanLedger.allPaths());
44376
44850
  }
44851
+ scanLedgerPathKeys() {
44852
+ return Promise.resolve(this.db.scanLedger.pathKeys());
44853
+ }
44377
44854
  recordScanned(entries) {
44378
44855
  this.db.scanLedger.upsertEntries(entries);
44379
44856
  return Promise.resolve();
@@ -44459,13 +44936,17 @@ function resolveGatewayForConfig(config2, meta4) {
44459
44936
  },
44460
44937
  store: postureStore,
44461
44938
  readStore: () => readStorePosture(config2.dbPath),
44462
- hostname: () => hostname6(),
44939
+ hostname: () => hostname5(),
44463
44940
  now: () => Date.now(),
44941
+ // The mode THIS gateway enforces, from the attachment resolved above,
44942
+ // so the report cannot name a mode the forward paths are not using.
44943
+ attachmentMode: attachment.mode,
44464
44944
  // The reporting build's identity, when the caller knows it (the plugin
44465
44945
  // adapters do; an embedder or a test may not). Composed with the SAME
44466
44946
  // policy store the sync child writes, so the block names the bundle
44467
- // actually in force. Key omitted rather than set undefined — the
44468
- // reporter keys on presence.
44947
+ // actually in force. The dependency key is omitted when no build is
44948
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
44949
+ // then adds no block.
44469
44950
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
44470
44951
  })
44471
44952
  });
@@ -44486,11 +44967,11 @@ import { randomUUID as randomUUID19 } from "crypto";
44486
44967
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
44487
44968
 
44488
44969
  // ../../packages/scanner/src/manifests.ts
44489
- import { statSync as statSync11 } from "fs";
44970
+ import { statSync as statSync9 } from "fs";
44490
44971
 
44491
44972
  // ../../packages/scanner/src/walk.ts
44492
- import { readdirSync as readdirSync6, readFileSync as readFileSync21, statSync as statSync10 } from "fs";
44493
- import { extname, join as join35, relative as relative2, sep as sep4 } from "path";
44973
+ import { readdirSync as readdirSync4, readFileSync as readFileSync17, statSync as statSync8 } from "fs";
44974
+ import { extname, join as join28, relative as relative2, sep as sep4 } from "path";
44494
44975
  var import_ignore2 = __toESM(require_ignore(), 1);
44495
44976
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
44496
44977
  ".ts",
@@ -44523,14 +45004,18 @@ var SKIP_DIRS = /* @__PURE__ */ new Set([
44523
45004
  var DEFAULT_MAX_BYTES = 512 * 1024;
44524
45005
  function* walkTree(rootDir, opts = {}) {
44525
45006
  const trackGitignore = opts.trackGitignore ?? false;
45007
+ const onRepositoryRoot = opts.onRepositoryRoot;
44526
45008
  const rootSkipLayers = opts.excludePatterns && opts.excludePatterns.length > 0 ? [{ matcher: (0, import_ignore2.default)().add(opts.excludePatterns), anchorLen: 0 }] : [];
44527
45009
  function* visit2(dir, dirRel, markLayers, skipLayers, inIgnoredDir) {
44528
45010
  let dirents;
44529
45011
  try {
44530
- dirents = readdirSync6(dir, { withFileTypes: true, encoding: "utf8" });
45012
+ dirents = readdirSync4(dir, { withFileTypes: true, encoding: "utf8" });
44531
45013
  } catch {
44532
45014
  return;
44533
45015
  }
45016
+ if (onRepositoryRoot !== void 0 && dirRel !== "" && dirents.some((entry) => entry.name === ".git")) {
45017
+ onRepositoryRoot(dirRel);
45018
+ }
44534
45019
  const dirMarkLayers = withLayer(
44535
45020
  markLayers,
44536
45021
  trackGitignore && !inIgnoredDir ? readIgnoreLayer(dir, ".gitignore", dirRel.length) : void 0
@@ -44541,7 +45026,7 @@ function* walkTree(rootDir, opts = {}) {
44541
45026
  );
44542
45027
  for (const entry of dirents) {
44543
45028
  const name = entry.name;
44544
- const fullPath = join35(dir, name);
45029
+ const fullPath = join28(dir, name);
44545
45030
  if (entry.isDirectory()) {
44546
45031
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
44547
45032
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {
@@ -44568,14 +45053,15 @@ function* walkSourceFiles(opts = {}) {
44568
45053
  const maxBytes = opts.maxFileSizeBytes ?? DEFAULT_MAX_BYTES;
44569
45054
  for (const file2 of walkTree(rootDir, {
44570
45055
  excludePatterns: opts.excludePatterns,
44571
- trackGitignore: true
45056
+ trackGitignore: true,
45057
+ onRepositoryRoot: opts.onRepositoryRoot
44572
45058
  })) {
44573
45059
  const ext = extname(file2.name);
44574
45060
  if (!extensions.has(ext)) continue;
44575
45061
  let size;
44576
45062
  let mtime;
44577
45063
  try {
44578
- const st = statSync10(file2.path);
45064
+ const st = statSync8(file2.path);
44579
45065
  size = st.size;
44580
45066
  mtime = st.mtime;
44581
45067
  } catch {
@@ -44595,7 +45081,7 @@ function* walkSourceFiles(opts = {}) {
44595
45081
  if (opts.shouldRead && !opts.shouldRead(meta4)) continue;
44596
45082
  let content;
44597
45083
  try {
44598
- content = readFileSync21(file2.path, "utf8");
45084
+ content = readFileSync17(file2.path, "utf8");
44599
45085
  } catch {
44600
45086
  continue;
44601
45087
  }
@@ -44611,13 +45097,13 @@ function* walkSourceFiles(opts = {}) {
44611
45097
 
44612
45098
  // ../../packages/scanner/src/manifests.ts
44613
45099
  var MAX_MANIFEST_BYTES = 512 * 1024;
44614
- function collectManifests(rootDir, maxFileSizeBytes = MAX_MANIFEST_BYTES) {
45100
+ function collectManifests(rootDir, maxFileSizeBytes = MAX_MANIFEST_BYTES, onRepositoryRoot) {
44615
45101
  const found = [];
44616
- for (const file2 of walkTree(rootDir)) {
45102
+ for (const file2 of walkTree(rootDir, { onRepositoryRoot })) {
44617
45103
  const kind = manifestKindOf(file2.name);
44618
45104
  if (kind === null) continue;
44619
45105
  try {
44620
- const st = statSync11(file2.path);
45106
+ const st = statSync9(file2.path);
44621
45107
  if (st.size > maxFileSizeBytes) continue;
44622
45108
  found.push({ path: file2.path, kind, mtime: st.mtime.toISOString(), size: st.size });
44623
45109
  } catch {
@@ -44634,35 +45120,66 @@ function computeResolutions(prior, current) {
44634
45120
  }
44635
45121
 
44636
45122
  // ../../packages/scanner/src/scope-key.ts
44637
- import { existsSync as existsSync13 } from "fs";
44638
- import { join as join36, posix as posix2, resolve as resolve3 } from "path";
45123
+ import { existsSync as existsSync11 } from "fs";
45124
+ import { dirname as dirname7, join as join29, posix as posix2, resolve as resolve3 } from "path";
44639
45125
  function scopeKeysUnder(rootDir) {
44640
45126
  const base = resolve3(rootDir);
44641
- const keyByDir = /* @__PURE__ */ new Map();
44642
- return (relativePath) => {
45127
+ let aboveBase;
45128
+ const rootAtOrAboveBase = () => {
45129
+ if (aboveBase === void 0) {
45130
+ let dir = base;
45131
+ let root;
45132
+ for (; ; ) {
45133
+ if (existsSync11(join29(dir, ".git"))) {
45134
+ root = dir;
45135
+ break;
45136
+ }
45137
+ const parent = dirname7(dir);
45138
+ if (parent === dir) break;
45139
+ dir = parent;
45140
+ }
45141
+ aboveBase = { root };
45142
+ }
45143
+ return aboveBase.root;
45144
+ };
45145
+ const confirmed = (root, key) => existsSync11(join29(root, ".git")) ? { root, key } : { root: void 0, key: void 0 };
45146
+ const repositoryByDir = /* @__PURE__ */ new Map();
45147
+ const repositoryOf = (relativePath) => {
44643
45148
  const climbed = [];
44644
45149
  let dir = posix2.dirname(relativePath);
44645
- let key;
45150
+ let found;
44646
45151
  for (; ; ) {
44647
- if (keyByDir.has(dir)) {
44648
- key = keyByDir.get(dir);
45152
+ const known = repositoryByDir.get(dir);
45153
+ if (known !== void 0) {
45154
+ found = known;
44649
45155
  break;
44650
45156
  }
44651
45157
  climbed.push(dir);
44652
45158
  const parent = posix2.dirname(dir);
44653
45159
  if (parent === dir) {
44654
- key = resolveRepoAttribution(base).scopeKey;
45160
+ const root = rootAtOrAboveBase();
45161
+ found = root === void 0 ? { root, key: resolveRepoAttribution(base, { cache: false }).scopeKey } : confirmed(root, resolveRepoAttribution(root, { cache: false }).scopeKey);
44655
45162
  break;
44656
45163
  }
44657
- if (existsSync13(join36(base, dir, ".git"))) {
44658
- key = resolveRepoAttribution(join36(base, dir)).scopeKey;
45164
+ if (existsSync11(join29(base, dir, ".git"))) {
45165
+ const root = join29(base, dir);
45166
+ found = confirmed(root, resolveRepoAttribution(root, { cache: false }).scopeKey);
44659
45167
  break;
44660
45168
  }
44661
45169
  dir = parent;
44662
45170
  }
44663
- for (const at of climbed) keyByDir.set(at, key);
44664
- return key;
45171
+ for (const at of climbed) repositoryByDir.set(at, found);
45172
+ return found;
44665
45173
  };
45174
+ const keyOfFile = (relativePath) => repositoryOf(relativePath).key;
45175
+ const ofRepositoryRoot = (relativeDir) => {
45176
+ const root = join29(base, relativeDir);
45177
+ const dotGit = join29(root, ".git");
45178
+ if (!existsSync11(dotGit)) return void 0;
45179
+ const key = resolveRepoAttribution(root, { cache: false }).scopeKey;
45180
+ return existsSync11(dotGit) ? key : void 0;
45181
+ };
45182
+ return Object.assign(keyOfFile, { repositoryOf, ofRepositoryRoot });
44666
45183
  }
44667
45184
 
44668
45185
  // ../../packages/scanner/src/scan.ts
@@ -44697,7 +45214,14 @@ function egressKey(root, absPath) {
44697
45214
  function startEgress(rootDir) {
44698
45215
  const project = resolveEgressProject(rootDir);
44699
45216
  if (project === null) return null;
44700
- return { project, files: [], scannedFiles: [], deletedFiles: [] };
45217
+ return {
45218
+ project,
45219
+ files: [],
45220
+ scannedFiles: [],
45221
+ deletedFiles: [],
45222
+ deletedPaths: [],
45223
+ nestedRoots: []
45224
+ };
44701
45225
  }
44702
45226
  function collectFileEgress(acc, absPath, content, manifestKind) {
44703
45227
  const file2 = egressKey(acc.project.root, absPath);
@@ -44746,17 +45270,39 @@ async function reopenRedetectedFindings(gateway, path, currentKeys, evidence, re
44746
45270
  }
44747
45271
  function isUnderRoot(path, rootDir) {
44748
45272
  const rel = relative3(rootDir, path);
44749
- return rel !== "" && !rel.startsWith("..") && !isAbsolute3(rel);
45273
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
44750
45274
  }
44751
45275
  async function sweepDeletedFiles(gateway, rootDir, paths) {
44752
45276
  const deleted = [];
44753
45277
  for (const path of paths) {
44754
- if (!isUnderRoot(path, rootDir) || existsSync14(path)) continue;
45278
+ if (!isUnderRoot(path, rootDir) || existsSync12(path)) continue;
44755
45279
  deleted.push(path);
44756
45280
  await resolveRemovedFindings(gateway, path, [], { deleted: true });
44757
45281
  }
44758
45282
  return deleted;
44759
45283
  }
45284
+ function repositoryToRecord(prev, now) {
45285
+ const recordedRoot = prev?.scopeRoot;
45286
+ if (recordedRoot === void 0) return now;
45287
+ if (now.root !== void 0 && isAtOrBelow(recordedRoot, now.root)) return now;
45288
+ return { root: recordedRoot, key: prev?.scopeKey };
45289
+ }
45290
+ function isAtOrBelow(ancestor, dir) {
45291
+ const rel = relative3(ancestor, dir);
45292
+ if (isAbsolute2(rel)) return false;
45293
+ const posixRel = toPosix(rel);
45294
+ return posixRel === "" || posixRel !== ".." && !posixRel.startsWith("../");
45295
+ }
45296
+ function repositoryColumns(repository) {
45297
+ return {
45298
+ ...repository.key !== void 0 ? { scopeKey: repository.key } : {},
45299
+ ...repository.root !== void 0 ? { scopeRoot: repository.root } : {}
45300
+ };
45301
+ }
45302
+ function repositoryDiffers(prev, decided) {
45303
+ return decided.key !== prev.scopeKey || decided.root !== prev.scopeRoot;
45304
+ }
45305
+ var NO_REPOSITORY = { root: void 0, key: void 0 };
44760
45306
  async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44761
45307
  const byRule = {};
44762
45308
  const bySeverity = {};
@@ -44767,10 +45313,25 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44767
45313
  let gitignoredFindings = 0;
44768
45314
  const egress = config2.settings.dataSharesInPlace ? startEgress(rootDir) : null;
44769
45315
  const scopeKeyOf2 = scopeKeysUnder(rootDir);
45316
+ const noteNestedRoot = (relativeDir) => {
45317
+ egress?.nestedRoots.push(relativeDir);
45318
+ };
44770
45319
  const shouldRead = (meta4) => {
44771
45320
  const prev = ledger.previous.get(meta4.path);
44772
45321
  if (prev?.mtime === meta4.mtime) {
44773
45322
  skipped++;
45323
+ if (egress !== null) {
45324
+ const decided = repositoryToRecord(prev, scopeKeyOf2.repositoryOf(meta4.relativePath));
45325
+ if (repositoryDiffers(prev, decided)) {
45326
+ updates.push({
45327
+ path: meta4.path,
45328
+ mtime: prev.mtime,
45329
+ contentHash: prev.contentHash,
45330
+ rulesetHash: ledger.rulesetHash,
45331
+ ...repositoryColumns(decided)
45332
+ });
45333
+ }
45334
+ }
44774
45335
  return false;
44775
45336
  }
44776
45337
  return true;
@@ -44778,16 +45339,19 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44778
45339
  for (const file2 of walkSourceFiles({
44779
45340
  ...opts,
44780
45341
  rootDir,
44781
- shouldRead: (meta4) => (opts.shouldRead?.(meta4) ?? true) && shouldRead(meta4)
45342
+ shouldRead: (meta4) => (opts.shouldRead?.(meta4) ?? true) && shouldRead(meta4),
45343
+ onRepositoryRoot: egress === null ? void 0 : noteNestedRoot
44782
45344
  })) {
44783
45345
  const hash2 = contentHashOf(file2.content);
45346
+ const prev = ledger.previous.get(file2.path);
45347
+ const repository = egress === null ? NO_REPOSITORY : repositoryToRecord(prev, scopeKeyOf2.repositoryOf(file2.relativePath));
44784
45348
  const ledgerEntry = {
44785
45349
  path: file2.path,
44786
45350
  mtime: file2.mtime,
44787
45351
  contentHash: hash2,
44788
- rulesetHash: ledger.rulesetHash
45352
+ rulesetHash: ledger.rulesetHash,
45353
+ ...repositoryColumns(repository)
44789
45354
  };
44790
- const prev = ledger.previous.get(file2.path);
44791
45355
  if (prev?.contentHash === hash2) {
44792
45356
  skipped++;
44793
45357
  updates.push(ledgerEntry);
@@ -44839,15 +45403,17 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44839
45403
  contentHash: hash2
44840
45404
  });
44841
45405
  }
44842
- if (egress) scanManifests(egress, ledger, updates, rootDir);
45406
+ if (egress) scanManifests(egress, ledger, updates, rootDir, scopeKeyOf2, noteNestedRoot);
44843
45407
  const deleted = await sweepDeletedFiles(gateway, rootDir, ledger.paths);
44844
45408
  if (egress) {
44845
45409
  for (const path of deleted) {
44846
45410
  const key = egressKey(egress.project.root, path);
44847
- if (key !== null) egress.deletedFiles.push(key);
45411
+ if (key === null) continue;
45412
+ egress.deletedFiles.push(key);
45413
+ egress.deletedPaths.push(path);
44848
45414
  }
44849
45415
  }
44850
- const committed = await commitEgress(gateway, egress);
45416
+ const committed = await commitEgress(gateway, egress, scopeKeyOf2);
44851
45417
  if (committed === null) {
44852
45418
  return { rootDir, scanned, skipped, findings, gitignoredFindings, byRule, bySeverity };
44853
45419
  }
@@ -44857,13 +45423,28 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44857
45423
  await gateway.recordScanned(ledgerable(updates, egress, committed));
44858
45424
  return { rootDir, scanned, skipped, findings, gitignoredFindings, byRule, bySeverity };
44859
45425
  }
44860
- function scanManifests(egress, ledger, updates, rootDir) {
44861
- for (const manifest of collectManifests(rootDir)) {
45426
+ function scanManifests(egress, ledger, updates, rootDir, scopeKeyOf2, onRepositoryRoot) {
45427
+ for (const manifest of collectManifests(rootDir, void 0, onRepositoryRoot)) {
44862
45428
  const prev = ledger.previous.get(manifest.path);
44863
- if (prev?.mtime === manifest.mtime) continue;
45429
+ const repository = repositoryToRecord(
45430
+ prev,
45431
+ scopeKeyOf2.repositoryOf(toPosix(relative3(rootDir, manifest.path)))
45432
+ );
45433
+ if (prev?.mtime === manifest.mtime) {
45434
+ if (repositoryDiffers(prev, repository)) {
45435
+ updates.push({
45436
+ path: manifest.path,
45437
+ mtime: prev.mtime,
45438
+ contentHash: prev.contentHash,
45439
+ rulesetHash: ledger.rulesetHash,
45440
+ ...repositoryColumns(repository)
45441
+ });
45442
+ }
45443
+ continue;
45444
+ }
44864
45445
  let content;
44865
45446
  try {
44866
- content = readFileSync22(manifest.path, "utf8");
45447
+ content = readFileSync18(manifest.path, "utf8");
44867
45448
  } catch {
44868
45449
  continue;
44869
45450
  }
@@ -44872,31 +45453,82 @@ function scanManifests(egress, ledger, updates, rootDir) {
44872
45453
  path: manifest.path,
44873
45454
  mtime: manifest.mtime,
44874
45455
  contentHash: hash2,
44875
- rulesetHash: ledger.rulesetHash
45456
+ rulesetHash: ledger.rulesetHash,
45457
+ ...repositoryColumns(repository)
44876
45458
  });
44877
45459
  if (prev?.contentHash === hash2) continue;
44878
45460
  collectFileEgress(egress, manifest.path, content, manifest.kind);
44879
45461
  }
44880
45462
  }
44881
- async function commitEgress(gateway, egress) {
45463
+ async function commitEgress(gateway, egress, scopeKeyOf2) {
44882
45464
  if (!egress) return EMPTY_DROPPED;
44883
- const { project, files, scannedFiles, deletedFiles } = egress;
45465
+ const { project, files, scannedFiles, deletedFiles, deletedPaths, nestedRoots } = egress;
44884
45466
  if (scannedFiles.length === 0 && deletedFiles.length === 0 && files.length === 0) {
44885
45467
  return EMPTY_DROPPED;
44886
45468
  }
45469
+ let nestedKeys;
45470
+ let deletedKeys;
44887
45471
  try {
44888
- const summary = await gateway.recordProjectEgress({
44889
- projectKey: project.projectKey,
44890
- project: project.project,
44891
- projectId: null,
44892
- reconcile: { mode: "ledger", scannedFiles, deletedFiles },
44893
- hits: resolveEgress(files)
44894
- });
45472
+ const summary = await gateway.recordProjectEgress(
45473
+ {
45474
+ projectKey: project.projectKey,
45475
+ project: project.project,
45476
+ projectId: null,
45477
+ reconcile: { mode: "ledger", scannedFiles, deletedFiles },
45478
+ hits: resolveEgress(files)
45479
+ },
45480
+ {
45481
+ // One key per nested root, from this scan's own lookup of a
45482
+ // repository ROOT (./scope-key.ts): the directory's own key, found
45483
+ // without climbing. A nested directory whose `.git` is a link to
45484
+ // nowhere, or is gone by the time a gateway asks, is `undefined` here
45485
+ // rather than the key of the repository around it; so is a nested
45486
+ // repository with no forge remote. Each root is read fresh, never from
45487
+ // the resolver's memory of an earlier answer for that directory. Always
45488
+ // a list, even an empty one: a scoped gateway reads a missing list as a
45489
+ // register nobody vouched for. The repository lookups it makes do not
45490
+ // throw on these inputs, and the gateway reads any throw in this read as
45491
+ // local anyway.
45492
+ //
45493
+ // A getter, memoized: only a gateway that reads the list causes a
45494
+ // repository read. The standalone gateway ignores it, and a
45495
+ // machine-wide attachment answers before reading it.
45496
+ get nestedScopeKeys() {
45497
+ nestedKeys ??= [...new Set(nestedRoots)].map((dir) => scopeKeyOf2.ofRepositoryRoot(dir));
45498
+ return nestedKeys;
45499
+ },
45500
+ // One key per entry of `reconcile.deletedFiles`, in its order: what the
45501
+ // ledger recorded when the path was last read, and none for a row that
45502
+ // recorded none. ASYNC and lazy, because the read of every row's key is a
45503
+ // read of the whole ledger: only a gateway that forwards by scope asks, and
45504
+ // only once it has found the register sendable at all, so the standalone
45505
+ // gateway and a machine-wide attachment never cause it. Memoized, so a
45506
+ // gateway that asks twice reads once. A scan that deleted nothing has no
45507
+ // keys to look up and reads nothing.
45508
+ deletedFileKeys: () => {
45509
+ deletedKeys ??= keysOfDeleted(gateway, deletedPaths);
45510
+ return deletedKeys;
45511
+ }
45512
+ }
45513
+ );
44895
45514
  return new Set(summary.droppedFiles);
44896
45515
  } catch {
44897
45516
  return null;
44898
45517
  }
44899
45518
  }
45519
+ async function keysOfDeleted(gateway, deletedPaths) {
45520
+ if (deletedPaths.length === 0) return [];
45521
+ const recorded = await readRecordedKeys(gateway);
45522
+ return deletedPaths.map((path) => recorded.get(path));
45523
+ }
45524
+ async function readRecordedKeys(gateway) {
45525
+ try {
45526
+ return await gateway.scanLedgerPathKeys?.() ?? NO_RECORDED_KEYS;
45527
+ } catch {
45528
+ return NO_RECORDED_KEYS;
45529
+ }
45530
+ }
45531
+ var NO_RECORDED_KEYS = /* @__PURE__ */ new Map();
44900
45532
  var EMPTY_DROPPED = /* @__PURE__ */ new Set();
44901
45533
  function ledgerable(updates, egress, dropped) {
44902
45534
  if (!egress || dropped.size === 0) return [...updates];