@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.
package/scripts/sync.js CHANGED
@@ -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;
@@ -872,19 +872,6 @@ var require_ignore = __commonJS({
872
872
  }
873
873
  });
874
874
 
875
- // ../../packages/persistence/src/attached-derived.ts
876
- import { rmSync } from "fs";
877
- import { join } from "path";
878
- var POLICY_CACHE_FILENAME = "policy-cache.json";
879
- var ATTACHED_SYNC_STATE_FILENAME = "attached-sync-state.json";
880
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
881
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
882
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
883
-
884
- // ../../packages/persistence/src/control-plane-credential.ts
885
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
886
- import { join as join2 } from "path";
887
-
888
875
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
889
876
  var DEFERRED_MIGRATION_TAGS = [
890
877
  "0031_audit_capture_by_time_index",
@@ -1056,7 +1043,7 @@ var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1056
1043
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1057
1044
 
1058
1045
  // ../../packages/schema/src/invisible-padding.ts
1059
- var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
1046
+ 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;
1060
1047
  function stripInvisiblePadding(text) {
1061
1048
  return text.replace(INVISIBLE_PADDING, "");
1062
1049
  }
@@ -3874,9 +3861,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3874
3861
  function stripTabAndNewline(value) {
3875
3862
  return value.replace(asciiTabOrNewline, "");
3876
3863
  }
3877
- function urlHostnameOk(url2, hostname7) {
3878
- hostname7.lastIndex = 0;
3879
- return hostname7.test(url2.hostname);
3864
+ function urlHostnameOk(url2, hostname6) {
3865
+ hostname6.lastIndex = 0;
3866
+ return hostname6.test(url2.hostname);
3880
3867
  }
3881
3868
  function urlProtocolOk(url2, protocol) {
3882
3869
  protocol.lastIndex = 0;
@@ -20796,13 +20783,16 @@ function serviceTierMultiplier(tier) {
20796
20783
  if (tier === void 0) return 1;
20797
20784
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20798
20785
  }
20786
+ function promptTokensOf(usage) {
20787
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
20788
+ }
20799
20789
  function costOf(price, usage) {
20800
20790
  const metered = [
20801
20791
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20802
20792
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20803
20793
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20804
20794
  ];
20805
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
20795
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20806
20796
  if (band !== null && (band.input === null || band.output === null)) return null;
20807
20797
  const inputRate = band?.input ?? price.input;
20808
20798
  const outputRate = band?.output ?? price.output;
@@ -20875,8 +20865,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20875
20865
  ["ollama", "local"],
20876
20866
  ["local", "local"]
20877
20867
  ]);
20878
- function hostingFor(platform2) {
20879
- return PLATFORM_HOSTING.get(platform2) ?? "api";
20868
+ function hostingFor(platform) {
20869
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20880
20870
  }
20881
20871
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20882
20872
  ["anthropic", "anthropic"],
@@ -20890,8 +20880,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20890
20880
  function firstPartyPlatformFor(vendor2) {
20891
20881
  return FIRST_PARTY.get(vendor2) ?? null;
20892
20882
  }
20893
- function isFirstParty(vendor2, platform2) {
20894
- return FIRST_PARTY.get(vendor2) === platform2;
20883
+ function isFirstParty(vendor2, platform) {
20884
+ return FIRST_PARTY.get(vendor2) === platform;
20895
20885
  }
20896
20886
  var PLATFORM_NAMESPACES = Object.freeze([
20897
20887
  "anthropic",
@@ -20952,14 +20942,14 @@ var ModelVendorBuilder = class {
20952
20942
  );
20953
20943
  }
20954
20944
  for (const ref of spec.on ?? []) {
20955
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20956
- const firstParty = isFirstParty(this.vendor, platform2);
20957
- const hosting = hostingFor(platform2);
20945
+ const { platform, price, retention, region } = normalizeRef(ref);
20946
+ const firstParty = isFirstParty(this.vendor, platform);
20947
+ const hosting = hostingFor(platform);
20958
20948
  const isSelfHosted = hosting === "local";
20959
20949
  platforms.set(
20960
- platform2,
20950
+ platform,
20961
20951
  Object.freeze({
20962
- platform: platform2,
20952
+ platform,
20963
20953
  hosting,
20964
20954
  firstParty,
20965
20955
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21012,35 +21002,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21012
21002
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21013
21003
  var BEDROCK_REVISION_RE = /:\d+$/u;
21014
21004
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21015
- var DATED_SUFFIX_RE = /-\d{8}$/u;
21005
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21016
21006
  function stripPlatformDecorations(model) {
21017
21007
  let id = model.trim();
21018
- let platform2 = null;
21008
+ let platform = null;
21019
21009
  if (GEO_PREFIX_RE.test(id)) {
21020
21010
  id = id.replace(GEO_PREFIX_RE, "");
21021
- platform2 = "bedrock";
21011
+ platform = "bedrock";
21022
21012
  }
21023
21013
  if (NAMESPACE_DOT_RE.test(id)) {
21024
21014
  id = id.replace(NAMESPACE_DOT_RE, "");
21025
- platform2 ??= "bedrock";
21015
+ platform ??= "bedrock";
21026
21016
  }
21027
21017
  if (BEDROCK_VERSION_RE.test(id)) {
21028
21018
  id = id.replace(BEDROCK_VERSION_RE, "");
21029
- platform2 ??= "bedrock";
21019
+ platform ??= "bedrock";
21030
21020
  } else if (BEDROCK_REVISION_RE.test(id)) {
21031
21021
  id = id.replace(BEDROCK_REVISION_RE, "");
21032
- platform2 ??= "bedrock";
21022
+ platform ??= "bedrock";
21033
21023
  }
21034
21024
  if (VERTEX_VERSION_RE.test(id)) {
21035
21025
  id = id.replace(VERTEX_VERSION_RE, "");
21036
- platform2 ??= "vertex";
21026
+ platform ??= "vertex";
21037
21027
  }
21038
21028
  if (NAMESPACE_SLASH_RE.test(id)) {
21039
21029
  id = id.replace(NAMESPACE_SLASH_RE, "");
21040
21030
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21041
21031
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21042
21032
  }
21043
- return { id, platform: platform2 };
21033
+ return { id, platform };
21044
21034
  }
21045
21035
  function buildModelIndex(entries) {
21046
21036
  const byId = /* @__PURE__ */ new Map();
@@ -21057,19 +21047,19 @@ function resolveModel(raw, index) {
21057
21047
  if (exact !== void 0) {
21058
21048
  return { entry: exact, canonicalId: raw, platform: null, raw };
21059
21049
  }
21060
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
21050
+ const { id, platform } = stripPlatformDecorations(raw);
21061
21051
  const stripped = index.byId.get(id);
21062
21052
  if (stripped !== void 0) {
21063
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
21053
+ return { entry: stripped, canonicalId: id, platform, raw };
21064
21054
  }
21065
21055
  if (DATED_SUFFIX_RE.test(id)) {
21066
21056
  const undated = id.replace(DATED_SUFFIX_RE, "");
21067
21057
  const byDate = index.byId.get(undated);
21068
21058
  if (byDate !== void 0) {
21069
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
21059
+ return { entry: byDate, canonicalId: undated, platform, raw };
21070
21060
  }
21071
21061
  }
21072
- return { entry: null, canonicalId: raw, platform: platform2, raw };
21062
+ return { entry: null, canonicalId: raw, platform, raw };
21073
21063
  }
21074
21064
 
21075
21065
  // ../../packages/schema/src/model/catalog.ts
@@ -21162,7 +21152,7 @@ anthropic.model("claude-haiku-4-5", {
21162
21152
  name: "Claude Haiku 4.5",
21163
21153
  ctx: 2e5,
21164
21154
  maxOut: 64e3,
21165
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
21155
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21166
21156
  capability: null,
21167
21157
  price: anthropicPrice(1, 5, 0.1),
21168
21158
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21293,6 +21283,11 @@ openai.model("gpt-4o", {
21293
21283
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21294
21284
  on: [...OPENAI_RESELLERS]
21295
21285
  });
21286
+ openai.model("gpt-4o-2024-05-13", {
21287
+ name: "GPT-4o (2024-05-13)",
21288
+ price: tokenPrice(5, 15),
21289
+ on: [...OPENAI_RESELLERS]
21290
+ });
21296
21291
  openai.model("gpt-4o-mini", {
21297
21292
  name: "GPT-4o mini",
21298
21293
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21312,6 +21307,24 @@ openai.model("o3", {
21312
21307
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21313
21308
  on: [...OPENAI_RESELLERS]
21314
21309
  });
21310
+ openai.model("text-embedding-3-small", {
21311
+ name: "text-embedding-3-small",
21312
+ capability: "embedding",
21313
+ price: tokenPrice(0.02, 0),
21314
+ on: [...OPENAI_RESELLERS]
21315
+ });
21316
+ openai.model("text-embedding-3-large", {
21317
+ name: "text-embedding-3-large",
21318
+ capability: "embedding",
21319
+ price: tokenPrice(0.13, 0),
21320
+ on: [...OPENAI_RESELLERS]
21321
+ });
21322
+ openai.model("text-embedding-ada-002", {
21323
+ name: "text-embedding-ada-002",
21324
+ capability: "embedding",
21325
+ price: tokenPrice(0.1, 0),
21326
+ on: [...OPENAI_RESELLERS]
21327
+ });
21315
21328
  openai.model("gpt-oss-120b", {
21316
21329
  name: "GPT-OSS 120B",
21317
21330
  openWeights: true,
@@ -21598,10 +21611,21 @@ var MODEL_ENTRIES = Object.freeze([
21598
21611
  ...alibaba.models(),
21599
21612
  ...amazon.models()
21600
21613
  ]);
21614
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
21615
+ [
21616
+ ...new Set(
21617
+ MODEL_ENTRIES.flatMap(
21618
+ (entry) => [...entry.platforms.values()].flatMap(
21619
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
21620
+ )
21621
+ )
21622
+ )
21623
+ ].sort((a, b) => a - b)
21624
+ );
21601
21625
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21602
21626
 
21603
21627
  // ../../packages/schema/src/model/governance.ts
21604
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
21628
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21605
21629
  var DataRetention = external_exports.enum([
21606
21630
  "zero_retention",
21607
21631
  "no_storage",
@@ -21697,16 +21721,16 @@ function platformForProvider(provider) {
21697
21721
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21698
21722
  }
21699
21723
  function isLocalProvider(provider) {
21700
- const platform2 = platformForProvider(provider);
21701
- return platform2 !== null && hostingFor(platform2) === "local";
21724
+ const platform = platformForProvider(provider);
21725
+ return platform !== null && hostingFor(platform) === "local";
21702
21726
  }
21703
21727
  function priceFor(provider, model) {
21704
21728
  if (isLocalProvider(provider)) return ZERO_PRICE;
21705
21729
  const resolved = resolveModel(model, MODEL_INDEX);
21706
21730
  if (resolved.entry === null) return null;
21707
- const platform2 = resolved.platform ?? platformForProvider(provider);
21708
- if (platform2 === null) return null;
21709
- return resolved.entry.platforms.get(platform2)?.price ?? null;
21731
+ const platform = resolved.platform ?? platformForProvider(provider);
21732
+ if (platform === null) return null;
21733
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21710
21734
  }
21711
21735
  var defaultCostModel = {
21712
21736
  normalizeModelId(provider, model) {
@@ -21732,7 +21756,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21732
21756
 
21733
21757
  // ../../packages/schema/src/token/token-report.ts
21734
21758
  var num = (value) => value ?? 0;
21735
- function costUsageOf(a) {
21759
+ function costUsageOf(a, promptTokens) {
21736
21760
  const usage = {
21737
21761
  inputTokens: num(a.input_tokens),
21738
21762
  outputTokens: num(a.output_tokens),
@@ -21742,11 +21766,12 @@ function costUsageOf(a) {
21742
21766
  webSearchRequests: num(a.web_search_requests)
21743
21767
  };
21744
21768
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
21769
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21745
21770
  return usage;
21746
21771
  }
21747
21772
  function buildTokenReports(leaves, costModel) {
21748
21773
  const bySession = /* @__PURE__ */ new Map();
21749
- for (const { sessionId, attributes } of leaves) {
21774
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21750
21775
  const provider = attributes.provider ?? "unknown";
21751
21776
  const model = attributes.model ?? "unknown";
21752
21777
  const key = `${provider} ${model}`;
@@ -21765,7 +21790,8 @@ function buildTokenReports(leaves, costModel) {
21765
21790
  cacheCreation: 0,
21766
21791
  cacheRead: 0,
21767
21792
  costUsd: 0,
21768
- priced: false
21793
+ priced: false,
21794
+ partial: false
21769
21795
  };
21770
21796
  rollups.set(key, acc);
21771
21797
  }
@@ -21773,8 +21799,14 @@ function buildTokenReports(leaves, costModel) {
21773
21799
  acc.output += num(attributes.output_tokens);
21774
21800
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21775
21801
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21776
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21777
- if (leafCost !== null) {
21802
+ const leafCost = costModel.costFor({
21803
+ provider,
21804
+ model,
21805
+ usage: costUsageOf(attributes, promptTokens)
21806
+ });
21807
+ if (leafCost === null) {
21808
+ acc.partial = true;
21809
+ } else {
21778
21810
  acc.costUsd += leafCost;
21779
21811
  acc.priced = true;
21780
21812
  }
@@ -21790,9 +21822,8 @@ function buildTokenReports(leaves, costModel) {
21790
21822
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21791
21823
  totalTokens += rollupTotal;
21792
21824
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21793
- if (estimatedCostUsd === null) {
21794
- anyUnpriced = true;
21795
- } else {
21825
+ if (acc.partial) anyUnpriced = true;
21826
+ if (estimatedCostUsd !== null) {
21796
21827
  anyPriced = true;
21797
21828
  costUsd += estimatedCostUsd;
21798
21829
  }
@@ -21815,7 +21846,7 @@ function buildTokenReports(leaves, costModel) {
21815
21846
  totalTokens,
21816
21847
  // Σ of the PRICED rollups; null when none had a known price.
21817
21848
  estimatedCostUsd: anyPriced ? costUsd : null,
21818
- // Any unknown (provider, model) means the total understates real spend.
21849
+ // Any call priced to null means the total understates real spend.
21819
21850
  costIsPartial: anyUnpriced
21820
21851
  });
21821
21852
  }
@@ -22694,8 +22725,9 @@ var SessionTokenReport = external_exports.object({
22694
22725
  totalTokens: external_exports.number().int().nonnegative(),
22695
22726
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22696
22727
  estimatedCostUsd: external_exports.number().nullable(),
22697
- // True whenever any rollup has a null cost (unknown provider/model), so the
22698
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
22728
+ // True whenever any call priced to null (an unknown provider/model, or a call
22729
+ // over a long-context threshold whose rate is unpublished), so the total
22730
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22699
22731
  // precise figure rather than silently dropping the unpriced calls.
22700
22732
  costIsPartial: external_exports.boolean()
22701
22733
  });
@@ -23572,7 +23604,15 @@ var StorePostureSnapshot = external_exports.object({
23572
23604
  policyCounts: StorePosturePolicyCounts,
23573
23605
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23574
23606
  // getting its 200 without a payload change.
23575
- plugin: StorePosturePlugin.optional()
23607
+ plugin: StorePosturePlugin.optional(),
23608
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
23609
+ // machine attachment omits it, so its body is byte for byte the one it
23610
+ // sent before this member existed. Absent therefore means machine-wide OR
23611
+ // a reporter older than this member, never "scoped". Both values parse, so
23612
+ // a sender that one day spells `machine` breaks no receiver; any other
23613
+ // value fails the whole snapshot, which is why the reporter sends a
23614
+ // constant and never the raw mode.
23615
+ attachmentMode: AttachmentMode.optional()
23576
23616
  }).meta({ id: "StorePostureSnapshot" });
23577
23617
  var CAPTURE_VERSION_PREFIX = "capture/";
23578
23618
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -24019,7 +24059,7 @@ var Rule = external_exports.strictObject({
24019
24059
  postValidators: external_exports.array(PostValidatorRef).optional(),
24020
24060
  requiresNearby: RequiresNearby.optional(),
24021
24061
  examples: external_exports.array(external_exports.string()).optional(),
24022
- // Whether the matched text is itself sensitive. Absent means 'value'.
24062
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24023
24063
  evidence: RuleEvidence.optional()
24024
24064
  }).meta({ id: "Rule" });
24025
24065
  var Author = external_exports.object({
@@ -24111,7 +24151,13 @@ var DetectionRule = external_exports.object({
24111
24151
  // Representative matching strings the rule author shipped with the rule. The
24112
24152
  // cheapest honest answer to "show me what this rule catches" — every bundled
24113
24153
  // rule has them, and they are already in the stored snapshot.
24114
- examples: external_exports.array(external_exports.string()).optional()
24154
+ examples: external_exports.array(external_exports.string()).optional(),
24155
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
24156
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
24157
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
24158
+ // in a value category (secret/pii/financial/phi) is always 'value',
24159
+ // whatever it declares.
24160
+ evidence: RuleEvidence.optional()
24115
24161
  }).meta({ id: "DetectionRule" });
24116
24162
  var DetectionUpdate = external_exports.object({
24117
24163
  available: external_exports.boolean(),
@@ -24179,8 +24225,10 @@ var ImportDetectionRequest = external_exports.object({
24179
24225
  }).meta({ id: "ImportDetectionRequest" });
24180
24226
 
24181
24227
  // ../../packages/schema/src/zod/detection-build.ts
24182
- function optional2(key, parsed2, raw) {
24183
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
24228
+ function optional2(key, raw, parse4) {
24229
+ if (raw === void 0) return {};
24230
+ const parsed2 = parse4(raw);
24231
+ if (!parsed2.success || parsed2.data === void 0) return {};
24184
24232
  return { [key]: parsed2.data };
24185
24233
  }
24186
24234
  function isStringArray(value) {
@@ -24215,10 +24263,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24215
24263
  category: r.category,
24216
24264
  severity: r.severity,
24217
24265
  matcher: parsed2.data,
24218
- // The rest of what decides whether this rule fires. Carried so a consumer
24219
- // re-running the rule (a preview, a tester) evaluates what the engine
24220
- // evaluates rather than a matcher stripped of its guards — half the
24221
- // bundled catalog carries at least one of these.
24266
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
24267
+ // decides whether this rule fires. Carried so a consumer re-running the
24268
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
24269
+ // than a matcher stripped of its guards — half the bundled catalog
24270
+ // carries at least one of these. `examples` and `evidence` describe the
24271
+ // rule and never gate a match.
24222
24272
  //
24223
24273
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24224
24274
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24228,18 +24278,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24228
24278
  // test should stay exactly what it was, namely a renderable matcher. A
24229
24279
  // field that fails validation is omitted, which reads as "not set" and is
24230
24280
  // the same thing the consumer saw before this change.
24231
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
24281
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24232
24282
  ...optional2(
24233
24283
  "postValidators",
24234
- PostValidatorRef.array().safeParse(r.postValidators),
24235
- r.postValidators
24284
+ r.postValidators,
24285
+ (v) => PostValidatorRef.array().safeParse(v)
24236
24286
  ),
24237
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
24287
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24238
24288
  ...optional2(
24239
24289
  "examples",
24240
- { success: isStringArray(r.examples), data: r.examples },
24241
- r.examples
24242
- )
24290
+ r.examples,
24291
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
24292
+ ),
24293
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24243
24294
  }
24244
24295
  ];
24245
24296
  });
@@ -24932,11 +24983,14 @@ var PolicyBundle = external_exports.object({
24932
24983
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24933
24984
  // Model ids (the raw `model` string a harness reports, e.g.
24934
24985
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24935
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24936
- // one (UserPromptSubmit). Optional so an older backend — and an older
24937
- // on-disk cache — still parses; consumers read `?? []`, which is the
24938
- // unenforced behaviour that predates this field and the safe direction to
24939
- // default.
24986
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24987
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24988
+ // wherever the organization governs the event: everywhere on a
24989
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24990
+ // one (the plugin runtime's `governanceApplies`).
24991
+ // Optional so an older backend — and an older on-disk cache — still
24992
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24993
+ // predates this field and the safe direction to default.
24940
24994
  //
24941
24995
  // Ids, not display names: the governance decision is keyed on the exact
24942
24996
  // string the harness reports (`model_status_override.versionId` in the
@@ -25395,6 +25449,8 @@ var AttachmentScopeEntry = external_exports.object({
25395
25449
  });
25396
25450
  var AttachmentScope = external_exports.object({
25397
25451
  endpoint: external_exports.string().min(1),
25452
+ tenantName: PluginWhoami.shape.tenantName.optional(),
25453
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25398
25454
  entries: external_exports.array(AttachmentScopeEntry)
25399
25455
  });
25400
25456
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25407,7 +25463,13 @@ function parseAttachmentScope(raw) {
25407
25463
  const entry = AttachmentScopeEntry.safeParse(candidate);
25408
25464
  if (entry.success) entries.push(entry.data);
25409
25465
  }
25410
- return { endpoint: envelope.data.endpoint, entries };
25466
+ const { endpoint, tenantName, userEmail } = envelope.data;
25467
+ return {
25468
+ endpoint,
25469
+ ...tenantName === void 0 ? {} : { tenantName },
25470
+ ...userEmail === void 0 ? {} : { userEmail },
25471
+ entries
25472
+ };
25411
25473
  } catch {
25412
25474
  return void 0;
25413
25475
  }
@@ -25772,6 +25834,27 @@ var ManagedSettings = external_exports.object({
25772
25834
  };
25773
25835
  }).meta({ id: "ManagedSettings" });
25774
25836
 
25837
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
25838
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
25839
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
25840
+ var ModPolicySnapshot = external_exports.object({
25841
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
25842
+ generatedAt: external_exports.iso.datetime(),
25843
+ // The complete effective ruleset, as the hook's runtime scans with it: the
25844
+ // user's enabled installed packs (user-modified and custom packs included).
25845
+ // Absent means the store holds no authoritative snapshot, and the reader
25846
+ // scans with the packs it ships — the hook's own fallback.
25847
+ rules: external_exports.array(Rule).optional(),
25848
+ // Rule-targeted actions (first enabled policy per rule wins).
25849
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25850
+ // The resolved action per detection category.
25851
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25852
+ // Rules with an active exception grant. Honouring a grant means matching a
25853
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25854
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25855
+ exceptionRuleIds: external_exports.array(external_exports.string())
25856
+ }).meta({ id: "ModPolicySnapshot" });
25857
+
25775
25858
  // ../../packages/schema/src/zod/project-files.ts
25776
25859
  var ProjectFileInput = external_exports.object({
25777
25860
  path: external_exports.string().min(1),
@@ -26092,7 +26175,16 @@ var AttachInput = external_exports.object({
26092
26175
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26093
26176
  // renders a longer one usefully.
26094
26177
  label: printable(200).optional(),
26095
- accessKey: external_exports.string()
26178
+ accessKey: external_exports.string(),
26179
+ // How much of this machine the attachment is for: everything, or only the
26180
+ // repositories its user enrolls. Optional, so an input without it still
26181
+ // parses; what an absent mode means is for whatever reads it to decide, not
26182
+ // this shape. This member validates the VALUE rather than leaving that to the
26183
+ // call site, a deliberate exception to this module's shape-only rule: a shape
26184
+ // rejection names the field, so a value that is not a mode is refused as a bad
26185
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
26186
+ // it as the mode to attach in.
26187
+ mode: AttachmentMode.optional()
26096
26188
  });
26097
26189
 
26098
26190
  // ../../packages/schema/src/zod/triage.ts
@@ -26378,6 +26470,19 @@ function fromCaptureStatusAttributes(bag) {
26378
26470
  return parsedStatus.success ? parsedStatus.data : null;
26379
26471
  }
26380
26472
 
26473
+ // ../../packages/persistence/src/attached-derived.ts
26474
+ import { rmSync } from "fs";
26475
+ import { join } from "path";
26476
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
26477
+ var ATTACHED_SYNC_STATE_FILENAME = "attached-sync-state.json";
26478
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
26479
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
26480
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
26481
+
26482
+ // ../../packages/persistence/src/control-plane-credential.ts
26483
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
26484
+ import { join as join2 } from "path";
26485
+
26381
26486
  // ../../packages/persistence/src/paths.ts
26382
26487
  import {
26383
26488
  chmodSync,
@@ -26524,6 +26629,14 @@ function repairOrRefuseMode(file2) {
26524
26629
  }
26525
26630
  return "ok";
26526
26631
  }
26632
+ function asReadableCredential(value) {
26633
+ const result = AttachedCredentialAny.safeParse(value);
26634
+ if (!result.success) return null;
26635
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
26636
+ return null;
26637
+ }
26638
+ return result.data;
26639
+ }
26527
26640
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26528
26641
  const file2 = controlPlaneCredentialPath(settingsDir2);
26529
26642
  let raw;
@@ -26542,20 +26655,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26542
26655
  } catch {
26543
26656
  return { usable: false, reason: "malformed" };
26544
26657
  }
26545
- const result = AttachedCredential.safeParse(parsed2);
26546
- if (!result.success) return { usable: false, reason: "malformed" };
26547
- if (!isSafeEndpoint(result.data.endpoint)) {
26658
+ const credential = asReadableCredential(parsed2);
26659
+ if (credential === null) return { usable: false, reason: "malformed" };
26660
+ if (!isSafeEndpoint(credential.endpoint)) {
26548
26661
  return { usable: false, reason: "unsafe-endpoint" };
26549
26662
  }
26550
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
26663
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26551
26664
  return {
26552
26665
  usable: false,
26553
26666
  reason: "endpoint-mismatch",
26554
- credentialEndpoint: result.data.endpoint,
26667
+ credentialEndpoint: credential.endpoint,
26555
26668
  settingsEndpoint: connection.endpoint
26556
26669
  };
26557
26670
  }
26558
- return { usable: true, credential: result.data };
26671
+ return { usable: true, credential };
26559
26672
  }
26560
26673
  function readControlPlaneCredential(settingsDir2, connection) {
26561
26674
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26564,7 +26677,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26564
26677
 
26565
26678
  // ../../packages/persistence/src/database.ts
26566
26679
  import { randomUUID as randomUUID11 } from "crypto";
26567
- import { dirname as dirname2, join as join7, sep } from "path";
26680
+ import { dirname as dirname2, join as join8, sep } from "path";
26568
26681
  import { DatabaseSync } from "node:sqlite";
26569
26682
 
26570
26683
  // ../../packages/persistence/src/ids.ts
@@ -26618,6 +26731,7 @@ function uuidFromDigest(digest) {
26618
26731
  function captureWireId(sessionId, contentHash, filePath = null) {
26619
26732
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26620
26733
  }
26734
+ var DOT = ".".charCodeAt(0);
26621
26735
 
26622
26736
  // ../../packages/persistence/src/internal/snapshot.ts
26623
26737
  import { randomUUID } from "crypto";
@@ -26945,6 +27059,25 @@ function scopeKeysParam(scopeKeys) {
26945
27059
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26946
27060
  FROM audit_events AS session_root
26947
27061
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
27062
+ var COUNTED_IN_SCOPE = `
27063
+ AND ${inScope("scope_key")}
27064
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
27065
+ var DRAIN_TOTALS = `SELECT
27066
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27067
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27068
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27069
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27070
+ THEN 1 ELSE 0 END) AS skipped,
27071
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27072
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27073
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27074
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27075
+ FROM audit_events
27076
+ WHERE event_type IN (${TYPE_LIST})`;
27077
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
27078
+ FROM audit_events
27079
+ WHERE synced_at = ${String(SKIPPED)}
27080
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26948
27081
  var ROW_COLUMNS = `id,
26949
27082
  parent_id AS parentId,
26950
27083
  root_session_id AS rootSessionId,
@@ -27020,7 +27153,7 @@ var SqliteHistorySyncRepository = class {
27020
27153
  );
27021
27154
  this.scopedCaptureRowsStmt = db.prepare(
27022
27155
  `SELECT ${ROW_COLUMNS}
27023
- FROM audit_events
27156
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27024
27157
  WHERE synced_at IS NULL
27025
27158
  AND sync_claimed_at IS NULL
27026
27159
  AND outbox_owed = 1
@@ -27073,40 +27206,28 @@ var SqliteHistorySyncRepository = class {
27073
27206
  );
27074
27207
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27075
27208
  FROM audit_events${COUNTED_SCOPE}`);
27209
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27210
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27076
27211
  this.partitionByKindStmt = db.prepare(
27077
27212
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27078
27213
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27079
27214
  GROUP BY event_type`
27080
27215
  );
27081
- this.countsStmt = db.prepare(
27082
- `SELECT
27083
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27084
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27085
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27086
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27087
- THEN 1 ELSE 0 END) AS skipped,
27088
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27089
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27090
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27091
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27092
- FROM audit_events
27093
- WHERE event_type IN (${TYPE_LIST})`
27094
- );
27095
- this.captureSkipCountStmt = db.prepare(
27096
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27097
- // way the structural totals are. The split exists because a refusal is
27098
- // terminal only against the deployment that gave it, and the structural
27099
- // re-arm frees it on a change of deployment. The capture lane has no such
27100
- // escape: re-arming a capture would offer one deployment's undelivered
27101
- // prompts, with their text, to a deployment that never saw them, which is
27102
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27103
- // reasons mean the same thing — this row will not be sent — and splitting
27104
- // them would put refused captures in a bucket nothing reads and nothing
27105
- // frees.
27106
- `SELECT COUNT(*) AS skipped
27107
- FROM audit_events
27108
- WHERE synced_at = ${String(SKIPPED)}
27109
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27216
+ this.scopedPartitionByKindStmt = db.prepare(
27217
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
27218
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
27219
+ GROUP BY event_type`
27220
+ );
27221
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
27222
+ this.scopedCountsStmt = db.prepare(
27223
+ `${DRAIN_TOTALS}
27224
+ AND ${inScope("scope_key")}
27225
+ AND ${inScope(ROOT_SCOPE_KEY)}`
27226
+ );
27227
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
27228
+ this.scopedCaptureSkipCountStmt = db.prepare(
27229
+ `${CAPTURE_SKIPS}
27230
+ AND ${inScope("scope_key")}`
27110
27231
  );
27111
27232
  this.fingerprintStmt = db.prepare(
27112
27233
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27220,6 +27341,10 @@ var SqliteHistorySyncRepository = class {
27220
27341
  scopedCaptureRowsStmt;
27221
27342
  scopedCaptureBacklogOwedStmt;
27222
27343
  markScopeCapturesOwedStmt;
27344
+ scopedPartitionStmt;
27345
+ scopedPartitionByKindStmt;
27346
+ scopedCountsStmt;
27347
+ scopedCaptureSkipCountStmt;
27223
27348
  /**
27224
27349
  * The masked detections recorded against one tool call.
27225
27350
  *
@@ -27441,7 +27566,29 @@ var SqliteHistorySyncRepository = class {
27441
27566
  * in" — and a machine that has never attached has no boundary to pass, so
27442
27567
  * requiring one would force a caller to invent one and report the whole store
27443
27568
  * as queued.
27569
+ *
27570
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
27571
+ * the rows that pass the drain's reachability rule for that scope
27572
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
27573
+ * drain never offers), so a personal repository's rows are in none of them.
27574
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
27575
+ * nothing.
27444
27576
  */
27577
+ partition(scopeKeys) {
27578
+ const row = getRow(
27579
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
27580
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27581
+ );
27582
+ return {
27583
+ queued: row?.queued ?? 0,
27584
+ inProgress: row?.inProgress ?? 0,
27585
+ synced: row?.synced ?? 0,
27586
+ failed: row?.failed ?? 0,
27587
+ refused: row?.refused ?? 0,
27588
+ detached: row?.detached ?? 0,
27589
+ total: row?.total ?? 0
27590
+ };
27591
+ }
27445
27592
  /**
27446
27593
  * The same partition, one row per kind that a lane carries.
27447
27594
  *
@@ -27451,11 +27598,14 @@ var SqliteHistorySyncRepository = class {
27451
27598
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27452
27599
  * rows", never as "zero sent"; the two look identical in a bar and mean
27453
27600
  * different things.
27601
+ *
27602
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
27603
+ * still sum to the scoped aggregate. An empty list returns no rows.
27454
27604
  */
27455
- partitionByKind() {
27605
+ partitionByKind(scopeKeys) {
27456
27606
  return allRows(
27457
- this.partitionByKindStmt,
27458
- {}
27607
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
27608
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27459
27609
  ).map((row) => ({
27460
27610
  kind: row.kind,
27461
27611
  queued: row.queued ?? 0,
@@ -27467,22 +27617,25 @@ var SqliteHistorySyncRepository = class {
27467
27617
  total: row.total ?? 0
27468
27618
  }));
27469
27619
  }
27470
- partition() {
27471
- const row = getRow(this.partitionStmt, {});
27472
- return {
27473
- queued: row?.queued ?? 0,
27474
- inProgress: row?.inProgress ?? 0,
27475
- synced: row?.synced ?? 0,
27476
- failed: row?.failed ?? 0,
27477
- refused: row?.refused ?? 0,
27478
- detached: row?.detached ?? 0,
27479
- total: row?.total ?? 0
27480
- };
27481
- }
27482
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27483
- counts(before) {
27484
- const row = getRow(this.countsStmt, { before });
27485
- const captures = getRow(this.captureSkipCountStmt);
27620
+ /**
27621
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
27622
+ * and skipped are totals.
27623
+ *
27624
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
27625
+ * `capturesSkipped` included: a structural row is counted only when its own
27626
+ * key and its session root's key are among them, a capture when its own key
27627
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
27628
+ * under the same keys and boundary. Omitted, this runs the machine
27629
+ * statements, unchanged; an empty list counts nothing.
27630
+ */
27631
+ counts(before, scopeKeys) {
27632
+ const row = getRow(
27633
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
27634
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
27635
+ );
27636
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
27637
+ scopeKeys: scopeKeysParam(scopeKeys)
27638
+ });
27486
27639
  return {
27487
27640
  pending: row?.pending ?? 0,
27488
27641
  sent: row?.sent ?? 0,
@@ -27734,6 +27887,7 @@ function applyMigrations(db, file2, options = {}) {
27734
27887
  }
27735
27888
  ensureSyncedAtColumn(db, "audit_events");
27736
27889
  ensureScopeKeyColumn(db);
27890
+ ensureScopeOwedIndex(db);
27737
27891
  ensureScanLedgerTable(db);
27738
27892
  ensureHistorySyncTable(db);
27739
27893
  ensureBlockedDetectionsTable(db);
@@ -28174,14 +28328,48 @@ function ensureScopeKeyColumn(db) {
28174
28328
  function hasScopeKeyColumn(db) {
28175
28329
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28176
28330
  }
28331
+ 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";
28332
+ function ensureScopeOwedIndex(db) {
28333
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
28334
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
28335
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
28336
+ if (!complete) return;
28337
+ db.exec(SCOPE_OWED_INDEX_DDL);
28338
+ }
28177
28339
  function ensureScanLedgerTable(db) {
28178
28340
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28179
28341
  path TEXT PRIMARY KEY,
28180
28342
  mtime TEXT NOT NULL,
28181
28343
  content_hash TEXT NOT NULL,
28182
28344
  ruleset_hash TEXT NOT NULL,
28183
- scanned_at INTEGER NOT NULL
28345
+ scanned_at INTEGER NOT NULL,
28346
+ scope_key TEXT,
28347
+ scope_root TEXT
28184
28348
  )`);
28349
+ ensureScanLedgerScopeKeyColumn(db);
28350
+ ensureScanLedgerScopeRootColumn(db);
28351
+ }
28352
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
28353
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
28354
+ function ensureScanLedgerScopeKeyColumn(db) {
28355
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
28356
+ }
28357
+ function ensureScanLedgerScopeRootColumn(db) {
28358
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
28359
+ }
28360
+ function ensureScanLedgerColumn(db, column, ddl) {
28361
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
28362
+ if (hasScanLedgerColumn(db, column)) return;
28363
+ withTransaction(
28364
+ db,
28365
+ () => {
28366
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
28367
+ },
28368
+ "IMMEDIATE"
28369
+ );
28370
+ }
28371
+ function hasScanLedgerColumn(db, column) {
28372
+ return columnNames(db, "scan_ledger").includes(column);
28185
28373
  }
28186
28374
  function ensureHistorySyncTable(db) {
28187
28375
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28232,6 +28420,106 @@ function ensureRuleProbeCacheTable(db) {
28232
28420
  )`);
28233
28421
  }
28234
28422
 
28423
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
28424
+ import { createHash as createHash2 } from "crypto";
28425
+ import { readFileSync as readFileSync2 } from "fs";
28426
+ import { join as join4 } from "path";
28427
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
28428
+ function modPolicySnapshotPath(dataDir2) {
28429
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
28430
+ }
28431
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
28432
+ const byRule = /* @__PURE__ */ new Map();
28433
+ const byCategory = /* @__PURE__ */ new Map();
28434
+ for (const policy of input2.policies) {
28435
+ if (!policy.enabled) continue;
28436
+ if ("ruleId" in policy.target) {
28437
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
28438
+ } else if (!byCategory.has(policy.target.category)) {
28439
+ byCategory.set(policy.target.category, policy.action);
28440
+ }
28441
+ }
28442
+ const categoryActions = {};
28443
+ for (const category of DetectionCategory.options) {
28444
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
28445
+ }
28446
+ return {
28447
+ version: MOD_POLICY_SNAPSHOT_VERSION,
28448
+ generatedAt: generatedAt.toISOString(),
28449
+ // `examples` is documentation the mod never reads, and a custom pack's are
28450
+ // whatever its author pasted in, so they stay behind.
28451
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
28452
+ ruleActions: Object.fromEntries(byRule),
28453
+ categoryActions,
28454
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
28455
+ };
28456
+ }
28457
+ function assignedRuleActionPolicies(installed) {
28458
+ const out = [];
28459
+ for (const [ruleId, action] of installed.ruleActions) {
28460
+ if (installed.assignedRules.has(ruleId))
28461
+ out.push({ target: { ruleId }, action, enabled: true });
28462
+ }
28463
+ return out;
28464
+ }
28465
+ function withoutExamples(rule) {
28466
+ const copy = { ...rule };
28467
+ delete copy.examples;
28468
+ return copy;
28469
+ }
28470
+ function sameContent(a, b) {
28471
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
28472
+ }
28473
+ function readModPolicySnapshot(dataDir2) {
28474
+ try {
28475
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
28476
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
28477
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
28478
+ return parsed2.success ? parsed2.data : null;
28479
+ } catch {
28480
+ return null;
28481
+ }
28482
+ }
28483
+ function writeModPolicySnapshot(dataDir2, snapshot) {
28484
+ const text = JSON.stringify(snapshot);
28485
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
28486
+ const existing = readModPolicySnapshot(dataDir2);
28487
+ if (existing !== null && sameContent(existing, snapshot)) return false;
28488
+ ensureDataDirSync(dataDir2);
28489
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
28490
+ return true;
28491
+ }
28492
+ function regexProbeKey(matcher) {
28493
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
28494
+ }
28495
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28496
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
28497
+ return rules.filter((rule) => {
28498
+ if (rule.matcher.type !== "regex") return true;
28499
+ const key = regexProbeKey(rule.matcher);
28500
+ const verdict = sources.probeVerdict(key);
28501
+ if (verdict === "quarantined") return false;
28502
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
28503
+ });
28504
+ }
28505
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28506
+ const policies = sources.readPolicies();
28507
+ const snapshot = sources.installedRuleset();
28508
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
28509
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
28510
+ return {
28511
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
28512
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
28513
+ exceptionRuleIds: sources.activeExceptionRuleIds()
28514
+ };
28515
+ }
28516
+ function refreshModPolicySnapshot(dataDir2, sources) {
28517
+ try {
28518
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
28519
+ } catch {
28520
+ }
28521
+ }
28522
+
28235
28523
  // ../../packages/persistence/src/internal/json.ts
28236
28524
  function safeJson(s, fallback) {
28237
28525
  if (s == null) return fallback;
@@ -28406,6 +28694,11 @@ var TIMELINE_COLUMNS = `
28406
28694
  json_extract(attributes, '$.targetId') AS target_id,
28407
28695
  json_extract(attributes, '$.internal') AS internal,
28408
28696
  json_extract(attributes, '$.flagged') AS flagged`;
28697
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
28698
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
28699
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
28700
+ " + "
28701
+ );
28409
28702
  var LLM_USAGE_SELECT = `
28410
28703
  SELECT root_session_id AS sessionId,
28411
28704
  provider,
@@ -28417,9 +28710,10 @@ var LLM_USAGE_SELECT = `
28417
28710
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28418
28711
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28419
28712
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28420
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
28713
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
28714
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28421
28715
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28422
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
28716
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28423
28717
  function usageLeaves(rows) {
28424
28718
  return rows.map((row) => {
28425
28719
  const attributes = {
@@ -28434,7 +28728,7 @@ function usageLeaves(rows) {
28434
28728
  if (row.provider !== null) attributes.provider = row.provider;
28435
28729
  if (row.model !== null) attributes.model = row.model;
28436
28730
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28437
- return { sessionId: row.sessionId, attributes };
28731
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28438
28732
  });
28439
28733
  }
28440
28734
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29768,9 +30062,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29768
30062
  AND conditions IS NULL
29769
30063
  AND ${ACTIVE_PREDICATE}`;
29770
30064
  var SqliteExceptionsRepository = class {
29771
- constructor(db, now = () => Date.now()) {
30065
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29772
30066
  this.db = db;
29773
30067
  this.now = now;
30068
+ this.onChange = onChange;
29774
30069
  this.consumeStmt = db.prepare(
29775
30070
  `UPDATE exceptions
29776
30071
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29789,6 +30084,7 @@ var SqliteExceptionsRepository = class {
29789
30084
  }
29790
30085
  db;
29791
30086
  now;
30087
+ onChange;
29792
30088
  consumeStmt;
29793
30089
  insertBlockedStmt;
29794
30090
  sweepBlockedStmt;
@@ -29804,7 +30100,9 @@ var SqliteExceptionsRepository = class {
29804
30100
  */
29805
30101
  create(input2) {
29806
30102
  try {
29807
- return Promise.resolve(this.createSync(input2));
30103
+ const created = this.createSync(input2);
30104
+ this.onChange();
30105
+ return Promise.resolve(created);
29808
30106
  } catch (err) {
29809
30107
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29810
30108
  }
@@ -29935,6 +30233,7 @@ var SqliteExceptionsRepository = class {
29935
30233
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29936
30234
  WHERE id = :id AND revoked_at IS NULL`
29937
30235
  ).run({ id, revokedBy, reason: reason ?? null, now });
30236
+ if (Number(result.changes) === 1) this.onChange();
29938
30237
  return Promise.resolve(Number(result.changes) === 1);
29939
30238
  }
29940
30239
  /**
@@ -29947,6 +30246,15 @@ var SqliteExceptionsRepository = class {
29947
30246
  const result = this.consumeStmt.run({ id, now });
29948
30247
  return Promise.resolve(Number(result.changes) === 1);
29949
30248
  }
30249
+ /** The rule ids with at least one active grant, under any key version. */
30250
+ activeRuleIds(now = this.now()) {
30251
+ return allRows(
30252
+ this.db.prepare(
30253
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
30254
+ ),
30255
+ { now }
30256
+ ).map((row) => row.ruleId);
30257
+ }
29950
30258
  /**
29951
30259
  * The evaluation subset of every active grant under one fingerprint key
29952
30260
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31070,28 +31378,28 @@ var SqliteInspectionFindingsRepository = class {
31070
31378
  };
31071
31379
 
31072
31380
  // ../../packages/persistence/src/repositories/installed-packs.ts
31073
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
31381
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31074
31382
 
31075
31383
  // ../../packages/persistence/src/policy-floor.ts
31076
- import { readFileSync as readFileSync5 } from "fs";
31077
- import { join as join6 } from "path";
31384
+ import { readFileSync as readFileSync6 } from "fs";
31385
+ import { join as join7 } from "path";
31078
31386
 
31079
31387
  // ../../packages/persistence/src/local-layout.ts
31080
31388
  import { renameSync as renameSync3 } from "fs";
31081
31389
  import { mkdir } from "fs/promises";
31082
31390
  import { homedir } from "os";
31083
- import { join as join4 } from "path";
31391
+ import { join as join5 } from "path";
31084
31392
  function defaultDataDir() {
31085
- return join4(homedir(), ".aka");
31393
+ return join5(homedir(), ".aka");
31086
31394
  }
31087
31395
  function settingsDir(base = defaultDataDir()) {
31088
- return join4(base, "settings");
31396
+ return join5(base, "settings");
31089
31397
  }
31090
31398
  function dataDir(base = defaultDataDir()) {
31091
- return join4(base, "data");
31399
+ return join5(base, "data");
31092
31400
  }
31093
31401
  function dbPath(base = defaultDataDir()) {
31094
- return join4(dataDir(base), "aka.db");
31402
+ return join5(dataDir(base), "aka.db");
31095
31403
  }
31096
31404
  async function ensureDataDir(dir = defaultDataDir()) {
31097
31405
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31108,8 +31416,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31108
31416
  for (const { name, dest } of moves) {
31109
31417
  try {
31110
31418
  ensureDataDirSync(dest);
31111
- const moved = join4(dest, name);
31112
- renameSync3(join4(base, name), moved);
31419
+ const moved = join5(dest, name);
31420
+ renameSync3(join5(base, name), moved);
31113
31421
  tightenFile(moved);
31114
31422
  } catch {
31115
31423
  }
@@ -31117,8 +31425,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31117
31425
  }
31118
31426
 
31119
31427
  // ../../packages/persistence/src/settings.ts
31120
- import { readFileSync as readFileSync4 } from "fs";
31121
- import { join as join5 } from "path";
31428
+ import { readFileSync as readFileSync5 } from "fs";
31429
+ import { join as join6 } from "path";
31122
31430
 
31123
31431
  // ../../packages/persistence/src/file-lock.ts
31124
31432
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31126,7 +31434,7 @@ import {
31126
31434
  closeSync,
31127
31435
  existsSync as existsSync2,
31128
31436
  openSync,
31129
- readFileSync as readFileSync2,
31437
+ readFileSync as readFileSync3,
31130
31438
  rmSync as rmSync5,
31131
31439
  statSync as statSync3,
31132
31440
  writeFileSync as writeFileSync2
@@ -31135,16 +31443,16 @@ import { hostname as hostname3 } from "os";
31135
31443
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31136
31444
 
31137
31445
  // ../../packages/persistence/src/managed-settings.ts
31138
- import { readFileSync as readFileSync3 } from "fs";
31446
+ import { readFileSync as readFileSync4 } from "fs";
31139
31447
  import { posix, win32 } from "path";
31140
- function managedSettingsPaths(platform2 = process.platform) {
31141
- if (platform2 === "darwin") {
31448
+ function managedSettingsPaths(platform = process.platform) {
31449
+ if (platform === "darwin") {
31142
31450
  return [
31143
31451
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31144
31452
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31145
31453
  ];
31146
31454
  }
31147
- if (platform2 === "win32") {
31455
+ if (platform === "win32") {
31148
31456
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31149
31457
  }
31150
31458
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -31154,7 +31462,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31154
31462
  for (const path of paths) {
31155
31463
  let text;
31156
31464
  try {
31157
- text = readFileSync3(path, "utf8");
31465
+ text = readFileSync4(path, "utf8");
31158
31466
  } catch {
31159
31467
  continue;
31160
31468
  }
@@ -31208,7 +31516,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31208
31516
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31209
31517
  }
31210
31518
  function readUserSettings(base) {
31211
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
31519
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31212
31520
  if (!record2) return defaultWorkspaceSettings();
31213
31521
  try {
31214
31522
  return WorkspaceSettings.parse(record2);
@@ -31219,7 +31527,7 @@ function readUserSettings(base) {
31219
31527
  function readJson(file2) {
31220
31528
  let text;
31221
31529
  try {
31222
- text = readFileSync4(file2, "utf8");
31530
+ text = readFileSync5(file2, "utf8");
31223
31531
  } catch {
31224
31532
  return null;
31225
31533
  }
@@ -31259,7 +31567,7 @@ var PolicyFloorError = class extends Error {
31259
31567
  };
31260
31568
  function readCachedPolicyBundle(base = defaultDataDir()) {
31261
31569
  try {
31262
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31570
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31263
31571
  const parsed2 = JSON.parse(raw);
31264
31572
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31265
31573
  return PolicyBundle.parse(parsed2.bundle);
@@ -31383,7 +31691,7 @@ function inventorySignature(packs2) {
31383
31691
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31384
31692
  }
31385
31693
  function hashRules(rulesJson) {
31386
- return createHash2("sha256").update(rulesJson).digest("hex");
31694
+ return createHash3("sha256").update(rulesJson).digest("hex");
31387
31695
  }
31388
31696
  function parseVersion(v) {
31389
31697
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31425,9 +31733,10 @@ var SqliteInstalledPacksRepository = class {
31425
31733
  * from `openLocalDatabase`, which is the single construction site that owns a
31426
31734
  * real `~/.aka`.
31427
31735
  */
31428
- constructor(db, baseDir) {
31736
+ constructor(db, baseDir, onChange = () => void 0) {
31429
31737
  this.db = db;
31430
31738
  this.baseDir = baseDir;
31739
+ this.onChange = onChange;
31431
31740
  this.insertMissingStmt = db.prepare(
31432
31741
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31433
31742
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31456,6 +31765,7 @@ var SqliteInstalledPacksRepository = class {
31456
31765
  }
31457
31766
  db;
31458
31767
  baseDir;
31768
+ onChange;
31459
31769
  insertMissingStmt;
31460
31770
  upsertAvailableStmt;
31461
31771
  signatureStmt;
@@ -31528,6 +31838,7 @@ var SqliteInstalledPacksRepository = class {
31528
31838
  },
31529
31839
  "IMMEDIATE"
31530
31840
  );
31841
+ this.onChange();
31531
31842
  } catch {
31532
31843
  }
31533
31844
  }
@@ -31602,6 +31913,7 @@ var SqliteInstalledPacksRepository = class {
31602
31913
  },
31603
31914
  "IMMEDIATE"
31604
31915
  );
31916
+ if (changed) this.onChange();
31605
31917
  return changed;
31606
31918
  }
31607
31919
  /**
@@ -31843,6 +32155,7 @@ var SqliteInstalledPacksRepository = class {
31843
32155
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31844
32156
  WHERE namespace = :namespace AND pack_id = :packId`
31845
32157
  ).run({ policyId, now: Date.now(), namespace, packId });
32158
+ if (Number(res.changes) > 0) this.onChange();
31846
32159
  return Number(res.changes) > 0;
31847
32160
  }
31848
32161
  /**
@@ -31867,6 +32180,7 @@ var SqliteInstalledPacksRepository = class {
31867
32180
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31868
32181
  WHERE namespace = :namespace AND pack_id = :packId`
31869
32182
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
32183
+ if (Number(res.changes) > 0) this.onChange();
31870
32184
  return Number(res.changes) > 0;
31871
32185
  }
31872
32186
  // Fingerprint of the recorded available mirror — compared against the
@@ -32764,13 +33078,19 @@ var SqliteInventoryAssetsRepository = class {
32764
33078
  import { randomUUID as randomUUID6 } from "crypto";
32765
33079
  var SEED_BATCH_WINDOW_MS = 6e4;
32766
33080
  var SqlitePoliciesRepository = class {
32767
- constructor(db) {
33081
+ constructor(db, onChange = () => void 0) {
32768
33082
  this.db = db;
33083
+ this.onChange = onChange;
32769
33084
  }
32770
33085
  db;
33086
+ onChange;
32771
33087
  readPolicies() {
33088
+ return Promise.resolve(this.listPolicies());
33089
+ }
33090
+ /** The synchronous read behind {@link readPolicies}. */
33091
+ listPolicies() {
32772
33092
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32773
- const policies = mapRowsTolerant(rows, (row) => {
33093
+ return mapRowsTolerant(rows, (row) => {
32774
33094
  const target = JSON.parse(row.target);
32775
33095
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32776
33096
  return Policy.parse({
@@ -32782,7 +33102,6 @@ var SqlitePoliciesRepository = class {
32782
33102
  customKeywords
32783
33103
  });
32784
33104
  });
32785
- return Promise.resolve(policies);
32786
33105
  }
32787
33106
  // Seed one policy per bundled category at Monitor so the detection-type config
32788
33107
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32793,7 +33112,7 @@ var SqlitePoliciesRepository = class {
32793
33112
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32794
33113
  if (count > 0) {
32795
33114
  this.markEarlierChoices();
32796
- this.monitorUntouchedSeeds();
33115
+ if (this.monitorUntouchedSeeds()) this.onChange();
32797
33116
  return;
32798
33117
  }
32799
33118
  const stmt = this.db.prepare(
@@ -32810,6 +33129,7 @@ var SqlitePoliciesRepository = class {
32810
33129
  });
32811
33130
  }
32812
33131
  });
33132
+ this.onChange();
32813
33133
  }
32814
33134
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32815
33135
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32875,7 +33195,7 @@ var SqlitePoliciesRepository = class {
32875
33195
  ).filter(
32876
33196
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32877
33197
  );
32878
- if (untouched.length === 0) return;
33198
+ if (untouched.length === 0) return false;
32879
33199
  const stmt = this.db.prepare(
32880
33200
  `UPDATE policies SET action = 'log'
32881
33201
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32886,6 +33206,7 @@ var SqlitePoliciesRepository = class {
32886
33206
  stmt.run({ category: row.category, seeded: row.action });
32887
33207
  }
32888
33208
  });
33209
+ return true;
32889
33210
  }
32890
33211
  // Insert-or-update the single global per-category policy row, keyed on the
32891
33212
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32902,6 +33223,7 @@ var SqlitePoliciesRepository = class {
32902
33223
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32903
33224
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32904
33225
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
33226
+ this.onChange();
32905
33227
  }
32906
33228
  // Caps every global per-category policy currently set to block/redact down
32907
33229
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32912,6 +33234,7 @@ var SqlitePoliciesRepository = class {
32912
33234
  WHERE scope='global' AND action IN ('block','redact')
32913
33235
  AND json_extract(target,'$.category') IS NOT NULL`
32914
33236
  ).run({ now: Date.now() });
33237
+ if (Number(info.changes) > 0) this.onChange();
32915
33238
  return Number(info.changes);
32916
33239
  }
32917
33240
  // Whether the category's row was ever written after it was created — by the
@@ -33231,31 +33554,45 @@ var SqliteScanLedgerRepository = class {
33231
33554
  constructor(db) {
33232
33555
  this.db = db;
33233
33556
  this.upsertStmt = db.prepare(
33234
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33235
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
33557
+ `INSERT INTO scan_ledger
33558
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
33559
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33236
33560
  ON CONFLICT (path) DO UPDATE SET
33237
33561
  mtime = excluded.mtime,
33238
33562
  content_hash = excluded.content_hash,
33239
33563
  ruleset_hash = excluded.ruleset_hash,
33564
+ scope_key = excluded.scope_key,
33565
+ scope_root = excluded.scope_root,
33240
33566
  scanned_at = excluded.scanned_at`
33241
33567
  );
33242
33568
  this.readStmt = db.prepare(
33243
- `SELECT path, mtime, content_hash AS contentHash
33569
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
33570
+ scope_root AS scopeRoot
33244
33571
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33245
33572
  );
33246
33573
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
33574
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33247
33575
  }
33248
33576
  db;
33249
33577
  upsertStmt;
33250
33578
  readStmt;
33251
33579
  pathsStmt;
33580
+ pathKeysStmt;
33252
33581
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33253
33582
  // older ruleset are simply absent, which reads as "never scanned".
33254
33583
  entriesForRuleset(rulesetHash) {
33255
- const rows = allRows(this.readStmt, {
33256
- rulesetHash
33257
- });
33258
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
33584
+ const rows = allRows(this.readStmt, { rulesetHash });
33585
+ return new Map(
33586
+ rows.map((r) => [
33587
+ r.path,
33588
+ {
33589
+ mtime: r.mtime,
33590
+ contentHash: r.contentHash,
33591
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
33592
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
33593
+ }
33594
+ ])
33595
+ );
33259
33596
  }
33260
33597
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33261
33598
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33264,6 +33601,14 @@ var SqliteScanLedgerRepository = class {
33264
33601
  allPaths() {
33265
33602
  return allRows(this.pathsStmt).map((r) => r.path);
33266
33603
  }
33604
+ // Every ledgered path with the repository it was in when it was last read,
33605
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
33606
+ // which repository a vanished file belonged to. `undefined` for a row with no
33607
+ // key, which is every row written before the column existed.
33608
+ pathKeys() {
33609
+ const rows = allRows(this.pathKeysStmt);
33610
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
33611
+ }
33267
33612
  upsertEntries(entries) {
33268
33613
  if (entries.length === 0) return;
33269
33614
  const scannedAt = Date.now();
@@ -33274,6 +33619,8 @@ var SqliteScanLedgerRepository = class {
33274
33619
  mtime: entry.mtime,
33275
33620
  contentHash: entry.contentHash,
33276
33621
  rulesetHash: entry.rulesetHash,
33622
+ scopeKey: entry.scopeKey ?? null,
33623
+ scopeRoot: entry.scopeRoot ?? null,
33277
33624
  scannedAt
33278
33625
  });
33279
33626
  }
@@ -34361,6 +34708,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34361
34708
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34362
34709
  };
34363
34710
  }
34711
+ function withoutTrailingSlashes(path) {
34712
+ let end = path.length;
34713
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
34714
+ return path.slice(0, end);
34715
+ }
34364
34716
  function toEndpointSummary(row) {
34365
34717
  return {
34366
34718
  id: row.id,
@@ -34648,7 +35000,7 @@ var SqliteSharesRepository = class {
34648
35000
  */
34649
35001
  reconcileCallSites(projectKey, reconcile) {
34650
35002
  if (reconcile.mode === "walk") {
34651
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
35003
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34652
35004
  this.db.prepare(
34653
35005
  `DELETE FROM share_call_site
34654
35006
  WHERE project_key = :key
@@ -35216,7 +35568,7 @@ function backupLegacyStore(db, file2) {
35216
35568
  discardStore(file2, backup);
35217
35569
  return backup;
35218
35570
  }
35219
- function openAndInitialize(file2, base, skipTags) {
35571
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35220
35572
  let db = openWithPragmas(file2);
35221
35573
  try {
35222
35574
  if (isForeignSqliteLineage(db)) {
@@ -35228,8 +35580,15 @@ function openAndInitialize(file2, base, skipTags) {
35228
35580
  }
35229
35581
  applyMigrations(db, file2, { skipTags });
35230
35582
  tightenPerms(file2);
35231
- const policies = new SqlitePoliciesRepository(db);
35232
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
35583
+ const modPolicy = {};
35584
+ const onPolicyStateChange = () => {
35585
+ if (modPolicy.current !== void 0)
35586
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
35587
+ };
35588
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
35589
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
35590
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
35591
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35233
35592
  const repositories = {
35234
35593
  events: new SqliteEventsRepository(db),
35235
35594
  findings: new SqliteFindingsRepository(db),
@@ -35238,9 +35597,9 @@ function openAndInitialize(file2, base, skipTags) {
35238
35597
  scanLedger: new SqliteScanLedgerRepository(db),
35239
35598
  historySync: new SqliteHistorySyncRepository(db),
35240
35599
  secretVault: new SqliteSecretVaultRepository(db),
35241
- exceptions: new SqliteExceptionsRepository(db),
35600
+ exceptions,
35242
35601
  resolutions: new SqliteResolutionsRepository(db),
35243
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
35602
+ ruleProbeCache,
35244
35603
  bodyRetention: new SqliteBodyRetentionRepository(db),
35245
35604
  security: new SqliteSecurityRepository(db),
35246
35605
  detections: new SqliteDetectionsRepository(db),
@@ -35258,6 +35617,13 @@ function openAndInitialize(file2, base, skipTags) {
35258
35617
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35259
35618
  configInventory: new SqliteConfigInventoryRepository(db)
35260
35619
  };
35620
+ modPolicy.current = {
35621
+ installedRuleset: () => installedPacks.installedRuleset(),
35622
+ readPolicies: () => policies.listPolicies(),
35623
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
35624
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
35625
+ bundledRegexMatchers: () => shippedRegexMatchers2
35626
+ };
35261
35627
  policies.seedDefaults();
35262
35628
  return { db, ...repositories };
35263
35629
  } catch (err) {
@@ -35269,7 +35635,7 @@ function openAndInitialize(file2, base, skipTags) {
35269
35635
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35270
35636
  function openLocalDatabase(dir, options = {}) {
35271
35637
  ensureDataDirSync(dir);
35272
- const file2 = join7(dir, DB_FILENAME);
35638
+ const file2 = join8(dir, DB_FILENAME);
35273
35639
  reapStalePartials(file2);
35274
35640
  const {
35275
35641
  db,
@@ -35305,7 +35671,8 @@ function openLocalDatabase(dir, options = {}) {
35305
35671
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35306
35672
  // settings/ and data/, and the pack-policy floor needs both halves.
35307
35673
  dirname2(dir),
35308
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
35674
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
35675
+ options.shippedRegexMatchers ?? []
35309
35676
  );
35310
35677
  function captureRowId(event) {
35311
35678
  return captureId(
@@ -35570,7 +35937,7 @@ function openLocalDatabase(dir, options = {}) {
35570
35937
  }
35571
35938
 
35572
35939
  // ../../packages/persistence/src/egress-wire.ts
35573
- import { createHash as createHash3 } from "crypto";
35940
+ import { createHash as createHash4 } from "crypto";
35574
35941
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35575
35942
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35576
35943
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35602,7 +35969,7 @@ function canonicalGitUrl(url2) {
35602
35969
  }
35603
35970
  function hashProjectKey(projectKey) {
35604
35971
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35605
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35972
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35606
35973
  }
35607
35974
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35608
35975
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35667,24 +36034,23 @@ function toEgressIngestRequest(input2) {
35667
36034
  }
35668
36035
 
35669
36036
  // ../../packages/persistence/src/finding-key.ts
35670
- import { createHash as createHash4 } from "crypto";
36037
+ import { createHash as createHash5 } from "crypto";
35671
36038
  function normalizeFilePath(filePath) {
35672
36039
  return filePath.replaceAll("\\", "/");
35673
36040
  }
35674
36041
  function computeFindingKey(input2) {
35675
36042
  const normalizedPath = normalizeFilePath(input2.filePath);
35676
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
36043
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35677
36044
  }
35678
36045
 
35679
36046
  // ../../packages/persistence/src/fingerprint.ts
35680
36047
  import { createHmac, randomBytes } from "crypto";
35681
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35682
- import { join as join8 } from "path";
35683
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
36048
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
36049
+ import { join as join9 } from "path";
35684
36050
  var EXCEPTION_KEY_FILENAME = "exception.key";
35685
36051
  var KEY_MATERIAL_BYTES = 32;
35686
36052
  function keyFilePath(dataDir2) {
35687
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
36053
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35688
36054
  }
35689
36055
  function parseKeyFile(raw) {
35690
36056
  const parsed2 = JSON.parse(raw);
@@ -35711,6 +36077,12 @@ var KEY_VERSION_COLUMNS = {
35711
36077
  };
35712
36078
  var SQLITE_ERROR2 = 1;
35713
36079
  var FLOOR_BUSY_TIMEOUT_MS = 250;
36080
+ function openReadOnly(file2) {
36081
+ const host = process;
36082
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
36083
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
36084
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
36085
+ }
35714
36086
  var FloorUnreadableError = class extends Error {
35715
36087
  code = "floor-unreadable";
35716
36088
  constructor(cause) {
@@ -35722,11 +36094,11 @@ var FloorUnreadableError = class extends Error {
35722
36094
  }
35723
36095
  };
35724
36096
  function storedKeyVersionFloor(dataDir2) {
35725
- const file2 = join8(dataDir2, DB_FILENAME);
36097
+ const file2 = join9(dataDir2, DB_FILENAME);
35726
36098
  if (!existsSync3(file2)) return 0;
35727
36099
  let db;
35728
36100
  try {
35729
- db = new DatabaseSync2(file2, { readOnly: true });
36101
+ db = openReadOnly(file2);
35730
36102
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35731
36103
  let floor = 0;
35732
36104
  for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35777,7 +36149,7 @@ function occupantMessage(file2, kind) {
35777
36149
  function readFingerprintKey(dataDir2) {
35778
36150
  let raw;
35779
36151
  try {
35780
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
36152
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35781
36153
  } catch (err) {
35782
36154
  if (err.code === "ENOENT") return null;
35783
36155
  throw err instanceof Error ? err : new Error(String(err));
@@ -35803,8 +36175,8 @@ function exactFingerprintValue(key, raw) {
35803
36175
  }
35804
36176
 
35805
36177
  // ../../packages/persistence/src/forward-health.ts
35806
- import { readFileSync as readFileSync7 } from "fs";
35807
- import { join as join9 } from "path";
36178
+ import { readFileSync as readFileSync8 } from "fs";
36179
+ import { join as join10 } from "path";
35808
36180
  var BREAKER_COOLDOWN_MS = 3e4;
35809
36181
  function parseForwardHealth(raw, nowMs) {
35810
36182
  try {
@@ -35828,20 +36200,21 @@ function isForwardPaused(health, nowMs) {
35828
36200
 
35829
36201
  // ../../packages/persistence/src/history-backfill.ts
35830
36202
  import { existsSync as existsSync4 } from "fs";
35831
- import { join as join10 } from "path";
36203
+ import { join as join11 } from "path";
35832
36204
 
35833
36205
  // ../../packages/persistence/src/history-preview.ts
35834
36206
  import { existsSync as existsSync5 } from "fs";
35835
- import { join as join11 } from "path";
35836
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36207
+ import { join as join12 } from "path";
36208
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35837
36209
 
35838
36210
  // ../../packages/persistence/src/history-sync-state.ts
35839
- import { readFileSync as readFileSync8 } from "fs";
35840
- import { join as join12 } from "path";
36211
+ import { readFileSync as readFileSync9 } from "fs";
36212
+ import { join as join13 } from "path";
36213
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35841
36214
 
35842
36215
  // ../../packages/persistence/src/store-symlinks.ts
35843
36216
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35844
- import { dirname as dirname3, join as join13, resolve } from "path";
36217
+ import { dirname as dirname3, join as join14, resolve } from "path";
35845
36218
 
35846
36219
  // ../../packages/persistence/src/vault/crypto.ts
35847
36220
  import {
@@ -35855,19 +36228,19 @@ import {
35855
36228
  // ../../packages/persistence/src/vault/key-provider.ts
35856
36229
  import { execFileSync } from "child_process";
35857
36230
  import { randomBytes as randomBytes2 } from "crypto";
35858
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35859
- import { join as join14 } from "path";
36231
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
36232
+ import { join as join15 } from "path";
35860
36233
 
35861
36234
  // ../../packages/persistence/src/vault/vault.ts
35862
36235
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35863
36236
 
35864
36237
  // ../../packages/persistence/src/warn-era-cap.ts
35865
36238
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35866
- import { join as join15 } from "path";
36239
+ import { join as join16 } from "path";
35867
36240
  var MARKER = "warn-era-capped";
35868
36241
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35869
36242
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35870
- const marker = join15(dataDir2, MARKER);
36243
+ const marker = join16(dataDir2, MARKER);
35871
36244
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35872
36245
  const capped = db.policies.capCategoryActions();
35873
36246
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35875,577 +36248,84 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35875
36248
  return { capped };
35876
36249
  }
35877
36250
 
35878
- // ../../packages/remote/src/http.ts
35879
- import { request as httpRequest } from "http";
35880
- import { request as httpsRequest } from "https";
35881
- var DEFAULT_TIMEOUT_MS = 1e4;
35882
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35883
- var RemoteRequestError = class extends Error {
35884
- constructor(status) {
35885
- super(`control-plane request failed with status ${String(status)}`);
35886
- this.status = status;
35887
- this.name = "RemoteRequestError";
35888
- }
35889
- status;
35890
- };
35891
- var RemoteRouteAbsent = class extends Error {
35892
- constructor(route) {
35893
- super(`control plane does not serve ${route}`);
35894
- this.route = route;
35895
- this.name = "RemoteRouteAbsent";
35896
- }
35897
- route;
35898
- };
35899
- var RemoteRequestInvalid = class extends Error {
35900
- constructor(route, cause) {
35901
- super(`refusing to send a malformed body to ${route}`);
35902
- this.cause = cause;
35903
- this.name = "RemoteRequestInvalid";
35904
- }
35905
- cause;
35906
- };
35907
- var RemoteEndpointRefused = class extends Error {
35908
- constructor(endpoint) {
35909
- super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
35910
- this.name = "RemoteEndpointRefused";
35911
- }
36251
+ // ../../packages/plugin-sdk/src/config.ts
36252
+ import { existsSync as existsSync8 } from "fs";
36253
+ import { join as join17 } from "path";
36254
+
36255
+ // ../../packages/plugin-sdk/src/provider-env.ts
36256
+ var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
36257
+ var booleanish = external_exports.string().optional().transform((v) => {
36258
+ if (v === void 0) return void 0;
36259
+ const t = v.trim().toLowerCase();
36260
+ if (t === "" || t === "false" || t === "0") return false;
36261
+ return true;
36262
+ }).catch(void 0);
36263
+ var optionalBaseUrl = external_exports.preprocess((v) => {
36264
+ if (typeof v === "string" && v.trim() === "") return void 0;
36265
+ return v;
36266
+ }, external_exports.string().optional()).catch(void 0);
36267
+ var providerEnvShape = {
36268
+ CLAUDE_CODE_USE_BEDROCK: booleanish,
36269
+ CLAUDE_CODE_USE_VERTEX: booleanish,
36270
+ ANTHROPIC_BASE_URL: optionalBaseUrl
35912
36271
  };
35913
- var RemoteResponseInvalid = class extends Error {
35914
- constructor(route, detail) {
35915
- super(`control plane answered ${route} with ${detail}`);
35916
- this.name = "RemoteResponseInvalid";
36272
+ var ProviderEnvSchema = external_exports.object(providerEnvShape);
36273
+
36274
+ // ../../packages/plugin-sdk/src/provider.ts
36275
+ function hostOf(url2) {
36276
+ try {
36277
+ const host = new URL(url2).host;
36278
+ if (host !== "") return host;
36279
+ } catch {
35917
36280
  }
35918
- };
35919
- var RemoteTransportError = class extends Error {
35920
- /**
35921
- * The status the peer sent, when headers arrived and only the BODY was
35922
- * refused.
35923
- *
35924
- * Undefined for the ordinary case this class was written for — no answer at
35925
- * all. It exists because two paths reject after a status has already been
35926
- * delivered: an oversized body and an aborted response. Discarding it there
35927
- * reported a deployment answering 401 with a verbose body as a network
35928
- * outage, which sends the reader to look at their network instead of their
35929
- * credential.
35930
- */
35931
- constructor(reason, status) {
35932
- super(`control-plane request did not complete: ${reason}`);
35933
- this.status = status;
35934
- this.name = "RemoteTransportError";
36281
+ try {
36282
+ const host = new URL(`https://${url2}`).host;
36283
+ return host !== "" ? host : void 0;
36284
+ } catch {
36285
+ return void 0;
35935
36286
  }
35936
- status;
35937
- };
35938
- async function send(options) {
35939
- const url2 = new URL(options.url);
35940
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35941
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
35942
- const requestOptions = {
35943
- method: options.method,
35944
- headers: {
35945
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
35946
- // last they win, and two of the values below are ones no caller may
35947
- // replace: `x-api-key` is the credential, and `content-length` is the
35948
- // byte count that stops a multi-byte body being truncated by the
35949
- // receiver. `SendOptions.headers` is a free-form record on an exported
35950
- // function, so "no caller does that today" is not the guarantee to rely
35951
- // on. The one header any caller actually passes — `if-none-match` on the
35952
- // conditional GET — is untouched by this order.
35953
- ...options.headers,
35954
- // The credential. One header, matching what the deployment authenticates
35955
- // on; a second copy in an `Authorization` header would be one more place
35956
- // it can be logged by an intermediary for no gain.
35957
- //
35958
- // Spread conditionally rather than assigned as `undefined`: Node's header
35959
- // handling and `content-length` bookkeeping treat a present-but-undefined
35960
- // key differently from an absent one, and "the header is not there" is
35961
- // the property the attach flow needs.
35962
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
35963
- accept: "application/json",
35964
- ...options.body === void 0 ? {} : {
35965
- "content-type": "application/json",
35966
- // Byte length, not string length: a multi-byte body sent with a
35967
- // character count is truncated by the receiver.
35968
- "content-length": String(Buffer.byteLength(options.body))
35969
- }
36287
+ }
36288
+ function resolveProvider() {
36289
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
36290
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
36291
+ if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
36292
+ if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
36293
+ const baseUrl = env.ANTHROPIC_BASE_URL;
36294
+ if (baseUrl !== void 0 && baseUrl !== "") {
36295
+ const host = hostOf(baseUrl);
36296
+ if (host !== void 0 && host !== DEFAULT_ANTHROPIC_HOST) {
36297
+ return { provider: "gateway", gatewayHost: host };
35970
36298
  }
35971
- };
35972
- return new Promise((resolve4, reject) => {
35973
- let settled = false;
35974
- const fail = (reason, status) => {
35975
- if (settled) return;
35976
- settled = true;
35977
- reject(new RemoteTransportError(reason, status));
35978
- };
35979
- const req = send_(url2, requestOptions, (res) => {
35980
- const chunks = [];
35981
- let size = 0;
35982
- res.on("data", (chunk) => {
35983
- size += chunk.length;
35984
- if (size > MAX_RESPONSE_BYTES) {
35985
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
35986
- res.destroy();
35987
- req.destroy();
35988
- return;
35989
- }
35990
- chunks.push(chunk);
35991
- });
35992
- res.on("aborted", () => {
35993
- fail("the response was aborted", res.statusCode);
35994
- });
35995
- res.on("end", () => {
35996
- if (settled) return;
35997
- settled = true;
35998
- resolve4({
35999
- status: res.statusCode ?? 0,
36000
- headers: res.headers,
36001
- body: Buffer.concat(chunks).toString("utf8")
36002
- });
36003
- });
36004
- });
36005
- const deadline = setTimeout(() => {
36006
- fail(`no response within ${String(timeoutMs)}ms`);
36007
- req.destroy();
36008
- }, timeoutMs);
36009
- deadline.unref();
36010
- req.on("upgrade", (_res, socket) => {
36011
- fail("the deployment answered with a protocol upgrade");
36012
- socket.destroy();
36013
- });
36014
- req.on("close", () => {
36015
- fail("the connection closed before a response was read");
36016
- clearTimeout(deadline);
36017
- });
36018
- req.on("error", (err) => {
36019
- fail(err.message);
36020
- });
36021
- if (options.body !== void 0) req.write(options.body);
36022
- req.end();
36023
- });
36299
+ }
36300
+ return { provider: "anthropic" };
36024
36301
  }
36025
36302
 
36026
- // ../../packages/remote/src/client.ts
36027
- var ROUTES = {
36028
- events: "/v1/events",
36029
- auditEvents: "/v1/audit-events",
36030
- auditEventsBatch: "/v1/audit-events/batch",
36031
- inventory: "/v1/inventory",
36032
- storePosture: "/v1/store-posture",
36033
- policyBundle: "/v1/policy-bundle",
36034
- whoami: "/v1/plugin/whoami",
36035
- shares: "/v1/shares",
36036
- commands: "/v1/plugin/commands"
36037
- };
36038
- function ackRoute(id) {
36039
- return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
36040
- }
36041
- function headerValue(response, name) {
36042
- const raw = response.headers[name];
36043
- if (raw === void 0) return void 0;
36044
- return Array.isArray(raw) ? raw[0] : raw;
36045
- }
36046
- function okBody(response) {
36047
- if (response.status < 200 || response.status >= 300) {
36048
- throw new RemoteRequestError(response.status);
36303
+ // ../../packages/plugin-sdk/src/config.ts
36304
+ function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
36305
+ try {
36306
+ ensureLayoutDirSync(base);
36307
+ const settingsFile = join17(settingsDir(base), "settings.json");
36308
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
36309
+ } catch {
36049
36310
  }
36050
- return response.body;
36311
+ migrateLegacyLayout(base);
36312
+ const settings = readWorkspaceSettings(base);
36313
+ return {
36314
+ settings,
36315
+ dataDir: dataDir(base),
36316
+ dbPath: dbPath(base),
36317
+ settingsDir: settingsDir(base),
36318
+ onboarded: settings.onboardedAt != null,
36319
+ provider: resolveProviderSafe(resolveProviderFn)
36320
+ };
36051
36321
  }
36052
- function parsed(schema, body, route) {
36053
- let json2;
36322
+ function resolveProviderSafe(resolveProviderFn) {
36054
36323
  try {
36055
- json2 = JSON.parse(body);
36324
+ return resolveProviderFn();
36056
36325
  } catch {
36057
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
36058
- }
36059
- const result = schema.safeParse(json2);
36060
- if (!result.success) {
36061
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
36326
+ return { provider: "anthropic" };
36062
36327
  }
36063
- return result.data;
36064
- }
36065
- function resolveBaseUrl(endpoint) {
36066
- if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
36067
- let end = endpoint.length;
36068
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
36069
- return endpoint.slice(0, end);
36070
36328
  }
36071
- var SLASH2 = "/".charCodeAt(0);
36072
- function createRemoteClient(options) {
36073
- const base = resolveBaseUrl(options.endpoint);
36074
- const url2 = (route) => `${base}${route}`;
36075
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
36076
- const sendOne = async (event) => {
36077
- const validated = RecordAuditEventRequest.safeParse(event);
36078
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
36079
- const response = await send({
36080
- ...common,
36081
- method: "POST",
36082
- url: url2(ROUTES.auditEvents),
36083
- body: JSON.stringify(validated.data)
36084
- });
36085
- okBody(response);
36086
- };
36087
- return {
36088
- async ingestEvents(batch) {
36089
- const response = await send({
36090
- ...common,
36091
- method: "POST",
36092
- url: url2(ROUTES.events),
36093
- body: JSON.stringify(batch)
36094
- });
36095
- return parsed(IngestAck, okBody(response), ROUTES.events);
36096
- },
36097
- async ingestInventory(context) {
36098
- const response = await send({
36099
- ...common,
36100
- method: "POST",
36101
- url: url2(ROUTES.inventory),
36102
- body: JSON.stringify(context)
36103
- });
36104
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
36105
- },
36106
- async recordAuditEvent(event) {
36107
- await sendOne(event);
36108
- },
36109
- async recordAuditEvents(events, opts) {
36110
- const validated = RecordAuditEventBatch.safeParse({ events });
36111
- if (!validated.success) {
36112
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
36113
- }
36114
- const response = await send({
36115
- ...common,
36116
- method: "POST",
36117
- url: url2(ROUTES.auditEventsBatch),
36118
- body: JSON.stringify(validated.data)
36119
- });
36120
- if (response.status === 404) {
36121
- if (opts?.fallbackToSingleEvents !== true) {
36122
- throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
36123
- }
36124
- for (const event of validated.data.events) await sendOne(event);
36125
- return { accepted: validated.data.events.length };
36126
- }
36127
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
36128
- },
36129
- async reportStorePosture(snapshot) {
36130
- const response = await send({
36131
- ...common,
36132
- method: "POST",
36133
- url: url2(ROUTES.storePosture),
36134
- body: JSON.stringify(snapshot)
36135
- });
36136
- okBody(response);
36137
- },
36138
- async getPolicyBundle(etag) {
36139
- const response = await send({
36140
- ...common,
36141
- method: "GET",
36142
- url: url2(ROUTES.policyBundle),
36143
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
36144
- });
36145
- if (response.status === 304) {
36146
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
36147
- }
36148
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
36149
- return { changed: true, bundle, etag: headerValue(response, "etag") };
36150
- },
36151
- async whoami() {
36152
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
36153
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
36154
- },
36155
- async recordProjectEgress(request) {
36156
- const validated = EgressIngestRequest.safeParse(request);
36157
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
36158
- const response = await send({
36159
- ...common,
36160
- method: "POST",
36161
- url: url2(ROUTES.shares),
36162
- body: JSON.stringify(validated.data)
36163
- });
36164
- if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
36165
- okBody(response);
36166
- },
36167
- async pollCommand() {
36168
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
36169
- if (response.status === 404) return null;
36170
- return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
36171
- },
36172
- async ackCommand(id, body) {
36173
- const validated = DeviceCommandAckBody.safeParse(body);
36174
- const route = ackRoute(id);
36175
- if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
36176
- const response = await send({
36177
- ...common,
36178
- method: "POST",
36179
- url: url2(route),
36180
- body: JSON.stringify(validated.data)
36181
- });
36182
- okBody(response);
36183
- }
36184
- };
36185
- }
36186
-
36187
- // ../../packages/remote/src/failure-kind.ts
36188
- function statusOf(err) {
36189
- if (typeof err !== "object" || err === null || !("status" in err)) return null;
36190
- const { status } = err;
36191
- if (typeof status !== "number" || !Number.isInteger(status)) return null;
36192
- return status >= 100 && status <= 599 ? status : null;
36193
- }
36194
- function nameOf(err) {
36195
- if (typeof err !== "object" || err === null || !("name" in err)) return null;
36196
- return typeof err.name === "string" ? err.name : null;
36197
- }
36198
- function classifyRemoteFailure(err) {
36199
- switch (nameOf(err)) {
36200
- case "RemoteRouteAbsent":
36201
- return "route-absent";
36202
- case "RemoteRequestInvalid":
36203
- case "RemoteEndpointRefused":
36204
- return "invalid-request";
36205
- case "RemoteResponseInvalid":
36206
- return "rejected";
36207
- default:
36208
- break;
36209
- }
36210
- const status = statusOf(err);
36211
- if (status === null) return "unreachable";
36212
- switch (status) {
36213
- case 401:
36214
- return "unauthorized";
36215
- case 403:
36216
- return "forbidden";
36217
- case 429:
36218
- return "unreachable";
36219
- case 404:
36220
- return "unreachable";
36221
- default:
36222
- return status >= 400 && status <= 499 ? "rejected" : "unreachable";
36223
- }
36224
- }
36225
-
36226
- // ../../packages/plugin-runtime/src/attached/failure.ts
36227
- function classifyFailure(err) {
36228
- switch (classifyRemoteFailure(err)) {
36229
- case "unauthorized":
36230
- return "unauthorized";
36231
- case "forbidden":
36232
- return "forbidden";
36233
- default:
36234
- return "unreachable";
36235
- }
36236
- }
36237
-
36238
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36239
- var REQUEST_TIMEOUT_MS = 2e3;
36240
- function withTimeout(promise2, ms) {
36241
- let timer;
36242
- const timeout = new Promise((_, reject) => {
36243
- timer = setTimeout(() => {
36244
- reject(new Error("attached gateway request timed out"));
36245
- }, ms);
36246
- });
36247
- promise2.catch(() => void 0);
36248
- return Promise.race([promise2, timeout]).finally(() => {
36249
- clearTimeout(timer);
36250
- });
36251
- }
36252
-
36253
- // ../../packages/plugin-runtime/src/attached/command-sync.ts
36254
- var COMMAND_REQUEST_TIMEOUT_MS = 3e4;
36255
- var SCAN_THREW = "scan_failed";
36256
- var SCAN_FOUND_NOTHING = "no_projects";
36257
- var COMMAND_EXPIRED = "expired";
36258
- function hasExpired(expiresAt, atMs) {
36259
- const deadlineMs = Date.parse(expiresAt);
36260
- return Number.isFinite(deadlineMs) && deadlineMs <= atMs;
36261
- }
36262
- var SERVICE = {
36263
- shares_rescan: (scan2) => scan2()
36264
- };
36265
- async function runCommandSync(deps) {
36266
- if (deps.scan === void 0) return null;
36267
- const settings = readWorkspaceSettings(deps.base);
36268
- const connection = isAttached(settings) ? settings.controlPlane : void 0;
36269
- const state = connection === void 0 ? void 0 : readControlPlaneCredentialFile(deps.settingsDir, connection);
36270
- if (connection === void 0 || !state?.usable) return null;
36271
- const client = createRemoteClient({
36272
- endpoint: connection.endpoint,
36273
- apiKey: state.credential.apiKey,
36274
- timeoutMs: COMMAND_REQUEST_TIMEOUT_MS
36275
- });
36276
- let command;
36277
- try {
36278
- command = await withTimeout(client.pollCommand(), COMMAND_REQUEST_TIMEOUT_MS);
36279
- } catch (err) {
36280
- const failure2 = classifyFailure(err);
36281
- return failure2 === "unreachable" ? "unreachable" : failure2;
36282
- }
36283
- if (command === null) return "none";
36284
- let projects = 0;
36285
- let reason = null;
36286
- if (hasExpired(command.expiresAt, (deps.now ?? Date.now)())) {
36287
- reason = COMMAND_EXPIRED;
36288
- } else {
36289
- try {
36290
- projects = (await SERVICE[command.kind](deps.scan)).projects;
36291
- if (projects === 0) reason = SCAN_FOUND_NOTHING;
36292
- } catch {
36293
- reason = SCAN_THREW;
36294
- }
36295
- }
36296
- try {
36297
- await withTimeout(
36298
- reason === null ? client.ackCommand(command.id, { outcome: "reported", projectsScanned: projects }) : client.ackCommand(command.id, {
36299
- outcome: "failed",
36300
- reason,
36301
- projectsScanned: projects
36302
- }),
36303
- COMMAND_REQUEST_TIMEOUT_MS
36304
- );
36305
- } catch (err) {
36306
- const failure2 = classifyFailure(err);
36307
- return failure2 === "unreachable" ? "unreachable" : failure2;
36308
- }
36309
- return reason === null ? "reported" : "failed";
36310
- }
36311
- function commandScanFor(config2, scanWorktree2, sourceTool) {
36312
- return async () => {
36313
- const summary = await scanWorktree2(config2, {
36314
- sourceTool,
36315
- // Never the home directory implicitly, and never anything the wire named.
36316
- rootDir: process.cwd()
36317
- });
36318
- return { projects: summary.scanned > 0 ? 1 : 0 };
36319
- };
36320
- }
36321
-
36322
- // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36323
- import { readFileSync as readFileSync10 } from "fs";
36324
- import { join as join16 } from "path";
36325
- var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36326
- function forwardDropsPath(dataDir2) {
36327
- return join16(dataDir2, FORWARD_DROPS_FILENAME);
36328
- }
36329
- function recordForwardDrops(dataDir2, count, nowMs) {
36330
- if (count <= 0) return;
36331
- try {
36332
- ensureDataDirSync(dataDir2);
36333
- const previous = readForwardDrops(dataDir2);
36334
- const next = {
36335
- droppedForwards: (previous?.droppedForwards ?? 0) + count,
36336
- lastDropAtMs: nowMs
36337
- };
36338
- writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
36339
- `);
36340
- } catch {
36341
- }
36342
- }
36343
- function readForwardDrops(dataDir2) {
36344
- try {
36345
- const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
36346
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36347
- const record2 = parsed2;
36348
- if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
36349
- return null;
36350
- }
36351
- if (record2.droppedForwards <= 0) return null;
36352
- if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
36353
- return null;
36354
- }
36355
- return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
36356
- } catch {
36357
- return null;
36358
- }
36359
- }
36360
-
36361
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36362
- import { randomUUID as randomUUID16 } from "crypto";
36363
- import { readFile, rename, writeFile } from "fs/promises";
36364
- import { join as join28 } from "path";
36365
-
36366
- // ../../packages/plugin-sdk/src/config.ts
36367
- import { existsSync as existsSync8 } from "fs";
36368
- import { join as join17 } from "path";
36369
-
36370
- // ../../packages/plugin-sdk/src/provider-env.ts
36371
- var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
36372
- var booleanish = external_exports.string().optional().transform((v) => {
36373
- if (v === void 0) return void 0;
36374
- const t = v.trim().toLowerCase();
36375
- if (t === "" || t === "false" || t === "0") return false;
36376
- return true;
36377
- }).catch(void 0);
36378
- var optionalBaseUrl = external_exports.preprocess((v) => {
36379
- if (typeof v === "string" && v.trim() === "") return void 0;
36380
- return v;
36381
- }, external_exports.string().optional()).catch(void 0);
36382
- var providerEnvShape = {
36383
- CLAUDE_CODE_USE_BEDROCK: booleanish,
36384
- CLAUDE_CODE_USE_VERTEX: booleanish,
36385
- ANTHROPIC_BASE_URL: optionalBaseUrl
36386
- };
36387
- var ProviderEnvSchema = external_exports.object(providerEnvShape);
36388
-
36389
- // ../../packages/plugin-sdk/src/provider.ts
36390
- function hostOf(url2) {
36391
- try {
36392
- const host = new URL(url2).host;
36393
- if (host !== "") return host;
36394
- } catch {
36395
- }
36396
- try {
36397
- const host = new URL(`https://${url2}`).host;
36398
- return host !== "" ? host : void 0;
36399
- } catch {
36400
- return void 0;
36401
- }
36402
- }
36403
- function resolveProvider() {
36404
- const parsed2 = ProviderEnvSchema.safeParse(process.env);
36405
- const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
36406
- if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
36407
- if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
36408
- const baseUrl = env.ANTHROPIC_BASE_URL;
36409
- if (baseUrl !== void 0 && baseUrl !== "") {
36410
- const host = hostOf(baseUrl);
36411
- if (host !== void 0 && host !== DEFAULT_ANTHROPIC_HOST) {
36412
- return { provider: "gateway", gatewayHost: host };
36413
- }
36414
- }
36415
- return { provider: "anthropic" };
36416
- }
36417
-
36418
- // ../../packages/plugin-sdk/src/config.ts
36419
- function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
36420
- try {
36421
- ensureLayoutDirSync(base);
36422
- const settingsFile = join17(settingsDir(base), "settings.json");
36423
- if (existsSync8(settingsFile)) tightenFile(settingsFile);
36424
- } catch {
36425
- }
36426
- migrateLegacyLayout(base);
36427
- const settings = readWorkspaceSettings(base);
36428
- return {
36429
- settings,
36430
- dataDir: dataDir(base),
36431
- dbPath: dbPath(base),
36432
- settingsDir: settingsDir(base),
36433
- onboarded: settings.onboardedAt != null,
36434
- provider: resolveProviderSafe(resolveProviderFn)
36435
- };
36436
- }
36437
- function resolveProviderSafe(resolveProviderFn) {
36438
- try {
36439
- return resolveProviderFn();
36440
- } catch {
36441
- return { provider: "anthropic" };
36442
- }
36443
- }
36444
-
36445
- // ../../packages/plugin-sdk/src/config-inventory.ts
36446
- import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
36447
- import { homedir as homedir2 } from "os";
36448
- import { basename as basename3, join as join19 } from "path";
36449
36329
 
36450
36330
  // ../../packages/detections/src/egress/registry.ts
36451
36331
  var EXTRACTOR_VERSION = "3";
@@ -37551,11 +37431,11 @@ var EXACT_KIND_BY_BASENAME = {
37551
37431
  "composer.json": "composer.json",
37552
37432
  "packages.config": "packages.config"
37553
37433
  };
37554
- function manifestKindOf(basename8) {
37555
- if (LOCKFILE_BASENAMES.has(basename8)) return null;
37556
- const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename8) ? EXACT_KIND_BY_BASENAME[basename8] : void 0;
37434
+ function manifestKindOf(basename6) {
37435
+ if (LOCKFILE_BASENAMES.has(basename6)) return null;
37436
+ const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename6) ? EXACT_KIND_BY_BASENAME[basename6] : void 0;
37557
37437
  if (exact !== void 0) return exact;
37558
- if (basename8.endsWith(".csproj")) return "csproj";
37438
+ if (basename6.endsWith(".csproj")) return "csproj";
37559
37439
  return null;
37560
37440
  }
37561
37441
  function extractManifestSdks(text, kind) {
@@ -38183,12 +38063,12 @@ var RegexMatcher2 = class {
38183
38063
  rule.matcher,
38184
38064
  () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
38185
38065
  );
38186
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
38066
+ const scanText = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
38187
38067
  const spans = [];
38188
38068
  let m;
38189
- const maxIterations = scanText2.length + 1;
38069
+ const maxIterations = scanText.length + 1;
38190
38070
  let iterations = 0;
38191
- while ((m = re.exec(scanText2)) !== null) {
38071
+ while ((m = re.exec(scanText)) !== null) {
38192
38072
  if (++iterations > maxIterations) break;
38193
38073
  const group = captureGroup != null ? m[captureGroup] : m[0];
38194
38074
  if (m[0].length === 0) re.lastIndex++;
@@ -38530,17 +38410,18 @@ function ruleEvidence(rule) {
38530
38410
 
38531
38411
  // ../../packages/detections/src/mask.ts
38532
38412
  function maskMatch(raw) {
38533
- if (raw.length <= 5) return "***";
38534
- const atIndex = raw.indexOf("@");
38535
- if (atIndex > 0 && atIndex < raw.length - 1) {
38536
- const domain2 = raw.slice(atIndex + 1);
38413
+ const visible = stripInvisiblePadding(raw);
38414
+ if (visible.length <= 5) return "***";
38415
+ const atIndex = visible.indexOf("@");
38416
+ if (atIndex > 0 && atIndex < visible.length - 1) {
38417
+ const domain2 = visible.slice(atIndex + 1);
38537
38418
  if (domain2.includes(".")) {
38538
- const local = raw.slice(0, atIndex);
38419
+ const local = visible.slice(0, atIndex);
38539
38420
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
38540
38421
  return `${maskedLocal}@${domain2}`;
38541
38422
  }
38542
38423
  }
38543
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
38424
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
38544
38425
  }
38545
38426
 
38546
38427
  // ../../packages/detections/src/pointer-shield.ts
@@ -38802,7 +38683,12 @@ var MIN_RAW_LEN = 4;
38802
38683
  var RAW_RUN_LEN = 8;
38803
38684
  function carriesRawRun(text, rawValues) {
38804
38685
  let windows = null;
38805
- for (const raw of new Set(rawValues)) {
38686
+ const values = /* @__PURE__ */ new Set();
38687
+ for (const raw of rawValues) {
38688
+ values.add(raw);
38689
+ values.add(stripInvisiblePadding(raw));
38690
+ }
38691
+ for (const raw of values) {
38806
38692
  if (raw.length < MIN_RAW_LEN) continue;
38807
38693
  if (raw.length < RAW_RUN_LEN) {
38808
38694
  if (text.includes(raw)) return true;
@@ -38826,11 +38712,16 @@ function carriesRawRun(text, rawValues) {
38826
38712
  return false;
38827
38713
  }
38828
38714
  function safeMaskedMatch(rawMatch) {
38829
- const masked = maskMatch(rawMatch);
38830
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
38831
- return "***";
38715
+ const visible = stripInvisiblePadding(rawMatch);
38716
+ const masked = maskMatch(visible);
38717
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
38718
+ if (!reveals(masked)) return masked;
38719
+ const atIndex = masked.indexOf("@");
38720
+ if (atIndex > 0 && atIndex < masked.length - 1) {
38721
+ const emailFallback = `*${masked.slice(atIndex)}`;
38722
+ if (!reveals(emailFallback)) return emailFallback;
38832
38723
  }
38833
- return masked;
38724
+ return "***";
38834
38725
  }
38835
38726
  function assertRawFree(text, rawValues) {
38836
38727
  if (carriesRawRun(text, rawValues)) {
@@ -41272,6 +41163,11 @@ function bundledDetections() {
41272
41163
  }));
41273
41164
  return cachedDetections;
41274
41165
  }
41166
+ function shippedRegexMatchers() {
41167
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
41168
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
41169
+ );
41170
+ }
41275
41171
 
41276
41172
  // ../../packages/plugin-sdk/src/mask.ts
41277
41173
  var packsReady = false;
@@ -41313,8 +41209,9 @@ function resolveRepoIdentity(cwd) {
41313
41209
  var ATTRIBUTION_MEMO_LIMIT = 64;
41314
41210
  var attributionMemo = /* @__PURE__ */ new Map();
41315
41211
  var NO_ATTRIBUTION = Object.freeze({});
41316
- function resolveRepoAttribution(cwd) {
41212
+ function resolveRepoAttribution(cwd, options) {
41317
41213
  try {
41214
+ if (options?.cache === false) return attributeRepo(cwd);
41318
41215
  const remembered = attributionMemo.get(cwd);
41319
41216
  if (remembered !== void 0) return remembered;
41320
41217
  const attribution = attributeRepo(cwd);
@@ -41421,9 +41318,9 @@ function slugFromUrl(url2) {
41421
41318
  }
41422
41319
 
41423
41320
  // ../../packages/plugin-sdk/src/events.ts
41424
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
41321
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
41425
41322
  function contentHashOf(text) {
41426
- return createHash5("sha256").update(text).digest("hex");
41323
+ return createHash6("sha256").update(text).digest("hex");
41427
41324
  }
41428
41325
  function buildIngestEvent(input2) {
41429
41326
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -41936,62 +41833,13 @@ function createGuardedScanner(partition, gateway, opts) {
41936
41833
  };
41937
41834
  }
41938
41835
 
41939
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
41940
- import { readFileSync as readFileSync13 } from "fs";
41941
- import { join as join20 } from "path";
41942
-
41943
- // ../../packages/plugin-sdk/src/host-floor.ts
41944
- import { readFileSync as readFileSync15 } from "fs";
41945
- import { join as join22 } from "path";
41946
-
41947
- // ../../packages/plugin-sdk/src/model-governance.ts
41948
- import {
41949
- closeSync as closeSync2,
41950
- fstatSync,
41951
- mkdirSync as mkdirSync2,
41952
- openSync as openSync2,
41953
- readFileSync as readFileSync14,
41954
- readSync,
41955
- writeFileSync as writeFileSync5
41956
- } from "fs";
41957
- import { join as join21 } from "path";
41958
- var TAIL_BYTES = 256 * 1024;
41959
-
41960
- // ../../packages/plugin-sdk/src/host-floor.ts
41961
- var HOST_FEATURE = {
41962
- ModelSwitch: "model-switch",
41963
- VaultPointerDisplay: "vault-pointer-display"
41964
- };
41965
- var HOST_FLOORS = {
41966
- [HOST_FEATURE.ModelSwitch]: {
41967
- label: "model-switch protection",
41968
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
41969
- since: "2.1.251"
41970
- },
41971
- [HOST_FEATURE.VaultPointerDisplay]: {
41972
- label: "vault pointer display",
41973
- hookEvents: ["MessageDisplay"],
41974
- since: "2.1.152"
41975
- }
41976
- };
41977
- var ANTIGRAVITY_HOST_FEATURE = {
41978
- EndOfTurnCapture: "end-of-turn-capture"
41979
- };
41980
- var ANTIGRAVITY_HOST_FLOORS = {
41981
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
41982
- label: "end-of-turn history capture",
41983
- hookEvents: ["Stop"],
41984
- since: "1.1.10"
41985
- }
41986
- };
41987
-
41988
41836
  // ../../packages/plugin-sdk/src/ignore-layers.ts
41989
41837
  var import_ignore = __toESM(require_ignore(), 1);
41990
- import { readFileSync as readFileSync16 } from "fs";
41991
- import { join as join23 } from "path";
41838
+ import { readFileSync as readFileSync12 } from "fs";
41839
+ import { join as join19 } from "path";
41992
41840
  function readIgnoreLayer(dir, filename, anchorLen) {
41993
41841
  try {
41994
- return { matcher: (0, import_ignore.default)().add(readFileSync16(join23(dir, filename), "utf8")), anchorLen };
41842
+ return { matcher: (0, import_ignore.default)().add(readFileSync12(join19(dir, filename), "utf8")), anchorLen };
41995
41843
  } catch {
41996
41844
  return void 0;
41997
41845
  }
@@ -42018,16 +41866,9 @@ function withLayer(layers, layer) {
42018
41866
  return layer ? [...layers, layer] : layers;
42019
41867
  }
42020
41868
 
42021
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
42022
- import { arch, hostname as hostname4, platform, release } from "os";
42023
-
42024
- // ../../packages/plugin-sdk/src/nudge.ts
42025
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "fs";
42026
- import { join as join24 } from "path";
42027
-
42028
41869
  // ../../packages/plugin-sdk/src/paths.ts
42029
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
42030
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
41870
+ import { readdirSync as readdirSync2, realpathSync as realpathSync2 } from "fs";
41871
+ import { basename as basename3, dirname as dirname5, sep as sep3 } from "path";
42031
41872
  function toPosix(path) {
42032
41873
  return path.split(sep3).join("/");
42033
41874
  }
@@ -42045,7 +41886,7 @@ function findProjectRoot(startDir, recognizeMarker) {
42045
41886
  }
42046
41887
  function directoryHasMarker(dir, recognizeMarker) {
42047
41888
  try {
42048
- for (const entry of readdirSync3(dir, { withFileTypes: true })) {
41889
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
42049
41890
  if (entry.isFile() && recognizeMarker(entry.name) != null) return true;
42050
41891
  }
42051
41892
  } catch {
@@ -42055,8 +41896,8 @@ function directoryHasMarker(dir, recognizeMarker) {
42055
41896
  }
42056
41897
  function resolveNonGitProject(startDir, recognizeMarker) {
42057
41898
  const projectRoot = findProjectRoot(startDir, recognizeMarker);
42058
- const realRoot = realpathSync3(projectRoot);
42059
- return { root: projectRoot, projectKey: `path:${realRoot}`, project: basename4(realRoot) };
41899
+ const realRoot = realpathSync2(projectRoot);
41900
+ return { root: projectRoot, projectKey: `path:${realRoot}`, project: basename3(realRoot) };
42060
41901
  }
42061
41902
 
42062
41903
  // ../../packages/plugin-sdk/src/policy-resolver.ts
@@ -42103,36 +41944,6 @@ function assignedRulePolicies(installed) {
42103
41944
  return out;
42104
41945
  }
42105
41946
 
42106
- // ../../packages/plugin-sdk/src/project-files.ts
42107
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
42108
- import { basename as basename5, join as join25 } from "path";
42109
-
42110
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
42111
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
42112
- if (typeof v === "string" && v.trim() === "") return void 0;
42113
- return v;
42114
- }, external_exports.string().optional()).catch(void 0);
42115
- var optionalFlag = external_exports.preprocess((v) => {
42116
- if (typeof v !== "string") return false;
42117
- const normalized = v.trim().toLowerCase();
42118
- return normalized !== "" && normalized !== "0" && normalized !== "false";
42119
- }, external_exports.boolean()).catch(false);
42120
- var antigravityProviderEnvShape = {
42121
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
42122
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
42123
- };
42124
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
42125
-
42126
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
42127
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
42128
- if (typeof v === "string" && v.trim() === "") return void 0;
42129
- return v;
42130
- }, external_exports.string().optional()).catch(void 0);
42131
- var codexProviderEnvShape = {
42132
- OPENAI_BASE_URL: optionalBaseUrl3
42133
- };
42134
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
42135
-
42136
41947
  // ../../packages/plugin-sdk/src/runtime.ts
42137
41948
  import { randomUUID as randomUUID15 } from "crypto";
42138
41949
  var ENFORCEMENT_CEILING_ENABLED = false;
@@ -42419,12 +42230,11 @@ function createPluginRuntime(gateway, settings, opts) {
42419
42230
  async function processText(text, context, opts2 = {}) {
42420
42231
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
42421
42232
  }
42422
- async function capture(input2, opts2 = {}) {
42233
+ async function evaluateCapture(input2, opts2) {
42423
42234
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
42424
- const filePath = input2.metadata?.filePath;
42425
42235
  const { decision, excepted, exceptionIds } = await evaluate(
42426
42236
  input2.text,
42427
- { filePath, eventKind: input2.kind },
42237
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
42428
42238
  {
42429
42239
  sourceTool: input2.sourceTool,
42430
42240
  metadata: input2.metadata,
@@ -42432,7 +42242,11 @@ function createPluginRuntime(gateway, settings, opts) {
42432
42242
  },
42433
42243
  opts2.rewritable
42434
42244
  );
42435
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
42245
+ return { decision, excepted, exceptionIds, timingStartedAt };
42246
+ }
42247
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
42248
+ const filePath = input2.metadata?.filePath;
42249
+ if (opts2.persist === "with-findings" && decision.findings.length === 0) return;
42436
42250
  try {
42437
42251
  const contentHash = contentHashOf(input2.text);
42438
42252
  const maskedFindings = decision.findings.filter(
@@ -42475,6 +42289,8 @@ function createPluginRuntime(gateway, settings, opts) {
42475
42289
  // exceptions/blocked_detections when a key is available;
42476
42290
  // falls back to the masked match so at-rest findings still get
42477
42291
  // a stable (if weaker) identity on a workspace with no dataDir.
42292
+ // Both ignore the same invisible padding, so a clean and a
42293
+ // padded occurrence of one secret key alike on either path.
42478
42294
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
42479
42295
  }) : void 0;
42480
42296
  return {
@@ -42502,7 +42318,37 @@ function createPluginRuntime(gateway, settings, opts) {
42502
42318
  }
42503
42319
  } catch {
42504
42320
  }
42505
- return decision;
42321
+ }
42322
+ async function enforcedIn(text, context) {
42323
+ try {
42324
+ await ensureInitialized();
42325
+ if (!scanner) return [];
42326
+ const shielded = shieldPointers(text);
42327
+ const matched = await scanner.scan(shielded.text, context);
42328
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
42329
+ const action = resolveAction(finding.ruleId, finding.category);
42330
+ return action === "block" || action === "redact";
42331
+ });
42332
+ } catch {
42333
+ return [];
42334
+ }
42335
+ }
42336
+ async function capture(input2, opts2 = {}) {
42337
+ const evaluated = await evaluateCapture(input2, opts2);
42338
+ await persistCapture(input2, opts2, evaluated);
42339
+ return evaluated.decision;
42340
+ }
42341
+ async function captureDeferred(input2, opts2 = {}) {
42342
+ const evaluated = await evaluateCapture(input2, opts2);
42343
+ let recorded = false;
42344
+ return {
42345
+ result: evaluated.decision,
42346
+ record: async () => {
42347
+ if (recorded) return;
42348
+ recorded = true;
42349
+ await persistCapture(input2, opts2, evaluated);
42350
+ }
42351
+ };
42506
42352
  }
42507
42353
  async function rulesetFingerprint() {
42508
42354
  try {
@@ -42523,21 +42369,526 @@ function createPluginRuntime(gateway, settings, opts) {
42523
42369
  }
42524
42370
  await gateway.close();
42525
42371
  }
42526
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
42372
+ return {
42373
+ processText,
42374
+ capture,
42375
+ captureDeferred,
42376
+ enforcedIn,
42377
+ rulesetFingerprint,
42378
+ scanIsolationDegraded,
42379
+ close
42380
+ };
42527
42381
  }
42528
42382
 
42529
- // ../../packages/plugin-sdk/src/scope-key.ts
42530
- import { existsSync as existsSync12 } from "fs";
42531
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
42383
+ // ../../packages/remote/src/http.ts
42384
+ import { request as httpRequest } from "http";
42385
+ import { request as httpsRequest } from "https";
42386
+ var DEFAULT_TIMEOUT_MS = 1e4;
42387
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
42388
+ var RemoteRequestError = class extends Error {
42389
+ constructor(status) {
42390
+ super(`control-plane request failed with status ${String(status)}`);
42391
+ this.status = status;
42392
+ this.name = "RemoteRequestError";
42393
+ }
42394
+ status;
42395
+ };
42396
+ var RemoteRouteAbsent = class extends Error {
42397
+ constructor(route) {
42398
+ super(`control plane does not serve ${route}`);
42399
+ this.route = route;
42400
+ this.name = "RemoteRouteAbsent";
42401
+ }
42402
+ route;
42403
+ };
42404
+ var RemoteRequestInvalid = class extends Error {
42405
+ constructor(route, cause) {
42406
+ super(`refusing to send a malformed body to ${route}`);
42407
+ this.cause = cause;
42408
+ this.name = "RemoteRequestInvalid";
42409
+ }
42410
+ cause;
42411
+ };
42412
+ var RemoteEndpointRefused = class extends Error {
42413
+ constructor(endpoint) {
42414
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
42415
+ this.name = "RemoteEndpointRefused";
42416
+ }
42417
+ };
42418
+ var RemoteResponseInvalid = class extends Error {
42419
+ constructor(route, detail) {
42420
+ super(`control plane answered ${route} with ${detail}`);
42421
+ this.name = "RemoteResponseInvalid";
42422
+ }
42423
+ };
42424
+ var RemoteTransportError = class extends Error {
42425
+ /**
42426
+ * The status the peer sent, when headers arrived and only the BODY was
42427
+ * refused.
42428
+ *
42429
+ * Undefined for the ordinary case this class was written for — no answer at
42430
+ * all. It exists because two paths reject after a status has already been
42431
+ * delivered: an oversized body and an aborted response. Discarding it there
42432
+ * reported a deployment answering 401 with a verbose body as a network
42433
+ * outage, which sends the reader to look at their network instead of their
42434
+ * credential.
42435
+ */
42436
+ constructor(reason, status) {
42437
+ super(`control-plane request did not complete: ${reason}`);
42438
+ this.status = status;
42439
+ this.name = "RemoteTransportError";
42440
+ }
42441
+ status;
42442
+ };
42443
+ async function send(options) {
42444
+ const url2 = new URL(options.url);
42445
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
42446
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
42447
+ const requestOptions = {
42448
+ method: options.method,
42449
+ headers: {
42450
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
42451
+ // last they win, and two of the values below are ones no caller may
42452
+ // replace: `x-api-key` is the credential, and `content-length` is the
42453
+ // byte count that stops a multi-byte body being truncated by the
42454
+ // receiver. `SendOptions.headers` is a free-form record on an exported
42455
+ // function, so "no caller does that today" is not the guarantee to rely
42456
+ // on. The one header any caller actually passes — `if-none-match` on the
42457
+ // conditional GET — is untouched by this order.
42458
+ ...options.headers,
42459
+ // The credential. One header, matching what the deployment authenticates
42460
+ // on; a second copy in an `Authorization` header would be one more place
42461
+ // it can be logged by an intermediary for no gain.
42462
+ //
42463
+ // Spread conditionally rather than assigned as `undefined`: Node's header
42464
+ // handling and `content-length` bookkeeping treat a present-but-undefined
42465
+ // key differently from an absent one, and "the header is not there" is
42466
+ // the property the attach flow needs.
42467
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
42468
+ accept: "application/json",
42469
+ ...options.body === void 0 ? {} : {
42470
+ "content-type": "application/json",
42471
+ // Byte length, not string length: a multi-byte body sent with a
42472
+ // character count is truncated by the receiver.
42473
+ "content-length": String(Buffer.byteLength(options.body))
42474
+ }
42475
+ }
42476
+ };
42477
+ return new Promise((resolve4, reject) => {
42478
+ let settled = false;
42479
+ const fail = (reason, status) => {
42480
+ if (settled) return;
42481
+ settled = true;
42482
+ reject(new RemoteTransportError(reason, status));
42483
+ };
42484
+ const req = send_(url2, requestOptions, (res) => {
42485
+ const chunks = [];
42486
+ let size = 0;
42487
+ res.on("data", (chunk) => {
42488
+ size += chunk.length;
42489
+ if (size > MAX_RESPONSE_BYTES) {
42490
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
42491
+ res.destroy();
42492
+ req.destroy();
42493
+ return;
42494
+ }
42495
+ chunks.push(chunk);
42496
+ });
42497
+ res.on("aborted", () => {
42498
+ fail("the response was aborted", res.statusCode);
42499
+ });
42500
+ res.on("end", () => {
42501
+ if (settled) return;
42502
+ settled = true;
42503
+ resolve4({
42504
+ status: res.statusCode ?? 0,
42505
+ headers: res.headers,
42506
+ body: Buffer.concat(chunks).toString("utf8")
42507
+ });
42508
+ });
42509
+ });
42510
+ const deadline = setTimeout(() => {
42511
+ fail(`no response within ${String(timeoutMs)}ms`);
42512
+ req.destroy();
42513
+ }, timeoutMs);
42514
+ deadline.unref();
42515
+ req.on("upgrade", (_res, socket) => {
42516
+ fail("the deployment answered with a protocol upgrade");
42517
+ socket.destroy();
42518
+ });
42519
+ req.on("close", () => {
42520
+ fail("the connection closed before a response was read");
42521
+ clearTimeout(deadline);
42522
+ });
42523
+ req.on("error", (err) => {
42524
+ fail(err.message);
42525
+ });
42526
+ if (options.body !== void 0) req.write(options.body);
42527
+ req.end();
42528
+ });
42529
+ }
42532
42530
 
42533
- // ../../packages/plugin-sdk/src/suppressions.ts
42534
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
42531
+ // ../../packages/remote/src/client.ts
42532
+ var ROUTES = {
42533
+ events: "/v1/events",
42534
+ auditEvents: "/v1/audit-events",
42535
+ auditEventsBatch: "/v1/audit-events/batch",
42536
+ inventory: "/v1/inventory",
42537
+ storePosture: "/v1/store-posture",
42538
+ policyBundle: "/v1/policy-bundle",
42539
+ whoami: "/v1/plugin/whoami",
42540
+ shares: "/v1/shares",
42541
+ commands: "/v1/plugin/commands"
42542
+ };
42543
+ function ackRoute(id) {
42544
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
42545
+ }
42546
+ function headerValue(response, name) {
42547
+ const raw = response.headers[name];
42548
+ if (raw === void 0) return void 0;
42549
+ return Array.isArray(raw) ? raw[0] : raw;
42550
+ }
42551
+ function okBody(response) {
42552
+ if (response.status < 200 || response.status >= 300) {
42553
+ throw new RemoteRequestError(response.status);
42554
+ }
42555
+ return response.body;
42556
+ }
42557
+ function parsed(schema, body, route) {
42558
+ let json2;
42559
+ try {
42560
+ json2 = JSON.parse(body);
42561
+ } catch {
42562
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
42563
+ }
42564
+ const result = schema.safeParse(json2);
42565
+ if (!result.success) {
42566
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
42567
+ }
42568
+ return result.data;
42569
+ }
42570
+ function resolveBaseUrl(endpoint) {
42571
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
42572
+ let end = endpoint.length;
42573
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
42574
+ return endpoint.slice(0, end);
42575
+ }
42576
+ var SLASH2 = "/".charCodeAt(0);
42577
+ function createRemoteClient(options) {
42578
+ const base = resolveBaseUrl(options.endpoint);
42579
+ const url2 = (route) => `${base}${route}`;
42580
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
42581
+ const sendOne = async (event) => {
42582
+ const validated = RecordAuditEventRequest.safeParse(event);
42583
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
42584
+ const response = await send({
42585
+ ...common,
42586
+ method: "POST",
42587
+ url: url2(ROUTES.auditEvents),
42588
+ body: JSON.stringify(validated.data)
42589
+ });
42590
+ okBody(response);
42591
+ };
42592
+ return {
42593
+ async ingestEvents(batch) {
42594
+ const response = await send({
42595
+ ...common,
42596
+ method: "POST",
42597
+ url: url2(ROUTES.events),
42598
+ body: JSON.stringify(batch)
42599
+ });
42600
+ return parsed(IngestAck, okBody(response), ROUTES.events);
42601
+ },
42602
+ async ingestInventory(context) {
42603
+ const response = await send({
42604
+ ...common,
42605
+ method: "POST",
42606
+ url: url2(ROUTES.inventory),
42607
+ body: JSON.stringify(context)
42608
+ });
42609
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
42610
+ },
42611
+ async recordAuditEvent(event) {
42612
+ await sendOne(event);
42613
+ },
42614
+ async recordAuditEvents(events, opts) {
42615
+ const validated = RecordAuditEventBatch.safeParse({ events });
42616
+ if (!validated.success) {
42617
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
42618
+ }
42619
+ const response = await send({
42620
+ ...common,
42621
+ method: "POST",
42622
+ url: url2(ROUTES.auditEventsBatch),
42623
+ body: JSON.stringify(validated.data)
42624
+ });
42625
+ if (response.status === 404) {
42626
+ if (opts?.fallbackToSingleEvents !== true) {
42627
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
42628
+ }
42629
+ for (const event of validated.data.events) await sendOne(event);
42630
+ return { accepted: validated.data.events.length };
42631
+ }
42632
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
42633
+ },
42634
+ async reportStorePosture(snapshot) {
42635
+ const response = await send({
42636
+ ...common,
42637
+ method: "POST",
42638
+ url: url2(ROUTES.storePosture),
42639
+ body: JSON.stringify(snapshot)
42640
+ });
42641
+ okBody(response);
42642
+ },
42643
+ async getPolicyBundle(etag) {
42644
+ const response = await send({
42645
+ ...common,
42646
+ method: "GET",
42647
+ url: url2(ROUTES.policyBundle),
42648
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
42649
+ });
42650
+ if (response.status === 304) {
42651
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
42652
+ }
42653
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
42654
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
42655
+ },
42656
+ async whoami() {
42657
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
42658
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
42659
+ },
42660
+ async recordProjectEgress(request) {
42661
+ const validated = EgressIngestRequest.safeParse(request);
42662
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
42663
+ const response = await send({
42664
+ ...common,
42665
+ method: "POST",
42666
+ url: url2(ROUTES.shares),
42667
+ body: JSON.stringify(validated.data)
42668
+ });
42669
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
42670
+ okBody(response);
42671
+ },
42672
+ async pollCommand() {
42673
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
42674
+ if (response.status === 404) return null;
42675
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
42676
+ },
42677
+ async ackCommand(id, body) {
42678
+ const validated = DeviceCommandAckBody.safeParse(body);
42679
+ const route = ackRoute(id);
42680
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
42681
+ const response = await send({
42682
+ ...common,
42683
+ method: "POST",
42684
+ url: url2(route),
42685
+ body: JSON.stringify(validated.data)
42686
+ });
42687
+ okBody(response);
42688
+ }
42689
+ };
42690
+ }
42535
42691
 
42536
- // ../../packages/plugin-sdk/src/throttle.ts
42537
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
42538
- import { join as join27 } from "path";
42692
+ // ../../packages/remote/src/failure-kind.ts
42693
+ function statusOf(err) {
42694
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
42695
+ const { status } = err;
42696
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
42697
+ return status >= 100 && status <= 599 ? status : null;
42698
+ }
42699
+ function nameOf(err) {
42700
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
42701
+ return typeof err.name === "string" ? err.name : null;
42702
+ }
42703
+ function classifyRemoteFailure(err) {
42704
+ switch (nameOf(err)) {
42705
+ case "RemoteRouteAbsent":
42706
+ return "route-absent";
42707
+ case "RemoteRequestInvalid":
42708
+ case "RemoteEndpointRefused":
42709
+ return "invalid-request";
42710
+ case "RemoteResponseInvalid":
42711
+ return "rejected";
42712
+ default:
42713
+ break;
42714
+ }
42715
+ const status = statusOf(err);
42716
+ if (status === null) return "unreachable";
42717
+ switch (status) {
42718
+ case 401:
42719
+ return "unauthorized";
42720
+ case 403:
42721
+ return "forbidden";
42722
+ case 429:
42723
+ return "unreachable";
42724
+ case 404:
42725
+ return "unreachable";
42726
+ default:
42727
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
42728
+ }
42729
+ }
42730
+
42731
+ // ../../packages/plugin-runtime/src/attached/failure.ts
42732
+ function classifyFailure(err) {
42733
+ switch (classifyRemoteFailure(err)) {
42734
+ case "unauthorized":
42735
+ return "unauthorized";
42736
+ case "forbidden":
42737
+ return "forbidden";
42738
+ default:
42739
+ return "unreachable";
42740
+ }
42741
+ }
42742
+
42743
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
42744
+ var REQUEST_TIMEOUT_MS = 2e3;
42745
+ function withTimeout(promise2, ms) {
42746
+ let timer;
42747
+ const timeout = new Promise((_, reject) => {
42748
+ timer = setTimeout(() => {
42749
+ reject(new Error("attached gateway request timed out"));
42750
+ }, ms);
42751
+ });
42752
+ promise2.catch(() => void 0);
42753
+ return Promise.race([promise2, timeout]).finally(() => {
42754
+ clearTimeout(timer);
42755
+ });
42756
+ }
42757
+
42758
+ // ../../packages/plugin-runtime/src/attached/command-sync.ts
42759
+ var COMMAND_REQUEST_TIMEOUT_MS = 3e4;
42760
+ var SCAN_THREW = "scan_failed";
42761
+ var SCAN_FOUND_NOTHING = "no_projects";
42762
+ var COMMAND_EXPIRED = "expired";
42763
+ function hasExpired(expiresAt, atMs) {
42764
+ const deadlineMs = Date.parse(expiresAt);
42765
+ return Number.isFinite(deadlineMs) && deadlineMs <= atMs;
42766
+ }
42767
+ function rootVerdict(settings, endpoint, credential, scan2) {
42768
+ try {
42769
+ const resolved = resolveScope({
42770
+ mode: attachmentModeOf(credential),
42771
+ scope: settings.attachmentScope,
42772
+ endpoint
42773
+ });
42774
+ return scopeVerdict(resolved, resolved.mode === "scoped" ? scan2.rootScopeKey() : void 0);
42775
+ } catch {
42776
+ return "local";
42777
+ }
42778
+ }
42779
+ var SERVICE = {
42780
+ shares_rescan: (scan2) => scan2.run()
42781
+ };
42782
+ async function runCommandSync(deps) {
42783
+ if (deps.scan === void 0) return null;
42784
+ const settings = readWorkspaceSettings(deps.base);
42785
+ const connection = isAttached(settings) ? settings.controlPlane : void 0;
42786
+ const state = connection === void 0 ? void 0 : readControlPlaneCredentialFile(deps.settingsDir, connection);
42787
+ if (connection === void 0 || !state?.usable) return null;
42788
+ const client = createRemoteClient({
42789
+ endpoint: connection.endpoint,
42790
+ apiKey: state.credential.apiKey,
42791
+ timeoutMs: COMMAND_REQUEST_TIMEOUT_MS
42792
+ });
42793
+ let command;
42794
+ try {
42795
+ command = await withTimeout(client.pollCommand(), COMMAND_REQUEST_TIMEOUT_MS);
42796
+ } catch (err) {
42797
+ const failure2 = classifyFailure(err);
42798
+ return failure2 === "unreachable" ? "unreachable" : failure2;
42799
+ }
42800
+ if (command === null) return "none";
42801
+ let projects = 0;
42802
+ let reason = null;
42803
+ if (hasExpired(command.expiresAt, (deps.now ?? Date.now)())) {
42804
+ reason = COMMAND_EXPIRED;
42805
+ } else if (rootVerdict(settings, connection.endpoint, state.credential, deps.scan) === "local") {
42806
+ return "out-of-scope";
42807
+ } else {
42808
+ try {
42809
+ projects = (await SERVICE[command.kind](deps.scan)).projects;
42810
+ if (projects === 0) reason = SCAN_FOUND_NOTHING;
42811
+ } catch {
42812
+ reason = SCAN_THREW;
42813
+ }
42814
+ }
42815
+ try {
42816
+ await withTimeout(
42817
+ reason === null ? client.ackCommand(command.id, { outcome: "reported", projectsScanned: projects }) : client.ackCommand(command.id, {
42818
+ outcome: "failed",
42819
+ reason,
42820
+ projectsScanned: projects
42821
+ }),
42822
+ COMMAND_REQUEST_TIMEOUT_MS
42823
+ );
42824
+ } catch (err) {
42825
+ const failure2 = classifyFailure(err);
42826
+ return failure2 === "unreachable" ? "unreachable" : failure2;
42827
+ }
42828
+ return reason === null ? "reported" : "failed";
42829
+ }
42830
+ function readSessionDirectory() {
42831
+ try {
42832
+ return process.cwd();
42833
+ } catch {
42834
+ return void 0;
42835
+ }
42836
+ }
42837
+ function commandScanFor(loadConfig2, scanWorktree2, sourceTool) {
42838
+ const rootDir = readSessionDirectory();
42839
+ return {
42840
+ rootScopeKey: () => rootDir === void 0 ? void 0 : resolveRepoAttribution(rootDir).scopeKey,
42841
+ run: async () => {
42842
+ if (rootDir === void 0) throw new Error("the session working directory cannot be read");
42843
+ const summary = await scanWorktree2(loadConfig2(), { sourceTool, rootDir });
42844
+ return { projects: summary.scanned > 0 ? 1 : 0 };
42845
+ }
42846
+ };
42847
+ }
42848
+
42849
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
42850
+ import { readFileSync as readFileSync13 } from "fs";
42851
+ import { join as join20 } from "path";
42852
+ var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
42853
+ function forwardDropsPath(dataDir2) {
42854
+ return join20(dataDir2, FORWARD_DROPS_FILENAME);
42855
+ }
42856
+ function recordForwardDrops(dataDir2, count, nowMs) {
42857
+ if (count <= 0) return;
42858
+ try {
42859
+ ensureDataDirSync(dataDir2);
42860
+ const previous = readForwardDrops(dataDir2);
42861
+ const next = {
42862
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
42863
+ lastDropAtMs: nowMs
42864
+ };
42865
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
42866
+ `);
42867
+ } catch {
42868
+ }
42869
+ }
42870
+ function readForwardDrops(dataDir2) {
42871
+ try {
42872
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
42873
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
42874
+ const record2 = parsed2;
42875
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
42876
+ return null;
42877
+ }
42878
+ if (record2.droppedForwards <= 0) return null;
42879
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
42880
+ return null;
42881
+ }
42882
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
42883
+ } catch {
42884
+ return null;
42885
+ }
42886
+ }
42539
42887
 
42540
42888
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
42889
+ import { randomUUID as randomUUID16 } from "crypto";
42890
+ import { readFile, rename, writeFile } from "fs/promises";
42891
+ import { join as join21 } from "path";
42541
42892
  function isInvalidRequest(err) {
42542
42893
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
42543
42894
  }
@@ -42556,7 +42907,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
42556
42907
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
42557
42908
  function createForwardPolicy(deps) {
42558
42909
  const now = deps.now ?? (() => Date.now());
42559
- const file2 = join28(deps.dir, STATE_FILENAME);
42910
+ const file2 = join21(deps.dir, STATE_FILENAME);
42560
42911
  let state = null;
42561
42912
  let loading = null;
42562
42913
  async function readState() {
@@ -42722,6 +43073,9 @@ var AttachedDataGateway = class {
42722
43073
  *
42723
43074
  * Machine mode answers before any key is read, so a machine attachment pays
42724
43075
  * nothing for scoping and forwards exactly what it always has.
43076
+ *
43077
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
43078
+ * forwarding key for key.
42725
43079
  */
42726
43080
  verdictFor(keyOf) {
42727
43081
  try {
@@ -42738,24 +43092,27 @@ var AttachedDataGateway = class {
42738
43092
  * the key its row holds in the local store, recorded per root (see
42739
43093
  * `rootVerdict`), not the key on the root event just handed in: roots are
42740
43094
  * first-write-wins in the store, so when two producers record a root for one
42741
- * session (the session-start hook, then a reconcile pass) the second leaves
42742
- * the stored row as it was, and the history drain decides that row, not this
42743
- * event. Whether this root EVENT is itself sent takes both keys: the stored
42744
- * one AND its own. The event's attributes (cwd, project, repo) describe where
42745
- * it was recorded from, so a root event keyed to a personal directory is never
42746
- * sent under an enrolled stored root, though the enrolled leaves still forward
42747
- * under it: the instance that wrote the stored root is expected to have
42748
- * forwarded it. If it did not (the root was written while standalone or under
42749
- * another attachment, or its forward failed), the plane refuses those leaves
42750
- * and the history drain ships the root first. Any other row with a root
42751
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
42752
- * is in scope AND this instance recorded an in-scope verdict for that root.
42753
- * The audit-event route has real foreign keys on both columns and stubs no
42754
- * missing root, so a leaf sent after its root was kept local is refused
42755
- * there, and a refused forward counts toward the breaker that guards every
42756
- * other one. A root this instance never recorded is therefore `'local'`: the
42757
- * only answer that cannot orphan a row. A row with no root reference at all
42758
- * has nothing to orphan, and is decided by its own key.
43095
+ * session (the session-start hook, then a reconcile pass) the second leaves the
43096
+ * stored row as it was. That stored row, not this event, is what a history
43097
+ * drain pass would decide, if the root started before the attach; the drain
43098
+ * never offers one that started after it (`started_at < backlogBefore`).
43099
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
43100
+ * its own. The event's attributes (cwd, project, repo) describe where it was
43101
+ * recorded from, so a root event keyed to a personal directory is never sent
43102
+ * under an enrolled stored root, though the enrolled leaves still forward under
43103
+ * it: the instance that wrote the stored root is expected to have forwarded it.
43104
+ * If it did not (the root was written while standalone or under another
43105
+ * attachment, or its forward failed), the plane refuses those leaves. A root
43106
+ * that started before the attach is shipped, ahead of its leaves, by the
43107
+ * history drain; one that started after it is never offered by the drain. Any
43108
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
43109
+ * only when its own key is in scope AND this instance recorded an in-scope
43110
+ * verdict for that root. The audit-event route has real foreign keys on both
43111
+ * columns and stubs no missing root, so a leaf sent after its root was kept
43112
+ * local is refused there, and a refused forward counts toward the breaker that
43113
+ * guards every other one. A root this instance never recorded is therefore
43114
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
43115
+ * reference at all has nothing to orphan, and is decided by its own key.
42759
43116
  *
42760
43117
  * What this costs is stated rather than discovered. A session whose stored
42761
43118
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -42826,6 +43183,87 @@ var AttachedDataGateway = class {
42826
43183
  return [];
42827
43184
  }
42828
43185
  }
43186
+ /**
43187
+ * The verdict for the repositories nested in a scanned project, answered
43188
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
43189
+ *
43190
+ * A walk descends into a nested clone or submodule and folds its files into
43191
+ * the project it is walking, so one register can carry several
43192
+ * repositories' call sites under one project key. Each of them must be in
43193
+ * scope for it to forward. One key out of scope, or a nested repository with
43194
+ * no remote (an `undefined` key), keeps the whole register local.
43195
+ *
43196
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
43197
+ * what is nested in it, and every scan passes the list, empty when nothing
43198
+ * is nested. A register nobody vouched for is not one a scoped attachment
43199
+ * may send.
43200
+ *
43201
+ * Machine mode answers before reading the context, so a machine attachment
43202
+ * forwards exactly what it always has.
43203
+ */
43204
+ nestedVerdict(context) {
43205
+ try {
43206
+ if (this.deps.attachment.mode === "machine") return "forward";
43207
+ const keys = context?.nestedScopeKeys;
43208
+ if (keys === void 0) return "local";
43209
+ for (const key of keys) {
43210
+ if (this.verdictFor(() => key) === "local") return "local";
43211
+ }
43212
+ return "forward";
43213
+ } catch {
43214
+ return "local";
43215
+ }
43216
+ }
43217
+ /**
43218
+ * The register a scoped attachment sends, once the project and the repositories
43219
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
43220
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
43221
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
43222
+ *
43223
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
43224
+ * and the ledger holds every file the scanner ever read under the root, nested
43225
+ * clones' included. So a clone that was removed, or one an ignore file now
43226
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
43227
+ * paths come back as deleted. The scan names the repository of each deleted
43228
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
43229
+ * and each is held to the same verdict as any other key. A path whose key is
43230
+ * absent, or out of scope, is not sent.
43231
+ *
43232
+ * The list is asked for here, and only here: it is an async read of the scan
43233
+ * ledger that the scan makes on being called, so a machine attachment, which
43234
+ * returns before this, and a register already kept local never cause it.
43235
+ *
43236
+ * Anything the scan did not vouch for sends no deleted path, and the register
43237
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
43238
+ * list whose length is not the register's. Deleting is the only thing a dropped
43239
+ * path could have done on the server, so the cost of a refusal is a stored row
43240
+ * that stays, never a path that leaves.
43241
+ *
43242
+ * Machine mode returns `input` itself, the same object and unread, so a machine
43243
+ * attachment's request is exactly what it was. A register that lists no deleted
43244
+ * path, or that is not a ledger register, has nothing to cut and is returned
43245
+ * as it came, with the list unread.
43246
+ */
43247
+ async registerForWire(input2, context) {
43248
+ try {
43249
+ if (this.deps.attachment.mode === "machine") return input2;
43250
+ const { reconcile } = input2;
43251
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
43252
+ const deleted = reconcile.deletedFiles;
43253
+ let kept = [];
43254
+ try {
43255
+ const keys = await context?.deletedFileKeys?.();
43256
+ if (keys?.length === deleted.length) {
43257
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
43258
+ }
43259
+ } catch {
43260
+ kept = [];
43261
+ }
43262
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
43263
+ } catch {
43264
+ return void 0;
43265
+ }
43266
+ }
42829
43267
  /**
42830
43268
  * The event `recordCapture` sends for a capture the verdict let through, or
42831
43269
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -43151,12 +43589,24 @@ var AttachedDataGateway = class {
43151
43589
  * payload onto the wire-boundary-safe shape (no snippet, hashed
43152
43590
  * projectKey), and its result is discarded: `forward.run` never throws or
43153
43591
  * rejects, so there is nothing here to act on.
43592
+ *
43593
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
43594
+ * not say: the key of every repository nested below the scan root, whose
43595
+ * files the walk folded into this register. On a scoped attachment the
43596
+ * register is forwarded only when the project's own key AND every one of
43597
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
43598
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
43599
+ * `registerForWire`). Machine mode never reads either, and the local write
43600
+ * never receives the context and gets the register whole.
43154
43601
  */
43155
- async recordProjectEgress(input2) {
43602
+ async recordProjectEgress(input2, context) {
43156
43603
  const summary = await this.deps.local.recordProjectEgress(input2);
43157
43604
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
43605
+ if (this.nestedVerdict(context) === "local") return summary;
43606
+ const register = await this.registerForWire(input2, context);
43607
+ if (register === void 0) return summary;
43158
43608
  await this.deps.forward.run(
43159
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
43609
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
43160
43610
  );
43161
43611
  return summary;
43162
43612
  }
@@ -43210,6 +43660,11 @@ var AttachedDataGateway = class {
43210
43660
  async scanLedgerPaths() {
43211
43661
  return this.deps.local.scanLedgerPaths();
43212
43662
  }
43663
+ // Delegated, like the path list. An inner gateway that cannot say answers an
43664
+ // empty map, which gives every deleted path no key.
43665
+ async scanLedgerPathKeys() {
43666
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
43667
+ }
43213
43668
  async recordScanned(entries) {
43214
43669
  return this.deps.local.recordScanned(entries);
43215
43670
  }
@@ -43276,6 +43731,12 @@ var AttachedDataGateway = class {
43276
43731
  // and the spread above would otherwise drop the field silently — which is
43277
43732
  // exactly what it did, leaving the whole control inert on every device
43278
43733
  // while every test around it stayed green.
43734
+ //
43735
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
43736
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
43737
+ // reads this bundle once to build detection, so the detections it carries
43738
+ // apply to every event on the machine. Where a prohibition applies is
43739
+ // answered per event by `governanceAppliesTo` below.
43279
43740
  prohibitedModels: cached2.prohibitedModels,
43280
43741
  // NAMED for the same reason as the line above, and it is the same defect
43281
43742
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -43335,6 +43796,30 @@ var AttachedDataGateway = class {
43335
43796
  };
43336
43797
  }
43337
43798
  // ---------------------------------------------------------------------
43799
+ // GovernanceScope — where the organization's model policy applies
43800
+ // ---------------------------------------------------------------------
43801
+ /**
43802
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
43803
+ * the question a model-guard site asks once it has decided to refuse.
43804
+ *
43805
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
43806
+ * with the same key would be forwarded. A machine-wide attachment governs
43807
+ * every event, keyless included, exactly as before. A scoped one governs an
43808
+ * event only when its key names an enrolled repository. An event in a
43809
+ * personal repository, in no repository, with an empty key, or met by a fault
43810
+ * is not governed.
43811
+ *
43812
+ * The event's OWN key, never its session root's. The root rule in
43813
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
43814
+ * this decides whether a refusal applies, which is a question about where the
43815
+ * event happened.
43816
+ *
43817
+ * Answered from memory: no store read, no bundle read, nothing sent.
43818
+ */
43819
+ governanceAppliesTo(scopeKey) {
43820
+ return this.verdictFor(() => scopeKey) === "forward";
43821
+ }
43822
+ // ---------------------------------------------------------------------
43338
43823
  // LocalStoreMaintenance — by delegation (D3).
43339
43824
  //
43340
43825
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -43443,8 +43928,8 @@ function toWireInspection(insp) {
43443
43928
  }
43444
43929
 
43445
43930
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
43446
- import { createHash as createHash6 } from "crypto";
43447
- import { hostname as hostname5 } from "os";
43931
+ import { createHash as createHash7 } from "crypto";
43932
+ import { hostname as hostname4 } from "os";
43448
43933
 
43449
43934
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
43450
43935
  var CORRELATION_ID = EventMetadata.shape.correlationId;
@@ -43462,17 +43947,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
43462
43947
 
43463
43948
  // ../../packages/plugin-runtime/src/attached/install-record.ts
43464
43949
  import { readFile as readFile2, stat } from "fs/promises";
43465
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
43950
+ import { basename as basename4, dirname as dirname6, join as join22, resolve as resolve2 } from "path";
43466
43951
  async function readInstalledVersion(installRoot) {
43467
43952
  try {
43468
43953
  const versionDir = resolve2(installRoot);
43469
- const pluginDir = dirname7(versionDir);
43470
- const marketplaceDir = dirname7(pluginDir);
43471
- const cacheDir = dirname7(marketplaceDir);
43472
- if (basename6(cacheDir) !== "cache") return null;
43473
- const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
43954
+ const pluginDir = dirname6(versionDir);
43955
+ const marketplaceDir = dirname6(pluginDir);
43956
+ const cacheDir = dirname6(marketplaceDir);
43957
+ if (basename4(cacheDir) !== "cache") return null;
43958
+ const key = `${basename4(pluginDir)}@${basename4(marketplaceDir)}`;
43474
43959
  const record2 = JSON.parse(
43475
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
43960
+ await readFile2(join22(dirname6(cacheDir), "installed_plugins.json"), "utf8")
43476
43961
  );
43477
43962
  const plugins = record2?.plugins;
43478
43963
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -43504,7 +43989,7 @@ async function exists(path) {
43504
43989
  }
43505
43990
 
43506
43991
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
43507
- import { readFileSync as readFileSync18 } from "fs";
43992
+ import { readFileSync as readFileSync14 } from "fs";
43508
43993
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
43509
43994
  function createPluginBlock(build, policyStore) {
43510
43995
  return async () => {
@@ -43534,7 +44019,7 @@ async function readInstalledVersionBounded(installRoot) {
43534
44019
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
43535
44020
  import { randomUUID as randomUUID17 } from "crypto";
43536
44021
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
43537
- import { join as join30 } from "path";
44022
+ import { join as join23 } from "path";
43538
44023
 
43539
44024
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
43540
44025
  import { rename as rename2 } from "fs/promises";
@@ -43563,7 +44048,7 @@ async function publishByRename(tmp, file2, move = rename2) {
43563
44048
 
43564
44049
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
43565
44050
  function createPolicyStore(dir = dataDir()) {
43566
- const file2 = join30(dir, "policy-cache.json");
44051
+ const file2 = join23(dir, "policy-cache.json");
43567
44052
  async function read() {
43568
44053
  try {
43569
44054
  const raw = await readFile3(file2, "utf8");
@@ -43682,8 +44167,8 @@ async function runPolicySync(deps) {
43682
44167
  }
43683
44168
 
43684
44169
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
43685
- import { readFileSync as readFileSync19 } from "fs";
43686
- import { join as join31 } from "path";
44170
+ import { readFileSync as readFileSync15 } from "fs";
44171
+ import { join as join24 } from "path";
43687
44172
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
43688
44173
  var OUTCOME_KEYS = {
43689
44174
  ok: true,
@@ -43697,7 +44182,7 @@ var OUTCOME_KEYS = {
43697
44182
  };
43698
44183
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
43699
44184
  function postureReportStatePath(dataDir2) {
43700
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
44185
+ return join24(dataDir2, POSTURE_REPORT_STATE_FILENAME);
43701
44186
  }
43702
44187
  function writePostureReportState(dataDir2, state) {
43703
44188
  try {
@@ -43738,10 +44223,19 @@ function createPostureReporter(deps) {
43738
44223
  hostname: deps.hostname(),
43739
44224
  capturedAt: nowMs,
43740
44225
  ...measurement,
43741
- // Omit the key rather than spread an explicit `undefined` —
43742
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
43743
- // factory.ts keys on presence.
43744
- ...plugin === void 0 ? {} : { plugin }
44226
+ // Omit the key rather than spread an explicit `undefined`. The type
44227
+ // admits `undefined` here (the schema's optional member), and
44228
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
44229
+ // in-memory object free of an explicit `undefined` member, which the
44230
+ // tests pin by key presence.
44231
+ ...plugin === void 0 ? {} : { plugin },
44232
+ // LAST, and only for a scoped attachment. A machine attachment omits
44233
+ // the key the same way, so its body is byte for byte the one it sent
44234
+ // before the member existed. Anything but exactly `machine` reports the
44235
+ // constant `scoped`, never the raw value: that is resolveScope's own
44236
+ // fail direction, and a value outside the wire's vocabulary would fail
44237
+ // the whole snapshot at the receiver, the wipe signal with it.
44238
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
43745
44239
  };
43746
44240
  } catch {
43747
44241
  return null;
@@ -43764,8 +44258,8 @@ function createPostureReporter(deps) {
43764
44258
  }
43765
44259
 
43766
44260
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
43767
- import { statSync as statSync9 } from "fs";
43768
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
44261
+ import { statSync as statSync7 } from "fs";
44262
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
43769
44263
 
43770
44264
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
43771
44265
  function emptyActionCounts() {
@@ -43795,7 +44289,7 @@ function emptyReadout(readError = false) {
43795
44289
  }
43796
44290
  function readStorePosture(dbPath2) {
43797
44291
  try {
43798
- statSync9(dbPath2);
44292
+ statSync7(dbPath2);
43799
44293
  } catch (err) {
43800
44294
  const code = err.code;
43801
44295
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -43823,7 +44317,7 @@ function readStorePosture(dbPath2) {
43823
44317
  readError: false
43824
44318
  });
43825
44319
  try {
43826
- db = new DatabaseSync4(dbPath2, { readOnly: true });
44320
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
43827
44321
  db.exec("PRAGMA busy_timeout = 2000");
43828
44322
  version2 = db.prepare("PRAGMA user_version").get().user_version;
43829
44323
  try {
@@ -43877,11 +44371,11 @@ function readStorePosture(dbPath2) {
43877
44371
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
43878
44372
  import { randomUUID as randomUUID18 } from "crypto";
43879
44373
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
43880
- import { join as join32 } from "path";
44374
+ import { join as join25 } from "path";
43881
44375
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
43882
44376
  function createPostureStore(dir = settingsDir(), legacyDir) {
43883
- const file2 = join32(dir, "posture-state.json");
43884
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
44377
+ const file2 = join25(dir, "posture-state.json");
44378
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
43885
44379
  async function persist(state) {
43886
44380
  await ensureDataDir(dir);
43887
44381
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -43949,11 +44443,11 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
43949
44443
  }
43950
44444
 
43951
44445
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
43952
- import { readFileSync as readFileSync20 } from "fs";
43953
- import { join as join33 } from "path";
44446
+ import { readFileSync as readFileSync16 } from "fs";
44447
+ import { join as join26 } from "path";
43954
44448
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
43955
44449
  function syncStatePath(dataDir2) {
43956
- return join33(dataDir2, SYNC_STATE_FILENAME);
44450
+ return join26(dataDir2, SYNC_STATE_FILENAME);
43957
44451
  }
43958
44452
  function writeSyncState(dataDir2, result) {
43959
44453
  try {
@@ -44015,7 +44509,7 @@ import { fileURLToPath as fileURLToPath4 } from "url";
44015
44509
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
44016
44510
 
44017
44511
  // ../../packages/plugin-runtime/src/attached/factory.ts
44018
- import { hostname as hostname6 } from "os";
44512
+ import { hostname as hostname5 } from "os";
44019
44513
 
44020
44514
  // ../../packages/plugin-runtime/src/recorder.ts
44021
44515
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -44028,7 +44522,7 @@ var StandaloneDataGateway = class {
44028
44522
  // One notice per gateway — see warnRulesetDiscarded.
44029
44523
  warnedRulesetDiscarded = false;
44030
44524
  constructor(dataDir2, detections = [], meta4) {
44031
- this.db = openLocalDatabase(dataDir2);
44525
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
44032
44526
  this.dataDir = dataDir2;
44033
44527
  this.db.installedPacks.recordInventory(detections, meta4);
44034
44528
  }
@@ -44377,6 +44871,9 @@ var StandaloneDataGateway = class {
44377
44871
  scanLedgerPaths() {
44378
44872
  return Promise.resolve(this.db.scanLedger.allPaths());
44379
44873
  }
44874
+ scanLedgerPathKeys() {
44875
+ return Promise.resolve(this.db.scanLedger.pathKeys());
44876
+ }
44380
44877
  recordScanned(entries) {
44381
44878
  this.db.scanLedger.upsertEntries(entries);
44382
44879
  return Promise.resolve();
@@ -44462,13 +44959,17 @@ function resolveGatewayForConfig(config2, meta4) {
44462
44959
  },
44463
44960
  store: postureStore,
44464
44961
  readStore: () => readStorePosture(config2.dbPath),
44465
- hostname: () => hostname6(),
44962
+ hostname: () => hostname5(),
44466
44963
  now: () => Date.now(),
44964
+ // The mode THIS gateway enforces, from the attachment resolved above,
44965
+ // so the report cannot name a mode the forward paths are not using.
44966
+ attachmentMode: attachment.mode,
44467
44967
  // The reporting build's identity, when the caller knows it (the plugin
44468
44968
  // adapters do; an embedder or a test may not). Composed with the SAME
44469
44969
  // policy store the sync child writes, so the block names the bundle
44470
- // actually in force. Key omitted rather than set undefined — the
44471
- // reporter keys on presence.
44970
+ // actually in force. The dependency key is omitted when no build is
44971
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
44972
+ // then adds no block.
44472
44973
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
44473
44974
  })
44474
44975
  });
@@ -44489,8 +44990,8 @@ import { randomUUID as randomUUID19 } from "crypto";
44489
44990
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
44490
44991
 
44491
44992
  // ../../packages/scanner/src/discover.ts
44492
- import { readdirSync as readdirSync5 } from "fs";
44493
- import { join as join34 } from "path";
44993
+ import { readdirSync as readdirSync3 } from "fs";
44994
+ import { join as join27 } from "path";
44494
44995
 
44495
44996
  // ../../packages/scanner/src/constants.ts
44496
44997
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -44511,18 +45012,18 @@ var DISCOVER_SKIP = /* @__PURE__ */ new Set([
44511
45012
  ]);
44512
45013
 
44513
45014
  // ../../packages/scanner/src/render.ts
44514
- import { basename as basename7, relative } from "path";
45015
+ import { basename as basename5, relative } from "path";
44515
45016
 
44516
45017
  // ../../packages/scanner/src/scan.ts
44517
- import { existsSync as existsSync14, readFileSync as readFileSync22 } from "fs";
44518
- import { extname as extname2, isAbsolute as isAbsolute3, relative as relative3 } from "path";
45018
+ import { existsSync as existsSync12, readFileSync as readFileSync18 } from "fs";
45019
+ import { extname as extname2, isAbsolute as isAbsolute2, relative as relative3 } from "path";
44519
45020
 
44520
45021
  // ../../packages/scanner/src/manifests.ts
44521
- import { statSync as statSync11 } from "fs";
45022
+ import { statSync as statSync9 } from "fs";
44522
45023
 
44523
45024
  // ../../packages/scanner/src/walk.ts
44524
- import { readdirSync as readdirSync6, readFileSync as readFileSync21, statSync as statSync10 } from "fs";
44525
- import { extname, join as join35, relative as relative2, sep as sep4 } from "path";
45025
+ import { readdirSync as readdirSync4, readFileSync as readFileSync17, statSync as statSync8 } from "fs";
45026
+ import { extname, join as join28, relative as relative2, sep as sep4 } from "path";
44526
45027
  var import_ignore2 = __toESM(require_ignore(), 1);
44527
45028
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
44528
45029
  ".ts",
@@ -44555,14 +45056,18 @@ var SKIP_DIRS = /* @__PURE__ */ new Set([
44555
45056
  var DEFAULT_MAX_BYTES = 512 * 1024;
44556
45057
  function* walkTree(rootDir, opts = {}) {
44557
45058
  const trackGitignore = opts.trackGitignore ?? false;
45059
+ const onRepositoryRoot = opts.onRepositoryRoot;
44558
45060
  const rootSkipLayers = opts.excludePatterns && opts.excludePatterns.length > 0 ? [{ matcher: (0, import_ignore2.default)().add(opts.excludePatterns), anchorLen: 0 }] : [];
44559
45061
  function* visit2(dir, dirRel, markLayers, skipLayers, inIgnoredDir) {
44560
45062
  let dirents;
44561
45063
  try {
44562
- dirents = readdirSync6(dir, { withFileTypes: true, encoding: "utf8" });
45064
+ dirents = readdirSync4(dir, { withFileTypes: true, encoding: "utf8" });
44563
45065
  } catch {
44564
45066
  return;
44565
45067
  }
45068
+ if (onRepositoryRoot !== void 0 && dirRel !== "" && dirents.some((entry) => entry.name === ".git")) {
45069
+ onRepositoryRoot(dirRel);
45070
+ }
44566
45071
  const dirMarkLayers = withLayer(
44567
45072
  markLayers,
44568
45073
  trackGitignore && !inIgnoredDir ? readIgnoreLayer(dir, ".gitignore", dirRel.length) : void 0
@@ -44573,7 +45078,7 @@ function* walkTree(rootDir, opts = {}) {
44573
45078
  );
44574
45079
  for (const entry of dirents) {
44575
45080
  const name = entry.name;
44576
- const fullPath = join35(dir, name);
45081
+ const fullPath = join28(dir, name);
44577
45082
  if (entry.isDirectory()) {
44578
45083
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
44579
45084
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {
@@ -44600,14 +45105,15 @@ function* walkSourceFiles(opts = {}) {
44600
45105
  const maxBytes = opts.maxFileSizeBytes ?? DEFAULT_MAX_BYTES;
44601
45106
  for (const file2 of walkTree(rootDir, {
44602
45107
  excludePatterns: opts.excludePatterns,
44603
- trackGitignore: true
45108
+ trackGitignore: true,
45109
+ onRepositoryRoot: opts.onRepositoryRoot
44604
45110
  })) {
44605
45111
  const ext = extname(file2.name);
44606
45112
  if (!extensions.has(ext)) continue;
44607
45113
  let size;
44608
45114
  let mtime;
44609
45115
  try {
44610
- const st = statSync10(file2.path);
45116
+ const st = statSync8(file2.path);
44611
45117
  size = st.size;
44612
45118
  mtime = st.mtime;
44613
45119
  } catch {
@@ -44627,7 +45133,7 @@ function* walkSourceFiles(opts = {}) {
44627
45133
  if (opts.shouldRead && !opts.shouldRead(meta4)) continue;
44628
45134
  let content;
44629
45135
  try {
44630
- content = readFileSync21(file2.path, "utf8");
45136
+ content = readFileSync17(file2.path, "utf8");
44631
45137
  } catch {
44632
45138
  continue;
44633
45139
  }
@@ -44643,13 +45149,13 @@ function* walkSourceFiles(opts = {}) {
44643
45149
 
44644
45150
  // ../../packages/scanner/src/manifests.ts
44645
45151
  var MAX_MANIFEST_BYTES = 512 * 1024;
44646
- function collectManifests(rootDir, maxFileSizeBytes = MAX_MANIFEST_BYTES) {
45152
+ function collectManifests(rootDir, maxFileSizeBytes = MAX_MANIFEST_BYTES, onRepositoryRoot) {
44647
45153
  const found = [];
44648
- for (const file2 of walkTree(rootDir)) {
45154
+ for (const file2 of walkTree(rootDir, { onRepositoryRoot })) {
44649
45155
  const kind = manifestKindOf(file2.name);
44650
45156
  if (kind === null) continue;
44651
45157
  try {
44652
- const st = statSync11(file2.path);
45158
+ const st = statSync9(file2.path);
44653
45159
  if (st.size > maxFileSizeBytes) continue;
44654
45160
  found.push({ path: file2.path, kind, mtime: st.mtime.toISOString(), size: st.size });
44655
45161
  } catch {
@@ -44666,35 +45172,66 @@ function computeResolutions(prior, current) {
44666
45172
  }
44667
45173
 
44668
45174
  // ../../packages/scanner/src/scope-key.ts
44669
- import { existsSync as existsSync13 } from "fs";
44670
- import { join as join36, posix as posix2, resolve as resolve3 } from "path";
45175
+ import { existsSync as existsSync11 } from "fs";
45176
+ import { dirname as dirname7, join as join29, posix as posix2, resolve as resolve3 } from "path";
44671
45177
  function scopeKeysUnder(rootDir) {
44672
45178
  const base = resolve3(rootDir);
44673
- const keyByDir = /* @__PURE__ */ new Map();
44674
- return (relativePath) => {
45179
+ let aboveBase;
45180
+ const rootAtOrAboveBase = () => {
45181
+ if (aboveBase === void 0) {
45182
+ let dir = base;
45183
+ let root;
45184
+ for (; ; ) {
45185
+ if (existsSync11(join29(dir, ".git"))) {
45186
+ root = dir;
45187
+ break;
45188
+ }
45189
+ const parent = dirname7(dir);
45190
+ if (parent === dir) break;
45191
+ dir = parent;
45192
+ }
45193
+ aboveBase = { root };
45194
+ }
45195
+ return aboveBase.root;
45196
+ };
45197
+ const confirmed = (root, key) => existsSync11(join29(root, ".git")) ? { root, key } : { root: void 0, key: void 0 };
45198
+ const repositoryByDir = /* @__PURE__ */ new Map();
45199
+ const repositoryOf = (relativePath) => {
44675
45200
  const climbed = [];
44676
45201
  let dir = posix2.dirname(relativePath);
44677
- let key;
45202
+ let found;
44678
45203
  for (; ; ) {
44679
- if (keyByDir.has(dir)) {
44680
- key = keyByDir.get(dir);
45204
+ const known = repositoryByDir.get(dir);
45205
+ if (known !== void 0) {
45206
+ found = known;
44681
45207
  break;
44682
45208
  }
44683
45209
  climbed.push(dir);
44684
45210
  const parent = posix2.dirname(dir);
44685
45211
  if (parent === dir) {
44686
- key = resolveRepoAttribution(base).scopeKey;
45212
+ const root = rootAtOrAboveBase();
45213
+ found = root === void 0 ? { root, key: resolveRepoAttribution(base, { cache: false }).scopeKey } : confirmed(root, resolveRepoAttribution(root, { cache: false }).scopeKey);
44687
45214
  break;
44688
45215
  }
44689
- if (existsSync13(join36(base, dir, ".git"))) {
44690
- key = resolveRepoAttribution(join36(base, dir)).scopeKey;
45216
+ if (existsSync11(join29(base, dir, ".git"))) {
45217
+ const root = join29(base, dir);
45218
+ found = confirmed(root, resolveRepoAttribution(root, { cache: false }).scopeKey);
44691
45219
  break;
44692
45220
  }
44693
45221
  dir = parent;
44694
45222
  }
44695
- for (const at of climbed) keyByDir.set(at, key);
44696
- return key;
45223
+ for (const at of climbed) repositoryByDir.set(at, found);
45224
+ return found;
44697
45225
  };
45226
+ const keyOfFile = (relativePath) => repositoryOf(relativePath).key;
45227
+ const ofRepositoryRoot = (relativeDir) => {
45228
+ const root = join29(base, relativeDir);
45229
+ const dotGit = join29(root, ".git");
45230
+ if (!existsSync11(dotGit)) return void 0;
45231
+ const key = resolveRepoAttribution(root, { cache: false }).scopeKey;
45232
+ return existsSync11(dotGit) ? key : void 0;
45233
+ };
45234
+ return Object.assign(keyOfFile, { repositoryOf, ofRepositoryRoot });
44698
45235
  }
44699
45236
 
44700
45237
  // ../../packages/scanner/src/scan.ts
@@ -44729,7 +45266,14 @@ function egressKey(root, absPath) {
44729
45266
  function startEgress(rootDir) {
44730
45267
  const project = resolveEgressProject(rootDir);
44731
45268
  if (project === null) return null;
44732
- return { project, files: [], scannedFiles: [], deletedFiles: [] };
45269
+ return {
45270
+ project,
45271
+ files: [],
45272
+ scannedFiles: [],
45273
+ deletedFiles: [],
45274
+ deletedPaths: [],
45275
+ nestedRoots: []
45276
+ };
44733
45277
  }
44734
45278
  function collectFileEgress(acc, absPath, content, manifestKind) {
44735
45279
  const file2 = egressKey(acc.project.root, absPath);
@@ -44778,17 +45322,39 @@ async function reopenRedetectedFindings(gateway, path, currentKeys, evidence, re
44778
45322
  }
44779
45323
  function isUnderRoot(path, rootDir) {
44780
45324
  const rel = relative3(rootDir, path);
44781
- return rel !== "" && !rel.startsWith("..") && !isAbsolute3(rel);
45325
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
44782
45326
  }
44783
45327
  async function sweepDeletedFiles(gateway, rootDir, paths) {
44784
45328
  const deleted = [];
44785
45329
  for (const path of paths) {
44786
- if (!isUnderRoot(path, rootDir) || existsSync14(path)) continue;
45330
+ if (!isUnderRoot(path, rootDir) || existsSync12(path)) continue;
44787
45331
  deleted.push(path);
44788
45332
  await resolveRemovedFindings(gateway, path, [], { deleted: true });
44789
45333
  }
44790
45334
  return deleted;
44791
45335
  }
45336
+ function repositoryToRecord(prev, now) {
45337
+ const recordedRoot = prev?.scopeRoot;
45338
+ if (recordedRoot === void 0) return now;
45339
+ if (now.root !== void 0 && isAtOrBelow(recordedRoot, now.root)) return now;
45340
+ return { root: recordedRoot, key: prev?.scopeKey };
45341
+ }
45342
+ function isAtOrBelow(ancestor, dir) {
45343
+ const rel = relative3(ancestor, dir);
45344
+ if (isAbsolute2(rel)) return false;
45345
+ const posixRel = toPosix(rel);
45346
+ return posixRel === "" || posixRel !== ".." && !posixRel.startsWith("../");
45347
+ }
45348
+ function repositoryColumns(repository) {
45349
+ return {
45350
+ ...repository.key !== void 0 ? { scopeKey: repository.key } : {},
45351
+ ...repository.root !== void 0 ? { scopeRoot: repository.root } : {}
45352
+ };
45353
+ }
45354
+ function repositoryDiffers(prev, decided) {
45355
+ return decided.key !== prev.scopeKey || decided.root !== prev.scopeRoot;
45356
+ }
45357
+ var NO_REPOSITORY = { root: void 0, key: void 0 };
44792
45358
  async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44793
45359
  const byRule = {};
44794
45360
  const bySeverity = {};
@@ -44799,10 +45365,25 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44799
45365
  let gitignoredFindings = 0;
44800
45366
  const egress = config2.settings.dataSharesInPlace ? startEgress(rootDir) : null;
44801
45367
  const scopeKeyOf2 = scopeKeysUnder(rootDir);
45368
+ const noteNestedRoot = (relativeDir) => {
45369
+ egress?.nestedRoots.push(relativeDir);
45370
+ };
44802
45371
  const shouldRead = (meta4) => {
44803
45372
  const prev = ledger.previous.get(meta4.path);
44804
45373
  if (prev?.mtime === meta4.mtime) {
44805
45374
  skipped++;
45375
+ if (egress !== null) {
45376
+ const decided = repositoryToRecord(prev, scopeKeyOf2.repositoryOf(meta4.relativePath));
45377
+ if (repositoryDiffers(prev, decided)) {
45378
+ updates.push({
45379
+ path: meta4.path,
45380
+ mtime: prev.mtime,
45381
+ contentHash: prev.contentHash,
45382
+ rulesetHash: ledger.rulesetHash,
45383
+ ...repositoryColumns(decided)
45384
+ });
45385
+ }
45386
+ }
44806
45387
  return false;
44807
45388
  }
44808
45389
  return true;
@@ -44810,16 +45391,19 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44810
45391
  for (const file2 of walkSourceFiles({
44811
45392
  ...opts,
44812
45393
  rootDir,
44813
- shouldRead: (meta4) => (opts.shouldRead?.(meta4) ?? true) && shouldRead(meta4)
45394
+ shouldRead: (meta4) => (opts.shouldRead?.(meta4) ?? true) && shouldRead(meta4),
45395
+ onRepositoryRoot: egress === null ? void 0 : noteNestedRoot
44814
45396
  })) {
44815
45397
  const hash2 = contentHashOf(file2.content);
45398
+ const prev = ledger.previous.get(file2.path);
45399
+ const repository = egress === null ? NO_REPOSITORY : repositoryToRecord(prev, scopeKeyOf2.repositoryOf(file2.relativePath));
44816
45400
  const ledgerEntry = {
44817
45401
  path: file2.path,
44818
45402
  mtime: file2.mtime,
44819
45403
  contentHash: hash2,
44820
- rulesetHash: ledger.rulesetHash
45404
+ rulesetHash: ledger.rulesetHash,
45405
+ ...repositoryColumns(repository)
44821
45406
  };
44822
- const prev = ledger.previous.get(file2.path);
44823
45407
  if (prev?.contentHash === hash2) {
44824
45408
  skipped++;
44825
45409
  updates.push(ledgerEntry);
@@ -44871,15 +45455,17 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44871
45455
  contentHash: hash2
44872
45456
  });
44873
45457
  }
44874
- if (egress) scanManifests(egress, ledger, updates, rootDir);
45458
+ if (egress) scanManifests(egress, ledger, updates, rootDir, scopeKeyOf2, noteNestedRoot);
44875
45459
  const deleted = await sweepDeletedFiles(gateway, rootDir, ledger.paths);
44876
45460
  if (egress) {
44877
45461
  for (const path of deleted) {
44878
45462
  const key = egressKey(egress.project.root, path);
44879
- if (key !== null) egress.deletedFiles.push(key);
45463
+ if (key === null) continue;
45464
+ egress.deletedFiles.push(key);
45465
+ egress.deletedPaths.push(path);
44880
45466
  }
44881
45467
  }
44882
- const committed = await commitEgress(gateway, egress);
45468
+ const committed = await commitEgress(gateway, egress, scopeKeyOf2);
44883
45469
  if (committed === null) {
44884
45470
  return { rootDir, scanned, skipped, findings, gitignoredFindings, byRule, bySeverity };
44885
45471
  }
@@ -44889,13 +45475,28 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44889
45475
  await gateway.recordScanned(ledgerable(updates, egress, committed));
44890
45476
  return { rootDir, scanned, skipped, findings, gitignoredFindings, byRule, bySeverity };
44891
45477
  }
44892
- function scanManifests(egress, ledger, updates, rootDir) {
44893
- for (const manifest of collectManifests(rootDir)) {
45478
+ function scanManifests(egress, ledger, updates, rootDir, scopeKeyOf2, onRepositoryRoot) {
45479
+ for (const manifest of collectManifests(rootDir, void 0, onRepositoryRoot)) {
44894
45480
  const prev = ledger.previous.get(manifest.path);
44895
- if (prev?.mtime === manifest.mtime) continue;
45481
+ const repository = repositoryToRecord(
45482
+ prev,
45483
+ scopeKeyOf2.repositoryOf(toPosix(relative3(rootDir, manifest.path)))
45484
+ );
45485
+ if (prev?.mtime === manifest.mtime) {
45486
+ if (repositoryDiffers(prev, repository)) {
45487
+ updates.push({
45488
+ path: manifest.path,
45489
+ mtime: prev.mtime,
45490
+ contentHash: prev.contentHash,
45491
+ rulesetHash: ledger.rulesetHash,
45492
+ ...repositoryColumns(repository)
45493
+ });
45494
+ }
45495
+ continue;
45496
+ }
44896
45497
  let content;
44897
45498
  try {
44898
- content = readFileSync22(manifest.path, "utf8");
45499
+ content = readFileSync18(manifest.path, "utf8");
44899
45500
  } catch {
44900
45501
  continue;
44901
45502
  }
@@ -44904,31 +45505,82 @@ function scanManifests(egress, ledger, updates, rootDir) {
44904
45505
  path: manifest.path,
44905
45506
  mtime: manifest.mtime,
44906
45507
  contentHash: hash2,
44907
- rulesetHash: ledger.rulesetHash
45508
+ rulesetHash: ledger.rulesetHash,
45509
+ ...repositoryColumns(repository)
44908
45510
  });
44909
45511
  if (prev?.contentHash === hash2) continue;
44910
45512
  collectFileEgress(egress, manifest.path, content, manifest.kind);
44911
45513
  }
44912
45514
  }
44913
- async function commitEgress(gateway, egress) {
45515
+ async function commitEgress(gateway, egress, scopeKeyOf2) {
44914
45516
  if (!egress) return EMPTY_DROPPED;
44915
- const { project, files, scannedFiles, deletedFiles } = egress;
45517
+ const { project, files, scannedFiles, deletedFiles, deletedPaths, nestedRoots } = egress;
44916
45518
  if (scannedFiles.length === 0 && deletedFiles.length === 0 && files.length === 0) {
44917
45519
  return EMPTY_DROPPED;
44918
45520
  }
45521
+ let nestedKeys;
45522
+ let deletedKeys;
44919
45523
  try {
44920
- const summary = await gateway.recordProjectEgress({
44921
- projectKey: project.projectKey,
44922
- project: project.project,
44923
- projectId: null,
44924
- reconcile: { mode: "ledger", scannedFiles, deletedFiles },
44925
- hits: resolveEgress(files)
44926
- });
45524
+ const summary = await gateway.recordProjectEgress(
45525
+ {
45526
+ projectKey: project.projectKey,
45527
+ project: project.project,
45528
+ projectId: null,
45529
+ reconcile: { mode: "ledger", scannedFiles, deletedFiles },
45530
+ hits: resolveEgress(files)
45531
+ },
45532
+ {
45533
+ // One key per nested root, from this scan's own lookup of a
45534
+ // repository ROOT (./scope-key.ts): the directory's own key, found
45535
+ // without climbing. A nested directory whose `.git` is a link to
45536
+ // nowhere, or is gone by the time a gateway asks, is `undefined` here
45537
+ // rather than the key of the repository around it; so is a nested
45538
+ // repository with no forge remote. Each root is read fresh, never from
45539
+ // the resolver's memory of an earlier answer for that directory. Always
45540
+ // a list, even an empty one: a scoped gateway reads a missing list as a
45541
+ // register nobody vouched for. The repository lookups it makes do not
45542
+ // throw on these inputs, and the gateway reads any throw in this read as
45543
+ // local anyway.
45544
+ //
45545
+ // A getter, memoized: only a gateway that reads the list causes a
45546
+ // repository read. The standalone gateway ignores it, and a
45547
+ // machine-wide attachment answers before reading it.
45548
+ get nestedScopeKeys() {
45549
+ nestedKeys ??= [...new Set(nestedRoots)].map((dir) => scopeKeyOf2.ofRepositoryRoot(dir));
45550
+ return nestedKeys;
45551
+ },
45552
+ // One key per entry of `reconcile.deletedFiles`, in its order: what the
45553
+ // ledger recorded when the path was last read, and none for a row that
45554
+ // recorded none. ASYNC and lazy, because the read of every row's key is a
45555
+ // read of the whole ledger: only a gateway that forwards by scope asks, and
45556
+ // only once it has found the register sendable at all, so the standalone
45557
+ // gateway and a machine-wide attachment never cause it. Memoized, so a
45558
+ // gateway that asks twice reads once. A scan that deleted nothing has no
45559
+ // keys to look up and reads nothing.
45560
+ deletedFileKeys: () => {
45561
+ deletedKeys ??= keysOfDeleted(gateway, deletedPaths);
45562
+ return deletedKeys;
45563
+ }
45564
+ }
45565
+ );
44927
45566
  return new Set(summary.droppedFiles);
44928
45567
  } catch {
44929
45568
  return null;
44930
45569
  }
44931
45570
  }
45571
+ async function keysOfDeleted(gateway, deletedPaths) {
45572
+ if (deletedPaths.length === 0) return [];
45573
+ const recorded = await readRecordedKeys(gateway);
45574
+ return deletedPaths.map((path) => recorded.get(path));
45575
+ }
45576
+ async function readRecordedKeys(gateway) {
45577
+ try {
45578
+ return await gateway.scanLedgerPathKeys?.() ?? NO_RECORDED_KEYS;
45579
+ } catch {
45580
+ return NO_RECORDED_KEYS;
45581
+ }
45582
+ }
45583
+ var NO_RECORDED_KEYS = /* @__PURE__ */ new Map();
44932
45584
  var EMPTY_DROPPED = /* @__PURE__ */ new Set();
44933
45585
  function ledgerable(updates, egress, dropped) {
44934
45586
  if (!egress || dropped.size === 0) return [...updates];
@@ -44953,7 +45605,7 @@ async function scanWorktree(config2, opts) {
44953
45605
  // src/sync.ts
44954
45606
  try {
44955
45607
  await runAttachedSync(void 0, {
44956
- scan: commandScanFor(loadConfig(), scanWorktree, SOURCE_TOOL.Codex)
45608
+ scan: commandScanFor(() => loadConfig(), scanWorktree, SOURCE_TOOL.Codex)
44957
45609
  });
44958
45610
  } catch {
44959
45611
  }