@akasecurity/ai-tc-codex 0.9.16 → 0.9.17

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
  }
@@ -22517,6 +22548,11 @@ var CaptureAttributes = external_exports.object({
22517
22548
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22518
22549
  // repeated rather than referenced because a store reader opens this file.
22519
22550
  redact_degraded_to: ActionTaken.optional(),
22551
+ // Why a capture has no content and no findings: its field was refused
22552
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
22553
+ // whose value this is). Absent on every capture that was scanned, so a
22554
+ // reader can tell a refused row from an empty clean one.
22555
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22520
22556
  // The scope key this capture was stamped with: the canonical repository
22521
22557
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22522
22558
  // against its working directory), else of its own working directory, or a
@@ -22694,8 +22730,9 @@ var SessionTokenReport = external_exports.object({
22694
22730
  totalTokens: external_exports.number().int().nonnegative(),
22695
22731
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22696
22732
  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
22733
+ // True whenever any call priced to null (an unknown provider/model, or a call
22734
+ // over a long-context threshold whose rate is unpublished), so the total
22735
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22699
22736
  // precise figure rather than silently dropping the unpriced calls.
22700
22737
  costIsPartial: external_exports.boolean()
22701
22738
  });
@@ -23572,7 +23609,15 @@ var StorePostureSnapshot = external_exports.object({
23572
23609
  policyCounts: StorePosturePolicyCounts,
23573
23610
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23574
23611
  // getting its 200 without a payload change.
23575
- plugin: StorePosturePlugin.optional()
23612
+ plugin: StorePosturePlugin.optional(),
23613
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
23614
+ // machine attachment omits it, so its body is byte for byte the one it
23615
+ // sent before this member existed. Absent therefore means machine-wide OR
23616
+ // a reporter older than this member, never "scoped". Both values parse, so
23617
+ // a sender that one day spells `machine` breaks no receiver; any other
23618
+ // value fails the whole snapshot, which is why the reporter sends a
23619
+ // constant and never the raw mode.
23620
+ attachmentMode: AttachmentMode.optional()
23576
23621
  }).meta({ id: "StorePostureSnapshot" });
23577
23622
  var CAPTURE_VERSION_PREFIX = "capture/";
23578
23623
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23849,7 +23894,19 @@ var EventMetadata = external_exports.object({
23849
23894
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23850
23895
  // Closing either means moving the reason onto the finding row, which
23851
23896
  // already carries its own action.
23852
- redactDegradedTo: ActionTaken.optional()
23897
+ redactDegradedTo: ActionTaken.optional(),
23898
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23899
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23900
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23901
+ // field instead of letting it through unscanned.
23902
+ //
23903
+ // - 'timeout': the bounded scan ran out of time.
23904
+ // - 'unavailable': no worker could run it.
23905
+ //
23906
+ // A refused row stores '' as its content and has no findings, which is
23907
+ // exactly what a clean, empty capture looks like — this marker is the only
23908
+ // thing that tells the two apart. Absent on every capture that was scanned.
23909
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23853
23910
  }).meta({ id: "EventMetadata" });
23854
23911
  var Event = external_exports.object({
23855
23912
  id: external_exports.guid(),
@@ -24019,7 +24076,7 @@ var Rule = external_exports.strictObject({
24019
24076
  postValidators: external_exports.array(PostValidatorRef).optional(),
24020
24077
  requiresNearby: RequiresNearby.optional(),
24021
24078
  examples: external_exports.array(external_exports.string()).optional(),
24022
- // Whether the matched text is itself sensitive. Absent means 'value'.
24079
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24023
24080
  evidence: RuleEvidence.optional()
24024
24081
  }).meta({ id: "Rule" });
24025
24082
  var Author = external_exports.object({
@@ -24111,7 +24168,13 @@ var DetectionRule = external_exports.object({
24111
24168
  // Representative matching strings the rule author shipped with the rule. The
24112
24169
  // cheapest honest answer to "show me what this rule catches" — every bundled
24113
24170
  // rule has them, and they are already in the stored snapshot.
24114
- examples: external_exports.array(external_exports.string()).optional()
24171
+ examples: external_exports.array(external_exports.string()).optional(),
24172
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
24173
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
24174
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
24175
+ // in a value category (secret/pii/financial/phi) is always 'value',
24176
+ // whatever it declares.
24177
+ evidence: RuleEvidence.optional()
24115
24178
  }).meta({ id: "DetectionRule" });
24116
24179
  var DetectionUpdate = external_exports.object({
24117
24180
  available: external_exports.boolean(),
@@ -24179,8 +24242,10 @@ var ImportDetectionRequest = external_exports.object({
24179
24242
  }).meta({ id: "ImportDetectionRequest" });
24180
24243
 
24181
24244
  // ../../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 {};
24245
+ function optional2(key, raw, parse4) {
24246
+ if (raw === void 0) return {};
24247
+ const parsed2 = parse4(raw);
24248
+ if (!parsed2.success || parsed2.data === void 0) return {};
24184
24249
  return { [key]: parsed2.data };
24185
24250
  }
24186
24251
  function isStringArray(value) {
@@ -24215,10 +24280,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24215
24280
  category: r.category,
24216
24281
  severity: r.severity,
24217
24282
  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.
24283
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
24284
+ // decides whether this rule fires. Carried so a consumer re-running the
24285
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
24286
+ // than a matcher stripped of its guards — half the bundled catalog
24287
+ // carries at least one of these. `examples` and `evidence` describe the
24288
+ // rule and never gate a match.
24222
24289
  //
24223
24290
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24224
24291
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24228,18 +24295,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24228
24295
  // test should stay exactly what it was, namely a renderable matcher. A
24229
24296
  // field that fails validation is omitted, which reads as "not set" and is
24230
24297
  // the same thing the consumer saw before this change.
24231
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
24298
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24232
24299
  ...optional2(
24233
24300
  "postValidators",
24234
- PostValidatorRef.array().safeParse(r.postValidators),
24235
- r.postValidators
24301
+ r.postValidators,
24302
+ (v) => PostValidatorRef.array().safeParse(v)
24236
24303
  ),
24237
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
24304
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24238
24305
  ...optional2(
24239
24306
  "examples",
24240
- { success: isStringArray(r.examples), data: r.examples },
24241
- r.examples
24242
- )
24307
+ r.examples,
24308
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
24309
+ ),
24310
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24243
24311
  }
24244
24312
  ];
24245
24313
  });
@@ -24932,11 +25000,14 @@ var PolicyBundle = external_exports.object({
24932
25000
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24933
25001
  // Model ids (the raw `model` string a harness reports, e.g.
24934
25002
  // `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.
25003
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
25004
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
25005
+ // wherever the organization governs the event: everywhere on a
25006
+ // machine-wide attachment, and only in enrolled repositories on a scoped
25007
+ // one (the plugin runtime's `governanceApplies`).
25008
+ // Optional so an older backend — and an older on-disk cache — still
25009
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
25010
+ // predates this field and the safe direction to default.
24940
25011
  //
24941
25012
  // Ids, not display names: the governance decision is keyed on the exact
24942
25013
  // string the harness reports (`model_status_override.versionId` in the
@@ -25395,6 +25466,8 @@ var AttachmentScopeEntry = external_exports.object({
25395
25466
  });
25396
25467
  var AttachmentScope = external_exports.object({
25397
25468
  endpoint: external_exports.string().min(1),
25469
+ tenantName: PluginWhoami.shape.tenantName.optional(),
25470
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25398
25471
  entries: external_exports.array(AttachmentScopeEntry)
25399
25472
  });
25400
25473
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25407,7 +25480,13 @@ function parseAttachmentScope(raw) {
25407
25480
  const entry = AttachmentScopeEntry.safeParse(candidate);
25408
25481
  if (entry.success) entries.push(entry.data);
25409
25482
  }
25410
- return { endpoint: envelope.data.endpoint, entries };
25483
+ const { endpoint, tenantName, userEmail } = envelope.data;
25484
+ return {
25485
+ endpoint,
25486
+ ...tenantName === void 0 ? {} : { tenantName },
25487
+ ...userEmail === void 0 ? {} : { userEmail },
25488
+ entries
25489
+ };
25411
25490
  } catch {
25412
25491
  return void 0;
25413
25492
  }
@@ -25644,6 +25723,7 @@ function toCaptureAttributes(event) {
25644
25723
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25645
25724
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25646
25725
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
25726
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25647
25727
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25648
25728
  // has ever populated either), but every legacy metadata key still rides
25649
25729
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25772,6 +25852,27 @@ var ManagedSettings = external_exports.object({
25772
25852
  };
25773
25853
  }).meta({ id: "ManagedSettings" });
25774
25854
 
25855
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
25856
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
25857
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
25858
+ var ModPolicySnapshot = external_exports.object({
25859
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
25860
+ generatedAt: external_exports.iso.datetime(),
25861
+ // The complete effective ruleset, as the hook's runtime scans with it: the
25862
+ // user's enabled installed packs (user-modified and custom packs included).
25863
+ // Absent means the store holds no authoritative snapshot, and the reader
25864
+ // scans with the packs it ships — the hook's own fallback.
25865
+ rules: external_exports.array(Rule).optional(),
25866
+ // Rule-targeted actions (first enabled policy per rule wins).
25867
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25868
+ // The resolved action per detection category.
25869
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25870
+ // Rules with an active exception grant. Honouring a grant means matching a
25871
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25872
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25873
+ exceptionRuleIds: external_exports.array(external_exports.string())
25874
+ }).meta({ id: "ModPolicySnapshot" });
25875
+
25775
25876
  // ../../packages/schema/src/zod/project-files.ts
25776
25877
  var ProjectFileInput = external_exports.object({
25777
25878
  path: external_exports.string().min(1),
@@ -26092,7 +26193,16 @@ var AttachInput = external_exports.object({
26092
26193
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26093
26194
  // renders a longer one usefully.
26094
26195
  label: printable(200).optional(),
26095
- accessKey: external_exports.string()
26196
+ accessKey: external_exports.string(),
26197
+ // How much of this machine the attachment is for: everything, or only the
26198
+ // repositories its user enrolls. Optional, so an input without it still
26199
+ // parses; what an absent mode means is for whatever reads it to decide, not
26200
+ // this shape. This member validates the VALUE rather than leaving that to the
26201
+ // call site, a deliberate exception to this module's shape-only rule: a shape
26202
+ // rejection names the field, so a value that is not a mode is refused as a bad
26203
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
26204
+ // it as the mode to attach in.
26205
+ mode: AttachmentMode.optional()
26096
26206
  });
26097
26207
 
26098
26208
  // ../../packages/schema/src/zod/triage.ts
@@ -26378,6 +26488,19 @@ function fromCaptureStatusAttributes(bag) {
26378
26488
  return parsedStatus.success ? parsedStatus.data : null;
26379
26489
  }
26380
26490
 
26491
+ // ../../packages/persistence/src/attached-derived.ts
26492
+ import { rmSync } from "fs";
26493
+ import { join } from "path";
26494
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
26495
+ var ATTACHED_SYNC_STATE_FILENAME = "attached-sync-state.json";
26496
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
26497
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
26498
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
26499
+
26500
+ // ../../packages/persistence/src/control-plane-credential.ts
26501
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
26502
+ import { join as join2 } from "path";
26503
+
26381
26504
  // ../../packages/persistence/src/paths.ts
26382
26505
  import {
26383
26506
  chmodSync,
@@ -26524,6 +26647,14 @@ function repairOrRefuseMode(file2) {
26524
26647
  }
26525
26648
  return "ok";
26526
26649
  }
26650
+ function asReadableCredential(value) {
26651
+ const result = AttachedCredentialAny.safeParse(value);
26652
+ if (!result.success) return null;
26653
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
26654
+ return null;
26655
+ }
26656
+ return result.data;
26657
+ }
26527
26658
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26528
26659
  const file2 = controlPlaneCredentialPath(settingsDir2);
26529
26660
  let raw;
@@ -26542,20 +26673,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26542
26673
  } catch {
26543
26674
  return { usable: false, reason: "malformed" };
26544
26675
  }
26545
- const result = AttachedCredential.safeParse(parsed2);
26546
- if (!result.success) return { usable: false, reason: "malformed" };
26547
- if (!isSafeEndpoint(result.data.endpoint)) {
26676
+ const credential = asReadableCredential(parsed2);
26677
+ if (credential === null) return { usable: false, reason: "malformed" };
26678
+ if (!isSafeEndpoint(credential.endpoint)) {
26548
26679
  return { usable: false, reason: "unsafe-endpoint" };
26549
26680
  }
26550
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
26681
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26551
26682
  return {
26552
26683
  usable: false,
26553
26684
  reason: "endpoint-mismatch",
26554
- credentialEndpoint: result.data.endpoint,
26685
+ credentialEndpoint: credential.endpoint,
26555
26686
  settingsEndpoint: connection.endpoint
26556
26687
  };
26557
26688
  }
26558
- return { usable: true, credential: result.data };
26689
+ return { usable: true, credential };
26559
26690
  }
26560
26691
  function readControlPlaneCredential(settingsDir2, connection) {
26561
26692
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26564,7 +26695,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26564
26695
 
26565
26696
  // ../../packages/persistence/src/database.ts
26566
26697
  import { randomUUID as randomUUID11 } from "crypto";
26567
- import { dirname as dirname2, join as join7, sep } from "path";
26698
+ import { dirname as dirname2, join as join8, sep } from "path";
26568
26699
  import { DatabaseSync } from "node:sqlite";
26569
26700
 
26570
26701
  // ../../packages/persistence/src/ids.ts
@@ -26618,6 +26749,7 @@ function uuidFromDigest(digest) {
26618
26749
  function captureWireId(sessionId, contentHash, filePath = null) {
26619
26750
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26620
26751
  }
26752
+ var DOT = ".".charCodeAt(0);
26621
26753
 
26622
26754
  // ../../packages/persistence/src/internal/snapshot.ts
26623
26755
  import { randomUUID } from "crypto";
@@ -26945,6 +27077,25 @@ function scopeKeysParam(scopeKeys) {
26945
27077
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26946
27078
  FROM audit_events AS session_root
26947
27079
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
27080
+ var COUNTED_IN_SCOPE = `
27081
+ AND ${inScope("scope_key")}
27082
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
27083
+ var DRAIN_TOTALS = `SELECT
27084
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27085
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27086
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27087
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27088
+ THEN 1 ELSE 0 END) AS skipped,
27089
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27090
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27091
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27092
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27093
+ FROM audit_events
27094
+ WHERE event_type IN (${TYPE_LIST})`;
27095
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
27096
+ FROM audit_events
27097
+ WHERE synced_at = ${String(SKIPPED)}
27098
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26948
27099
  var ROW_COLUMNS = `id,
26949
27100
  parent_id AS parentId,
26950
27101
  root_session_id AS rootSessionId,
@@ -27020,7 +27171,7 @@ var SqliteHistorySyncRepository = class {
27020
27171
  );
27021
27172
  this.scopedCaptureRowsStmt = db.prepare(
27022
27173
  `SELECT ${ROW_COLUMNS}
27023
- FROM audit_events
27174
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27024
27175
  WHERE synced_at IS NULL
27025
27176
  AND sync_claimed_at IS NULL
27026
27177
  AND outbox_owed = 1
@@ -27073,40 +27224,28 @@ var SqliteHistorySyncRepository = class {
27073
27224
  );
27074
27225
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27075
27226
  FROM audit_events${COUNTED_SCOPE}`);
27227
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27228
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27076
27229
  this.partitionByKindStmt = db.prepare(
27077
27230
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27078
27231
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27079
27232
  GROUP BY event_type`
27080
27233
  );
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})`
27234
+ this.scopedPartitionByKindStmt = db.prepare(
27235
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
27236
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
27237
+ GROUP BY event_type`
27238
+ );
27239
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
27240
+ this.scopedCountsStmt = db.prepare(
27241
+ `${DRAIN_TOTALS}
27242
+ AND ${inScope("scope_key")}
27243
+ AND ${inScope(ROOT_SCOPE_KEY)}`
27244
+ );
27245
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
27246
+ this.scopedCaptureSkipCountStmt = db.prepare(
27247
+ `${CAPTURE_SKIPS}
27248
+ AND ${inScope("scope_key")}`
27110
27249
  );
27111
27250
  this.fingerprintStmt = db.prepare(
27112
27251
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27220,6 +27359,10 @@ var SqliteHistorySyncRepository = class {
27220
27359
  scopedCaptureRowsStmt;
27221
27360
  scopedCaptureBacklogOwedStmt;
27222
27361
  markScopeCapturesOwedStmt;
27362
+ scopedPartitionStmt;
27363
+ scopedPartitionByKindStmt;
27364
+ scopedCountsStmt;
27365
+ scopedCaptureSkipCountStmt;
27223
27366
  /**
27224
27367
  * The masked detections recorded against one tool call.
27225
27368
  *
@@ -27441,7 +27584,29 @@ var SqliteHistorySyncRepository = class {
27441
27584
  * in" — and a machine that has never attached has no boundary to pass, so
27442
27585
  * requiring one would force a caller to invent one and report the whole store
27443
27586
  * as queued.
27587
+ *
27588
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
27589
+ * the rows that pass the drain's reachability rule for that scope
27590
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
27591
+ * drain never offers), so a personal repository's rows are in none of them.
27592
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
27593
+ * nothing.
27444
27594
  */
27595
+ partition(scopeKeys) {
27596
+ const row = getRow(
27597
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
27598
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27599
+ );
27600
+ return {
27601
+ queued: row?.queued ?? 0,
27602
+ inProgress: row?.inProgress ?? 0,
27603
+ synced: row?.synced ?? 0,
27604
+ failed: row?.failed ?? 0,
27605
+ refused: row?.refused ?? 0,
27606
+ detached: row?.detached ?? 0,
27607
+ total: row?.total ?? 0
27608
+ };
27609
+ }
27445
27610
  /**
27446
27611
  * The same partition, one row per kind that a lane carries.
27447
27612
  *
@@ -27451,11 +27616,14 @@ var SqliteHistorySyncRepository = class {
27451
27616
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27452
27617
  * rows", never as "zero sent"; the two look identical in a bar and mean
27453
27618
  * different things.
27619
+ *
27620
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
27621
+ * still sum to the scoped aggregate. An empty list returns no rows.
27454
27622
  */
27455
- partitionByKind() {
27623
+ partitionByKind(scopeKeys) {
27456
27624
  return allRows(
27457
- this.partitionByKindStmt,
27458
- {}
27625
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
27626
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27459
27627
  ).map((row) => ({
27460
27628
  kind: row.kind,
27461
27629
  queued: row.queued ?? 0,
@@ -27467,22 +27635,25 @@ var SqliteHistorySyncRepository = class {
27467
27635
  total: row.total ?? 0
27468
27636
  }));
27469
27637
  }
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);
27638
+ /**
27639
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
27640
+ * and skipped are totals.
27641
+ *
27642
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
27643
+ * `capturesSkipped` included: a structural row is counted only when its own
27644
+ * key and its session root's key are among them, a capture when its own key
27645
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
27646
+ * under the same keys and boundary. Omitted, this runs the machine
27647
+ * statements, unchanged; an empty list counts nothing.
27648
+ */
27649
+ counts(before, scopeKeys) {
27650
+ const row = getRow(
27651
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
27652
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
27653
+ );
27654
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
27655
+ scopeKeys: scopeKeysParam(scopeKeys)
27656
+ });
27486
27657
  return {
27487
27658
  pending: row?.pending ?? 0,
27488
27659
  sent: row?.sent ?? 0,
@@ -27734,6 +27905,7 @@ function applyMigrations(db, file2, options = {}) {
27734
27905
  }
27735
27906
  ensureSyncedAtColumn(db, "audit_events");
27736
27907
  ensureScopeKeyColumn(db);
27908
+ ensureScopeOwedIndex(db);
27737
27909
  ensureScanLedgerTable(db);
27738
27910
  ensureHistorySyncTable(db);
27739
27911
  ensureBlockedDetectionsTable(db);
@@ -28174,14 +28346,48 @@ function ensureScopeKeyColumn(db) {
28174
28346
  function hasScopeKeyColumn(db) {
28175
28347
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28176
28348
  }
28349
+ 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";
28350
+ function ensureScopeOwedIndex(db) {
28351
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
28352
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
28353
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
28354
+ if (!complete) return;
28355
+ db.exec(SCOPE_OWED_INDEX_DDL);
28356
+ }
28177
28357
  function ensureScanLedgerTable(db) {
28178
28358
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28179
28359
  path TEXT PRIMARY KEY,
28180
28360
  mtime TEXT NOT NULL,
28181
28361
  content_hash TEXT NOT NULL,
28182
28362
  ruleset_hash TEXT NOT NULL,
28183
- scanned_at INTEGER NOT NULL
28363
+ scanned_at INTEGER NOT NULL,
28364
+ scope_key TEXT,
28365
+ scope_root TEXT
28184
28366
  )`);
28367
+ ensureScanLedgerScopeKeyColumn(db);
28368
+ ensureScanLedgerScopeRootColumn(db);
28369
+ }
28370
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
28371
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
28372
+ function ensureScanLedgerScopeKeyColumn(db) {
28373
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
28374
+ }
28375
+ function ensureScanLedgerScopeRootColumn(db) {
28376
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
28377
+ }
28378
+ function ensureScanLedgerColumn(db, column, ddl) {
28379
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
28380
+ if (hasScanLedgerColumn(db, column)) return;
28381
+ withTransaction(
28382
+ db,
28383
+ () => {
28384
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
28385
+ },
28386
+ "IMMEDIATE"
28387
+ );
28388
+ }
28389
+ function hasScanLedgerColumn(db, column) {
28390
+ return columnNames(db, "scan_ledger").includes(column);
28185
28391
  }
28186
28392
  function ensureHistorySyncTable(db) {
28187
28393
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28232,6 +28438,106 @@ function ensureRuleProbeCacheTable(db) {
28232
28438
  )`);
28233
28439
  }
28234
28440
 
28441
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
28442
+ import { createHash as createHash2 } from "crypto";
28443
+ import { readFileSync as readFileSync2 } from "fs";
28444
+ import { join as join4 } from "path";
28445
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
28446
+ function modPolicySnapshotPath(dataDir2) {
28447
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
28448
+ }
28449
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
28450
+ const byRule = /* @__PURE__ */ new Map();
28451
+ const byCategory = /* @__PURE__ */ new Map();
28452
+ for (const policy of input2.policies) {
28453
+ if (!policy.enabled) continue;
28454
+ if ("ruleId" in policy.target) {
28455
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
28456
+ } else if (!byCategory.has(policy.target.category)) {
28457
+ byCategory.set(policy.target.category, policy.action);
28458
+ }
28459
+ }
28460
+ const categoryActions = {};
28461
+ for (const category of DetectionCategory.options) {
28462
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
28463
+ }
28464
+ return {
28465
+ version: MOD_POLICY_SNAPSHOT_VERSION,
28466
+ generatedAt: generatedAt.toISOString(),
28467
+ // `examples` is documentation the mod never reads, and a custom pack's are
28468
+ // whatever its author pasted in, so they stay behind.
28469
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
28470
+ ruleActions: Object.fromEntries(byRule),
28471
+ categoryActions,
28472
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
28473
+ };
28474
+ }
28475
+ function assignedRuleActionPolicies(installed) {
28476
+ const out = [];
28477
+ for (const [ruleId, action] of installed.ruleActions) {
28478
+ if (installed.assignedRules.has(ruleId))
28479
+ out.push({ target: { ruleId }, action, enabled: true });
28480
+ }
28481
+ return out;
28482
+ }
28483
+ function withoutExamples(rule) {
28484
+ const copy = { ...rule };
28485
+ delete copy.examples;
28486
+ return copy;
28487
+ }
28488
+ function sameContent(a, b) {
28489
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
28490
+ }
28491
+ function readModPolicySnapshot(dataDir2) {
28492
+ try {
28493
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
28494
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
28495
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
28496
+ return parsed2.success ? parsed2.data : null;
28497
+ } catch {
28498
+ return null;
28499
+ }
28500
+ }
28501
+ function writeModPolicySnapshot(dataDir2, snapshot) {
28502
+ const text = JSON.stringify(snapshot);
28503
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
28504
+ const existing = readModPolicySnapshot(dataDir2);
28505
+ if (existing !== null && sameContent(existing, snapshot)) return false;
28506
+ ensureDataDirSync(dataDir2);
28507
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
28508
+ return true;
28509
+ }
28510
+ function regexProbeKey(matcher) {
28511
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
28512
+ }
28513
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28514
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
28515
+ return rules.filter((rule) => {
28516
+ if (rule.matcher.type !== "regex") return true;
28517
+ const key = regexProbeKey(rule.matcher);
28518
+ const verdict = sources.probeVerdict(key);
28519
+ if (verdict === "quarantined") return false;
28520
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
28521
+ });
28522
+ }
28523
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28524
+ const policies = sources.readPolicies();
28525
+ const snapshot = sources.installedRuleset();
28526
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
28527
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
28528
+ return {
28529
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
28530
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
28531
+ exceptionRuleIds: sources.activeExceptionRuleIds()
28532
+ };
28533
+ }
28534
+ function refreshModPolicySnapshot(dataDir2, sources) {
28535
+ try {
28536
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
28537
+ } catch {
28538
+ }
28539
+ }
28540
+
28235
28541
  // ../../packages/persistence/src/internal/json.ts
28236
28542
  function safeJson(s, fallback) {
28237
28543
  if (s == null) return fallback;
@@ -28406,6 +28712,11 @@ var TIMELINE_COLUMNS = `
28406
28712
  json_extract(attributes, '$.targetId') AS target_id,
28407
28713
  json_extract(attributes, '$.internal') AS internal,
28408
28714
  json_extract(attributes, '$.flagged') AS flagged`;
28715
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
28716
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
28717
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
28718
+ " + "
28719
+ );
28409
28720
  var LLM_USAGE_SELECT = `
28410
28721
  SELECT root_session_id AS sessionId,
28411
28722
  provider,
@@ -28417,9 +28728,10 @@ var LLM_USAGE_SELECT = `
28417
28728
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28418
28729
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28419
28730
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28420
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
28731
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
28732
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28421
28733
  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`;
28734
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28423
28735
  function usageLeaves(rows) {
28424
28736
  return rows.map((row) => {
28425
28737
  const attributes = {
@@ -28434,7 +28746,7 @@ function usageLeaves(rows) {
28434
28746
  if (row.provider !== null) attributes.provider = row.provider;
28435
28747
  if (row.model !== null) attributes.model = row.model;
28436
28748
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28437
- return { sessionId: row.sessionId, attributes };
28749
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28438
28750
  });
28439
28751
  }
28440
28752
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29768,9 +30080,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29768
30080
  AND conditions IS NULL
29769
30081
  AND ${ACTIVE_PREDICATE}`;
29770
30082
  var SqliteExceptionsRepository = class {
29771
- constructor(db, now = () => Date.now()) {
30083
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29772
30084
  this.db = db;
29773
30085
  this.now = now;
30086
+ this.onChange = onChange;
29774
30087
  this.consumeStmt = db.prepare(
29775
30088
  `UPDATE exceptions
29776
30089
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29789,6 +30102,7 @@ var SqliteExceptionsRepository = class {
29789
30102
  }
29790
30103
  db;
29791
30104
  now;
30105
+ onChange;
29792
30106
  consumeStmt;
29793
30107
  insertBlockedStmt;
29794
30108
  sweepBlockedStmt;
@@ -29804,7 +30118,9 @@ var SqliteExceptionsRepository = class {
29804
30118
  */
29805
30119
  create(input2) {
29806
30120
  try {
29807
- return Promise.resolve(this.createSync(input2));
30121
+ const created = this.createSync(input2);
30122
+ this.onChange();
30123
+ return Promise.resolve(created);
29808
30124
  } catch (err) {
29809
30125
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29810
30126
  }
@@ -29935,6 +30251,7 @@ var SqliteExceptionsRepository = class {
29935
30251
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29936
30252
  WHERE id = :id AND revoked_at IS NULL`
29937
30253
  ).run({ id, revokedBy, reason: reason ?? null, now });
30254
+ if (Number(result.changes) === 1) this.onChange();
29938
30255
  return Promise.resolve(Number(result.changes) === 1);
29939
30256
  }
29940
30257
  /**
@@ -29947,6 +30264,15 @@ var SqliteExceptionsRepository = class {
29947
30264
  const result = this.consumeStmt.run({ id, now });
29948
30265
  return Promise.resolve(Number(result.changes) === 1);
29949
30266
  }
30267
+ /** The rule ids with at least one active grant, under any key version. */
30268
+ activeRuleIds(now = this.now()) {
30269
+ return allRows(
30270
+ this.db.prepare(
30271
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
30272
+ ),
30273
+ { now }
30274
+ ).map((row) => row.ruleId);
30275
+ }
29950
30276
  /**
29951
30277
  * The evaluation subset of every active grant under one fingerprint key
29952
30278
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31070,28 +31396,28 @@ var SqliteInspectionFindingsRepository = class {
31070
31396
  };
31071
31397
 
31072
31398
  // ../../packages/persistence/src/repositories/installed-packs.ts
31073
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
31399
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31074
31400
 
31075
31401
  // ../../packages/persistence/src/policy-floor.ts
31076
- import { readFileSync as readFileSync5 } from "fs";
31077
- import { join as join6 } from "path";
31402
+ import { readFileSync as readFileSync6 } from "fs";
31403
+ import { join as join7 } from "path";
31078
31404
 
31079
31405
  // ../../packages/persistence/src/local-layout.ts
31080
31406
  import { renameSync as renameSync3 } from "fs";
31081
31407
  import { mkdir } from "fs/promises";
31082
31408
  import { homedir } from "os";
31083
- import { join as join4 } from "path";
31409
+ import { join as join5 } from "path";
31084
31410
  function defaultDataDir() {
31085
- return join4(homedir(), ".aka");
31411
+ return join5(homedir(), ".aka");
31086
31412
  }
31087
31413
  function settingsDir(base = defaultDataDir()) {
31088
- return join4(base, "settings");
31414
+ return join5(base, "settings");
31089
31415
  }
31090
31416
  function dataDir(base = defaultDataDir()) {
31091
- return join4(base, "data");
31417
+ return join5(base, "data");
31092
31418
  }
31093
31419
  function dbPath(base = defaultDataDir()) {
31094
- return join4(dataDir(base), "aka.db");
31420
+ return join5(dataDir(base), "aka.db");
31095
31421
  }
31096
31422
  async function ensureDataDir(dir = defaultDataDir()) {
31097
31423
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31108,8 +31434,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31108
31434
  for (const { name, dest } of moves) {
31109
31435
  try {
31110
31436
  ensureDataDirSync(dest);
31111
- const moved = join4(dest, name);
31112
- renameSync3(join4(base, name), moved);
31437
+ const moved = join5(dest, name);
31438
+ renameSync3(join5(base, name), moved);
31113
31439
  tightenFile(moved);
31114
31440
  } catch {
31115
31441
  }
@@ -31117,8 +31443,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31117
31443
  }
31118
31444
 
31119
31445
  // ../../packages/persistence/src/settings.ts
31120
- import { readFileSync as readFileSync4 } from "fs";
31121
- import { join as join5 } from "path";
31446
+ import { readFileSync as readFileSync5 } from "fs";
31447
+ import { join as join6 } from "path";
31122
31448
 
31123
31449
  // ../../packages/persistence/src/file-lock.ts
31124
31450
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31126,7 +31452,7 @@ import {
31126
31452
  closeSync,
31127
31453
  existsSync as existsSync2,
31128
31454
  openSync,
31129
- readFileSync as readFileSync2,
31455
+ readFileSync as readFileSync3,
31130
31456
  rmSync as rmSync5,
31131
31457
  statSync as statSync3,
31132
31458
  writeFileSync as writeFileSync2
@@ -31135,16 +31461,16 @@ import { hostname as hostname3 } from "os";
31135
31461
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31136
31462
 
31137
31463
  // ../../packages/persistence/src/managed-settings.ts
31138
- import { readFileSync as readFileSync3 } from "fs";
31464
+ import { readFileSync as readFileSync4 } from "fs";
31139
31465
  import { posix, win32 } from "path";
31140
- function managedSettingsPaths(platform2 = process.platform) {
31141
- if (platform2 === "darwin") {
31466
+ function managedSettingsPaths(platform = process.platform) {
31467
+ if (platform === "darwin") {
31142
31468
  return [
31143
31469
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31144
31470
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31145
31471
  ];
31146
31472
  }
31147
- if (platform2 === "win32") {
31473
+ if (platform === "win32") {
31148
31474
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31149
31475
  }
31150
31476
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -31154,7 +31480,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31154
31480
  for (const path of paths) {
31155
31481
  let text;
31156
31482
  try {
31157
- text = readFileSync3(path, "utf8");
31483
+ text = readFileSync4(path, "utf8");
31158
31484
  } catch {
31159
31485
  continue;
31160
31486
  }
@@ -31208,7 +31534,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31208
31534
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31209
31535
  }
31210
31536
  function readUserSettings(base) {
31211
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
31537
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31212
31538
  if (!record2) return defaultWorkspaceSettings();
31213
31539
  try {
31214
31540
  return WorkspaceSettings.parse(record2);
@@ -31219,7 +31545,7 @@ function readUserSettings(base) {
31219
31545
  function readJson(file2) {
31220
31546
  let text;
31221
31547
  try {
31222
- text = readFileSync4(file2, "utf8");
31548
+ text = readFileSync5(file2, "utf8");
31223
31549
  } catch {
31224
31550
  return null;
31225
31551
  }
@@ -31259,7 +31585,7 @@ var PolicyFloorError = class extends Error {
31259
31585
  };
31260
31586
  function readCachedPolicyBundle(base = defaultDataDir()) {
31261
31587
  try {
31262
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31588
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31263
31589
  const parsed2 = JSON.parse(raw);
31264
31590
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31265
31591
  return PolicyBundle.parse(parsed2.bundle);
@@ -31383,7 +31709,7 @@ function inventorySignature(packs2) {
31383
31709
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31384
31710
  }
31385
31711
  function hashRules(rulesJson) {
31386
- return createHash2("sha256").update(rulesJson).digest("hex");
31712
+ return createHash3("sha256").update(rulesJson).digest("hex");
31387
31713
  }
31388
31714
  function parseVersion(v) {
31389
31715
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31425,9 +31751,10 @@ var SqliteInstalledPacksRepository = class {
31425
31751
  * from `openLocalDatabase`, which is the single construction site that owns a
31426
31752
  * real `~/.aka`.
31427
31753
  */
31428
- constructor(db, baseDir) {
31754
+ constructor(db, baseDir, onChange = () => void 0) {
31429
31755
  this.db = db;
31430
31756
  this.baseDir = baseDir;
31757
+ this.onChange = onChange;
31431
31758
  this.insertMissingStmt = db.prepare(
31432
31759
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31433
31760
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31456,6 +31783,7 @@ var SqliteInstalledPacksRepository = class {
31456
31783
  }
31457
31784
  db;
31458
31785
  baseDir;
31786
+ onChange;
31459
31787
  insertMissingStmt;
31460
31788
  upsertAvailableStmt;
31461
31789
  signatureStmt;
@@ -31528,6 +31856,7 @@ var SqliteInstalledPacksRepository = class {
31528
31856
  },
31529
31857
  "IMMEDIATE"
31530
31858
  );
31859
+ this.onChange();
31531
31860
  } catch {
31532
31861
  }
31533
31862
  }
@@ -31602,6 +31931,7 @@ var SqliteInstalledPacksRepository = class {
31602
31931
  },
31603
31932
  "IMMEDIATE"
31604
31933
  );
31934
+ if (changed) this.onChange();
31605
31935
  return changed;
31606
31936
  }
31607
31937
  /**
@@ -31843,6 +32173,7 @@ var SqliteInstalledPacksRepository = class {
31843
32173
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31844
32174
  WHERE namespace = :namespace AND pack_id = :packId`
31845
32175
  ).run({ policyId, now: Date.now(), namespace, packId });
32176
+ if (Number(res.changes) > 0) this.onChange();
31846
32177
  return Number(res.changes) > 0;
31847
32178
  }
31848
32179
  /**
@@ -31867,6 +32198,7 @@ var SqliteInstalledPacksRepository = class {
31867
32198
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31868
32199
  WHERE namespace = :namespace AND pack_id = :packId`
31869
32200
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
32201
+ if (Number(res.changes) > 0) this.onChange();
31870
32202
  return Number(res.changes) > 0;
31871
32203
  }
31872
32204
  // Fingerprint of the recorded available mirror — compared against the
@@ -32764,13 +33096,19 @@ var SqliteInventoryAssetsRepository = class {
32764
33096
  import { randomUUID as randomUUID6 } from "crypto";
32765
33097
  var SEED_BATCH_WINDOW_MS = 6e4;
32766
33098
  var SqlitePoliciesRepository = class {
32767
- constructor(db) {
33099
+ constructor(db, onChange = () => void 0) {
32768
33100
  this.db = db;
33101
+ this.onChange = onChange;
32769
33102
  }
32770
33103
  db;
33104
+ onChange;
32771
33105
  readPolicies() {
33106
+ return Promise.resolve(this.listPolicies());
33107
+ }
33108
+ /** The synchronous read behind {@link readPolicies}. */
33109
+ listPolicies() {
32772
33110
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32773
- const policies = mapRowsTolerant(rows, (row) => {
33111
+ return mapRowsTolerant(rows, (row) => {
32774
33112
  const target = JSON.parse(row.target);
32775
33113
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32776
33114
  return Policy.parse({
@@ -32782,7 +33120,6 @@ var SqlitePoliciesRepository = class {
32782
33120
  customKeywords
32783
33121
  });
32784
33122
  });
32785
- return Promise.resolve(policies);
32786
33123
  }
32787
33124
  // Seed one policy per bundled category at Monitor so the detection-type config
32788
33125
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32793,7 +33130,7 @@ var SqlitePoliciesRepository = class {
32793
33130
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32794
33131
  if (count > 0) {
32795
33132
  this.markEarlierChoices();
32796
- this.monitorUntouchedSeeds();
33133
+ if (this.monitorUntouchedSeeds()) this.onChange();
32797
33134
  return;
32798
33135
  }
32799
33136
  const stmt = this.db.prepare(
@@ -32810,6 +33147,7 @@ var SqlitePoliciesRepository = class {
32810
33147
  });
32811
33148
  }
32812
33149
  });
33150
+ this.onChange();
32813
33151
  }
32814
33152
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32815
33153
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32875,7 +33213,7 @@ var SqlitePoliciesRepository = class {
32875
33213
  ).filter(
32876
33214
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32877
33215
  );
32878
- if (untouched.length === 0) return;
33216
+ if (untouched.length === 0) return false;
32879
33217
  const stmt = this.db.prepare(
32880
33218
  `UPDATE policies SET action = 'log'
32881
33219
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32886,6 +33224,7 @@ var SqlitePoliciesRepository = class {
32886
33224
  stmt.run({ category: row.category, seeded: row.action });
32887
33225
  }
32888
33226
  });
33227
+ return true;
32889
33228
  }
32890
33229
  // Insert-or-update the single global per-category policy row, keyed on the
32891
33230
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32902,6 +33241,7 @@ var SqlitePoliciesRepository = class {
32902
33241
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32903
33242
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32904
33243
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
33244
+ this.onChange();
32905
33245
  }
32906
33246
  // Caps every global per-category policy currently set to block/redact down
32907
33247
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32912,6 +33252,7 @@ var SqlitePoliciesRepository = class {
32912
33252
  WHERE scope='global' AND action IN ('block','redact')
32913
33253
  AND json_extract(target,'$.category') IS NOT NULL`
32914
33254
  ).run({ now: Date.now() });
33255
+ if (Number(info.changes) > 0) this.onChange();
32915
33256
  return Number(info.changes);
32916
33257
  }
32917
33258
  // Whether the category's row was ever written after it was created — by the
@@ -33231,31 +33572,45 @@ var SqliteScanLedgerRepository = class {
33231
33572
  constructor(db) {
33232
33573
  this.db = db;
33233
33574
  this.upsertStmt = db.prepare(
33234
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33235
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
33575
+ `INSERT INTO scan_ledger
33576
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
33577
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33236
33578
  ON CONFLICT (path) DO UPDATE SET
33237
33579
  mtime = excluded.mtime,
33238
33580
  content_hash = excluded.content_hash,
33239
33581
  ruleset_hash = excluded.ruleset_hash,
33582
+ scope_key = excluded.scope_key,
33583
+ scope_root = excluded.scope_root,
33240
33584
  scanned_at = excluded.scanned_at`
33241
33585
  );
33242
33586
  this.readStmt = db.prepare(
33243
- `SELECT path, mtime, content_hash AS contentHash
33587
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
33588
+ scope_root AS scopeRoot
33244
33589
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33245
33590
  );
33246
33591
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
33592
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33247
33593
  }
33248
33594
  db;
33249
33595
  upsertStmt;
33250
33596
  readStmt;
33251
33597
  pathsStmt;
33598
+ pathKeysStmt;
33252
33599
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33253
33600
  // older ruleset are simply absent, which reads as "never scanned".
33254
33601
  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 }]));
33602
+ const rows = allRows(this.readStmt, { rulesetHash });
33603
+ return new Map(
33604
+ rows.map((r) => [
33605
+ r.path,
33606
+ {
33607
+ mtime: r.mtime,
33608
+ contentHash: r.contentHash,
33609
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
33610
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
33611
+ }
33612
+ ])
33613
+ );
33259
33614
  }
33260
33615
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33261
33616
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33264,6 +33619,14 @@ var SqliteScanLedgerRepository = class {
33264
33619
  allPaths() {
33265
33620
  return allRows(this.pathsStmt).map((r) => r.path);
33266
33621
  }
33622
+ // Every ledgered path with the repository it was in when it was last read,
33623
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
33624
+ // which repository a vanished file belonged to. `undefined` for a row with no
33625
+ // key, which is every row written before the column existed.
33626
+ pathKeys() {
33627
+ const rows = allRows(this.pathKeysStmt);
33628
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
33629
+ }
33267
33630
  upsertEntries(entries) {
33268
33631
  if (entries.length === 0) return;
33269
33632
  const scannedAt = Date.now();
@@ -33274,6 +33637,8 @@ var SqliteScanLedgerRepository = class {
33274
33637
  mtime: entry.mtime,
33275
33638
  contentHash: entry.contentHash,
33276
33639
  rulesetHash: entry.rulesetHash,
33640
+ scopeKey: entry.scopeKey ?? null,
33641
+ scopeRoot: entry.scopeRoot ?? null,
33277
33642
  scannedAt
33278
33643
  });
33279
33644
  }
@@ -34361,6 +34726,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34361
34726
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34362
34727
  };
34363
34728
  }
34729
+ function withoutTrailingSlashes(path) {
34730
+ let end = path.length;
34731
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
34732
+ return path.slice(0, end);
34733
+ }
34364
34734
  function toEndpointSummary(row) {
34365
34735
  return {
34366
34736
  id: row.id,
@@ -34648,7 +35018,7 @@ var SqliteSharesRepository = class {
34648
35018
  */
34649
35019
  reconcileCallSites(projectKey, reconcile) {
34650
35020
  if (reconcile.mode === "walk") {
34651
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
35021
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34652
35022
  this.db.prepare(
34653
35023
  `DELETE FROM share_call_site
34654
35024
  WHERE project_key = :key
@@ -35216,7 +35586,7 @@ function backupLegacyStore(db, file2) {
35216
35586
  discardStore(file2, backup);
35217
35587
  return backup;
35218
35588
  }
35219
- function openAndInitialize(file2, base, skipTags) {
35589
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35220
35590
  let db = openWithPragmas(file2);
35221
35591
  try {
35222
35592
  if (isForeignSqliteLineage(db)) {
@@ -35228,8 +35598,15 @@ function openAndInitialize(file2, base, skipTags) {
35228
35598
  }
35229
35599
  applyMigrations(db, file2, { skipTags });
35230
35600
  tightenPerms(file2);
35231
- const policies = new SqlitePoliciesRepository(db);
35232
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
35601
+ const modPolicy = {};
35602
+ const onPolicyStateChange = () => {
35603
+ if (modPolicy.current !== void 0)
35604
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
35605
+ };
35606
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
35607
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
35608
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
35609
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35233
35610
  const repositories = {
35234
35611
  events: new SqliteEventsRepository(db),
35235
35612
  findings: new SqliteFindingsRepository(db),
@@ -35238,9 +35615,9 @@ function openAndInitialize(file2, base, skipTags) {
35238
35615
  scanLedger: new SqliteScanLedgerRepository(db),
35239
35616
  historySync: new SqliteHistorySyncRepository(db),
35240
35617
  secretVault: new SqliteSecretVaultRepository(db),
35241
- exceptions: new SqliteExceptionsRepository(db),
35618
+ exceptions,
35242
35619
  resolutions: new SqliteResolutionsRepository(db),
35243
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
35620
+ ruleProbeCache,
35244
35621
  bodyRetention: new SqliteBodyRetentionRepository(db),
35245
35622
  security: new SqliteSecurityRepository(db),
35246
35623
  detections: new SqliteDetectionsRepository(db),
@@ -35258,6 +35635,13 @@ function openAndInitialize(file2, base, skipTags) {
35258
35635
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35259
35636
  configInventory: new SqliteConfigInventoryRepository(db)
35260
35637
  };
35638
+ modPolicy.current = {
35639
+ installedRuleset: () => installedPacks.installedRuleset(),
35640
+ readPolicies: () => policies.listPolicies(),
35641
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
35642
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
35643
+ bundledRegexMatchers: () => shippedRegexMatchers2
35644
+ };
35261
35645
  policies.seedDefaults();
35262
35646
  return { db, ...repositories };
35263
35647
  } catch (err) {
@@ -35269,7 +35653,7 @@ function openAndInitialize(file2, base, skipTags) {
35269
35653
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35270
35654
  function openLocalDatabase(dir, options = {}) {
35271
35655
  ensureDataDirSync(dir);
35272
- const file2 = join7(dir, DB_FILENAME);
35656
+ const file2 = join8(dir, DB_FILENAME);
35273
35657
  reapStalePartials(file2);
35274
35658
  const {
35275
35659
  db,
@@ -35305,7 +35689,8 @@ function openLocalDatabase(dir, options = {}) {
35305
35689
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35306
35690
  // settings/ and data/, and the pack-policy floor needs both halves.
35307
35691
  dirname2(dir),
35308
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
35692
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
35693
+ options.shippedRegexMatchers ?? []
35309
35694
  );
35310
35695
  function captureRowId(event) {
35311
35696
  return captureId(
@@ -35570,7 +35955,7 @@ function openLocalDatabase(dir, options = {}) {
35570
35955
  }
35571
35956
 
35572
35957
  // ../../packages/persistence/src/egress-wire.ts
35573
- import { createHash as createHash3 } from "crypto";
35958
+ import { createHash as createHash4 } from "crypto";
35574
35959
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35575
35960
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35576
35961
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35602,7 +35987,7 @@ function canonicalGitUrl(url2) {
35602
35987
  }
35603
35988
  function hashProjectKey(projectKey) {
35604
35989
  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");
35990
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35606
35991
  }
35607
35992
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35608
35993
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35667,24 +36052,23 @@ function toEgressIngestRequest(input2) {
35667
36052
  }
35668
36053
 
35669
36054
  // ../../packages/persistence/src/finding-key.ts
35670
- import { createHash as createHash4 } from "crypto";
36055
+ import { createHash as createHash5 } from "crypto";
35671
36056
  function normalizeFilePath(filePath) {
35672
36057
  return filePath.replaceAll("\\", "/");
35673
36058
  }
35674
36059
  function computeFindingKey(input2) {
35675
36060
  const normalizedPath = normalizeFilePath(input2.filePath);
35676
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
36061
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35677
36062
  }
35678
36063
 
35679
36064
  // ../../packages/persistence/src/fingerprint.ts
35680
36065
  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";
36066
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
36067
+ import { join as join9 } from "path";
35684
36068
  var EXCEPTION_KEY_FILENAME = "exception.key";
35685
36069
  var KEY_MATERIAL_BYTES = 32;
35686
36070
  function keyFilePath(dataDir2) {
35687
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
36071
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35688
36072
  }
35689
36073
  function parseKeyFile(raw) {
35690
36074
  const parsed2 = JSON.parse(raw);
@@ -35711,6 +36095,12 @@ var KEY_VERSION_COLUMNS = {
35711
36095
  };
35712
36096
  var SQLITE_ERROR2 = 1;
35713
36097
  var FLOOR_BUSY_TIMEOUT_MS = 250;
36098
+ function openReadOnly(file2) {
36099
+ const host = process;
36100
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
36101
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
36102
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
36103
+ }
35714
36104
  var FloorUnreadableError = class extends Error {
35715
36105
  code = "floor-unreadable";
35716
36106
  constructor(cause) {
@@ -35722,11 +36112,11 @@ var FloorUnreadableError = class extends Error {
35722
36112
  }
35723
36113
  };
35724
36114
  function storedKeyVersionFloor(dataDir2) {
35725
- const file2 = join8(dataDir2, DB_FILENAME);
36115
+ const file2 = join9(dataDir2, DB_FILENAME);
35726
36116
  if (!existsSync3(file2)) return 0;
35727
36117
  let db;
35728
36118
  try {
35729
- db = new DatabaseSync2(file2, { readOnly: true });
36119
+ db = openReadOnly(file2);
35730
36120
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35731
36121
  let floor = 0;
35732
36122
  for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35777,7 +36167,7 @@ function occupantMessage(file2, kind) {
35777
36167
  function readFingerprintKey(dataDir2) {
35778
36168
  let raw;
35779
36169
  try {
35780
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
36170
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35781
36171
  } catch (err) {
35782
36172
  if (err.code === "ENOENT") return null;
35783
36173
  throw err instanceof Error ? err : new Error(String(err));
@@ -35803,8 +36193,8 @@ function exactFingerprintValue(key, raw) {
35803
36193
  }
35804
36194
 
35805
36195
  // ../../packages/persistence/src/forward-health.ts
35806
- import { readFileSync as readFileSync7 } from "fs";
35807
- import { join as join9 } from "path";
36196
+ import { readFileSync as readFileSync8 } from "fs";
36197
+ import { join as join10 } from "path";
35808
36198
  var BREAKER_COOLDOWN_MS = 3e4;
35809
36199
  function parseForwardHealth(raw, nowMs) {
35810
36200
  try {
@@ -35828,20 +36218,21 @@ function isForwardPaused(health, nowMs) {
35828
36218
 
35829
36219
  // ../../packages/persistence/src/history-backfill.ts
35830
36220
  import { existsSync as existsSync4 } from "fs";
35831
- import { join as join10 } from "path";
36221
+ import { join as join11 } from "path";
35832
36222
 
35833
36223
  // ../../packages/persistence/src/history-preview.ts
35834
36224
  import { existsSync as existsSync5 } from "fs";
35835
- import { join as join11 } from "path";
35836
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36225
+ import { join as join12 } from "path";
36226
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35837
36227
 
35838
36228
  // ../../packages/persistence/src/history-sync-state.ts
35839
- import { readFileSync as readFileSync8 } from "fs";
35840
- import { join as join12 } from "path";
36229
+ import { readFileSync as readFileSync9 } from "fs";
36230
+ import { join as join13 } from "path";
36231
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35841
36232
 
35842
36233
  // ../../packages/persistence/src/store-symlinks.ts
35843
36234
  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";
36235
+ import { dirname as dirname3, join as join14, resolve } from "path";
35845
36236
 
35846
36237
  // ../../packages/persistence/src/vault/crypto.ts
35847
36238
  import {
@@ -35855,19 +36246,19 @@ import {
35855
36246
  // ../../packages/persistence/src/vault/key-provider.ts
35856
36247
  import { execFileSync } from "child_process";
35857
36248
  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";
36249
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
36250
+ import { join as join15 } from "path";
35860
36251
 
35861
36252
  // ../../packages/persistence/src/vault/vault.ts
35862
36253
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35863
36254
 
35864
36255
  // ../../packages/persistence/src/warn-era-cap.ts
35865
36256
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35866
- import { join as join15 } from "path";
36257
+ import { join as join16 } from "path";
35867
36258
  var MARKER = "warn-era-capped";
35868
36259
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35869
36260
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35870
- const marker = join15(dataDir2, MARKER);
36261
+ const marker = join16(dataDir2, MARKER);
35871
36262
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35872
36263
  const capped = db.policies.capCategoryActions();
35873
36264
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35875,577 +36266,84 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35875
36266
  return { capped };
35876
36267
  }
35877
36268
 
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
- }
36269
+ // ../../packages/plugin-sdk/src/config.ts
36270
+ import { existsSync as existsSync8 } from "fs";
36271
+ import { join as join17 } from "path";
36272
+
36273
+ // ../../packages/plugin-sdk/src/provider-env.ts
36274
+ var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
36275
+ var booleanish = external_exports.string().optional().transform((v) => {
36276
+ if (v === void 0) return void 0;
36277
+ const t = v.trim().toLowerCase();
36278
+ if (t === "" || t === "false" || t === "0") return false;
36279
+ return true;
36280
+ }).catch(void 0);
36281
+ var optionalBaseUrl = external_exports.preprocess((v) => {
36282
+ if (typeof v === "string" && v.trim() === "") return void 0;
36283
+ return v;
36284
+ }, external_exports.string().optional()).catch(void 0);
36285
+ var providerEnvShape = {
36286
+ CLAUDE_CODE_USE_BEDROCK: booleanish,
36287
+ CLAUDE_CODE_USE_VERTEX: booleanish,
36288
+ ANTHROPIC_BASE_URL: optionalBaseUrl
35912
36289
  };
35913
- var RemoteResponseInvalid = class extends Error {
35914
- constructor(route, detail) {
35915
- super(`control plane answered ${route} with ${detail}`);
35916
- this.name = "RemoteResponseInvalid";
36290
+ var ProviderEnvSchema = external_exports.object(providerEnvShape);
36291
+
36292
+ // ../../packages/plugin-sdk/src/provider.ts
36293
+ function hostOf(url2) {
36294
+ try {
36295
+ const host = new URL(url2).host;
36296
+ if (host !== "") return host;
36297
+ } catch {
35917
36298
  }
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";
36299
+ try {
36300
+ const host = new URL(`https://${url2}`).host;
36301
+ return host !== "" ? host : void 0;
36302
+ } catch {
36303
+ return void 0;
35935
36304
  }
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
- }
36305
+ }
36306
+ function resolveProvider() {
36307
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
36308
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
36309
+ if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
36310
+ if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
36311
+ const baseUrl = env.ANTHROPIC_BASE_URL;
36312
+ if (baseUrl !== void 0 && baseUrl !== "") {
36313
+ const host = hostOf(baseUrl);
36314
+ if (host !== void 0 && host !== DEFAULT_ANTHROPIC_HOST) {
36315
+ return { provider: "gateway", gatewayHost: host };
35970
36316
  }
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
- });
36317
+ }
36318
+ return { provider: "anthropic" };
36024
36319
  }
36025
36320
 
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);
36321
+ // ../../packages/plugin-sdk/src/config.ts
36322
+ function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
36323
+ try {
36324
+ ensureLayoutDirSync(base);
36325
+ const settingsFile = join17(settingsDir(base), "settings.json");
36326
+ if (existsSync8(settingsFile)) tightenFile(settingsFile);
36327
+ } catch {
36049
36328
  }
36050
- return response.body;
36329
+ migrateLegacyLayout(base);
36330
+ const settings = readWorkspaceSettings(base);
36331
+ return {
36332
+ settings,
36333
+ dataDir: dataDir(base),
36334
+ dbPath: dbPath(base),
36335
+ settingsDir: settingsDir(base),
36336
+ onboarded: settings.onboardedAt != null,
36337
+ provider: resolveProviderSafe(resolveProviderFn)
36338
+ };
36051
36339
  }
36052
- function parsed(schema, body, route) {
36053
- let json2;
36340
+ function resolveProviderSafe(resolveProviderFn) {
36054
36341
  try {
36055
- json2 = JSON.parse(body);
36342
+ return resolveProviderFn();
36056
36343
  } 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");
36344
+ return { provider: "anthropic" };
36062
36345
  }
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
36346
  }
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
36347
 
36450
36348
  // ../../packages/detections/src/egress/registry.ts
36451
36349
  var EXTRACTOR_VERSION = "3";
@@ -37551,11 +37449,11 @@ var EXACT_KIND_BY_BASENAME = {
37551
37449
  "composer.json": "composer.json",
37552
37450
  "packages.config": "packages.config"
37553
37451
  };
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;
37452
+ function manifestKindOf(basename6) {
37453
+ if (LOCKFILE_BASENAMES.has(basename6)) return null;
37454
+ const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename6) ? EXACT_KIND_BY_BASENAME[basename6] : void 0;
37557
37455
  if (exact !== void 0) return exact;
37558
- if (basename8.endsWith(".csproj")) return "csproj";
37456
+ if (basename6.endsWith(".csproj")) return "csproj";
37559
37457
  return null;
37560
37458
  }
37561
37459
  function extractManifestSdks(text, kind) {
@@ -38183,12 +38081,12 @@ var RegexMatcher2 = class {
38183
38081
  rule.matcher,
38184
38082
  () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
38185
38083
  );
38186
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
38084
+ const scanText = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
38187
38085
  const spans = [];
38188
38086
  let m;
38189
- const maxIterations = scanText2.length + 1;
38087
+ const maxIterations = scanText.length + 1;
38190
38088
  let iterations = 0;
38191
- while ((m = re.exec(scanText2)) !== null) {
38089
+ while ((m = re.exec(scanText)) !== null) {
38192
38090
  if (++iterations > maxIterations) break;
38193
38091
  const group = captureGroup != null ? m[captureGroup] : m[0];
38194
38092
  if (m[0].length === 0) re.lastIndex++;
@@ -38530,17 +38428,18 @@ function ruleEvidence(rule) {
38530
38428
 
38531
38429
  // ../../packages/detections/src/mask.ts
38532
38430
  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);
38431
+ const visible = stripInvisiblePadding(raw);
38432
+ if (visible.length <= 5) return "***";
38433
+ const atIndex = visible.indexOf("@");
38434
+ if (atIndex > 0 && atIndex < visible.length - 1) {
38435
+ const domain2 = visible.slice(atIndex + 1);
38537
38436
  if (domain2.includes(".")) {
38538
- const local = raw.slice(0, atIndex);
38437
+ const local = visible.slice(0, atIndex);
38539
38438
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
38540
38439
  return `${maskedLocal}@${domain2}`;
38541
38440
  }
38542
38441
  }
38543
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
38442
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
38544
38443
  }
38545
38444
 
38546
38445
  // ../../packages/detections/src/pointer-shield.ts
@@ -38776,6 +38675,38 @@ function worstProbeMs(rule, now = wallClock, corroborate) {
38776
38675
  }
38777
38676
  var CPU_CORROBORATION_SHARE = 0.2;
38778
38677
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
38678
+ function repeatTo(unit, length) {
38679
+ return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
38680
+ }
38681
+ function joinTo(length, open3, close, item) {
38682
+ const parts = [];
38683
+ let size = open3.length;
38684
+ for (let i = 0; size < length; i++) {
38685
+ const next = (i === 0 ? "" : ",") + item(i);
38686
+ parts.push(next);
38687
+ size += next.length;
38688
+ }
38689
+ return (open3 + parts.join("") + close).slice(0, length);
38690
+ }
38691
+ var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
38692
+ var GROWTH_CORPORA = [
38693
+ {
38694
+ name: "one-line JSON dictionary",
38695
+ build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
38696
+ },
38697
+ {
38698
+ name: "JSON array of quoted SQL keywords",
38699
+ build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
38700
+ },
38701
+ { name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
38702
+ { name: "double-quote run", build: (length) => repeatTo('"', length) },
38703
+ { name: "space run", build: (length) => repeatTo(" ", length) },
38704
+ { name: "newline run", build: (length) => repeatTo("\n", length) },
38705
+ ...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
38706
+ name: `unit run ${JSON.stringify(unit)}`,
38707
+ build: (length) => repeatTo(unit, length)
38708
+ }))
38709
+ ];
38779
38710
  function checkRuleTiming(rule, corroborate) {
38780
38711
  const { ms, probe, corroboratedMs } = worstProbeMs(rule, wallClock, corroborate);
38781
38712
  const work = corroboratedMs ?? 0;
@@ -38802,7 +38733,12 @@ var MIN_RAW_LEN = 4;
38802
38733
  var RAW_RUN_LEN = 8;
38803
38734
  function carriesRawRun(text, rawValues) {
38804
38735
  let windows = null;
38805
- for (const raw of new Set(rawValues)) {
38736
+ const values = /* @__PURE__ */ new Set();
38737
+ for (const raw of rawValues) {
38738
+ values.add(raw);
38739
+ values.add(stripInvisiblePadding(raw));
38740
+ }
38741
+ for (const raw of values) {
38806
38742
  if (raw.length < MIN_RAW_LEN) continue;
38807
38743
  if (raw.length < RAW_RUN_LEN) {
38808
38744
  if (text.includes(raw)) return true;
@@ -38826,11 +38762,16 @@ function carriesRawRun(text, rawValues) {
38826
38762
  return false;
38827
38763
  }
38828
38764
  function safeMaskedMatch(rawMatch) {
38829
- const masked = maskMatch(rawMatch);
38830
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
38831
- return "***";
38765
+ const visible = stripInvisiblePadding(rawMatch);
38766
+ const masked = maskMatch(visible);
38767
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
38768
+ if (!reveals(masked)) return masked;
38769
+ const atIndex = masked.indexOf("@");
38770
+ if (atIndex > 0 && atIndex < masked.length - 1) {
38771
+ const emailFallback = `*${masked.slice(atIndex)}`;
38772
+ if (!reveals(emailFallback)) return emailFallback;
38832
38773
  }
38833
- return masked;
38774
+ return "***";
38834
38775
  }
38835
38776
  function assertRawFree(text, rawValues) {
38836
38777
  if (carriesRawRun(text, rawValues)) {
@@ -39067,7 +39008,7 @@ var auth_jwt_no_verify_default = {
39067
39008
  severity: "critical",
39068
39009
  matcher: {
39069
39010
  type: "regex",
39070
- pattern: "(verify\\s*=\\s*false|verify_signature.*false|algorithms\\s*=\\s*\\[\\])",
39011
+ pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
39071
39012
  flags: "gi"
39072
39013
  },
39073
39014
  requiresNearby: {
@@ -39155,7 +39096,7 @@ var cmd_inject_shell_default = {
39155
39096
  severity: "critical",
39156
39097
  matcher: {
39157
39098
  type: "regex",
39158
- pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
39099
+ pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
39159
39100
  flags: "gi"
39160
39101
  },
39161
39102
  requiresNearby: {
@@ -39284,7 +39225,7 @@ var deser_yaml_unsafe_default = {
39284
39225
  severity: "high",
39285
39226
  matcher: {
39286
39227
  type: "regex",
39287
- pattern: "\\byaml\\.load\\s*\\((?![^)]*SafeLoader|[^)]*safe_load)",
39228
+ pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
39288
39229
  flags: "gi"
39289
39230
  },
39290
39231
  examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
@@ -39501,7 +39442,7 @@ var sql_inject_concat_dot_default = {
39501
39442
  severity: "high",
39502
39443
  matcher: {
39503
39444
  type: "regex",
39504
- pattern: `["'][^\\n]*?(select|insert|update|delete|drop|where)[^\\n]*?["']\\s*\\.`,
39445
+ pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
39505
39446
  flags: "gi"
39506
39447
  },
39507
39448
  appliesTo: {
@@ -39519,7 +39460,7 @@ var sql_inject_concat_default = {
39519
39460
  severity: "high",
39520
39461
  matcher: {
39521
39462
  type: "regex",
39522
- pattern: `["']\\s*(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?["']\\s*\\+`,
39463
+ pattern: `(["'])\\s*(?=(select\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?=))\\2(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?["']\\s*\\+`,
39523
39464
  flags: "gi"
39524
39465
  },
39525
39466
  examples: ['"SELECT * FROM users WHERE id = " + userId']
@@ -39534,7 +39475,7 @@ var sql_inject_format_default = {
39534
39475
  severity: "high",
39535
39476
  matcher: {
39536
39477
  type: "regex",
39537
- pattern: "\\b(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?(?:[%][sd]|\\{[^}]+\\})",
39478
+ pattern: "\\b(?=(select\\b(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))\\1(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})|\\b(?=(where\\b(?:(?!\\bwhere\\b)[^\\n])*?=))\\2(?:(?!\\bwhere\\b)[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})",
39538
39479
  flags: "gi"
39539
39480
  },
39540
39481
  examples: [
@@ -39552,7 +39493,7 @@ var sql_inject_interp_default = {
39552
39493
  severity: "high",
39553
39494
  matcher: {
39554
39495
  type: "regex",
39555
- pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
39496
+ pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
39556
39497
  flags: "gi"
39557
39498
  },
39558
39499
  examples: [
@@ -39927,7 +39868,7 @@ var stack_trace_default = {
39927
39868
  severity: "low",
39928
39869
  matcher: {
39929
39870
  type: "regex",
39930
- pattern: "(?:^|\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
39871
+ pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
39931
39872
  flags: "g"
39932
39873
  },
39933
39874
  examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
@@ -41085,7 +41026,7 @@ var BUNDLED_PACKS = [
41085
41026
  {
41086
41027
  packId: "code-flaws",
41087
41028
  name: "Code Security Flaws",
41088
- version: "0.1.0",
41029
+ version: "0.1.1",
41089
41030
  rawRules: [
41090
41031
  sql_inject_concat_default,
41091
41032
  sql_inject_concat_dot_default,
@@ -41135,7 +41076,7 @@ var BUNDLED_PACKS = [
41135
41076
  {
41136
41077
  packId: "core-code-context",
41137
41078
  name: "Code Context",
41138
- version: "0.2.1",
41079
+ version: "0.2.2",
41139
41080
  rawRules: [
41140
41081
  internal_ip_default,
41141
41082
  localhost_ref_default,
@@ -41272,6 +41213,11 @@ function bundledDetections() {
41272
41213
  }));
41273
41214
  return cachedDetections;
41274
41215
  }
41216
+ function shippedRegexMatchers() {
41217
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
41218
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
41219
+ );
41220
+ }
41275
41221
 
41276
41222
  // ../../packages/plugin-sdk/src/mask.ts
41277
41223
  var packsReady = false;
@@ -41313,8 +41259,9 @@ function resolveRepoIdentity(cwd) {
41313
41259
  var ATTRIBUTION_MEMO_LIMIT = 64;
41314
41260
  var attributionMemo = /* @__PURE__ */ new Map();
41315
41261
  var NO_ATTRIBUTION = Object.freeze({});
41316
- function resolveRepoAttribution(cwd) {
41262
+ function resolveRepoAttribution(cwd, options) {
41317
41263
  try {
41264
+ if (options?.cache === false) return attributeRepo(cwd);
41318
41265
  const remembered = attributionMemo.get(cwd);
41319
41266
  if (remembered !== void 0) return remembered;
41320
41267
  const attribution = attributeRepo(cwd);
@@ -41421,9 +41368,9 @@ function slugFromUrl(url2) {
41421
41368
  }
41422
41369
 
41423
41370
  // ../../packages/plugin-sdk/src/events.ts
41424
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
41371
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
41425
41372
  function contentHashOf(text) {
41426
- return createHash5("sha256").update(text).digest("hex");
41373
+ return createHash6("sha256").update(text).digest("hex");
41427
41374
  }
41428
41375
  function buildIngestEvent(input2) {
41429
41376
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -41598,9 +41545,10 @@ function createIsolatedScanner(data, opts = {}) {
41598
41545
  if (job.timer !== void 0) return;
41599
41546
  job.startedAt = performance.now();
41600
41547
  job.progressAt = job.startedAt;
41548
+ const budget = job.deadlineAt === void 0 ? job.budgetMs : Math.max(0, Math.min(job.budgetMs, job.deadlineAt - job.startedAt));
41601
41549
  job.timer = setTimeout(() => {
41602
41550
  onDeadline(job);
41603
- }, job.budgetMs);
41551
+ }, budget);
41604
41552
  }
41605
41553
  function runOne(spec, fail) {
41606
41554
  if (closed) {
@@ -41611,6 +41559,12 @@ function createIsolatedScanner(data, opts = {}) {
41611
41559
  fail({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
41612
41560
  return;
41613
41561
  }
41562
+ const now = performance.now();
41563
+ const deadlineAt = spec.deadlineAt;
41564
+ if (deadlineAt !== void 0 && deadlineAt <= now) {
41565
+ fail({ status: "timeout", culpritIndex: void 0, elapsedMs: 0 });
41566
+ return;
41567
+ }
41614
41568
  const started = ensureWorker();
41615
41569
  if (!(started instanceof Worker)) {
41616
41570
  broken = started.error;
@@ -41618,11 +41572,11 @@ function createIsolatedScanner(data, opts = {}) {
41618
41572
  return;
41619
41573
  }
41620
41574
  const id = nextJobId++;
41621
- const now = performance.now();
41622
41575
  const job = {
41623
41576
  id,
41624
41577
  worker: started,
41625
41578
  budgetMs: spec.budgetMs,
41579
+ deadlineAt,
41626
41580
  startedAt: now,
41627
41581
  progressIndex: -1,
41628
41582
  progressAt: now,
@@ -41636,14 +41590,19 @@ function createIsolatedScanner(data, opts = {}) {
41636
41590
  if (readyWorker === started) {
41637
41591
  beginDeadline(job);
41638
41592
  } else {
41593
+ const startBudget = spec.startBudgetMs ?? startBudgetMs;
41594
+ const callerLimited = deadlineAt !== void 0 && deadlineAt - now < startBudget;
41595
+ const startWaitMs = callerLimited ? deadlineAt - now : startBudget;
41639
41596
  job.startupTimer = setTimeout(() => {
41640
41597
  if (pending !== job) return;
41641
41598
  kill(job.worker);
41642
- failPending({
41643
- status: "unavailable",
41644
- reason: `the scan worker did not start within ${String(startBudgetMs)}ms`
41645
- });
41646
- }, startBudgetMs);
41599
+ failPending(
41600
+ callerLimited ? { status: "timeout", culpritIndex: void 0, elapsedMs: performance.now() - now } : {
41601
+ status: "unavailable",
41602
+ reason: `the scan worker did not start within ${String(startBudget)}ms`
41603
+ }
41604
+ );
41605
+ }, startWaitMs);
41647
41606
  }
41648
41607
  try {
41649
41608
  started.postMessage(spec.build(id));
@@ -41672,7 +41631,9 @@ function createIsolatedScanner(data, opts = {}) {
41672
41631
  return enqueue((resolve4) => {
41673
41632
  runOne(
41674
41633
  {
41675
- budgetMs,
41634
+ budgetMs: scanOpts?.budgetMs ?? budgetMs,
41635
+ startBudgetMs: scanOpts?.startBudgetMs,
41636
+ deadlineAt: scanOpts?.deadlineAt,
41676
41637
  build: (id) => ({
41677
41638
  kind: "scan",
41678
41639
  id,
@@ -41866,6 +41827,9 @@ function createGuardedScanner(partition, gateway, opts) {
41866
41827
  let unverified = partition.unverified;
41867
41828
  let isolated = unverified.length > 0 ? createIsolatedScanner({ verified, unverified }, opts) : void 0;
41868
41829
  let retired = false;
41830
+ let bounded;
41831
+ let boundedWarned = false;
41832
+ let closed = false;
41869
41833
  function inProcess(text, context) {
41870
41834
  return scan(text, verified, context);
41871
41835
  }
@@ -41927,71 +41891,59 @@ function createGuardedScanner(partition, gateway, opts) {
41927
41891
  await degrade();
41928
41892
  return inProcess(text, context);
41929
41893
  }
41894
+ async function scanBounded(text, context, bound) {
41895
+ const remainingMs = bound.remainingMs;
41896
+ let outcome;
41897
+ if (closed) {
41898
+ outcome = { status: "unavailable", reason: "the scan worker is closed" };
41899
+ } else if (remainingMs !== void 0 && !(remainingMs > 0)) {
41900
+ outcome = { status: "timeout", culpritIndex: void 0, elapsedMs: 0 };
41901
+ } else {
41902
+ bounded ??= createIsolatedScanner({ verified, unverified }, opts);
41903
+ const deadlineAt = remainingMs === void 0 ? void 0 : performance.now() + remainingMs;
41904
+ try {
41905
+ outcome = await bounded.scan(text, context, {
41906
+ budgetMs: bound.budgetMs,
41907
+ startBudgetMs: bound.startBudgetMs,
41908
+ deadlineAt
41909
+ });
41910
+ } catch (error62) {
41911
+ outcome = {
41912
+ status: "unavailable",
41913
+ reason: error62 instanceof Error ? error62.message : "the scan worker failed unexpectedly"
41914
+ };
41915
+ }
41916
+ }
41917
+ if (outcome.status !== "ok" && !boundedWarned) {
41918
+ boundedWarned = true;
41919
+ process.stderr.write(
41920
+ outcome.status === "timeout" ? `[aka] a large input could not be scanned within its time limit and was refused.
41921
+ ` : `[aka] a large input could not be scanned and was refused: ${outcome.reason}.
41922
+ `
41923
+ );
41924
+ }
41925
+ return outcome;
41926
+ }
41930
41927
  return {
41931
41928
  scan: guardedScan,
41929
+ scanBounded,
41932
41930
  degraded: () => retired,
41933
41931
  async close() {
41934
- await retire();
41932
+ closed = true;
41933
+ const live = bounded;
41934
+ bounded = void 0;
41935
+ await Promise.all([retire(), live?.close()]);
41935
41936
  }
41936
41937
  };
41937
41938
  }
41938
41939
 
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
41940
  // ../../packages/plugin-sdk/src/ignore-layers.ts
41989
41941
  var import_ignore = __toESM(require_ignore(), 1);
41990
- import { readFileSync as readFileSync16 } from "fs";
41991
- import { join as join23 } from "path";
41942
+ import { readFileSync as readFileSync12 } from "fs";
41943
+ import { join as join19 } from "path";
41992
41944
  function readIgnoreLayer(dir, filename, anchorLen) {
41993
41945
  try {
41994
- return { matcher: (0, import_ignore.default)().add(readFileSync16(join23(dir, filename), "utf8")), anchorLen };
41946
+ return { matcher: (0, import_ignore.default)().add(readFileSync12(join19(dir, filename), "utf8")), anchorLen };
41995
41947
  } catch {
41996
41948
  return void 0;
41997
41949
  }
@@ -42018,16 +41970,9 @@ function withLayer(layers, layer) {
42018
41970
  return layer ? [...layers, layer] : layers;
42019
41971
  }
42020
41972
 
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
41973
  // ../../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";
41974
+ import { readdirSync as readdirSync2, realpathSync as realpathSync2 } from "fs";
41975
+ import { basename as basename3, dirname as dirname5, sep as sep3 } from "path";
42031
41976
  function toPosix(path) {
42032
41977
  return path.split(sep3).join("/");
42033
41978
  }
@@ -42045,7 +41990,7 @@ function findProjectRoot(startDir, recognizeMarker) {
42045
41990
  }
42046
41991
  function directoryHasMarker(dir, recognizeMarker) {
42047
41992
  try {
42048
- for (const entry of readdirSync3(dir, { withFileTypes: true })) {
41993
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
42049
41994
  if (entry.isFile() && recognizeMarker(entry.name) != null) return true;
42050
41995
  }
42051
41996
  } catch {
@@ -42055,8 +42000,8 @@ function directoryHasMarker(dir, recognizeMarker) {
42055
42000
  }
42056
42001
  function resolveNonGitProject(startDir, recognizeMarker) {
42057
42002
  const projectRoot = findProjectRoot(startDir, recognizeMarker);
42058
- const realRoot = realpathSync3(projectRoot);
42059
- return { root: projectRoot, projectKey: `path:${realRoot}`, project: basename4(realRoot) };
42003
+ const realRoot = realpathSync2(projectRoot);
42004
+ return { root: projectRoot, projectKey: `path:${realRoot}`, project: basename3(realRoot) };
42060
42005
  }
42061
42006
 
42062
42007
  // ../../packages/plugin-sdk/src/policy-resolver.ts
@@ -42103,36 +42048,6 @@ function assignedRulePolicies(installed) {
42103
42048
  return out;
42104
42049
  }
42105
42050
 
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
42051
  // ../../packages/plugin-sdk/src/runtime.ts
42137
42052
  import { randomUUID as randomUUID15 } from "crypto";
42138
42053
  var ENFORCEMENT_CEILING_ENABLED = false;
@@ -42173,6 +42088,16 @@ function conditionsMatch(conditions, ctx) {
42173
42088
  if (conditions.provider !== void 0) return false;
42174
42089
  return true;
42175
42090
  }
42091
+ function readRemainingMs(largeInput) {
42092
+ const read = largeInput.remainingMs;
42093
+ if (read === void 0) return void 0;
42094
+ try {
42095
+ const remaining = read();
42096
+ return typeof remaining !== "number" || Number.isNaN(remaining) ? 0 : remaining;
42097
+ } catch {
42098
+ return 0;
42099
+ }
42100
+ }
42176
42101
  var bundlesPacked = false;
42177
42102
  function createPluginRuntime(gateway, settings, opts) {
42178
42103
  if (!bundlesPacked) {
@@ -42182,6 +42107,7 @@ function createPluginRuntime(gateway, settings, opts) {
42182
42107
  const policyMode = settings.policy;
42183
42108
  let redactFallback = settings.redactFallback;
42184
42109
  const dataDir2 = opts?.dataDir;
42110
+ const largeInput = opts?.largeInput;
42185
42111
  let rules = [];
42186
42112
  let evidenceOf = evidenceLookup(rules);
42187
42113
  let scanner;
@@ -42394,7 +42320,24 @@ function createPluginRuntime(gateway, settings, opts) {
42394
42320
  await ensureInitialized();
42395
42321
  if (!scanner) throw new Error("the runtime initialized without a scanner");
42396
42322
  const shielded = shieldPointers(text);
42397
- const matched = await scanner.scan(shielded.text, context);
42323
+ let matched;
42324
+ if (largeInput !== void 0 && shielded.text.length >= largeInput.thresholdChars) {
42325
+ const outcome = await scanner.scanBounded(shielded.text, context, {
42326
+ budgetMs: largeInput.budgetMs,
42327
+ startBudgetMs: largeInput.startBudgetMs,
42328
+ remainingMs: readRemainingMs(largeInput)
42329
+ });
42330
+ if (outcome.status !== "ok") {
42331
+ return {
42332
+ decision: { action: "block", text: null, findings: [], scanIncomplete: outcome.status },
42333
+ excepted: /* @__PURE__ */ new Set(),
42334
+ exceptionIds: []
42335
+ };
42336
+ }
42337
+ matched = outcome.findings;
42338
+ } else {
42339
+ matched = await scanner.scan(shielded.text, context);
42340
+ }
42398
42341
  const findings = dropShieldedFindings(matched, shielded.spans);
42399
42342
  const fpCache = /* @__PURE__ */ new Map();
42400
42343
  const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
@@ -42419,12 +42362,11 @@ function createPluginRuntime(gateway, settings, opts) {
42419
42362
  async function processText(text, context, opts2 = {}) {
42420
42363
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
42421
42364
  }
42422
- async function capture(input2, opts2 = {}) {
42365
+ async function evaluateCapture(input2, opts2) {
42423
42366
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
42424
- const filePath = input2.metadata?.filePath;
42425
42367
  const { decision, excepted, exceptionIds } = await evaluate(
42426
42368
  input2.text,
42427
- { filePath, eventKind: input2.kind },
42369
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
42428
42370
  {
42429
42371
  sourceTool: input2.sourceTool,
42430
42372
  metadata: input2.metadata,
@@ -42432,20 +42374,28 @@ function createPluginRuntime(gateway, settings, opts) {
42432
42374
  },
42433
42375
  opts2.rewritable
42434
42376
  );
42435
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
42377
+ return { decision, excepted, exceptionIds, timingStartedAt };
42378
+ }
42379
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
42380
+ const filePath = input2.metadata?.filePath;
42381
+ if (opts2.persist === "with-findings" && decision.findings.length === 0 && decision.scanIncomplete === void 0) {
42382
+ return;
42383
+ }
42436
42384
  try {
42437
42385
  const contentHash = contentHashOf(input2.text);
42438
42386
  const maskedFindings = decision.findings.filter(
42439
42387
  (match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
42440
42388
  );
42441
- const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
42389
+ const storedContent = decision.scanIncomplete !== void 0 ? "" : maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
42442
42390
  const inspectionMs = elapsedMs(timingStartedAt);
42443
42391
  const redactDegradedTo = decision.redactDegradedTo;
42444
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
42392
+ const scanIncomplete = decision.scanIncomplete;
42393
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 || scanIncomplete !== void 0 ? {
42445
42394
  ...input2.metadata,
42446
42395
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
42447
42396
  ...inspectionMs !== void 0 ? { inspectionMs } : {},
42448
- ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
42397
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {},
42398
+ ...scanIncomplete !== void 0 ? { scanIncomplete } : {}
42449
42399
  } : input2.metadata;
42450
42400
  const event = buildIngestEvent({
42451
42401
  kind: input2.kind,
@@ -42475,6 +42425,8 @@ function createPluginRuntime(gateway, settings, opts) {
42475
42425
  // exceptions/blocked_detections when a key is available;
42476
42426
  // falls back to the masked match so at-rest findings still get
42477
42427
  // a stable (if weaker) identity on a workspace with no dataDir.
42428
+ // Both ignore the same invisible padding, so a clean and a
42429
+ // padded occurrence of one secret key alike on either path.
42478
42430
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
42479
42431
  }) : void 0;
42480
42432
  return {
@@ -42502,7 +42454,37 @@ function createPluginRuntime(gateway, settings, opts) {
42502
42454
  }
42503
42455
  } catch {
42504
42456
  }
42505
- return decision;
42457
+ }
42458
+ async function enforcedIn(text, context) {
42459
+ try {
42460
+ await ensureInitialized();
42461
+ if (!scanner) return [];
42462
+ const shielded = shieldPointers(text);
42463
+ const matched = await scanner.scan(shielded.text, context);
42464
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
42465
+ const action = resolveAction(finding.ruleId, finding.category);
42466
+ return action === "block" || action === "redact";
42467
+ });
42468
+ } catch {
42469
+ return [];
42470
+ }
42471
+ }
42472
+ async function capture(input2, opts2 = {}) {
42473
+ const evaluated = await evaluateCapture(input2, opts2);
42474
+ await persistCapture(input2, opts2, evaluated);
42475
+ return evaluated.decision;
42476
+ }
42477
+ async function captureDeferred(input2, opts2 = {}) {
42478
+ const evaluated = await evaluateCapture(input2, opts2);
42479
+ let recorded = false;
42480
+ return {
42481
+ result: evaluated.decision,
42482
+ record: async () => {
42483
+ if (recorded) return;
42484
+ recorded = true;
42485
+ await persistCapture(input2, opts2, evaluated);
42486
+ }
42487
+ };
42506
42488
  }
42507
42489
  async function rulesetFingerprint() {
42508
42490
  try {
@@ -42523,21 +42505,526 @@ function createPluginRuntime(gateway, settings, opts) {
42523
42505
  }
42524
42506
  await gateway.close();
42525
42507
  }
42526
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
42508
+ return {
42509
+ processText,
42510
+ capture,
42511
+ captureDeferred,
42512
+ enforcedIn,
42513
+ rulesetFingerprint,
42514
+ scanIsolationDegraded,
42515
+ close
42516
+ };
42527
42517
  }
42528
42518
 
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";
42519
+ // ../../packages/remote/src/http.ts
42520
+ import { request as httpRequest } from "http";
42521
+ import { request as httpsRequest } from "https";
42522
+ var DEFAULT_TIMEOUT_MS = 1e4;
42523
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
42524
+ var RemoteRequestError = class extends Error {
42525
+ constructor(status) {
42526
+ super(`control-plane request failed with status ${String(status)}`);
42527
+ this.status = status;
42528
+ this.name = "RemoteRequestError";
42529
+ }
42530
+ status;
42531
+ };
42532
+ var RemoteRouteAbsent = class extends Error {
42533
+ constructor(route) {
42534
+ super(`control plane does not serve ${route}`);
42535
+ this.route = route;
42536
+ this.name = "RemoteRouteAbsent";
42537
+ }
42538
+ route;
42539
+ };
42540
+ var RemoteRequestInvalid = class extends Error {
42541
+ constructor(route, cause) {
42542
+ super(`refusing to send a malformed body to ${route}`);
42543
+ this.cause = cause;
42544
+ this.name = "RemoteRequestInvalid";
42545
+ }
42546
+ cause;
42547
+ };
42548
+ var RemoteEndpointRefused = class extends Error {
42549
+ constructor(endpoint) {
42550
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
42551
+ this.name = "RemoteEndpointRefused";
42552
+ }
42553
+ };
42554
+ var RemoteResponseInvalid = class extends Error {
42555
+ constructor(route, detail) {
42556
+ super(`control plane answered ${route} with ${detail}`);
42557
+ this.name = "RemoteResponseInvalid";
42558
+ }
42559
+ };
42560
+ var RemoteTransportError = class extends Error {
42561
+ /**
42562
+ * The status the peer sent, when headers arrived and only the BODY was
42563
+ * refused.
42564
+ *
42565
+ * Undefined for the ordinary case this class was written for — no answer at
42566
+ * all. It exists because two paths reject after a status has already been
42567
+ * delivered: an oversized body and an aborted response. Discarding it there
42568
+ * reported a deployment answering 401 with a verbose body as a network
42569
+ * outage, which sends the reader to look at their network instead of their
42570
+ * credential.
42571
+ */
42572
+ constructor(reason, status) {
42573
+ super(`control-plane request did not complete: ${reason}`);
42574
+ this.status = status;
42575
+ this.name = "RemoteTransportError";
42576
+ }
42577
+ status;
42578
+ };
42579
+ async function send(options) {
42580
+ const url2 = new URL(options.url);
42581
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
42582
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
42583
+ const requestOptions = {
42584
+ method: options.method,
42585
+ headers: {
42586
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
42587
+ // last they win, and two of the values below are ones no caller may
42588
+ // replace: `x-api-key` is the credential, and `content-length` is the
42589
+ // byte count that stops a multi-byte body being truncated by the
42590
+ // receiver. `SendOptions.headers` is a free-form record on an exported
42591
+ // function, so "no caller does that today" is not the guarantee to rely
42592
+ // on. The one header any caller actually passes — `if-none-match` on the
42593
+ // conditional GET — is untouched by this order.
42594
+ ...options.headers,
42595
+ // The credential. One header, matching what the deployment authenticates
42596
+ // on; a second copy in an `Authorization` header would be one more place
42597
+ // it can be logged by an intermediary for no gain.
42598
+ //
42599
+ // Spread conditionally rather than assigned as `undefined`: Node's header
42600
+ // handling and `content-length` bookkeeping treat a present-but-undefined
42601
+ // key differently from an absent one, and "the header is not there" is
42602
+ // the property the attach flow needs.
42603
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
42604
+ accept: "application/json",
42605
+ ...options.body === void 0 ? {} : {
42606
+ "content-type": "application/json",
42607
+ // Byte length, not string length: a multi-byte body sent with a
42608
+ // character count is truncated by the receiver.
42609
+ "content-length": String(Buffer.byteLength(options.body))
42610
+ }
42611
+ }
42612
+ };
42613
+ return new Promise((resolve4, reject) => {
42614
+ let settled = false;
42615
+ const fail = (reason, status) => {
42616
+ if (settled) return;
42617
+ settled = true;
42618
+ reject(new RemoteTransportError(reason, status));
42619
+ };
42620
+ const req = send_(url2, requestOptions, (res) => {
42621
+ const chunks = [];
42622
+ let size = 0;
42623
+ res.on("data", (chunk) => {
42624
+ size += chunk.length;
42625
+ if (size > MAX_RESPONSE_BYTES) {
42626
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
42627
+ res.destroy();
42628
+ req.destroy();
42629
+ return;
42630
+ }
42631
+ chunks.push(chunk);
42632
+ });
42633
+ res.on("aborted", () => {
42634
+ fail("the response was aborted", res.statusCode);
42635
+ });
42636
+ res.on("end", () => {
42637
+ if (settled) return;
42638
+ settled = true;
42639
+ resolve4({
42640
+ status: res.statusCode ?? 0,
42641
+ headers: res.headers,
42642
+ body: Buffer.concat(chunks).toString("utf8")
42643
+ });
42644
+ });
42645
+ });
42646
+ const deadline = setTimeout(() => {
42647
+ fail(`no response within ${String(timeoutMs)}ms`);
42648
+ req.destroy();
42649
+ }, timeoutMs);
42650
+ deadline.unref();
42651
+ req.on("upgrade", (_res, socket) => {
42652
+ fail("the deployment answered with a protocol upgrade");
42653
+ socket.destroy();
42654
+ });
42655
+ req.on("close", () => {
42656
+ fail("the connection closed before a response was read");
42657
+ clearTimeout(deadline);
42658
+ });
42659
+ req.on("error", (err) => {
42660
+ fail(err.message);
42661
+ });
42662
+ if (options.body !== void 0) req.write(options.body);
42663
+ req.end();
42664
+ });
42665
+ }
42532
42666
 
42533
- // ../../packages/plugin-sdk/src/suppressions.ts
42534
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
42667
+ // ../../packages/remote/src/client.ts
42668
+ var ROUTES = {
42669
+ events: "/v1/events",
42670
+ auditEvents: "/v1/audit-events",
42671
+ auditEventsBatch: "/v1/audit-events/batch",
42672
+ inventory: "/v1/inventory",
42673
+ storePosture: "/v1/store-posture",
42674
+ policyBundle: "/v1/policy-bundle",
42675
+ whoami: "/v1/plugin/whoami",
42676
+ shares: "/v1/shares",
42677
+ commands: "/v1/plugin/commands"
42678
+ };
42679
+ function ackRoute(id) {
42680
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
42681
+ }
42682
+ function headerValue(response, name) {
42683
+ const raw = response.headers[name];
42684
+ if (raw === void 0) return void 0;
42685
+ return Array.isArray(raw) ? raw[0] : raw;
42686
+ }
42687
+ function okBody(response) {
42688
+ if (response.status < 200 || response.status >= 300) {
42689
+ throw new RemoteRequestError(response.status);
42690
+ }
42691
+ return response.body;
42692
+ }
42693
+ function parsed(schema, body, route) {
42694
+ let json2;
42695
+ try {
42696
+ json2 = JSON.parse(body);
42697
+ } catch {
42698
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
42699
+ }
42700
+ const result = schema.safeParse(json2);
42701
+ if (!result.success) {
42702
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
42703
+ }
42704
+ return result.data;
42705
+ }
42706
+ function resolveBaseUrl(endpoint) {
42707
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
42708
+ let end = endpoint.length;
42709
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
42710
+ return endpoint.slice(0, end);
42711
+ }
42712
+ var SLASH2 = "/".charCodeAt(0);
42713
+ function createRemoteClient(options) {
42714
+ const base = resolveBaseUrl(options.endpoint);
42715
+ const url2 = (route) => `${base}${route}`;
42716
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
42717
+ const sendOne = async (event) => {
42718
+ const validated = RecordAuditEventRequest.safeParse(event);
42719
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
42720
+ const response = await send({
42721
+ ...common,
42722
+ method: "POST",
42723
+ url: url2(ROUTES.auditEvents),
42724
+ body: JSON.stringify(validated.data)
42725
+ });
42726
+ okBody(response);
42727
+ };
42728
+ return {
42729
+ async ingestEvents(batch) {
42730
+ const response = await send({
42731
+ ...common,
42732
+ method: "POST",
42733
+ url: url2(ROUTES.events),
42734
+ body: JSON.stringify(batch)
42735
+ });
42736
+ return parsed(IngestAck, okBody(response), ROUTES.events);
42737
+ },
42738
+ async ingestInventory(context) {
42739
+ const response = await send({
42740
+ ...common,
42741
+ method: "POST",
42742
+ url: url2(ROUTES.inventory),
42743
+ body: JSON.stringify(context)
42744
+ });
42745
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
42746
+ },
42747
+ async recordAuditEvent(event) {
42748
+ await sendOne(event);
42749
+ },
42750
+ async recordAuditEvents(events, opts) {
42751
+ const validated = RecordAuditEventBatch.safeParse({ events });
42752
+ if (!validated.success) {
42753
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
42754
+ }
42755
+ const response = await send({
42756
+ ...common,
42757
+ method: "POST",
42758
+ url: url2(ROUTES.auditEventsBatch),
42759
+ body: JSON.stringify(validated.data)
42760
+ });
42761
+ if (response.status === 404) {
42762
+ if (opts?.fallbackToSingleEvents !== true) {
42763
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
42764
+ }
42765
+ for (const event of validated.data.events) await sendOne(event);
42766
+ return { accepted: validated.data.events.length };
42767
+ }
42768
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
42769
+ },
42770
+ async reportStorePosture(snapshot) {
42771
+ const response = await send({
42772
+ ...common,
42773
+ method: "POST",
42774
+ url: url2(ROUTES.storePosture),
42775
+ body: JSON.stringify(snapshot)
42776
+ });
42777
+ okBody(response);
42778
+ },
42779
+ async getPolicyBundle(etag) {
42780
+ const response = await send({
42781
+ ...common,
42782
+ method: "GET",
42783
+ url: url2(ROUTES.policyBundle),
42784
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
42785
+ });
42786
+ if (response.status === 304) {
42787
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
42788
+ }
42789
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
42790
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
42791
+ },
42792
+ async whoami() {
42793
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
42794
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
42795
+ },
42796
+ async recordProjectEgress(request) {
42797
+ const validated = EgressIngestRequest.safeParse(request);
42798
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
42799
+ const response = await send({
42800
+ ...common,
42801
+ method: "POST",
42802
+ url: url2(ROUTES.shares),
42803
+ body: JSON.stringify(validated.data)
42804
+ });
42805
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
42806
+ okBody(response);
42807
+ },
42808
+ async pollCommand() {
42809
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
42810
+ if (response.status === 404) return null;
42811
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
42812
+ },
42813
+ async ackCommand(id, body) {
42814
+ const validated = DeviceCommandAckBody.safeParse(body);
42815
+ const route = ackRoute(id);
42816
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
42817
+ const response = await send({
42818
+ ...common,
42819
+ method: "POST",
42820
+ url: url2(route),
42821
+ body: JSON.stringify(validated.data)
42822
+ });
42823
+ okBody(response);
42824
+ }
42825
+ };
42826
+ }
42535
42827
 
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";
42828
+ // ../../packages/remote/src/failure-kind.ts
42829
+ function statusOf(err) {
42830
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
42831
+ const { status } = err;
42832
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
42833
+ return status >= 100 && status <= 599 ? status : null;
42834
+ }
42835
+ function nameOf(err) {
42836
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
42837
+ return typeof err.name === "string" ? err.name : null;
42838
+ }
42839
+ function classifyRemoteFailure(err) {
42840
+ switch (nameOf(err)) {
42841
+ case "RemoteRouteAbsent":
42842
+ return "route-absent";
42843
+ case "RemoteRequestInvalid":
42844
+ case "RemoteEndpointRefused":
42845
+ return "invalid-request";
42846
+ case "RemoteResponseInvalid":
42847
+ return "rejected";
42848
+ default:
42849
+ break;
42850
+ }
42851
+ const status = statusOf(err);
42852
+ if (status === null) return "unreachable";
42853
+ switch (status) {
42854
+ case 401:
42855
+ return "unauthorized";
42856
+ case 403:
42857
+ return "forbidden";
42858
+ case 429:
42859
+ return "unreachable";
42860
+ case 404:
42861
+ return "unreachable";
42862
+ default:
42863
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
42864
+ }
42865
+ }
42866
+
42867
+ // ../../packages/plugin-runtime/src/attached/failure.ts
42868
+ function classifyFailure(err) {
42869
+ switch (classifyRemoteFailure(err)) {
42870
+ case "unauthorized":
42871
+ return "unauthorized";
42872
+ case "forbidden":
42873
+ return "forbidden";
42874
+ default:
42875
+ return "unreachable";
42876
+ }
42877
+ }
42878
+
42879
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
42880
+ var REQUEST_TIMEOUT_MS = 2e3;
42881
+ function withTimeout(promise2, ms) {
42882
+ let timer;
42883
+ const timeout = new Promise((_, reject) => {
42884
+ timer = setTimeout(() => {
42885
+ reject(new Error("attached gateway request timed out"));
42886
+ }, ms);
42887
+ });
42888
+ promise2.catch(() => void 0);
42889
+ return Promise.race([promise2, timeout]).finally(() => {
42890
+ clearTimeout(timer);
42891
+ });
42892
+ }
42893
+
42894
+ // ../../packages/plugin-runtime/src/attached/command-sync.ts
42895
+ var COMMAND_REQUEST_TIMEOUT_MS = 3e4;
42896
+ var SCAN_THREW = "scan_failed";
42897
+ var SCAN_FOUND_NOTHING = "no_projects";
42898
+ var COMMAND_EXPIRED = "expired";
42899
+ function hasExpired(expiresAt, atMs) {
42900
+ const deadlineMs = Date.parse(expiresAt);
42901
+ return Number.isFinite(deadlineMs) && deadlineMs <= atMs;
42902
+ }
42903
+ function rootVerdict(settings, endpoint, credential, scan2) {
42904
+ try {
42905
+ const resolved = resolveScope({
42906
+ mode: attachmentModeOf(credential),
42907
+ scope: settings.attachmentScope,
42908
+ endpoint
42909
+ });
42910
+ return scopeVerdict(resolved, resolved.mode === "scoped" ? scan2.rootScopeKey() : void 0);
42911
+ } catch {
42912
+ return "local";
42913
+ }
42914
+ }
42915
+ var SERVICE = {
42916
+ shares_rescan: (scan2) => scan2.run()
42917
+ };
42918
+ async function runCommandSync(deps) {
42919
+ if (deps.scan === void 0) return null;
42920
+ const settings = readWorkspaceSettings(deps.base);
42921
+ const connection = isAttached(settings) ? settings.controlPlane : void 0;
42922
+ const state = connection === void 0 ? void 0 : readControlPlaneCredentialFile(deps.settingsDir, connection);
42923
+ if (connection === void 0 || !state?.usable) return null;
42924
+ const client = createRemoteClient({
42925
+ endpoint: connection.endpoint,
42926
+ apiKey: state.credential.apiKey,
42927
+ timeoutMs: COMMAND_REQUEST_TIMEOUT_MS
42928
+ });
42929
+ let command;
42930
+ try {
42931
+ command = await withTimeout(client.pollCommand(), COMMAND_REQUEST_TIMEOUT_MS);
42932
+ } catch (err) {
42933
+ const failure2 = classifyFailure(err);
42934
+ return failure2 === "unreachable" ? "unreachable" : failure2;
42935
+ }
42936
+ if (command === null) return "none";
42937
+ let projects = 0;
42938
+ let reason = null;
42939
+ if (hasExpired(command.expiresAt, (deps.now ?? Date.now)())) {
42940
+ reason = COMMAND_EXPIRED;
42941
+ } else if (rootVerdict(settings, connection.endpoint, state.credential, deps.scan) === "local") {
42942
+ return "out-of-scope";
42943
+ } else {
42944
+ try {
42945
+ projects = (await SERVICE[command.kind](deps.scan)).projects;
42946
+ if (projects === 0) reason = SCAN_FOUND_NOTHING;
42947
+ } catch {
42948
+ reason = SCAN_THREW;
42949
+ }
42950
+ }
42951
+ try {
42952
+ await withTimeout(
42953
+ reason === null ? client.ackCommand(command.id, { outcome: "reported", projectsScanned: projects }) : client.ackCommand(command.id, {
42954
+ outcome: "failed",
42955
+ reason,
42956
+ projectsScanned: projects
42957
+ }),
42958
+ COMMAND_REQUEST_TIMEOUT_MS
42959
+ );
42960
+ } catch (err) {
42961
+ const failure2 = classifyFailure(err);
42962
+ return failure2 === "unreachable" ? "unreachable" : failure2;
42963
+ }
42964
+ return reason === null ? "reported" : "failed";
42965
+ }
42966
+ function readSessionDirectory() {
42967
+ try {
42968
+ return process.cwd();
42969
+ } catch {
42970
+ return void 0;
42971
+ }
42972
+ }
42973
+ function commandScanFor(loadConfig2, scanWorktree2, sourceTool) {
42974
+ const rootDir = readSessionDirectory();
42975
+ return {
42976
+ rootScopeKey: () => rootDir === void 0 ? void 0 : resolveRepoAttribution(rootDir).scopeKey,
42977
+ run: async () => {
42978
+ if (rootDir === void 0) throw new Error("the session working directory cannot be read");
42979
+ const summary = await scanWorktree2(loadConfig2(), { sourceTool, rootDir });
42980
+ return { projects: summary.scanned > 0 ? 1 : 0 };
42981
+ }
42982
+ };
42983
+ }
42984
+
42985
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
42986
+ import { readFileSync as readFileSync13 } from "fs";
42987
+ import { join as join20 } from "path";
42988
+ var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
42989
+ function forwardDropsPath(dataDir2) {
42990
+ return join20(dataDir2, FORWARD_DROPS_FILENAME);
42991
+ }
42992
+ function recordForwardDrops(dataDir2, count, nowMs) {
42993
+ if (count <= 0) return;
42994
+ try {
42995
+ ensureDataDirSync(dataDir2);
42996
+ const previous = readForwardDrops(dataDir2);
42997
+ const next = {
42998
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
42999
+ lastDropAtMs: nowMs
43000
+ };
43001
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
43002
+ `);
43003
+ } catch {
43004
+ }
43005
+ }
43006
+ function readForwardDrops(dataDir2) {
43007
+ try {
43008
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
43009
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
43010
+ const record2 = parsed2;
43011
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
43012
+ return null;
43013
+ }
43014
+ if (record2.droppedForwards <= 0) return null;
43015
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
43016
+ return null;
43017
+ }
43018
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
43019
+ } catch {
43020
+ return null;
43021
+ }
43022
+ }
42539
43023
 
42540
43024
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
43025
+ import { randomUUID as randomUUID16 } from "crypto";
43026
+ import { readFile, rename, writeFile } from "fs/promises";
43027
+ import { join as join21 } from "path";
42541
43028
  function isInvalidRequest(err) {
42542
43029
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
42543
43030
  }
@@ -42556,7 +43043,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
42556
43043
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
42557
43044
  function createForwardPolicy(deps) {
42558
43045
  const now = deps.now ?? (() => Date.now());
42559
- const file2 = join28(deps.dir, STATE_FILENAME);
43046
+ const file2 = join21(deps.dir, STATE_FILENAME);
42560
43047
  let state = null;
42561
43048
  let loading = null;
42562
43049
  async function readState() {
@@ -42722,6 +43209,9 @@ var AttachedDataGateway = class {
42722
43209
  *
42723
43210
  * Machine mode answers before any key is read, so a machine attachment pays
42724
43211
  * nothing for scoping and forwards exactly what it always has.
43212
+ *
43213
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
43214
+ * forwarding key for key.
42725
43215
  */
42726
43216
  verdictFor(keyOf) {
42727
43217
  try {
@@ -42738,24 +43228,27 @@ var AttachedDataGateway = class {
42738
43228
  * the key its row holds in the local store, recorded per root (see
42739
43229
  * `rootVerdict`), not the key on the root event just handed in: roots are
42740
43230
  * 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.
43231
+ * session (the session-start hook, then a reconcile pass) the second leaves the
43232
+ * stored row as it was. That stored row, not this event, is what a history
43233
+ * drain pass would decide, if the root started before the attach; the drain
43234
+ * never offers one that started after it (`started_at < backlogBefore`).
43235
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
43236
+ * its own. The event's attributes (cwd, project, repo) describe where it was
43237
+ * recorded from, so a root event keyed to a personal directory is never sent
43238
+ * under an enrolled stored root, though the enrolled leaves still forward under
43239
+ * it: the instance that wrote the stored root is expected to have forwarded it.
43240
+ * If it did not (the root was written while standalone or under another
43241
+ * attachment, or its forward failed), the plane refuses those leaves. A root
43242
+ * that started before the attach is shipped, ahead of its leaves, by the
43243
+ * history drain; one that started after it is never offered by the drain. Any
43244
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
43245
+ * only when its own key is in scope AND this instance recorded an in-scope
43246
+ * verdict for that root. The audit-event route has real foreign keys on both
43247
+ * columns and stubs no missing root, so a leaf sent after its root was kept
43248
+ * local is refused there, and a refused forward counts toward the breaker that
43249
+ * guards every other one. A root this instance never recorded is therefore
43250
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
43251
+ * reference at all has nothing to orphan, and is decided by its own key.
42759
43252
  *
42760
43253
  * What this costs is stated rather than discovered. A session whose stored
42761
43254
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -42826,6 +43319,87 @@ var AttachedDataGateway = class {
42826
43319
  return [];
42827
43320
  }
42828
43321
  }
43322
+ /**
43323
+ * The verdict for the repositories nested in a scanned project, answered
43324
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
43325
+ *
43326
+ * A walk descends into a nested clone or submodule and folds its files into
43327
+ * the project it is walking, so one register can carry several
43328
+ * repositories' call sites under one project key. Each of them must be in
43329
+ * scope for it to forward. One key out of scope, or a nested repository with
43330
+ * no remote (an `undefined` key), keeps the whole register local.
43331
+ *
43332
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
43333
+ * what is nested in it, and every scan passes the list, empty when nothing
43334
+ * is nested. A register nobody vouched for is not one a scoped attachment
43335
+ * may send.
43336
+ *
43337
+ * Machine mode answers before reading the context, so a machine attachment
43338
+ * forwards exactly what it always has.
43339
+ */
43340
+ nestedVerdict(context) {
43341
+ try {
43342
+ if (this.deps.attachment.mode === "machine") return "forward";
43343
+ const keys = context?.nestedScopeKeys;
43344
+ if (keys === void 0) return "local";
43345
+ for (const key of keys) {
43346
+ if (this.verdictFor(() => key) === "local") return "local";
43347
+ }
43348
+ return "forward";
43349
+ } catch {
43350
+ return "local";
43351
+ }
43352
+ }
43353
+ /**
43354
+ * The register a scoped attachment sends, once the project and the repositories
43355
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
43356
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
43357
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
43358
+ *
43359
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
43360
+ * and the ledger holds every file the scanner ever read under the root, nested
43361
+ * clones' included. So a clone that was removed, or one an ignore file now
43362
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
43363
+ * paths come back as deleted. The scan names the repository of each deleted
43364
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
43365
+ * and each is held to the same verdict as any other key. A path whose key is
43366
+ * absent, or out of scope, is not sent.
43367
+ *
43368
+ * The list is asked for here, and only here: it is an async read of the scan
43369
+ * ledger that the scan makes on being called, so a machine attachment, which
43370
+ * returns before this, and a register already kept local never cause it.
43371
+ *
43372
+ * Anything the scan did not vouch for sends no deleted path, and the register
43373
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
43374
+ * list whose length is not the register's. Deleting is the only thing a dropped
43375
+ * path could have done on the server, so the cost of a refusal is a stored row
43376
+ * that stays, never a path that leaves.
43377
+ *
43378
+ * Machine mode returns `input` itself, the same object and unread, so a machine
43379
+ * attachment's request is exactly what it was. A register that lists no deleted
43380
+ * path, or that is not a ledger register, has nothing to cut and is returned
43381
+ * as it came, with the list unread.
43382
+ */
43383
+ async registerForWire(input2, context) {
43384
+ try {
43385
+ if (this.deps.attachment.mode === "machine") return input2;
43386
+ const { reconcile } = input2;
43387
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
43388
+ const deleted = reconcile.deletedFiles;
43389
+ let kept = [];
43390
+ try {
43391
+ const keys = await context?.deletedFileKeys?.();
43392
+ if (keys?.length === deleted.length) {
43393
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
43394
+ }
43395
+ } catch {
43396
+ kept = [];
43397
+ }
43398
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
43399
+ } catch {
43400
+ return void 0;
43401
+ }
43402
+ }
42829
43403
  /**
42830
43404
  * The event `recordCapture` sends for a capture the verdict let through, or
42831
43405
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -43151,12 +43725,24 @@ var AttachedDataGateway = class {
43151
43725
  * payload onto the wire-boundary-safe shape (no snippet, hashed
43152
43726
  * projectKey), and its result is discarded: `forward.run` never throws or
43153
43727
  * rejects, so there is nothing here to act on.
43728
+ *
43729
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
43730
+ * not say: the key of every repository nested below the scan root, whose
43731
+ * files the walk folded into this register. On a scoped attachment the
43732
+ * register is forwarded only when the project's own key AND every one of
43733
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
43734
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
43735
+ * `registerForWire`). Machine mode never reads either, and the local write
43736
+ * never receives the context and gets the register whole.
43154
43737
  */
43155
- async recordProjectEgress(input2) {
43738
+ async recordProjectEgress(input2, context) {
43156
43739
  const summary = await this.deps.local.recordProjectEgress(input2);
43157
43740
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
43741
+ if (this.nestedVerdict(context) === "local") return summary;
43742
+ const register = await this.registerForWire(input2, context);
43743
+ if (register === void 0) return summary;
43158
43744
  await this.deps.forward.run(
43159
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
43745
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
43160
43746
  );
43161
43747
  return summary;
43162
43748
  }
@@ -43210,6 +43796,11 @@ var AttachedDataGateway = class {
43210
43796
  async scanLedgerPaths() {
43211
43797
  return this.deps.local.scanLedgerPaths();
43212
43798
  }
43799
+ // Delegated, like the path list. An inner gateway that cannot say answers an
43800
+ // empty map, which gives every deleted path no key.
43801
+ async scanLedgerPathKeys() {
43802
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
43803
+ }
43213
43804
  async recordScanned(entries) {
43214
43805
  return this.deps.local.recordScanned(entries);
43215
43806
  }
@@ -43276,6 +43867,12 @@ var AttachedDataGateway = class {
43276
43867
  // and the spread above would otherwise drop the field silently — which is
43277
43868
  // exactly what it did, leaving the whole control inert on every device
43278
43869
  // while every test around it stayed green.
43870
+ //
43871
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
43872
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
43873
+ // reads this bundle once to build detection, so the detections it carries
43874
+ // apply to every event on the machine. Where a prohibition applies is
43875
+ // answered per event by `governanceAppliesTo` below.
43279
43876
  prohibitedModels: cached2.prohibitedModels,
43280
43877
  // NAMED for the same reason as the line above, and it is the same defect
43281
43878
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -43335,6 +43932,30 @@ var AttachedDataGateway = class {
43335
43932
  };
43336
43933
  }
43337
43934
  // ---------------------------------------------------------------------
43935
+ // GovernanceScope — where the organization's model policy applies
43936
+ // ---------------------------------------------------------------------
43937
+ /**
43938
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
43939
+ * the question a model-guard site asks once it has decided to refuse.
43940
+ *
43941
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
43942
+ * with the same key would be forwarded. A machine-wide attachment governs
43943
+ * every event, keyless included, exactly as before. A scoped one governs an
43944
+ * event only when its key names an enrolled repository. An event in a
43945
+ * personal repository, in no repository, with an empty key, or met by a fault
43946
+ * is not governed.
43947
+ *
43948
+ * The event's OWN key, never its session root's. The root rule in
43949
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
43950
+ * this decides whether a refusal applies, which is a question about where the
43951
+ * event happened.
43952
+ *
43953
+ * Answered from memory: no store read, no bundle read, nothing sent.
43954
+ */
43955
+ governanceAppliesTo(scopeKey) {
43956
+ return this.verdictFor(() => scopeKey) === "forward";
43957
+ }
43958
+ // ---------------------------------------------------------------------
43338
43959
  // LocalStoreMaintenance — by delegation (D3).
43339
43960
  //
43340
43961
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -43443,14 +44064,15 @@ function toWireInspection(insp) {
43443
44064
  }
43444
44065
 
43445
44066
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
43446
- import { createHash as createHash6 } from "crypto";
43447
- import { hostname as hostname5 } from "os";
44067
+ import { createHash as createHash7 } from "crypto";
44068
+ import { hostname as hostname4 } from "os";
43448
44069
 
43449
44070
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
43450
44071
  var CORRELATION_ID = EventMetadata.shape.correlationId;
43451
44072
  var TRACE_ID = EventMetadata.shape.traceId;
43452
44073
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
43453
44074
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
44075
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
43454
44076
 
43455
44077
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
43456
44078
  var CAPTURE_BATCH_BYTES = 1024 * 1024;
@@ -43462,17 +44084,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
43462
44084
 
43463
44085
  // ../../packages/plugin-runtime/src/attached/install-record.ts
43464
44086
  import { readFile as readFile2, stat } from "fs/promises";
43465
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
44087
+ import { basename as basename4, dirname as dirname6, join as join22, resolve as resolve2 } from "path";
43466
44088
  async function readInstalledVersion(installRoot) {
43467
44089
  try {
43468
44090
  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)}`;
44091
+ const pluginDir = dirname6(versionDir);
44092
+ const marketplaceDir = dirname6(pluginDir);
44093
+ const cacheDir = dirname6(marketplaceDir);
44094
+ if (basename4(cacheDir) !== "cache") return null;
44095
+ const key = `${basename4(pluginDir)}@${basename4(marketplaceDir)}`;
43474
44096
  const record2 = JSON.parse(
43475
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
44097
+ await readFile2(join22(dirname6(cacheDir), "installed_plugins.json"), "utf8")
43476
44098
  );
43477
44099
  const plugins = record2?.plugins;
43478
44100
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -43504,7 +44126,7 @@ async function exists(path) {
43504
44126
  }
43505
44127
 
43506
44128
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
43507
- import { readFileSync as readFileSync18 } from "fs";
44129
+ import { readFileSync as readFileSync14 } from "fs";
43508
44130
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
43509
44131
  function createPluginBlock(build, policyStore) {
43510
44132
  return async () => {
@@ -43534,7 +44156,7 @@ async function readInstalledVersionBounded(installRoot) {
43534
44156
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
43535
44157
  import { randomUUID as randomUUID17 } from "crypto";
43536
44158
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
43537
- import { join as join30 } from "path";
44159
+ import { join as join23 } from "path";
43538
44160
 
43539
44161
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
43540
44162
  import { rename as rename2 } from "fs/promises";
@@ -43563,7 +44185,7 @@ async function publishByRename(tmp, file2, move = rename2) {
43563
44185
 
43564
44186
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
43565
44187
  function createPolicyStore(dir = dataDir()) {
43566
- const file2 = join30(dir, "policy-cache.json");
44188
+ const file2 = join23(dir, "policy-cache.json");
43567
44189
  async function read() {
43568
44190
  try {
43569
44191
  const raw = await readFile3(file2, "utf8");
@@ -43682,8 +44304,8 @@ async function runPolicySync(deps) {
43682
44304
  }
43683
44305
 
43684
44306
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
43685
- import { readFileSync as readFileSync19 } from "fs";
43686
- import { join as join31 } from "path";
44307
+ import { readFileSync as readFileSync15 } from "fs";
44308
+ import { join as join24 } from "path";
43687
44309
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
43688
44310
  var OUTCOME_KEYS = {
43689
44311
  ok: true,
@@ -43697,7 +44319,7 @@ var OUTCOME_KEYS = {
43697
44319
  };
43698
44320
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
43699
44321
  function postureReportStatePath(dataDir2) {
43700
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
44322
+ return join24(dataDir2, POSTURE_REPORT_STATE_FILENAME);
43701
44323
  }
43702
44324
  function writePostureReportState(dataDir2, state) {
43703
44325
  try {
@@ -43738,10 +44360,19 @@ function createPostureReporter(deps) {
43738
44360
  hostname: deps.hostname(),
43739
44361
  capturedAt: nowMs,
43740
44362
  ...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 }
44363
+ // Omit the key rather than spread an explicit `undefined`. The type
44364
+ // admits `undefined` here (the schema's optional member), and
44365
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
44366
+ // in-memory object free of an explicit `undefined` member, which the
44367
+ // tests pin by key presence.
44368
+ ...plugin === void 0 ? {} : { plugin },
44369
+ // LAST, and only for a scoped attachment. A machine attachment omits
44370
+ // the key the same way, so its body is byte for byte the one it sent
44371
+ // before the member existed. Anything but exactly `machine` reports the
44372
+ // constant `scoped`, never the raw value: that is resolveScope's own
44373
+ // fail direction, and a value outside the wire's vocabulary would fail
44374
+ // the whole snapshot at the receiver, the wipe signal with it.
44375
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
43745
44376
  };
43746
44377
  } catch {
43747
44378
  return null;
@@ -43764,8 +44395,8 @@ function createPostureReporter(deps) {
43764
44395
  }
43765
44396
 
43766
44397
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
43767
- import { statSync as statSync9 } from "fs";
43768
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
44398
+ import { statSync as statSync7 } from "fs";
44399
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
43769
44400
 
43770
44401
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
43771
44402
  function emptyActionCounts() {
@@ -43795,7 +44426,7 @@ function emptyReadout(readError = false) {
43795
44426
  }
43796
44427
  function readStorePosture(dbPath2) {
43797
44428
  try {
43798
- statSync9(dbPath2);
44429
+ statSync7(dbPath2);
43799
44430
  } catch (err) {
43800
44431
  const code = err.code;
43801
44432
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -43823,7 +44454,7 @@ function readStorePosture(dbPath2) {
43823
44454
  readError: false
43824
44455
  });
43825
44456
  try {
43826
- db = new DatabaseSync4(dbPath2, { readOnly: true });
44457
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
43827
44458
  db.exec("PRAGMA busy_timeout = 2000");
43828
44459
  version2 = db.prepare("PRAGMA user_version").get().user_version;
43829
44460
  try {
@@ -43877,11 +44508,11 @@ function readStorePosture(dbPath2) {
43877
44508
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
43878
44509
  import { randomUUID as randomUUID18 } from "crypto";
43879
44510
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
43880
- import { join as join32 } from "path";
44511
+ import { join as join25 } from "path";
43881
44512
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
43882
44513
  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");
44514
+ const file2 = join25(dir, "posture-state.json");
44515
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
43885
44516
  async function persist(state) {
43886
44517
  await ensureDataDir(dir);
43887
44518
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -43949,11 +44580,11 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
43949
44580
  }
43950
44581
 
43951
44582
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
43952
- import { readFileSync as readFileSync20 } from "fs";
43953
- import { join as join33 } from "path";
44583
+ import { readFileSync as readFileSync16 } from "fs";
44584
+ import { join as join26 } from "path";
43954
44585
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
43955
44586
  function syncStatePath(dataDir2) {
43956
- return join33(dataDir2, SYNC_STATE_FILENAME);
44587
+ return join26(dataDir2, SYNC_STATE_FILENAME);
43957
44588
  }
43958
44589
  function writeSyncState(dataDir2, result) {
43959
44590
  try {
@@ -44015,7 +44646,7 @@ import { fileURLToPath as fileURLToPath4 } from "url";
44015
44646
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
44016
44647
 
44017
44648
  // ../../packages/plugin-runtime/src/attached/factory.ts
44018
- import { hostname as hostname6 } from "os";
44649
+ import { hostname as hostname5 } from "os";
44019
44650
 
44020
44651
  // ../../packages/plugin-runtime/src/recorder.ts
44021
44652
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -44028,7 +44659,7 @@ var StandaloneDataGateway = class {
44028
44659
  // One notice per gateway — see warnRulesetDiscarded.
44029
44660
  warnedRulesetDiscarded = false;
44030
44661
  constructor(dataDir2, detections = [], meta4) {
44031
- this.db = openLocalDatabase(dataDir2);
44662
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
44032
44663
  this.dataDir = dataDir2;
44033
44664
  this.db.installedPacks.recordInventory(detections, meta4);
44034
44665
  }
@@ -44377,6 +45008,9 @@ var StandaloneDataGateway = class {
44377
45008
  scanLedgerPaths() {
44378
45009
  return Promise.resolve(this.db.scanLedger.allPaths());
44379
45010
  }
45011
+ scanLedgerPathKeys() {
45012
+ return Promise.resolve(this.db.scanLedger.pathKeys());
45013
+ }
44380
45014
  recordScanned(entries) {
44381
45015
  this.db.scanLedger.upsertEntries(entries);
44382
45016
  return Promise.resolve();
@@ -44462,13 +45096,17 @@ function resolveGatewayForConfig(config2, meta4) {
44462
45096
  },
44463
45097
  store: postureStore,
44464
45098
  readStore: () => readStorePosture(config2.dbPath),
44465
- hostname: () => hostname6(),
45099
+ hostname: () => hostname5(),
44466
45100
  now: () => Date.now(),
45101
+ // The mode THIS gateway enforces, from the attachment resolved above,
45102
+ // so the report cannot name a mode the forward paths are not using.
45103
+ attachmentMode: attachment.mode,
44467
45104
  // The reporting build's identity, when the caller knows it (the plugin
44468
45105
  // adapters do; an embedder or a test may not). Composed with the SAME
44469
45106
  // 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.
45107
+ // actually in force. The dependency key is omitted when no build is
45108
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
45109
+ // then adds no block.
44472
45110
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
44473
45111
  })
44474
45112
  });
@@ -44489,8 +45127,8 @@ import { randomUUID as randomUUID19 } from "crypto";
44489
45127
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
44490
45128
 
44491
45129
  // ../../packages/scanner/src/discover.ts
44492
- import { readdirSync as readdirSync5 } from "fs";
44493
- import { join as join34 } from "path";
45130
+ import { readdirSync as readdirSync3 } from "fs";
45131
+ import { join as join27 } from "path";
44494
45132
 
44495
45133
  // ../../packages/scanner/src/constants.ts
44496
45134
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -44511,18 +45149,18 @@ var DISCOVER_SKIP = /* @__PURE__ */ new Set([
44511
45149
  ]);
44512
45150
 
44513
45151
  // ../../packages/scanner/src/render.ts
44514
- import { basename as basename7, relative } from "path";
45152
+ import { basename as basename5, relative } from "path";
44515
45153
 
44516
45154
  // ../../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";
45155
+ import { existsSync as existsSync12, readFileSync as readFileSync18 } from "fs";
45156
+ import { extname as extname2, isAbsolute as isAbsolute2, relative as relative3 } from "path";
44519
45157
 
44520
45158
  // ../../packages/scanner/src/manifests.ts
44521
- import { statSync as statSync11 } from "fs";
45159
+ import { statSync as statSync9 } from "fs";
44522
45160
 
44523
45161
  // ../../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";
45162
+ import { readdirSync as readdirSync4, readFileSync as readFileSync17, statSync as statSync8 } from "fs";
45163
+ import { extname, join as join28, relative as relative2, sep as sep4 } from "path";
44526
45164
  var import_ignore2 = __toESM(require_ignore(), 1);
44527
45165
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
44528
45166
  ".ts",
@@ -44555,14 +45193,18 @@ var SKIP_DIRS = /* @__PURE__ */ new Set([
44555
45193
  var DEFAULT_MAX_BYTES = 512 * 1024;
44556
45194
  function* walkTree(rootDir, opts = {}) {
44557
45195
  const trackGitignore = opts.trackGitignore ?? false;
45196
+ const onRepositoryRoot = opts.onRepositoryRoot;
44558
45197
  const rootSkipLayers = opts.excludePatterns && opts.excludePatterns.length > 0 ? [{ matcher: (0, import_ignore2.default)().add(opts.excludePatterns), anchorLen: 0 }] : [];
44559
45198
  function* visit2(dir, dirRel, markLayers, skipLayers, inIgnoredDir) {
44560
45199
  let dirents;
44561
45200
  try {
44562
- dirents = readdirSync6(dir, { withFileTypes: true, encoding: "utf8" });
45201
+ dirents = readdirSync4(dir, { withFileTypes: true, encoding: "utf8" });
44563
45202
  } catch {
44564
45203
  return;
44565
45204
  }
45205
+ if (onRepositoryRoot !== void 0 && dirRel !== "" && dirents.some((entry) => entry.name === ".git")) {
45206
+ onRepositoryRoot(dirRel);
45207
+ }
44566
45208
  const dirMarkLayers = withLayer(
44567
45209
  markLayers,
44568
45210
  trackGitignore && !inIgnoredDir ? readIgnoreLayer(dir, ".gitignore", dirRel.length) : void 0
@@ -44573,7 +45215,7 @@ function* walkTree(rootDir, opts = {}) {
44573
45215
  );
44574
45216
  for (const entry of dirents) {
44575
45217
  const name = entry.name;
44576
- const fullPath = join35(dir, name);
45218
+ const fullPath = join28(dir, name);
44577
45219
  if (entry.isDirectory()) {
44578
45220
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
44579
45221
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {
@@ -44600,14 +45242,15 @@ function* walkSourceFiles(opts = {}) {
44600
45242
  const maxBytes = opts.maxFileSizeBytes ?? DEFAULT_MAX_BYTES;
44601
45243
  for (const file2 of walkTree(rootDir, {
44602
45244
  excludePatterns: opts.excludePatterns,
44603
- trackGitignore: true
45245
+ trackGitignore: true,
45246
+ onRepositoryRoot: opts.onRepositoryRoot
44604
45247
  })) {
44605
45248
  const ext = extname(file2.name);
44606
45249
  if (!extensions.has(ext)) continue;
44607
45250
  let size;
44608
45251
  let mtime;
44609
45252
  try {
44610
- const st = statSync10(file2.path);
45253
+ const st = statSync8(file2.path);
44611
45254
  size = st.size;
44612
45255
  mtime = st.mtime;
44613
45256
  } catch {
@@ -44627,7 +45270,7 @@ function* walkSourceFiles(opts = {}) {
44627
45270
  if (opts.shouldRead && !opts.shouldRead(meta4)) continue;
44628
45271
  let content;
44629
45272
  try {
44630
- content = readFileSync21(file2.path, "utf8");
45273
+ content = readFileSync17(file2.path, "utf8");
44631
45274
  } catch {
44632
45275
  continue;
44633
45276
  }
@@ -44643,13 +45286,13 @@ function* walkSourceFiles(opts = {}) {
44643
45286
 
44644
45287
  // ../../packages/scanner/src/manifests.ts
44645
45288
  var MAX_MANIFEST_BYTES = 512 * 1024;
44646
- function collectManifests(rootDir, maxFileSizeBytes = MAX_MANIFEST_BYTES) {
45289
+ function collectManifests(rootDir, maxFileSizeBytes = MAX_MANIFEST_BYTES, onRepositoryRoot) {
44647
45290
  const found = [];
44648
- for (const file2 of walkTree(rootDir)) {
45291
+ for (const file2 of walkTree(rootDir, { onRepositoryRoot })) {
44649
45292
  const kind = manifestKindOf(file2.name);
44650
45293
  if (kind === null) continue;
44651
45294
  try {
44652
- const st = statSync11(file2.path);
45295
+ const st = statSync9(file2.path);
44653
45296
  if (st.size > maxFileSizeBytes) continue;
44654
45297
  found.push({ path: file2.path, kind, mtime: st.mtime.toISOString(), size: st.size });
44655
45298
  } catch {
@@ -44666,35 +45309,66 @@ function computeResolutions(prior, current) {
44666
45309
  }
44667
45310
 
44668
45311
  // ../../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";
45312
+ import { existsSync as existsSync11 } from "fs";
45313
+ import { dirname as dirname7, join as join29, posix as posix2, resolve as resolve3 } from "path";
44671
45314
  function scopeKeysUnder(rootDir) {
44672
45315
  const base = resolve3(rootDir);
44673
- const keyByDir = /* @__PURE__ */ new Map();
44674
- return (relativePath) => {
45316
+ let aboveBase;
45317
+ const rootAtOrAboveBase = () => {
45318
+ if (aboveBase === void 0) {
45319
+ let dir = base;
45320
+ let root;
45321
+ for (; ; ) {
45322
+ if (existsSync11(join29(dir, ".git"))) {
45323
+ root = dir;
45324
+ break;
45325
+ }
45326
+ const parent = dirname7(dir);
45327
+ if (parent === dir) break;
45328
+ dir = parent;
45329
+ }
45330
+ aboveBase = { root };
45331
+ }
45332
+ return aboveBase.root;
45333
+ };
45334
+ const confirmed = (root, key) => existsSync11(join29(root, ".git")) ? { root, key } : { root: void 0, key: void 0 };
45335
+ const repositoryByDir = /* @__PURE__ */ new Map();
45336
+ const repositoryOf = (relativePath) => {
44675
45337
  const climbed = [];
44676
45338
  let dir = posix2.dirname(relativePath);
44677
- let key;
45339
+ let found;
44678
45340
  for (; ; ) {
44679
- if (keyByDir.has(dir)) {
44680
- key = keyByDir.get(dir);
45341
+ const known = repositoryByDir.get(dir);
45342
+ if (known !== void 0) {
45343
+ found = known;
44681
45344
  break;
44682
45345
  }
44683
45346
  climbed.push(dir);
44684
45347
  const parent = posix2.dirname(dir);
44685
45348
  if (parent === dir) {
44686
- key = resolveRepoAttribution(base).scopeKey;
45349
+ const root = rootAtOrAboveBase();
45350
+ found = root === void 0 ? { root, key: resolveRepoAttribution(base, { cache: false }).scopeKey } : confirmed(root, resolveRepoAttribution(root, { cache: false }).scopeKey);
44687
45351
  break;
44688
45352
  }
44689
- if (existsSync13(join36(base, dir, ".git"))) {
44690
- key = resolveRepoAttribution(join36(base, dir)).scopeKey;
45353
+ if (existsSync11(join29(base, dir, ".git"))) {
45354
+ const root = join29(base, dir);
45355
+ found = confirmed(root, resolveRepoAttribution(root, { cache: false }).scopeKey);
44691
45356
  break;
44692
45357
  }
44693
45358
  dir = parent;
44694
45359
  }
44695
- for (const at of climbed) keyByDir.set(at, key);
44696
- return key;
45360
+ for (const at of climbed) repositoryByDir.set(at, found);
45361
+ return found;
45362
+ };
45363
+ const keyOfFile = (relativePath) => repositoryOf(relativePath).key;
45364
+ const ofRepositoryRoot = (relativeDir) => {
45365
+ const root = join29(base, relativeDir);
45366
+ const dotGit = join29(root, ".git");
45367
+ if (!existsSync11(dotGit)) return void 0;
45368
+ const key = resolveRepoAttribution(root, { cache: false }).scopeKey;
45369
+ return existsSync11(dotGit) ? key : void 0;
44697
45370
  };
45371
+ return Object.assign(keyOfFile, { repositoryOf, ofRepositoryRoot });
44698
45372
  }
44699
45373
 
44700
45374
  // ../../packages/scanner/src/scan.ts
@@ -44729,7 +45403,14 @@ function egressKey(root, absPath) {
44729
45403
  function startEgress(rootDir) {
44730
45404
  const project = resolveEgressProject(rootDir);
44731
45405
  if (project === null) return null;
44732
- return { project, files: [], scannedFiles: [], deletedFiles: [] };
45406
+ return {
45407
+ project,
45408
+ files: [],
45409
+ scannedFiles: [],
45410
+ deletedFiles: [],
45411
+ deletedPaths: [],
45412
+ nestedRoots: []
45413
+ };
44733
45414
  }
44734
45415
  function collectFileEgress(acc, absPath, content, manifestKind) {
44735
45416
  const file2 = egressKey(acc.project.root, absPath);
@@ -44778,17 +45459,39 @@ async function reopenRedetectedFindings(gateway, path, currentKeys, evidence, re
44778
45459
  }
44779
45460
  function isUnderRoot(path, rootDir) {
44780
45461
  const rel = relative3(rootDir, path);
44781
- return rel !== "" && !rel.startsWith("..") && !isAbsolute3(rel);
45462
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
44782
45463
  }
44783
45464
  async function sweepDeletedFiles(gateway, rootDir, paths) {
44784
45465
  const deleted = [];
44785
45466
  for (const path of paths) {
44786
- if (!isUnderRoot(path, rootDir) || existsSync14(path)) continue;
45467
+ if (!isUnderRoot(path, rootDir) || existsSync12(path)) continue;
44787
45468
  deleted.push(path);
44788
45469
  await resolveRemovedFindings(gateway, path, [], { deleted: true });
44789
45470
  }
44790
45471
  return deleted;
44791
45472
  }
45473
+ function repositoryToRecord(prev, now) {
45474
+ const recordedRoot = prev?.scopeRoot;
45475
+ if (recordedRoot === void 0) return now;
45476
+ if (now.root !== void 0 && isAtOrBelow(recordedRoot, now.root)) return now;
45477
+ return { root: recordedRoot, key: prev?.scopeKey };
45478
+ }
45479
+ function isAtOrBelow(ancestor, dir) {
45480
+ const rel = relative3(ancestor, dir);
45481
+ if (isAbsolute2(rel)) return false;
45482
+ const posixRel = toPosix(rel);
45483
+ return posixRel === "" || posixRel !== ".." && !posixRel.startsWith("../");
45484
+ }
45485
+ function repositoryColumns(repository) {
45486
+ return {
45487
+ ...repository.key !== void 0 ? { scopeKey: repository.key } : {},
45488
+ ...repository.root !== void 0 ? { scopeRoot: repository.root } : {}
45489
+ };
45490
+ }
45491
+ function repositoryDiffers(prev, decided) {
45492
+ return decided.key !== prev.scopeKey || decided.root !== prev.scopeRoot;
45493
+ }
45494
+ var NO_REPOSITORY = { root: void 0, key: void 0 };
44792
45495
  async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44793
45496
  const byRule = {};
44794
45497
  const bySeverity = {};
@@ -44799,10 +45502,25 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44799
45502
  let gitignoredFindings = 0;
44800
45503
  const egress = config2.settings.dataSharesInPlace ? startEgress(rootDir) : null;
44801
45504
  const scopeKeyOf2 = scopeKeysUnder(rootDir);
45505
+ const noteNestedRoot = (relativeDir) => {
45506
+ egress?.nestedRoots.push(relativeDir);
45507
+ };
44802
45508
  const shouldRead = (meta4) => {
44803
45509
  const prev = ledger.previous.get(meta4.path);
44804
45510
  if (prev?.mtime === meta4.mtime) {
44805
45511
  skipped++;
45512
+ if (egress !== null) {
45513
+ const decided = repositoryToRecord(prev, scopeKeyOf2.repositoryOf(meta4.relativePath));
45514
+ if (repositoryDiffers(prev, decided)) {
45515
+ updates.push({
45516
+ path: meta4.path,
45517
+ mtime: prev.mtime,
45518
+ contentHash: prev.contentHash,
45519
+ rulesetHash: ledger.rulesetHash,
45520
+ ...repositoryColumns(decided)
45521
+ });
45522
+ }
45523
+ }
44806
45524
  return false;
44807
45525
  }
44808
45526
  return true;
@@ -44810,16 +45528,19 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44810
45528
  for (const file2 of walkSourceFiles({
44811
45529
  ...opts,
44812
45530
  rootDir,
44813
- shouldRead: (meta4) => (opts.shouldRead?.(meta4) ?? true) && shouldRead(meta4)
45531
+ shouldRead: (meta4) => (opts.shouldRead?.(meta4) ?? true) && shouldRead(meta4),
45532
+ onRepositoryRoot: egress === null ? void 0 : noteNestedRoot
44814
45533
  })) {
44815
45534
  const hash2 = contentHashOf(file2.content);
45535
+ const prev = ledger.previous.get(file2.path);
45536
+ const repository = egress === null ? NO_REPOSITORY : repositoryToRecord(prev, scopeKeyOf2.repositoryOf(file2.relativePath));
44816
45537
  const ledgerEntry = {
44817
45538
  path: file2.path,
44818
45539
  mtime: file2.mtime,
44819
45540
  contentHash: hash2,
44820
- rulesetHash: ledger.rulesetHash
45541
+ rulesetHash: ledger.rulesetHash,
45542
+ ...repositoryColumns(repository)
44821
45543
  };
44822
- const prev = ledger.previous.get(file2.path);
44823
45544
  if (prev?.contentHash === hash2) {
44824
45545
  skipped++;
44825
45546
  updates.push(ledgerEntry);
@@ -44871,15 +45592,17 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44871
45592
  contentHash: hash2
44872
45593
  });
44873
45594
  }
44874
- if (egress) scanManifests(egress, ledger, updates, rootDir);
45595
+ if (egress) scanManifests(egress, ledger, updates, rootDir, scopeKeyOf2, noteNestedRoot);
44875
45596
  const deleted = await sweepDeletedFiles(gateway, rootDir, ledger.paths);
44876
45597
  if (egress) {
44877
45598
  for (const path of deleted) {
44878
45599
  const key = egressKey(egress.project.root, path);
44879
- if (key !== null) egress.deletedFiles.push(key);
45600
+ if (key === null) continue;
45601
+ egress.deletedFiles.push(key);
45602
+ egress.deletedPaths.push(path);
44880
45603
  }
44881
45604
  }
44882
- const committed = await commitEgress(gateway, egress);
45605
+ const committed = await commitEgress(gateway, egress, scopeKeyOf2);
44883
45606
  if (committed === null) {
44884
45607
  return { rootDir, scanned, skipped, findings, gitignoredFindings, byRule, bySeverity };
44885
45608
  }
@@ -44889,13 +45612,28 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
44889
45612
  await gateway.recordScanned(ledgerable(updates, egress, committed));
44890
45613
  return { rootDir, scanned, skipped, findings, gitignoredFindings, byRule, bySeverity };
44891
45614
  }
44892
- function scanManifests(egress, ledger, updates, rootDir) {
44893
- for (const manifest of collectManifests(rootDir)) {
45615
+ function scanManifests(egress, ledger, updates, rootDir, scopeKeyOf2, onRepositoryRoot) {
45616
+ for (const manifest of collectManifests(rootDir, void 0, onRepositoryRoot)) {
44894
45617
  const prev = ledger.previous.get(manifest.path);
44895
- if (prev?.mtime === manifest.mtime) continue;
45618
+ const repository = repositoryToRecord(
45619
+ prev,
45620
+ scopeKeyOf2.repositoryOf(toPosix(relative3(rootDir, manifest.path)))
45621
+ );
45622
+ if (prev?.mtime === manifest.mtime) {
45623
+ if (repositoryDiffers(prev, repository)) {
45624
+ updates.push({
45625
+ path: manifest.path,
45626
+ mtime: prev.mtime,
45627
+ contentHash: prev.contentHash,
45628
+ rulesetHash: ledger.rulesetHash,
45629
+ ...repositoryColumns(repository)
45630
+ });
45631
+ }
45632
+ continue;
45633
+ }
44896
45634
  let content;
44897
45635
  try {
44898
- content = readFileSync22(manifest.path, "utf8");
45636
+ content = readFileSync18(manifest.path, "utf8");
44899
45637
  } catch {
44900
45638
  continue;
44901
45639
  }
@@ -44904,31 +45642,82 @@ function scanManifests(egress, ledger, updates, rootDir) {
44904
45642
  path: manifest.path,
44905
45643
  mtime: manifest.mtime,
44906
45644
  contentHash: hash2,
44907
- rulesetHash: ledger.rulesetHash
45645
+ rulesetHash: ledger.rulesetHash,
45646
+ ...repositoryColumns(repository)
44908
45647
  });
44909
45648
  if (prev?.contentHash === hash2) continue;
44910
45649
  collectFileEgress(egress, manifest.path, content, manifest.kind);
44911
45650
  }
44912
45651
  }
44913
- async function commitEgress(gateway, egress) {
45652
+ async function commitEgress(gateway, egress, scopeKeyOf2) {
44914
45653
  if (!egress) return EMPTY_DROPPED;
44915
- const { project, files, scannedFiles, deletedFiles } = egress;
45654
+ const { project, files, scannedFiles, deletedFiles, deletedPaths, nestedRoots } = egress;
44916
45655
  if (scannedFiles.length === 0 && deletedFiles.length === 0 && files.length === 0) {
44917
45656
  return EMPTY_DROPPED;
44918
45657
  }
45658
+ let nestedKeys;
45659
+ let deletedKeys;
44919
45660
  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
- });
45661
+ const summary = await gateway.recordProjectEgress(
45662
+ {
45663
+ projectKey: project.projectKey,
45664
+ project: project.project,
45665
+ projectId: null,
45666
+ reconcile: { mode: "ledger", scannedFiles, deletedFiles },
45667
+ hits: resolveEgress(files)
45668
+ },
45669
+ {
45670
+ // One key per nested root, from this scan's own lookup of a
45671
+ // repository ROOT (./scope-key.ts): the directory's own key, found
45672
+ // without climbing. A nested directory whose `.git` is a link to
45673
+ // nowhere, or is gone by the time a gateway asks, is `undefined` here
45674
+ // rather than the key of the repository around it; so is a nested
45675
+ // repository with no forge remote. Each root is read fresh, never from
45676
+ // the resolver's memory of an earlier answer for that directory. Always
45677
+ // a list, even an empty one: a scoped gateway reads a missing list as a
45678
+ // register nobody vouched for. The repository lookups it makes do not
45679
+ // throw on these inputs, and the gateway reads any throw in this read as
45680
+ // local anyway.
45681
+ //
45682
+ // A getter, memoized: only a gateway that reads the list causes a
45683
+ // repository read. The standalone gateway ignores it, and a
45684
+ // machine-wide attachment answers before reading it.
45685
+ get nestedScopeKeys() {
45686
+ nestedKeys ??= [...new Set(nestedRoots)].map((dir) => scopeKeyOf2.ofRepositoryRoot(dir));
45687
+ return nestedKeys;
45688
+ },
45689
+ // One key per entry of `reconcile.deletedFiles`, in its order: what the
45690
+ // ledger recorded when the path was last read, and none for a row that
45691
+ // recorded none. ASYNC and lazy, because the read of every row's key is a
45692
+ // read of the whole ledger: only a gateway that forwards by scope asks, and
45693
+ // only once it has found the register sendable at all, so the standalone
45694
+ // gateway and a machine-wide attachment never cause it. Memoized, so a
45695
+ // gateway that asks twice reads once. A scan that deleted nothing has no
45696
+ // keys to look up and reads nothing.
45697
+ deletedFileKeys: () => {
45698
+ deletedKeys ??= keysOfDeleted(gateway, deletedPaths);
45699
+ return deletedKeys;
45700
+ }
45701
+ }
45702
+ );
44927
45703
  return new Set(summary.droppedFiles);
44928
45704
  } catch {
44929
45705
  return null;
44930
45706
  }
44931
45707
  }
45708
+ async function keysOfDeleted(gateway, deletedPaths) {
45709
+ if (deletedPaths.length === 0) return [];
45710
+ const recorded = await readRecordedKeys(gateway);
45711
+ return deletedPaths.map((path) => recorded.get(path));
45712
+ }
45713
+ async function readRecordedKeys(gateway) {
45714
+ try {
45715
+ return await gateway.scanLedgerPathKeys?.() ?? NO_RECORDED_KEYS;
45716
+ } catch {
45717
+ return NO_RECORDED_KEYS;
45718
+ }
45719
+ }
45720
+ var NO_RECORDED_KEYS = /* @__PURE__ */ new Map();
44932
45721
  var EMPTY_DROPPED = /* @__PURE__ */ new Set();
44933
45722
  function ledgerable(updates, egress, dropped) {
44934
45723
  if (!egress || dropped.size === 0) return [...updates];
@@ -44953,7 +45742,7 @@ async function scanWorktree(config2, opts) {
44953
45742
  // src/sync.ts
44954
45743
  try {
44955
45744
  await runAttachedSync(void 0, {
44956
- scan: commandScanFor(loadConfig(), scanWorktree, SOURCE_TOOL.Codex)
45745
+ scan: commandScanFor(() => loadConfig(), scanWorktree, SOURCE_TOOL.Codex)
44957
45746
  });
44958
45747
  } catch {
44959
45748
  }