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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,7 +52,7 @@ var require_ignore = __commonJS({
52
52
  var DOUBLE_SLASH = "//";
53
53
  var SLASH_CODE = 47;
54
54
  var DOT_CODE = 46;
55
- var SLASH3 = "/";
55
+ var SLASH4 = "/";
56
56
  var TMP_KEY_IGNORE = "node-ignore";
57
57
  if (typeof Symbol !== "undefined") {
58
58
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -289,13 +289,13 @@ var require_ignore = __commonJS({
289
289
  // A leading slash matches the beginning of the pathname
290
290
  /^\//,
291
291
  () => "^",
292
- SLASH3
292
+ SLASH4
293
293
  ],
294
294
  // replace special metacharacter slash after the leading slash
295
295
  [
296
296
  /\//g,
297
297
  () => "\\/",
298
- SLASH3
298
+ SLASH4
299
299
  ],
300
300
  [
301
301
  // > A leading "**" followed by a slash means match in all directories.
@@ -411,7 +411,7 @@ var require_ignore = __commonJS({
411
411
  if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
412
412
  return source;
413
413
  }
414
- return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
414
+ return last === SLASH4 ? `${source}$` : `${source}(?=$|\\/$)`;
415
415
  }
416
416
  ]
417
417
  ];
@@ -541,7 +541,7 @@ var require_ignore = __commonJS({
541
541
  ) : replaced;
542
542
  };
543
543
  var checkSourceOf = (body, prefix) => {
544
- if (body[body.length - 1] === SLASH3) {
544
+ if (body[body.length - 1] === SLASH4) {
545
545
  prefix = makeRegexPrefix(body.slice(0, -1));
546
546
  }
547
547
  const head = prefix.slice(0, -1);
@@ -549,26 +549,26 @@ var require_ignore = __commonJS({
549
549
  return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
550
  };
551
551
  var matchesBasename = (body) => {
552
- const index = body.indexOf(SLASH3);
552
+ const index = body.indexOf(SLASH4);
553
553
  return index < 0 || index === body.length - 1;
554
554
  };
555
555
  var basenameOf = (path) => {
556
556
  const end = path.length - 1;
557
557
  const index = path.lastIndexOf(
558
- SLASH3,
559
- path[end] === SLASH3 ? end - 1 : end
558
+ SLASH4,
559
+ path[end] === SLASH4 ? end - 1 : end
560
560
  );
561
561
  return index < 0 ? path : path.slice(index + 1);
562
562
  };
563
563
  var parentOf = (path) => {
564
564
  if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
565
- const slices = path.split(SLASH3).filter(Boolean);
565
+ const slices = path.split(SLASH4).filter(Boolean);
566
566
  slices.pop();
567
- return slices.length ? slices.join(SLASH3) + SLASH3 : EMPTY;
567
+ return slices.length ? slices.join(SLASH4) + SLASH4 : EMPTY;
568
568
  }
569
569
  const end = path.length - 1;
570
570
  const cut = path.lastIndexOf(
571
- SLASH3,
571
+ SLASH4,
572
572
  path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
573
573
  );
574
574
  return cut < 0 ? EMPTY : path.slice(0, cut + 1);
@@ -679,7 +679,7 @@ var require_ignore = __commonJS({
679
679
  // are left out once, rather than tested or compiled for every path.
680
680
  testLiteral(path) {
681
681
  const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
- ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
682
+ ({ body }) => body[body.length - (body[body.length - 1] === SLASH4 ? 2 : 1)] === "*"
683
683
  ));
684
684
  let ignored = false;
685
685
  let unignored = false;
@@ -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 basename7 = 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 ? basename7 : path
726
726
  )) {
727
727
  ignored = !negative;
728
728
  unignored = negative;
@@ -873,19 +873,7 @@ var require_ignore = __commonJS({
873
873
  });
874
874
 
875
875
  // src/hooks/session-start.ts
876
- import { readFileSync as readFileSync25 } from "fs";
877
-
878
- // ../../packages/persistence/src/attached-derived.ts
879
- import { rmSync } from "fs";
880
- import { join } from "path";
881
- var POLICY_CACHE_FILENAME = "policy-cache.json";
882
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
883
- var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
884
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
885
-
886
- // ../../packages/persistence/src/control-plane-credential.ts
887
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
888
- import { join as join2 } from "path";
876
+ import { readFileSync as readFileSync24 } from "fs";
889
877
 
890
878
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
891
879
  var DEFERRED_MIGRATION_TAGS = [
@@ -1057,6 +1045,12 @@ var HOUR_MS = 60 * MINUTE_MS;
1057
1045
  var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1058
1046
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1059
1047
 
1048
+ // ../../packages/schema/src/invisible-padding.ts
1049
+ 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;
1050
+ function stripInvisiblePadding(text) {
1051
+ return text.replace(INVISIBLE_PADDING, "");
1052
+ }
1053
+
1060
1054
  // ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
1061
1055
  var external_exports = {};
1062
1056
  __export(external_exports, {
@@ -20792,13 +20786,16 @@ function serviceTierMultiplier(tier) {
20792
20786
  if (tier === void 0) return 1;
20793
20787
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20794
20788
  }
20789
+ function promptTokensOf(usage) {
20790
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
20791
+ }
20795
20792
  function costOf(price, usage) {
20796
20793
  const metered = [
20797
20794
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20798
20795
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20799
20796
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20800
20797
  ];
20801
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
20798
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20802
20799
  if (band !== null && (band.input === null || band.output === null)) return null;
20803
20800
  const inputRate = band?.input ?? price.input;
20804
20801
  const outputRate = band?.output ?? price.output;
@@ -21008,7 +21005,7 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21008
21005
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21009
21006
  var BEDROCK_REVISION_RE = /:\d+$/u;
21010
21007
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21011
- var DATED_SUFFIX_RE = /-\d{8}$/u;
21008
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21012
21009
  function stripPlatformDecorations(model) {
21013
21010
  let id = model.trim();
21014
21011
  let platform2 = null;
@@ -21158,7 +21155,7 @@ anthropic.model("claude-haiku-4-5", {
21158
21155
  name: "Claude Haiku 4.5",
21159
21156
  ctx: 2e5,
21160
21157
  maxOut: 64e3,
21161
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
21158
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21162
21159
  capability: null,
21163
21160
  price: anthropicPrice(1, 5, 0.1),
21164
21161
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21289,6 +21286,11 @@ openai.model("gpt-4o", {
21289
21286
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21290
21287
  on: [...OPENAI_RESELLERS]
21291
21288
  });
21289
+ openai.model("gpt-4o-2024-05-13", {
21290
+ name: "GPT-4o (2024-05-13)",
21291
+ price: tokenPrice(5, 15),
21292
+ on: [...OPENAI_RESELLERS]
21293
+ });
21292
21294
  openai.model("gpt-4o-mini", {
21293
21295
  name: "GPT-4o mini",
21294
21296
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21308,6 +21310,24 @@ openai.model("o3", {
21308
21310
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21309
21311
  on: [...OPENAI_RESELLERS]
21310
21312
  });
21313
+ openai.model("text-embedding-3-small", {
21314
+ name: "text-embedding-3-small",
21315
+ capability: "embedding",
21316
+ price: tokenPrice(0.02, 0),
21317
+ on: [...OPENAI_RESELLERS]
21318
+ });
21319
+ openai.model("text-embedding-3-large", {
21320
+ name: "text-embedding-3-large",
21321
+ capability: "embedding",
21322
+ price: tokenPrice(0.13, 0),
21323
+ on: [...OPENAI_RESELLERS]
21324
+ });
21325
+ openai.model("text-embedding-ada-002", {
21326
+ name: "text-embedding-ada-002",
21327
+ capability: "embedding",
21328
+ price: tokenPrice(0.1, 0),
21329
+ on: [...OPENAI_RESELLERS]
21330
+ });
21311
21331
  openai.model("gpt-oss-120b", {
21312
21332
  name: "GPT-OSS 120B",
21313
21333
  openWeights: true,
@@ -21594,10 +21614,21 @@ var MODEL_ENTRIES = Object.freeze([
21594
21614
  ...alibaba.models(),
21595
21615
  ...amazon.models()
21596
21616
  ]);
21617
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
21618
+ [
21619
+ ...new Set(
21620
+ MODEL_ENTRIES.flatMap(
21621
+ (entry) => [...entry.platforms.values()].flatMap(
21622
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
21623
+ )
21624
+ )
21625
+ )
21626
+ ].sort((a, b) => a - b)
21627
+ );
21597
21628
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21598
21629
 
21599
21630
  // ../../packages/schema/src/model/governance.ts
21600
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
21631
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21601
21632
  var DataRetention = external_exports.enum([
21602
21633
  "zero_retention",
21603
21634
  "no_storage",
@@ -21728,7 +21759,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21728
21759
 
21729
21760
  // ../../packages/schema/src/token/token-report.ts
21730
21761
  var num = (value) => value ?? 0;
21731
- function costUsageOf(a) {
21762
+ function costUsageOf(a, promptTokens) {
21732
21763
  const usage = {
21733
21764
  inputTokens: num(a.input_tokens),
21734
21765
  outputTokens: num(a.output_tokens),
@@ -21738,11 +21769,12 @@ function costUsageOf(a) {
21738
21769
  webSearchRequests: num(a.web_search_requests)
21739
21770
  };
21740
21771
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
21772
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21741
21773
  return usage;
21742
21774
  }
21743
21775
  function buildTokenReports(leaves, costModel) {
21744
21776
  const bySession = /* @__PURE__ */ new Map();
21745
- for (const { sessionId, attributes } of leaves) {
21777
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21746
21778
  const provider = attributes.provider ?? "unknown";
21747
21779
  const model = attributes.model ?? "unknown";
21748
21780
  const key = `${provider} ${model}`;
@@ -21761,7 +21793,8 @@ function buildTokenReports(leaves, costModel) {
21761
21793
  cacheCreation: 0,
21762
21794
  cacheRead: 0,
21763
21795
  costUsd: 0,
21764
- priced: false
21796
+ priced: false,
21797
+ partial: false
21765
21798
  };
21766
21799
  rollups.set(key, acc);
21767
21800
  }
@@ -21769,8 +21802,14 @@ function buildTokenReports(leaves, costModel) {
21769
21802
  acc.output += num(attributes.output_tokens);
21770
21803
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21771
21804
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21772
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21773
- if (leafCost !== null) {
21805
+ const leafCost = costModel.costFor({
21806
+ provider,
21807
+ model,
21808
+ usage: costUsageOf(attributes, promptTokens)
21809
+ });
21810
+ if (leafCost === null) {
21811
+ acc.partial = true;
21812
+ } else {
21774
21813
  acc.costUsd += leafCost;
21775
21814
  acc.priced = true;
21776
21815
  }
@@ -21786,9 +21825,8 @@ function buildTokenReports(leaves, costModel) {
21786
21825
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21787
21826
  totalTokens += rollupTotal;
21788
21827
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21789
- if (estimatedCostUsd === null) {
21790
- anyUnpriced = true;
21791
- } else {
21828
+ if (acc.partial) anyUnpriced = true;
21829
+ if (estimatedCostUsd !== null) {
21792
21830
  anyPriced = true;
21793
21831
  costUsd += estimatedCostUsd;
21794
21832
  }
@@ -21811,7 +21849,7 @@ function buildTokenReports(leaves, costModel) {
21811
21849
  totalTokens,
21812
21850
  // Σ of the PRICED rollups; null when none had a known price.
21813
21851
  estimatedCostUsd: anyPriced ? costUsd : null,
21814
- // Any unknown (provider, model) means the total understates real spend.
21852
+ // Any call priced to null means the total understates real spend.
21815
21853
  costIsPartial: anyUnpriced
21816
21854
  });
21817
21855
  }
@@ -22693,8 +22731,9 @@ var SessionTokenReport = external_exports.object({
22693
22731
  totalTokens: external_exports.number().int().nonnegative(),
22694
22732
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22695
22733
  estimatedCostUsd: external_exports.number().nullable(),
22696
- // True whenever any rollup has a null cost (unknown provider/model), so the
22697
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
22734
+ // True whenever any call priced to null (an unknown provider/model, or a call
22735
+ // over a long-context threshold whose rate is unpublished), so the total
22736
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22698
22737
  // precise figure rather than silently dropping the unpriced calls.
22699
22738
  costIsPartial: external_exports.boolean()
22700
22739
  });
@@ -23685,7 +23724,15 @@ var StorePostureSnapshot = external_exports.object({
23685
23724
  policyCounts: StorePosturePolicyCounts,
23686
23725
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23687
23726
  // getting its 200 without a payload change.
23688
- plugin: StorePosturePlugin.optional()
23727
+ plugin: StorePosturePlugin.optional(),
23728
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
23729
+ // machine attachment omits it, so its body is byte for byte the one it
23730
+ // sent before this member existed. Absent therefore means machine-wide OR
23731
+ // a reporter older than this member, never "scoped". Both values parse, so
23732
+ // a sender that one day spells `machine` breaks no receiver; any other
23733
+ // value fails the whole snapshot, which is why the reporter sends a
23734
+ // constant and never the raw mode.
23735
+ attachmentMode: AttachmentMode.optional()
23689
23736
  }).meta({ id: "StorePostureSnapshot" });
23690
23737
  var CAPTURE_VERSION_PREFIX = "capture/";
23691
23738
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -24132,7 +24179,7 @@ var Rule = external_exports.strictObject({
24132
24179
  postValidators: external_exports.array(PostValidatorRef).optional(),
24133
24180
  requiresNearby: RequiresNearby.optional(),
24134
24181
  examples: external_exports.array(external_exports.string()).optional(),
24135
- // Whether the matched text is itself sensitive. Absent means 'value'.
24182
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24136
24183
  evidence: RuleEvidence.optional()
24137
24184
  }).meta({ id: "Rule" });
24138
24185
  var Author = external_exports.object({
@@ -24224,7 +24271,13 @@ var DetectionRule = external_exports.object({
24224
24271
  // Representative matching strings the rule author shipped with the rule. The
24225
24272
  // cheapest honest answer to "show me what this rule catches" — every bundled
24226
24273
  // rule has them, and they are already in the stored snapshot.
24227
- examples: external_exports.array(external_exports.string()).optional()
24274
+ examples: external_exports.array(external_exports.string()).optional(),
24275
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
24276
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
24277
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
24278
+ // in a value category (secret/pii/financial/phi) is always 'value',
24279
+ // whatever it declares.
24280
+ evidence: RuleEvidence.optional()
24228
24281
  }).meta({ id: "DetectionRule" });
24229
24282
  var DetectionUpdate = external_exports.object({
24230
24283
  available: external_exports.boolean(),
@@ -24292,8 +24345,10 @@ var ImportDetectionRequest = external_exports.object({
24292
24345
  }).meta({ id: "ImportDetectionRequest" });
24293
24346
 
24294
24347
  // ../../packages/schema/src/zod/detection-build.ts
24295
- function optional2(key, parsed2, raw) {
24296
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
24348
+ function optional2(key, raw, parse4) {
24349
+ if (raw === void 0) return {};
24350
+ const parsed2 = parse4(raw);
24351
+ if (!parsed2.success || parsed2.data === void 0) return {};
24297
24352
  return { [key]: parsed2.data };
24298
24353
  }
24299
24354
  function isStringArray(value) {
@@ -24328,10 +24383,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24328
24383
  category: r.category,
24329
24384
  severity: r.severity,
24330
24385
  matcher: parsed2.data,
24331
- // The rest of what decides whether this rule fires. Carried so a consumer
24332
- // re-running the rule (a preview, a tester) evaluates what the engine
24333
- // evaluates rather than a matcher stripped of its guards — half the
24334
- // bundled catalog carries at least one of these.
24386
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
24387
+ // decides whether this rule fires. Carried so a consumer re-running the
24388
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
24389
+ // than a matcher stripped of its guards — half the bundled catalog
24390
+ // carries at least one of these. `examples` and `evidence` describe the
24391
+ // rule and never gate a match.
24335
24392
  //
24336
24393
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24337
24394
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24341,18 +24398,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24341
24398
  // test should stay exactly what it was, namely a renderable matcher. A
24342
24399
  // field that fails validation is omitted, which reads as "not set" and is
24343
24400
  // the same thing the consumer saw before this change.
24344
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
24401
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24345
24402
  ...optional2(
24346
24403
  "postValidators",
24347
- PostValidatorRef.array().safeParse(r.postValidators),
24348
- r.postValidators
24404
+ r.postValidators,
24405
+ (v) => PostValidatorRef.array().safeParse(v)
24349
24406
  ),
24350
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
24407
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24351
24408
  ...optional2(
24352
24409
  "examples",
24353
- { success: isStringArray(r.examples), data: r.examples },
24354
- r.examples
24355
- )
24410
+ r.examples,
24411
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
24412
+ ),
24413
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24356
24414
  }
24357
24415
  ];
24358
24416
  });
@@ -25045,11 +25103,14 @@ var PolicyBundle = external_exports.object({
25045
25103
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
25046
25104
  // Model ids (the raw `model` string a harness reports, e.g.
25047
25105
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
25048
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
25049
- // one (UserPromptSubmit). Optional so an older backend — and an older
25050
- // on-disk cache — still parses; consumers read `?? []`, which is the
25051
- // unenforced behaviour that predates this field and the safe direction to
25052
- // default.
25106
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
25107
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
25108
+ // wherever the organization governs the event: everywhere on a
25109
+ // machine-wide attachment, and only in enrolled repositories on a scoped
25110
+ // one (the plugin runtime's `governanceApplies`).
25111
+ // Optional so an older backend — and an older on-disk cache — still
25112
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
25113
+ // predates this field and the safe direction to default.
25053
25114
  //
25054
25115
  // Ids, not display names: the governance decision is keyed on the exact
25055
25116
  // string the harness reports (`model_status_override.versionId` in the
@@ -25511,6 +25572,8 @@ var AttachmentScopeEntry = external_exports.object({
25511
25572
  });
25512
25573
  var AttachmentScope = external_exports.object({
25513
25574
  endpoint: external_exports.string().min(1),
25575
+ tenantName: PluginWhoami.shape.tenantName.optional(),
25576
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25514
25577
  entries: external_exports.array(AttachmentScopeEntry)
25515
25578
  });
25516
25579
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25523,7 +25586,13 @@ function parseAttachmentScope(raw) {
25523
25586
  const entry = AttachmentScopeEntry.safeParse(candidate);
25524
25587
  if (entry.success) entries.push(entry.data);
25525
25588
  }
25526
- return { endpoint: envelope.data.endpoint, entries };
25589
+ const { endpoint, tenantName, userEmail } = envelope.data;
25590
+ return {
25591
+ endpoint,
25592
+ ...tenantName === void 0 ? {} : { tenantName },
25593
+ ...userEmail === void 0 ? {} : { userEmail },
25594
+ entries
25595
+ };
25527
25596
  } catch {
25528
25597
  return void 0;
25529
25598
  }
@@ -25888,6 +25957,27 @@ var ManagedSettings = external_exports.object({
25888
25957
  };
25889
25958
  }).meta({ id: "ManagedSettings" });
25890
25959
 
25960
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
25961
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
25962
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
25963
+ var ModPolicySnapshot = external_exports.object({
25964
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
25965
+ generatedAt: external_exports.iso.datetime(),
25966
+ // The complete effective ruleset, as the hook's runtime scans with it: the
25967
+ // user's enabled installed packs (user-modified and custom packs included).
25968
+ // Absent means the store holds no authoritative snapshot, and the reader
25969
+ // scans with the packs it ships — the hook's own fallback.
25970
+ rules: external_exports.array(Rule).optional(),
25971
+ // Rule-targeted actions (first enabled policy per rule wins).
25972
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25973
+ // The resolved action per detection category.
25974
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25975
+ // Rules with an active exception grant. Honouring a grant means matching a
25976
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25977
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25978
+ exceptionRuleIds: external_exports.array(external_exports.string())
25979
+ }).meta({ id: "ModPolicySnapshot" });
25980
+
25891
25981
  // ../../packages/schema/src/zod/project-files.ts
25892
25982
  var ProjectFileInput = external_exports.object({
25893
25983
  path: external_exports.string().min(1),
@@ -26208,7 +26298,16 @@ var AttachInput = external_exports.object({
26208
26298
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26209
26299
  // renders a longer one usefully.
26210
26300
  label: printable(200).optional(),
26211
- accessKey: external_exports.string()
26301
+ accessKey: external_exports.string(),
26302
+ // How much of this machine the attachment is for: everything, or only the
26303
+ // repositories its user enrolls. Optional, so an input without it still
26304
+ // parses; what an absent mode means is for whatever reads it to decide, not
26305
+ // this shape. This member validates the VALUE rather than leaving that to the
26306
+ // call site, a deliberate exception to this module's shape-only rule: a shape
26307
+ // rejection names the field, so a value that is not a mode is refused as a bad
26308
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
26309
+ // it as the mode to attach in.
26310
+ mode: AttachmentMode.optional()
26212
26311
  });
26213
26312
 
26214
26313
  // ../../packages/schema/src/zod/triage.ts
@@ -26494,6 +26593,18 @@ function fromCaptureStatusAttributes(bag) {
26494
26593
  return parsedStatus.success ? parsedStatus.data : null;
26495
26594
  }
26496
26595
 
26596
+ // ../../packages/persistence/src/attached-derived.ts
26597
+ import { rmSync } from "fs";
26598
+ import { join } from "path";
26599
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
26600
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
26601
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
26602
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
26603
+
26604
+ // ../../packages/persistence/src/control-plane-credential.ts
26605
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
26606
+ import { join as join2 } from "path";
26607
+
26497
26608
  // ../../packages/persistence/src/paths.ts
26498
26609
  import {
26499
26610
  chmodSync,
@@ -26624,6 +26735,14 @@ function readControlPlaneCredentialState(settingsDir2, connection) {
26624
26735
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
26625
26736
  return read.usable ? { usable: true } : read;
26626
26737
  }
26738
+ function asReadableCredential(value) {
26739
+ const result = AttachedCredentialAny.safeParse(value);
26740
+ if (!result.success) return null;
26741
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
26742
+ return null;
26743
+ }
26744
+ return result.data;
26745
+ }
26627
26746
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26628
26747
  const file2 = controlPlaneCredentialPath(settingsDir2);
26629
26748
  let raw;
@@ -26642,20 +26761,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26642
26761
  } catch {
26643
26762
  return { usable: false, reason: "malformed" };
26644
26763
  }
26645
- const result = AttachedCredential.safeParse(parsed2);
26646
- if (!result.success) return { usable: false, reason: "malformed" };
26647
- if (!isSafeEndpoint(result.data.endpoint)) {
26764
+ const credential = asReadableCredential(parsed2);
26765
+ if (credential === null) return { usable: false, reason: "malformed" };
26766
+ if (!isSafeEndpoint(credential.endpoint)) {
26648
26767
  return { usable: false, reason: "unsafe-endpoint" };
26649
26768
  }
26650
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
26769
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26651
26770
  return {
26652
26771
  usable: false,
26653
26772
  reason: "endpoint-mismatch",
26654
- credentialEndpoint: result.data.endpoint,
26773
+ credentialEndpoint: credential.endpoint,
26655
26774
  settingsEndpoint: connection.endpoint
26656
26775
  };
26657
26776
  }
26658
- return { usable: true, credential: result.data };
26777
+ return { usable: true, credential };
26659
26778
  }
26660
26779
  function readControlPlaneCredential(settingsDir2, connection) {
26661
26780
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26664,7 +26783,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26664
26783
 
26665
26784
  // ../../packages/persistence/src/database.ts
26666
26785
  import { randomUUID as randomUUID11 } from "crypto";
26667
- import { dirname as dirname2, join as join7, sep } from "path";
26786
+ import { dirname as dirname2, join as join8, sep } from "path";
26668
26787
  import { DatabaseSync } from "node:sqlite";
26669
26788
 
26670
26789
  // ../../packages/persistence/src/ids.ts
@@ -26708,6 +26827,7 @@ function captureId(sessionId, contentHash, filePath = null) {
26708
26827
  canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
26709
26828
  );
26710
26829
  }
26830
+ var DOT = ".".charCodeAt(0);
26711
26831
 
26712
26832
  // ../../packages/persistence/src/internal/snapshot.ts
26713
26833
  import { randomUUID } from "crypto";
@@ -27035,6 +27155,25 @@ function scopeKeysParam(scopeKeys) {
27035
27155
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
27036
27156
  FROM audit_events AS session_root
27037
27157
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
27158
+ var COUNTED_IN_SCOPE = `
27159
+ AND ${inScope("scope_key")}
27160
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
27161
+ var DRAIN_TOTALS = `SELECT
27162
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27163
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27164
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27165
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27166
+ THEN 1 ELSE 0 END) AS skipped,
27167
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27168
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27169
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27170
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27171
+ FROM audit_events
27172
+ WHERE event_type IN (${TYPE_LIST})`;
27173
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
27174
+ FROM audit_events
27175
+ WHERE synced_at = ${String(SKIPPED)}
27176
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
27038
27177
  var ROW_COLUMNS = `id,
27039
27178
  parent_id AS parentId,
27040
27179
  root_session_id AS rootSessionId,
@@ -27110,7 +27249,7 @@ var SqliteHistorySyncRepository = class {
27110
27249
  );
27111
27250
  this.scopedCaptureRowsStmt = db.prepare(
27112
27251
  `SELECT ${ROW_COLUMNS}
27113
- FROM audit_events
27252
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27114
27253
  WHERE synced_at IS NULL
27115
27254
  AND sync_claimed_at IS NULL
27116
27255
  AND outbox_owed = 1
@@ -27163,40 +27302,28 @@ var SqliteHistorySyncRepository = class {
27163
27302
  );
27164
27303
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27165
27304
  FROM audit_events${COUNTED_SCOPE}`);
27305
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27306
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27166
27307
  this.partitionByKindStmt = db.prepare(
27167
27308
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27168
27309
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27169
27310
  GROUP BY event_type`
27170
27311
  );
27171
- this.countsStmt = db.prepare(
27172
- `SELECT
27173
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27174
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27175
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27176
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27177
- THEN 1 ELSE 0 END) AS skipped,
27178
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27179
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27180
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27181
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27182
- FROM audit_events
27183
- WHERE event_type IN (${TYPE_LIST})`
27312
+ this.scopedPartitionByKindStmt = db.prepare(
27313
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
27314
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
27315
+ GROUP BY event_type`
27184
27316
  );
27185
- this.captureSkipCountStmt = db.prepare(
27186
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27187
- // way the structural totals are. The split exists because a refusal is
27188
- // terminal only against the deployment that gave it, and the structural
27189
- // re-arm frees it on a change of deployment. The capture lane has no such
27190
- // escape: re-arming a capture would offer one deployment's undelivered
27191
- // prompts, with their text, to a deployment that never saw them, which is
27192
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27193
- // reasons mean the same thing — this row will not be sent — and splitting
27194
- // them would put refused captures in a bucket nothing reads and nothing
27195
- // frees.
27196
- `SELECT COUNT(*) AS skipped
27197
- FROM audit_events
27198
- WHERE synced_at = ${String(SKIPPED)}
27199
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27317
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
27318
+ this.scopedCountsStmt = db.prepare(
27319
+ `${DRAIN_TOTALS}
27320
+ AND ${inScope("scope_key")}
27321
+ AND ${inScope(ROOT_SCOPE_KEY)}`
27322
+ );
27323
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
27324
+ this.scopedCaptureSkipCountStmt = db.prepare(
27325
+ `${CAPTURE_SKIPS}
27326
+ AND ${inScope("scope_key")}`
27200
27327
  );
27201
27328
  this.fingerprintStmt = db.prepare(
27202
27329
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27310,6 +27437,10 @@ var SqliteHistorySyncRepository = class {
27310
27437
  scopedCaptureRowsStmt;
27311
27438
  scopedCaptureBacklogOwedStmt;
27312
27439
  markScopeCapturesOwedStmt;
27440
+ scopedPartitionStmt;
27441
+ scopedPartitionByKindStmt;
27442
+ scopedCountsStmt;
27443
+ scopedCaptureSkipCountStmt;
27313
27444
  /**
27314
27445
  * The masked detections recorded against one tool call.
27315
27446
  *
@@ -27531,7 +27662,29 @@ var SqliteHistorySyncRepository = class {
27531
27662
  * in" — and a machine that has never attached has no boundary to pass, so
27532
27663
  * requiring one would force a caller to invent one and report the whole store
27533
27664
  * as queued.
27665
+ *
27666
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
27667
+ * the rows that pass the drain's reachability rule for that scope
27668
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
27669
+ * drain never offers), so a personal repository's rows are in none of them.
27670
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
27671
+ * nothing.
27534
27672
  */
27673
+ partition(scopeKeys) {
27674
+ const row = getRow(
27675
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
27676
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27677
+ );
27678
+ return {
27679
+ queued: row?.queued ?? 0,
27680
+ inProgress: row?.inProgress ?? 0,
27681
+ synced: row?.synced ?? 0,
27682
+ failed: row?.failed ?? 0,
27683
+ refused: row?.refused ?? 0,
27684
+ detached: row?.detached ?? 0,
27685
+ total: row?.total ?? 0
27686
+ };
27687
+ }
27535
27688
  /**
27536
27689
  * The same partition, one row per kind that a lane carries.
27537
27690
  *
@@ -27541,11 +27694,14 @@ var SqliteHistorySyncRepository = class {
27541
27694
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27542
27695
  * rows", never as "zero sent"; the two look identical in a bar and mean
27543
27696
  * different things.
27697
+ *
27698
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
27699
+ * still sum to the scoped aggregate. An empty list returns no rows.
27544
27700
  */
27545
- partitionByKind() {
27701
+ partitionByKind(scopeKeys) {
27546
27702
  return allRows(
27547
- this.partitionByKindStmt,
27548
- {}
27703
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
27704
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27549
27705
  ).map((row) => ({
27550
27706
  kind: row.kind,
27551
27707
  queued: row.queued ?? 0,
@@ -27557,22 +27713,25 @@ var SqliteHistorySyncRepository = class {
27557
27713
  total: row.total ?? 0
27558
27714
  }));
27559
27715
  }
27560
- partition() {
27561
- const row = getRow(this.partitionStmt, {});
27562
- return {
27563
- queued: row?.queued ?? 0,
27564
- inProgress: row?.inProgress ?? 0,
27565
- synced: row?.synced ?? 0,
27566
- failed: row?.failed ?? 0,
27567
- refused: row?.refused ?? 0,
27568
- detached: row?.detached ?? 0,
27569
- total: row?.total ?? 0
27570
- };
27571
- }
27572
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27573
- counts(before) {
27574
- const row = getRow(this.countsStmt, { before });
27575
- const captures = getRow(this.captureSkipCountStmt);
27716
+ /**
27717
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
27718
+ * and skipped are totals.
27719
+ *
27720
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
27721
+ * `capturesSkipped` included: a structural row is counted only when its own
27722
+ * key and its session root's key are among them, a capture when its own key
27723
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
27724
+ * under the same keys and boundary. Omitted, this runs the machine
27725
+ * statements, unchanged; an empty list counts nothing.
27726
+ */
27727
+ counts(before, scopeKeys) {
27728
+ const row = getRow(
27729
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
27730
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
27731
+ );
27732
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
27733
+ scopeKeys: scopeKeysParam(scopeKeys)
27734
+ });
27576
27735
  return {
27577
27736
  pending: row?.pending ?? 0,
27578
27737
  sent: row?.sent ?? 0,
@@ -27824,6 +27983,7 @@ function applyMigrations(db, file2, options = {}) {
27824
27983
  }
27825
27984
  ensureSyncedAtColumn(db, "audit_events");
27826
27985
  ensureScopeKeyColumn(db);
27986
+ ensureScopeOwedIndex(db);
27827
27987
  ensureScanLedgerTable(db);
27828
27988
  ensureHistorySyncTable(db);
27829
27989
  ensureBlockedDetectionsTable(db);
@@ -28264,14 +28424,48 @@ function ensureScopeKeyColumn(db) {
28264
28424
  function hasScopeKeyColumn(db) {
28265
28425
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28266
28426
  }
28427
+ 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";
28428
+ function ensureScopeOwedIndex(db) {
28429
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
28430
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
28431
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
28432
+ if (!complete) return;
28433
+ db.exec(SCOPE_OWED_INDEX_DDL);
28434
+ }
28267
28435
  function ensureScanLedgerTable(db) {
28268
28436
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28269
28437
  path TEXT PRIMARY KEY,
28270
28438
  mtime TEXT NOT NULL,
28271
28439
  content_hash TEXT NOT NULL,
28272
28440
  ruleset_hash TEXT NOT NULL,
28273
- scanned_at INTEGER NOT NULL
28441
+ scanned_at INTEGER NOT NULL,
28442
+ scope_key TEXT,
28443
+ scope_root TEXT
28274
28444
  )`);
28445
+ ensureScanLedgerScopeKeyColumn(db);
28446
+ ensureScanLedgerScopeRootColumn(db);
28447
+ }
28448
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
28449
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
28450
+ function ensureScanLedgerScopeKeyColumn(db) {
28451
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
28452
+ }
28453
+ function ensureScanLedgerScopeRootColumn(db) {
28454
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
28455
+ }
28456
+ function ensureScanLedgerColumn(db, column, ddl) {
28457
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
28458
+ if (hasScanLedgerColumn(db, column)) return;
28459
+ withTransaction(
28460
+ db,
28461
+ () => {
28462
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
28463
+ },
28464
+ "IMMEDIATE"
28465
+ );
28466
+ }
28467
+ function hasScanLedgerColumn(db, column) {
28468
+ return columnNames(db, "scan_ledger").includes(column);
28275
28469
  }
28276
28470
  function ensureHistorySyncTable(db) {
28277
28471
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28322,6 +28516,106 @@ function ensureRuleProbeCacheTable(db) {
28322
28516
  )`);
28323
28517
  }
28324
28518
 
28519
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
28520
+ import { createHash as createHash2 } from "crypto";
28521
+ import { readFileSync as readFileSync2 } from "fs";
28522
+ import { join as join4 } from "path";
28523
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
28524
+ function modPolicySnapshotPath(dataDir2) {
28525
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
28526
+ }
28527
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
28528
+ const byRule = /* @__PURE__ */ new Map();
28529
+ const byCategory = /* @__PURE__ */ new Map();
28530
+ for (const policy of input2.policies) {
28531
+ if (!policy.enabled) continue;
28532
+ if ("ruleId" in policy.target) {
28533
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
28534
+ } else if (!byCategory.has(policy.target.category)) {
28535
+ byCategory.set(policy.target.category, policy.action);
28536
+ }
28537
+ }
28538
+ const categoryActions = {};
28539
+ for (const category of DetectionCategory.options) {
28540
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
28541
+ }
28542
+ return {
28543
+ version: MOD_POLICY_SNAPSHOT_VERSION,
28544
+ generatedAt: generatedAt.toISOString(),
28545
+ // `examples` is documentation the mod never reads, and a custom pack's are
28546
+ // whatever its author pasted in, so they stay behind.
28547
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
28548
+ ruleActions: Object.fromEntries(byRule),
28549
+ categoryActions,
28550
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
28551
+ };
28552
+ }
28553
+ function assignedRuleActionPolicies(installed) {
28554
+ const out = [];
28555
+ for (const [ruleId, action] of installed.ruleActions) {
28556
+ if (installed.assignedRules.has(ruleId))
28557
+ out.push({ target: { ruleId }, action, enabled: true });
28558
+ }
28559
+ return out;
28560
+ }
28561
+ function withoutExamples(rule) {
28562
+ const copy = { ...rule };
28563
+ delete copy.examples;
28564
+ return copy;
28565
+ }
28566
+ function sameContent(a, b) {
28567
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
28568
+ }
28569
+ function readModPolicySnapshot(dataDir2) {
28570
+ try {
28571
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
28572
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
28573
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
28574
+ return parsed2.success ? parsed2.data : null;
28575
+ } catch {
28576
+ return null;
28577
+ }
28578
+ }
28579
+ function writeModPolicySnapshot(dataDir2, snapshot) {
28580
+ const text = JSON.stringify(snapshot);
28581
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
28582
+ const existing = readModPolicySnapshot(dataDir2);
28583
+ if (existing !== null && sameContent(existing, snapshot)) return false;
28584
+ ensureDataDirSync(dataDir2);
28585
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
28586
+ return true;
28587
+ }
28588
+ function regexProbeKey(matcher) {
28589
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
28590
+ }
28591
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28592
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
28593
+ return rules.filter((rule) => {
28594
+ if (rule.matcher.type !== "regex") return true;
28595
+ const key = regexProbeKey(rule.matcher);
28596
+ const verdict = sources.probeVerdict(key);
28597
+ if (verdict === "quarantined") return false;
28598
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
28599
+ });
28600
+ }
28601
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
28602
+ const policies = sources.readPolicies();
28603
+ const snapshot = sources.installedRuleset();
28604
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
28605
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
28606
+ return {
28607
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
28608
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
28609
+ exceptionRuleIds: sources.activeExceptionRuleIds()
28610
+ };
28611
+ }
28612
+ function refreshModPolicySnapshot(dataDir2, sources) {
28613
+ try {
28614
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
28615
+ } catch {
28616
+ }
28617
+ }
28618
+
28325
28619
  // ../../packages/persistence/src/internal/json.ts
28326
28620
  function safeJson(s, fallback) {
28327
28621
  if (s == null) return fallback;
@@ -28496,6 +28790,11 @@ var TIMELINE_COLUMNS = `
28496
28790
  json_extract(attributes, '$.targetId') AS target_id,
28497
28791
  json_extract(attributes, '$.internal') AS internal,
28498
28792
  json_extract(attributes, '$.flagged') AS flagged`;
28793
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
28794
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
28795
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
28796
+ " + "
28797
+ );
28499
28798
  var LLM_USAGE_SELECT = `
28500
28799
  SELECT root_session_id AS sessionId,
28501
28800
  provider,
@@ -28507,9 +28806,10 @@ var LLM_USAGE_SELECT = `
28507
28806
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28508
28807
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28509
28808
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28510
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
28809
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
28810
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28511
28811
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28512
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
28812
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28513
28813
  function usageLeaves(rows) {
28514
28814
  return rows.map((row) => {
28515
28815
  const attributes = {
@@ -28524,7 +28824,7 @@ function usageLeaves(rows) {
28524
28824
  if (row.provider !== null) attributes.provider = row.provider;
28525
28825
  if (row.model !== null) attributes.model = row.model;
28526
28826
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28527
- return { sessionId: row.sessionId, attributes };
28827
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28528
28828
  });
28529
28829
  }
28530
28830
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29858,9 +30158,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29858
30158
  AND conditions IS NULL
29859
30159
  AND ${ACTIVE_PREDICATE}`;
29860
30160
  var SqliteExceptionsRepository = class {
29861
- constructor(db, now = () => Date.now()) {
30161
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29862
30162
  this.db = db;
29863
30163
  this.now = now;
30164
+ this.onChange = onChange;
29864
30165
  this.consumeStmt = db.prepare(
29865
30166
  `UPDATE exceptions
29866
30167
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29879,6 +30180,7 @@ var SqliteExceptionsRepository = class {
29879
30180
  }
29880
30181
  db;
29881
30182
  now;
30183
+ onChange;
29882
30184
  consumeStmt;
29883
30185
  insertBlockedStmt;
29884
30186
  sweepBlockedStmt;
@@ -29894,7 +30196,9 @@ var SqliteExceptionsRepository = class {
29894
30196
  */
29895
30197
  create(input2) {
29896
30198
  try {
29897
- return Promise.resolve(this.createSync(input2));
30199
+ const created = this.createSync(input2);
30200
+ this.onChange();
30201
+ return Promise.resolve(created);
29898
30202
  } catch (err) {
29899
30203
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29900
30204
  }
@@ -30025,6 +30329,7 @@ var SqliteExceptionsRepository = class {
30025
30329
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
30026
30330
  WHERE id = :id AND revoked_at IS NULL`
30027
30331
  ).run({ id, revokedBy, reason: reason ?? null, now });
30332
+ if (Number(result.changes) === 1) this.onChange();
30028
30333
  return Promise.resolve(Number(result.changes) === 1);
30029
30334
  }
30030
30335
  /**
@@ -30037,6 +30342,15 @@ var SqliteExceptionsRepository = class {
30037
30342
  const result = this.consumeStmt.run({ id, now });
30038
30343
  return Promise.resolve(Number(result.changes) === 1);
30039
30344
  }
30345
+ /** The rule ids with at least one active grant, under any key version. */
30346
+ activeRuleIds(now = this.now()) {
30347
+ return allRows(
30348
+ this.db.prepare(
30349
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
30350
+ ),
30351
+ { now }
30352
+ ).map((row) => row.ruleId);
30353
+ }
30040
30354
  /**
30041
30355
  * The evaluation subset of every active grant under one fingerprint key
30042
30356
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31160,31 +31474,31 @@ var SqliteInspectionFindingsRepository = class {
31160
31474
  };
31161
31475
 
31162
31476
  // ../../packages/persistence/src/repositories/installed-packs.ts
31163
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
31477
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31164
31478
 
31165
31479
  // ../../packages/persistence/src/policy-floor.ts
31166
- import { readFileSync as readFileSync5 } from "fs";
31167
- import { join as join6 } from "path";
31480
+ import { readFileSync as readFileSync6 } from "fs";
31481
+ import { join as join7 } from "path";
31168
31482
 
31169
31483
  // ../../packages/persistence/src/local-layout.ts
31170
31484
  import { renameSync as renameSync3 } from "fs";
31171
31485
  import { mkdir } from "fs/promises";
31172
31486
  import { homedir } from "os";
31173
- import { join as join4 } from "path";
31487
+ import { join as join5 } from "path";
31174
31488
  function defaultDataDir() {
31175
- return join4(homedir(), ".aka");
31489
+ return join5(homedir(), ".aka");
31176
31490
  }
31177
31491
  function settingsDir(base = defaultDataDir()) {
31178
- return join4(base, "settings");
31492
+ return join5(base, "settings");
31179
31493
  }
31180
31494
  function dataDir(base = defaultDataDir()) {
31181
- return join4(base, "data");
31495
+ return join5(base, "data");
31182
31496
  }
31183
31497
  function dbPath(base = defaultDataDir()) {
31184
- return join4(dataDir(base), "aka.db");
31498
+ return join5(dataDir(base), "aka.db");
31185
31499
  }
31186
31500
  function keysDir(base = defaultDataDir()) {
31187
- return join4(base, "keys");
31501
+ return join5(base, "keys");
31188
31502
  }
31189
31503
  async function ensureDataDir(dir = defaultDataDir()) {
31190
31504
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31201,8 +31515,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31201
31515
  for (const { name, dest } of moves) {
31202
31516
  try {
31203
31517
  ensureDataDirSync(dest);
31204
- const moved = join4(dest, name);
31205
- renameSync3(join4(base, name), moved);
31518
+ const moved = join5(dest, name);
31519
+ renameSync3(join5(base, name), moved);
31206
31520
  tightenFile(moved);
31207
31521
  } catch {
31208
31522
  }
@@ -31210,8 +31524,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31210
31524
  }
31211
31525
 
31212
31526
  // ../../packages/persistence/src/settings.ts
31213
- import { readFileSync as readFileSync4 } from "fs";
31214
- import { join as join5 } from "path";
31527
+ import { readFileSync as readFileSync5 } from "fs";
31528
+ import { join as join6 } from "path";
31215
31529
 
31216
31530
  // ../../packages/persistence/src/file-lock.ts
31217
31531
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31219,7 +31533,7 @@ import {
31219
31533
  closeSync,
31220
31534
  existsSync as existsSync2,
31221
31535
  openSync,
31222
- readFileSync as readFileSync2,
31536
+ readFileSync as readFileSync3,
31223
31537
  rmSync as rmSync5,
31224
31538
  statSync as statSync3,
31225
31539
  writeFileSync as writeFileSync2
@@ -31228,7 +31542,7 @@ import { hostname as hostname3 } from "os";
31228
31542
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31229
31543
 
31230
31544
  // ../../packages/persistence/src/managed-settings.ts
31231
- import { readFileSync as readFileSync3 } from "fs";
31545
+ import { readFileSync as readFileSync4 } from "fs";
31232
31546
  import { posix, win32 } from "path";
31233
31547
  function managedSettingsPaths(platform2 = process.platform) {
31234
31548
  if (platform2 === "darwin") {
@@ -31247,7 +31561,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31247
31561
  for (const path of paths) {
31248
31562
  let text;
31249
31563
  try {
31250
- text = readFileSync3(path, "utf8");
31564
+ text = readFileSync4(path, "utf8");
31251
31565
  } catch {
31252
31566
  continue;
31253
31567
  }
@@ -31301,7 +31615,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31301
31615
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31302
31616
  }
31303
31617
  function readUserSettings(base) {
31304
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
31618
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31305
31619
  if (!record2) return defaultWorkspaceSettings();
31306
31620
  try {
31307
31621
  return WorkspaceSettings.parse(record2);
@@ -31312,7 +31626,7 @@ function readUserSettings(base) {
31312
31626
  function readJson(file2) {
31313
31627
  let text;
31314
31628
  try {
31315
- text = readFileSync4(file2, "utf8");
31629
+ text = readFileSync5(file2, "utf8");
31316
31630
  } catch {
31317
31631
  return null;
31318
31632
  }
@@ -31352,7 +31666,7 @@ var PolicyFloorError = class extends Error {
31352
31666
  };
31353
31667
  function readCachedPolicyBundle(base = defaultDataDir()) {
31354
31668
  try {
31355
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31669
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31356
31670
  const parsed2 = JSON.parse(raw);
31357
31671
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31358
31672
  return PolicyBundle.parse(parsed2.bundle);
@@ -31476,7 +31790,7 @@ function inventorySignature(packs2) {
31476
31790
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31477
31791
  }
31478
31792
  function hashRules(rulesJson) {
31479
- return createHash2("sha256").update(rulesJson).digest("hex");
31793
+ return createHash3("sha256").update(rulesJson).digest("hex");
31480
31794
  }
31481
31795
  function parseVersion(v) {
31482
31796
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31518,9 +31832,10 @@ var SqliteInstalledPacksRepository = class {
31518
31832
  * from `openLocalDatabase`, which is the single construction site that owns a
31519
31833
  * real `~/.aka`.
31520
31834
  */
31521
- constructor(db, baseDir) {
31835
+ constructor(db, baseDir, onChange = () => void 0) {
31522
31836
  this.db = db;
31523
31837
  this.baseDir = baseDir;
31838
+ this.onChange = onChange;
31524
31839
  this.insertMissingStmt = db.prepare(
31525
31840
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31526
31841
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31549,6 +31864,7 @@ var SqliteInstalledPacksRepository = class {
31549
31864
  }
31550
31865
  db;
31551
31866
  baseDir;
31867
+ onChange;
31552
31868
  insertMissingStmt;
31553
31869
  upsertAvailableStmt;
31554
31870
  signatureStmt;
@@ -31621,6 +31937,7 @@ var SqliteInstalledPacksRepository = class {
31621
31937
  },
31622
31938
  "IMMEDIATE"
31623
31939
  );
31940
+ this.onChange();
31624
31941
  } catch {
31625
31942
  }
31626
31943
  }
@@ -31695,6 +32012,7 @@ var SqliteInstalledPacksRepository = class {
31695
32012
  },
31696
32013
  "IMMEDIATE"
31697
32014
  );
32015
+ if (changed) this.onChange();
31698
32016
  return changed;
31699
32017
  }
31700
32018
  /**
@@ -31936,6 +32254,7 @@ var SqliteInstalledPacksRepository = class {
31936
32254
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31937
32255
  WHERE namespace = :namespace AND pack_id = :packId`
31938
32256
  ).run({ policyId, now: Date.now(), namespace, packId });
32257
+ if (Number(res.changes) > 0) this.onChange();
31939
32258
  return Number(res.changes) > 0;
31940
32259
  }
31941
32260
  /**
@@ -31960,6 +32279,7 @@ var SqliteInstalledPacksRepository = class {
31960
32279
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31961
32280
  WHERE namespace = :namespace AND pack_id = :packId`
31962
32281
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
32282
+ if (Number(res.changes) > 0) this.onChange();
31963
32283
  return Number(res.changes) > 0;
31964
32284
  }
31965
32285
  // Fingerprint of the recorded available mirror — compared against the
@@ -32857,13 +33177,19 @@ var SqliteInventoryAssetsRepository = class {
32857
33177
  import { randomUUID as randomUUID6 } from "crypto";
32858
33178
  var SEED_BATCH_WINDOW_MS = 6e4;
32859
33179
  var SqlitePoliciesRepository = class {
32860
- constructor(db) {
33180
+ constructor(db, onChange = () => void 0) {
32861
33181
  this.db = db;
33182
+ this.onChange = onChange;
32862
33183
  }
32863
33184
  db;
33185
+ onChange;
32864
33186
  readPolicies() {
33187
+ return Promise.resolve(this.listPolicies());
33188
+ }
33189
+ /** The synchronous read behind {@link readPolicies}. */
33190
+ listPolicies() {
32865
33191
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32866
- const policies = mapRowsTolerant(rows, (row) => {
33192
+ return mapRowsTolerant(rows, (row) => {
32867
33193
  const target = JSON.parse(row.target);
32868
33194
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32869
33195
  return Policy.parse({
@@ -32875,7 +33201,6 @@ var SqlitePoliciesRepository = class {
32875
33201
  customKeywords
32876
33202
  });
32877
33203
  });
32878
- return Promise.resolve(policies);
32879
33204
  }
32880
33205
  // Seed one policy per bundled category at Monitor so the detection-type config
32881
33206
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32886,7 +33211,7 @@ var SqlitePoliciesRepository = class {
32886
33211
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32887
33212
  if (count > 0) {
32888
33213
  this.markEarlierChoices();
32889
- this.monitorUntouchedSeeds();
33214
+ if (this.monitorUntouchedSeeds()) this.onChange();
32890
33215
  return;
32891
33216
  }
32892
33217
  const stmt = this.db.prepare(
@@ -32903,6 +33228,7 @@ var SqlitePoliciesRepository = class {
32903
33228
  });
32904
33229
  }
32905
33230
  });
33231
+ this.onChange();
32906
33232
  }
32907
33233
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32908
33234
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32968,7 +33294,7 @@ var SqlitePoliciesRepository = class {
32968
33294
  ).filter(
32969
33295
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32970
33296
  );
32971
- if (untouched.length === 0) return;
33297
+ if (untouched.length === 0) return false;
32972
33298
  const stmt = this.db.prepare(
32973
33299
  `UPDATE policies SET action = 'log'
32974
33300
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32979,6 +33305,7 @@ var SqlitePoliciesRepository = class {
32979
33305
  stmt.run({ category: row.category, seeded: row.action });
32980
33306
  }
32981
33307
  });
33308
+ return true;
32982
33309
  }
32983
33310
  // Insert-or-update the single global per-category policy row, keyed on the
32984
33311
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32995,6 +33322,7 @@ var SqlitePoliciesRepository = class {
32995
33322
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32996
33323
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32997
33324
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
33325
+ this.onChange();
32998
33326
  }
32999
33327
  // Caps every global per-category policy currently set to block/redact down
33000
33328
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -33005,6 +33333,7 @@ var SqlitePoliciesRepository = class {
33005
33333
  WHERE scope='global' AND action IN ('block','redact')
33006
33334
  AND json_extract(target,'$.category') IS NOT NULL`
33007
33335
  ).run({ now: Date.now() });
33336
+ if (Number(info.changes) > 0) this.onChange();
33008
33337
  return Number(info.changes);
33009
33338
  }
33010
33339
  // Whether the category's row was ever written after it was created — by the
@@ -33312,9 +33641,9 @@ var SqliteRuleProbeCacheRepository = class {
33312
33641
  });
33313
33642
  return { refused: !committed, cleared: before - this.countQuarantined() };
33314
33643
  }
33315
- setVerdict(ruleKey, verdict, worstProbeMs) {
33644
+ setVerdict(ruleKey, verdict, worstProbeMs2) {
33316
33645
  failOpenTransaction(this.db, () => {
33317
- this.upsertStmt.run({ ruleKey, verdict, worstProbeMs, checkedAt: Date.now() });
33646
+ this.upsertStmt.run({ ruleKey, verdict, worstProbeMs: worstProbeMs2, checkedAt: Date.now() });
33318
33647
  });
33319
33648
  }
33320
33649
  };
@@ -33324,31 +33653,45 @@ var SqliteScanLedgerRepository = class {
33324
33653
  constructor(db) {
33325
33654
  this.db = db;
33326
33655
  this.upsertStmt = db.prepare(
33327
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33328
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
33656
+ `INSERT INTO scan_ledger
33657
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
33658
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33329
33659
  ON CONFLICT (path) DO UPDATE SET
33330
33660
  mtime = excluded.mtime,
33331
33661
  content_hash = excluded.content_hash,
33332
33662
  ruleset_hash = excluded.ruleset_hash,
33663
+ scope_key = excluded.scope_key,
33664
+ scope_root = excluded.scope_root,
33333
33665
  scanned_at = excluded.scanned_at`
33334
33666
  );
33335
33667
  this.readStmt = db.prepare(
33336
- `SELECT path, mtime, content_hash AS contentHash
33668
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
33669
+ scope_root AS scopeRoot
33337
33670
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33338
33671
  );
33339
33672
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
33673
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33340
33674
  }
33341
33675
  db;
33342
33676
  upsertStmt;
33343
33677
  readStmt;
33344
33678
  pathsStmt;
33679
+ pathKeysStmt;
33345
33680
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33346
33681
  // older ruleset are simply absent, which reads as "never scanned".
33347
33682
  entriesForRuleset(rulesetHash) {
33348
- const rows = allRows(this.readStmt, {
33349
- rulesetHash
33350
- });
33351
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
33683
+ const rows = allRows(this.readStmt, { rulesetHash });
33684
+ return new Map(
33685
+ rows.map((r) => [
33686
+ r.path,
33687
+ {
33688
+ mtime: r.mtime,
33689
+ contentHash: r.contentHash,
33690
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
33691
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
33692
+ }
33693
+ ])
33694
+ );
33352
33695
  }
33353
33696
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33354
33697
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33357,6 +33700,14 @@ var SqliteScanLedgerRepository = class {
33357
33700
  allPaths() {
33358
33701
  return allRows(this.pathsStmt).map((r) => r.path);
33359
33702
  }
33703
+ // Every ledgered path with the repository it was in when it was last read,
33704
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
33705
+ // which repository a vanished file belonged to. `undefined` for a row with no
33706
+ // key, which is every row written before the column existed.
33707
+ pathKeys() {
33708
+ const rows = allRows(this.pathKeysStmt);
33709
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
33710
+ }
33360
33711
  upsertEntries(entries) {
33361
33712
  if (entries.length === 0) return;
33362
33713
  const scannedAt = Date.now();
@@ -33367,6 +33718,8 @@ var SqliteScanLedgerRepository = class {
33367
33718
  mtime: entry.mtime,
33368
33719
  contentHash: entry.contentHash,
33369
33720
  rulesetHash: entry.rulesetHash,
33721
+ scopeKey: entry.scopeKey ?? null,
33722
+ scopeRoot: entry.scopeRoot ?? null,
33370
33723
  scannedAt
33371
33724
  });
33372
33725
  }
@@ -34454,6 +34807,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34454
34807
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34455
34808
  };
34456
34809
  }
34810
+ function withoutTrailingSlashes(path) {
34811
+ let end = path.length;
34812
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
34813
+ return path.slice(0, end);
34814
+ }
34457
34815
  function toEndpointSummary(row) {
34458
34816
  return {
34459
34817
  id: row.id,
@@ -34741,7 +35099,7 @@ var SqliteSharesRepository = class {
34741
35099
  */
34742
35100
  reconcileCallSites(projectKey, reconcile) {
34743
35101
  if (reconcile.mode === "walk") {
34744
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
35102
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34745
35103
  this.db.prepare(
34746
35104
  `DELETE FROM share_call_site
34747
35105
  WHERE project_key = :key
@@ -35309,7 +35667,7 @@ function backupLegacyStore(db, file2) {
35309
35667
  discardStore(file2, backup);
35310
35668
  return backup;
35311
35669
  }
35312
- function openAndInitialize(file2, base, skipTags) {
35670
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35313
35671
  let db = openWithPragmas(file2);
35314
35672
  try {
35315
35673
  if (isForeignSqliteLineage(db)) {
@@ -35321,8 +35679,15 @@ function openAndInitialize(file2, base, skipTags) {
35321
35679
  }
35322
35680
  applyMigrations(db, file2, { skipTags });
35323
35681
  tightenPerms(file2);
35324
- const policies = new SqlitePoliciesRepository(db);
35325
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
35682
+ const modPolicy = {};
35683
+ const onPolicyStateChange = () => {
35684
+ if (modPolicy.current !== void 0)
35685
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
35686
+ };
35687
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
35688
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
35689
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
35690
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35326
35691
  const repositories = {
35327
35692
  events: new SqliteEventsRepository(db),
35328
35693
  findings: new SqliteFindingsRepository(db),
@@ -35331,9 +35696,9 @@ function openAndInitialize(file2, base, skipTags) {
35331
35696
  scanLedger: new SqliteScanLedgerRepository(db),
35332
35697
  historySync: new SqliteHistorySyncRepository(db),
35333
35698
  secretVault: new SqliteSecretVaultRepository(db),
35334
- exceptions: new SqliteExceptionsRepository(db),
35699
+ exceptions,
35335
35700
  resolutions: new SqliteResolutionsRepository(db),
35336
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
35701
+ ruleProbeCache,
35337
35702
  bodyRetention: new SqliteBodyRetentionRepository(db),
35338
35703
  security: new SqliteSecurityRepository(db),
35339
35704
  detections: new SqliteDetectionsRepository(db),
@@ -35351,6 +35716,13 @@ function openAndInitialize(file2, base, skipTags) {
35351
35716
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35352
35717
  configInventory: new SqliteConfigInventoryRepository(db)
35353
35718
  };
35719
+ modPolicy.current = {
35720
+ installedRuleset: () => installedPacks.installedRuleset(),
35721
+ readPolicies: () => policies.listPolicies(),
35722
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
35723
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
35724
+ bundledRegexMatchers: () => shippedRegexMatchers2
35725
+ };
35354
35726
  policies.seedDefaults();
35355
35727
  return { db, ...repositories };
35356
35728
  } catch (err) {
@@ -35362,7 +35734,7 @@ function openAndInitialize(file2, base, skipTags) {
35362
35734
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35363
35735
  function openLocalDatabase(dir, options = {}) {
35364
35736
  ensureDataDirSync(dir);
35365
- const file2 = join7(dir, DB_FILENAME);
35737
+ const file2 = join8(dir, DB_FILENAME);
35366
35738
  reapStalePartials(file2);
35367
35739
  const {
35368
35740
  db,
@@ -35398,7 +35770,8 @@ function openLocalDatabase(dir, options = {}) {
35398
35770
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35399
35771
  // settings/ and data/, and the pack-policy floor needs both halves.
35400
35772
  dirname2(dir),
35401
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
35773
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
35774
+ options.shippedRegexMatchers ?? []
35402
35775
  );
35403
35776
  function captureRowId(event) {
35404
35777
  return captureId(
@@ -35663,7 +36036,7 @@ function openLocalDatabase(dir, options = {}) {
35663
36036
  }
35664
36037
 
35665
36038
  // ../../packages/persistence/src/egress-wire.ts
35666
- import { createHash as createHash3 } from "crypto";
36039
+ import { createHash as createHash4 } from "crypto";
35667
36040
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35668
36041
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35669
36042
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35695,7 +36068,7 @@ function canonicalGitUrl(url2) {
35695
36068
  }
35696
36069
  function hashProjectKey(projectKey) {
35697
36070
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35698
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
36071
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35699
36072
  }
35700
36073
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35701
36074
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35760,17 +36133,16 @@ function toEgressIngestRequest(input2) {
35760
36133
  }
35761
36134
 
35762
36135
  // ../../packages/persistence/src/finding-key.ts
35763
- import { createHash as createHash4 } from "crypto";
36136
+ import { createHash as createHash5 } from "crypto";
35764
36137
 
35765
36138
  // ../../packages/persistence/src/fingerprint.ts
35766
36139
  import { createHmac, randomBytes } from "crypto";
35767
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35768
- import { join as join8 } from "path";
35769
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
36140
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
36141
+ import { join as join9 } from "path";
35770
36142
  var EXCEPTION_KEY_FILENAME = "exception.key";
35771
36143
  var KEY_MATERIAL_BYTES = 32;
35772
36144
  function keyFilePath(dataDir2) {
35773
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
36145
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35774
36146
  }
35775
36147
  function parseKeyFile(raw) {
35776
36148
  const parsed2 = JSON.parse(raw);
@@ -35793,7 +36165,7 @@ function parseKeyFile(raw) {
35793
36165
  function readFingerprintKey(dataDir2) {
35794
36166
  let raw;
35795
36167
  try {
35796
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
36168
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35797
36169
  } catch (err) {
35798
36170
  if (err.code === "ENOENT") return null;
35799
36171
  throw err instanceof Error ? err : new Error(String(err));
@@ -35802,8 +36174,8 @@ function readFingerprintKey(dataDir2) {
35802
36174
  }
35803
36175
 
35804
36176
  // ../../packages/persistence/src/forward-health.ts
35805
- import { readFileSync as readFileSync7 } from "fs";
35806
- import { join as join9 } from "path";
36177
+ import { readFileSync as readFileSync8 } from "fs";
36178
+ import { join as join10 } from "path";
35807
36179
  var BREAKER_COOLDOWN_MS = 3e4;
35808
36180
  function parseForwardHealth(raw, nowMs) {
35809
36181
  try {
@@ -35827,20 +36199,21 @@ function isForwardPaused(health, nowMs) {
35827
36199
 
35828
36200
  // ../../packages/persistence/src/history-backfill.ts
35829
36201
  import { existsSync as existsSync4 } from "fs";
35830
- import { join as join10 } from "path";
36202
+ import { join as join11 } from "path";
35831
36203
 
35832
36204
  // ../../packages/persistence/src/history-preview.ts
35833
36205
  import { existsSync as existsSync5 } from "fs";
35834
- import { join as join11 } from "path";
35835
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36206
+ import { join as join12 } from "path";
36207
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35836
36208
 
35837
36209
  // ../../packages/persistence/src/history-sync-state.ts
35838
- import { readFileSync as readFileSync8 } from "fs";
35839
- import { join as join12 } from "path";
36210
+ import { readFileSync as readFileSync9 } from "fs";
36211
+ import { join as join13 } from "path";
36212
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35840
36213
 
35841
36214
  // ../../packages/persistence/src/store-symlinks.ts
35842
36215
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35843
- import { dirname as dirname3, join as join13, resolve } from "path";
36216
+ import { dirname as dirname3, join as join14, resolve } from "path";
35844
36217
  var STORE_DB = "the store database (including the prompt corpus)";
35845
36218
  var STORE_SETTINGS = "your settings file";
35846
36219
  function storeContents(home) {
@@ -35849,7 +36222,7 @@ function storeContents(home) {
35849
36222
  [settingsDir(home), STORE_SETTINGS],
35850
36223
  [dataDir(home), STORE_DB],
35851
36224
  [keysDir(home), "the vault key"],
35852
- [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
36225
+ [join14(settingsDir(home), "settings.json"), STORE_SETTINGS],
35853
36226
  [dbPath(home), STORE_DB]
35854
36227
  ]);
35855
36228
  }
@@ -35901,19 +36274,19 @@ import {
35901
36274
  // ../../packages/persistence/src/vault/key-provider.ts
35902
36275
  import { execFileSync } from "child_process";
35903
36276
  import { randomBytes as randomBytes2 } from "crypto";
35904
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35905
- import { join as join14 } from "path";
36277
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
36278
+ import { join as join15 } from "path";
35906
36279
 
35907
36280
  // ../../packages/persistence/src/vault/vault.ts
35908
36281
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35909
36282
 
35910
36283
  // ../../packages/persistence/src/warn-era-cap.ts
35911
36284
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35912
- import { join as join15 } from "path";
36285
+ import { join as join16 } from "path";
35913
36286
  var MARKER = "warn-era-capped";
35914
36287
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35915
36288
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35916
- const marker = join15(dataDir2, MARKER);
36289
+ const marker = join16(dataDir2, MARKER);
35917
36290
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35918
36291
  const capped = db.policies.capCategoryActions();
35919
36292
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35921,425 +36294,6 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35921
36294
  return { capped };
35922
36295
  }
35923
36296
 
35924
- // ../../packages/remote/src/http.ts
35925
- import { request as httpRequest } from "http";
35926
- import { request as httpsRequest } from "https";
35927
- var DEFAULT_TIMEOUT_MS = 1e4;
35928
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35929
- var RemoteRequestError = class extends Error {
35930
- constructor(status) {
35931
- super(`control-plane request failed with status ${String(status)}`);
35932
- this.status = status;
35933
- this.name = "RemoteRequestError";
35934
- }
35935
- status;
35936
- };
35937
- var RemoteRouteAbsent = class extends Error {
35938
- constructor(route) {
35939
- super(`control plane does not serve ${route}`);
35940
- this.route = route;
35941
- this.name = "RemoteRouteAbsent";
35942
- }
35943
- route;
35944
- };
35945
- var RemoteRequestInvalid = class extends Error {
35946
- constructor(route, cause) {
35947
- super(`refusing to send a malformed body to ${route}`);
35948
- this.cause = cause;
35949
- this.name = "RemoteRequestInvalid";
35950
- }
35951
- cause;
35952
- };
35953
- var RemoteEndpointRefused = class extends Error {
35954
- constructor(endpoint) {
35955
- super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
35956
- this.name = "RemoteEndpointRefused";
35957
- }
35958
- };
35959
- var RemoteResponseInvalid = class extends Error {
35960
- constructor(route, detail) {
35961
- super(`control plane answered ${route} with ${detail}`);
35962
- this.name = "RemoteResponseInvalid";
35963
- }
35964
- };
35965
- var RemoteTransportError = class extends Error {
35966
- /**
35967
- * The status the peer sent, when headers arrived and only the BODY was
35968
- * refused.
35969
- *
35970
- * Undefined for the ordinary case this class was written for — no answer at
35971
- * all. It exists because two paths reject after a status has already been
35972
- * delivered: an oversized body and an aborted response. Discarding it there
35973
- * reported a deployment answering 401 with a verbose body as a network
35974
- * outage, which sends the reader to look at their network instead of their
35975
- * credential.
35976
- */
35977
- constructor(reason, status) {
35978
- super(`control-plane request did not complete: ${reason}`);
35979
- this.status = status;
35980
- this.name = "RemoteTransportError";
35981
- }
35982
- status;
35983
- };
35984
- async function send(options) {
35985
- const url2 = new URL(options.url);
35986
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35987
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
35988
- const requestOptions = {
35989
- method: options.method,
35990
- headers: {
35991
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
35992
- // last they win, and two of the values below are ones no caller may
35993
- // replace: `x-api-key` is the credential, and `content-length` is the
35994
- // byte count that stops a multi-byte body being truncated by the
35995
- // receiver. `SendOptions.headers` is a free-form record on an exported
35996
- // function, so "no caller does that today" is not the guarantee to rely
35997
- // on. The one header any caller actually passes — `if-none-match` on the
35998
- // conditional GET — is untouched by this order.
35999
- ...options.headers,
36000
- // The credential. One header, matching what the deployment authenticates
36001
- // on; a second copy in an `Authorization` header would be one more place
36002
- // it can be logged by an intermediary for no gain.
36003
- //
36004
- // Spread conditionally rather than assigned as `undefined`: Node's header
36005
- // handling and `content-length` bookkeeping treat a present-but-undefined
36006
- // key differently from an absent one, and "the header is not there" is
36007
- // the property the attach flow needs.
36008
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
36009
- accept: "application/json",
36010
- ...options.body === void 0 ? {} : {
36011
- "content-type": "application/json",
36012
- // Byte length, not string length: a multi-byte body sent with a
36013
- // character count is truncated by the receiver.
36014
- "content-length": String(Buffer.byteLength(options.body))
36015
- }
36016
- }
36017
- };
36018
- return new Promise((resolve3, reject) => {
36019
- let settled = false;
36020
- const fail = (reason, status) => {
36021
- if (settled) return;
36022
- settled = true;
36023
- reject(new RemoteTransportError(reason, status));
36024
- };
36025
- const req = send_(url2, requestOptions, (res) => {
36026
- const chunks = [];
36027
- let size = 0;
36028
- res.on("data", (chunk) => {
36029
- size += chunk.length;
36030
- if (size > MAX_RESPONSE_BYTES) {
36031
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
36032
- res.destroy();
36033
- req.destroy();
36034
- return;
36035
- }
36036
- chunks.push(chunk);
36037
- });
36038
- res.on("aborted", () => {
36039
- fail("the response was aborted", res.statusCode);
36040
- });
36041
- res.on("end", () => {
36042
- if (settled) return;
36043
- settled = true;
36044
- resolve3({
36045
- status: res.statusCode ?? 0,
36046
- headers: res.headers,
36047
- body: Buffer.concat(chunks).toString("utf8")
36048
- });
36049
- });
36050
- });
36051
- const deadline = setTimeout(() => {
36052
- fail(`no response within ${String(timeoutMs)}ms`);
36053
- req.destroy();
36054
- }, timeoutMs);
36055
- deadline.unref();
36056
- req.on("upgrade", (_res, socket) => {
36057
- fail("the deployment answered with a protocol upgrade");
36058
- socket.destroy();
36059
- });
36060
- req.on("close", () => {
36061
- fail("the connection closed before a response was read");
36062
- clearTimeout(deadline);
36063
- });
36064
- req.on("error", (err) => {
36065
- fail(err.message);
36066
- });
36067
- if (options.body !== void 0) req.write(options.body);
36068
- req.end();
36069
- });
36070
- }
36071
-
36072
- // ../../packages/remote/src/client.ts
36073
- var ROUTES = {
36074
- events: "/v1/events",
36075
- auditEvents: "/v1/audit-events",
36076
- auditEventsBatch: "/v1/audit-events/batch",
36077
- inventory: "/v1/inventory",
36078
- storePosture: "/v1/store-posture",
36079
- policyBundle: "/v1/policy-bundle",
36080
- whoami: "/v1/plugin/whoami",
36081
- shares: "/v1/shares",
36082
- commands: "/v1/plugin/commands"
36083
- };
36084
- function ackRoute(id) {
36085
- return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
36086
- }
36087
- function headerValue(response, name) {
36088
- const raw = response.headers[name];
36089
- if (raw === void 0) return void 0;
36090
- return Array.isArray(raw) ? raw[0] : raw;
36091
- }
36092
- function okBody(response) {
36093
- if (response.status < 200 || response.status >= 300) {
36094
- throw new RemoteRequestError(response.status);
36095
- }
36096
- return response.body;
36097
- }
36098
- function parsed(schema, body, route) {
36099
- let json2;
36100
- try {
36101
- json2 = JSON.parse(body);
36102
- } catch {
36103
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
36104
- }
36105
- const result = schema.safeParse(json2);
36106
- if (!result.success) {
36107
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
36108
- }
36109
- return result.data;
36110
- }
36111
- function resolveBaseUrl(endpoint) {
36112
- if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
36113
- let end = endpoint.length;
36114
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
36115
- return endpoint.slice(0, end);
36116
- }
36117
- var SLASH2 = "/".charCodeAt(0);
36118
- function createRemoteClient(options) {
36119
- const base = resolveBaseUrl(options.endpoint);
36120
- const url2 = (route) => `${base}${route}`;
36121
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
36122
- const sendOne = async (event) => {
36123
- const validated = RecordAuditEventRequest.safeParse(event);
36124
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
36125
- const response = await send({
36126
- ...common,
36127
- method: "POST",
36128
- url: url2(ROUTES.auditEvents),
36129
- body: JSON.stringify(validated.data)
36130
- });
36131
- okBody(response);
36132
- };
36133
- return {
36134
- async ingestEvents(batch) {
36135
- const response = await send({
36136
- ...common,
36137
- method: "POST",
36138
- url: url2(ROUTES.events),
36139
- body: JSON.stringify(batch)
36140
- });
36141
- return parsed(IngestAck, okBody(response), ROUTES.events);
36142
- },
36143
- async ingestInventory(context) {
36144
- const response = await send({
36145
- ...common,
36146
- method: "POST",
36147
- url: url2(ROUTES.inventory),
36148
- body: JSON.stringify(context)
36149
- });
36150
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
36151
- },
36152
- async recordAuditEvent(event) {
36153
- await sendOne(event);
36154
- },
36155
- async recordAuditEvents(events, opts) {
36156
- const validated = RecordAuditEventBatch.safeParse({ events });
36157
- if (!validated.success) {
36158
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
36159
- }
36160
- const response = await send({
36161
- ...common,
36162
- method: "POST",
36163
- url: url2(ROUTES.auditEventsBatch),
36164
- body: JSON.stringify(validated.data)
36165
- });
36166
- if (response.status === 404) {
36167
- if (opts?.fallbackToSingleEvents !== true) {
36168
- throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
36169
- }
36170
- for (const event of validated.data.events) await sendOne(event);
36171
- return { accepted: validated.data.events.length };
36172
- }
36173
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
36174
- },
36175
- async reportStorePosture(snapshot) {
36176
- const response = await send({
36177
- ...common,
36178
- method: "POST",
36179
- url: url2(ROUTES.storePosture),
36180
- body: JSON.stringify(snapshot)
36181
- });
36182
- okBody(response);
36183
- },
36184
- async getPolicyBundle(etag) {
36185
- const response = await send({
36186
- ...common,
36187
- method: "GET",
36188
- url: url2(ROUTES.policyBundle),
36189
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
36190
- });
36191
- if (response.status === 304) {
36192
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
36193
- }
36194
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
36195
- return { changed: true, bundle, etag: headerValue(response, "etag") };
36196
- },
36197
- async whoami() {
36198
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
36199
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
36200
- },
36201
- async recordProjectEgress(request) {
36202
- const validated = EgressIngestRequest.safeParse(request);
36203
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
36204
- const response = await send({
36205
- ...common,
36206
- method: "POST",
36207
- url: url2(ROUTES.shares),
36208
- body: JSON.stringify(validated.data)
36209
- });
36210
- if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
36211
- okBody(response);
36212
- },
36213
- async pollCommand() {
36214
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
36215
- if (response.status === 404) return null;
36216
- return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
36217
- },
36218
- async ackCommand(id, body) {
36219
- const validated = DeviceCommandAckBody.safeParse(body);
36220
- const route = ackRoute(id);
36221
- if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
36222
- const response = await send({
36223
- ...common,
36224
- method: "POST",
36225
- url: url2(route),
36226
- body: JSON.stringify(validated.data)
36227
- });
36228
- okBody(response);
36229
- }
36230
- };
36231
- }
36232
-
36233
- // ../../packages/remote/src/failure-kind.ts
36234
- function statusOf(err) {
36235
- if (typeof err !== "object" || err === null || !("status" in err)) return null;
36236
- const { status } = err;
36237
- if (typeof status !== "number" || !Number.isInteger(status)) return null;
36238
- return status >= 100 && status <= 599 ? status : null;
36239
- }
36240
- function nameOf(err) {
36241
- if (typeof err !== "object" || err === null || !("name" in err)) return null;
36242
- return typeof err.name === "string" ? err.name : null;
36243
- }
36244
- function classifyRemoteFailure(err) {
36245
- switch (nameOf(err)) {
36246
- case "RemoteRouteAbsent":
36247
- return "route-absent";
36248
- case "RemoteRequestInvalid":
36249
- case "RemoteEndpointRefused":
36250
- return "invalid-request";
36251
- case "RemoteResponseInvalid":
36252
- return "rejected";
36253
- default:
36254
- break;
36255
- }
36256
- const status = statusOf(err);
36257
- if (status === null) return "unreachable";
36258
- switch (status) {
36259
- case 401:
36260
- return "unauthorized";
36261
- case 403:
36262
- return "forbidden";
36263
- case 429:
36264
- return "unreachable";
36265
- case 404:
36266
- return "unreachable";
36267
- default:
36268
- return status >= 400 && status <= 499 ? "rejected" : "unreachable";
36269
- }
36270
- }
36271
-
36272
- // ../../packages/plugin-runtime/src/attached/failure.ts
36273
- function classifyFailure(err) {
36274
- switch (classifyRemoteFailure(err)) {
36275
- case "unauthorized":
36276
- return "unauthorized";
36277
- case "forbidden":
36278
- return "forbidden";
36279
- default:
36280
- return "unreachable";
36281
- }
36282
- }
36283
-
36284
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36285
- var REQUEST_TIMEOUT_MS = 2e3;
36286
- function withTimeout(promise2, ms) {
36287
- let timer;
36288
- const timeout = new Promise((_, reject) => {
36289
- timer = setTimeout(() => {
36290
- reject(new Error("attached gateway request timed out"));
36291
- }, ms);
36292
- });
36293
- promise2.catch(() => void 0);
36294
- return Promise.race([promise2, timeout]).finally(() => {
36295
- clearTimeout(timer);
36296
- });
36297
- }
36298
-
36299
- // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36300
- import { readFileSync as readFileSync10 } from "fs";
36301
- import { join as join16 } from "path";
36302
- var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36303
- function forwardDropsPath(dataDir2) {
36304
- return join16(dataDir2, FORWARD_DROPS_FILENAME);
36305
- }
36306
- function recordForwardDrops(dataDir2, count, nowMs) {
36307
- if (count <= 0) return;
36308
- try {
36309
- ensureDataDirSync(dataDir2);
36310
- const previous = readForwardDrops(dataDir2);
36311
- const next = {
36312
- droppedForwards: (previous?.droppedForwards ?? 0) + count,
36313
- lastDropAtMs: nowMs
36314
- };
36315
- writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
36316
- `);
36317
- } catch {
36318
- }
36319
- }
36320
- function readForwardDrops(dataDir2) {
36321
- try {
36322
- const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
36323
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36324
- const record2 = parsed2;
36325
- if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
36326
- return null;
36327
- }
36328
- if (record2.droppedForwards <= 0) return null;
36329
- if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
36330
- return null;
36331
- }
36332
- return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
36333
- } catch {
36334
- return null;
36335
- }
36336
- }
36337
-
36338
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36339
- import { randomUUID as randomUUID16 } from "crypto";
36340
- import { readFile, rename, writeFile } from "fs/promises";
36341
- import { join as join28 } from "path";
36342
-
36343
36297
  // ../../packages/plugin-sdk/src/config.ts
36344
36298
  import { existsSync as existsSync8 } from "fs";
36345
36299
  import { join as join17 } from "path";
@@ -37534,17 +37488,18 @@ function ruleEvidence(rule) {
37534
37488
 
37535
37489
  // ../../packages/detections/src/mask.ts
37536
37490
  function maskMatch(raw) {
37537
- if (raw.length <= 5) return "***";
37538
- const atIndex = raw.indexOf("@");
37539
- if (atIndex > 0 && atIndex < raw.length - 1) {
37540
- const domain2 = raw.slice(atIndex + 1);
37491
+ const visible = stripInvisiblePadding(raw);
37492
+ if (visible.length <= 5) return "***";
37493
+ const atIndex = visible.indexOf("@");
37494
+ if (atIndex > 0 && atIndex < visible.length - 1) {
37495
+ const domain2 = visible.slice(atIndex + 1);
37541
37496
  if (domain2.includes(".")) {
37542
- const local = raw.slice(0, atIndex);
37497
+ const local = visible.slice(0, atIndex);
37543
37498
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
37544
37499
  return `${maskedLocal}@${domain2}`;
37545
37500
  }
37546
37501
  }
37547
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
37502
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
37548
37503
  }
37549
37504
 
37550
37505
  // ../../packages/detections/src/pointer-shield.ts
@@ -37779,8 +37734,95 @@ var EXPONENTIAL_PROBES = EXPONENTIAL_UNITS.flatMap(
37779
37734
  var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map(
37780
37735
  (unit) => unit.repeat(1e4).slice(0, 4e4) + "!"
37781
37736
  );
37737
+ function literalPrefix(pattern) {
37738
+ let prefix = "";
37739
+ let i = 0;
37740
+ if (pattern[i] === "^") i++;
37741
+ while (i < pattern.length) {
37742
+ const c = pattern[i];
37743
+ if (c === void 0) break;
37744
+ if (c === "\\") {
37745
+ const next = pattern[i + 1];
37746
+ if (next === "b" || next === "B") {
37747
+ i += 2;
37748
+ continue;
37749
+ }
37750
+ if (next === void 0 || /[dDwWsSnrtfv.]/.test(next)) break;
37751
+ prefix += next;
37752
+ i += 2;
37753
+ continue;
37754
+ }
37755
+ if ("([{.*+?|)]}^$".includes(c)) break;
37756
+ prefix += c;
37757
+ i++;
37758
+ }
37759
+ return prefix;
37760
+ }
37761
+ function fuelChars(pattern) {
37762
+ const fuel = /* @__PURE__ */ new Set();
37763
+ for (const m of pattern.matchAll(/\[\^?([^\]]+)\]/g)) {
37764
+ const body = m[1];
37765
+ if (body === void 0) continue;
37766
+ const range = /([A-Za-z0-9])-[A-Za-z0-9]/.exec(body);
37767
+ const rangeStart = range?.[1];
37768
+ if (rangeStart !== void 0) fuel.add(rangeStart);
37769
+ else {
37770
+ const literal2 = body.replace(/\\/g, "")[0];
37771
+ if (literal2 !== void 0 && literal2 !== "^") fuel.add(literal2);
37772
+ }
37773
+ }
37774
+ if (pattern.includes("\\w")) fuel.add("a");
37775
+ if (pattern.includes("\\d")) fuel.add("0");
37776
+ if (pattern.includes("\\s")) fuel.add(" ");
37777
+ if (/(?<!\\)\./.test(pattern)) fuel.add("a");
37778
+ if (fuel.size === 0) fuel.add("a");
37779
+ return [...fuel];
37780
+ }
37781
+ function derivedProbes(pattern) {
37782
+ const prefix = literalPrefix(pattern);
37783
+ const fuel = fuelChars(pattern);
37784
+ const terminators = ["!", "#", "~", "\n"];
37785
+ const probes = [];
37786
+ for (const f of fuel) {
37787
+ for (const term of terminators) {
37788
+ if (term === f) continue;
37789
+ for (const len of [23, 25]) probes.push(prefix + f.repeat(len) + term);
37790
+ }
37791
+ }
37792
+ return probes;
37793
+ }
37794
+ function probesFor(rule) {
37795
+ const derived2 = rule.matcher.type === "regex" ? derivedProbes(rule.matcher.pattern) : [];
37796
+ return [...derived2, ...EXPONENTIAL_PROBES, ...POLYNOMIAL_PROBES];
37797
+ }
37798
+ var wallClock = () => performance.now();
37799
+ function worstProbeMs(rule, now = wallClock, corroborate) {
37800
+ let ms = 0;
37801
+ let probe = "";
37802
+ let corroboratedMs;
37803
+ for (const text of probesFor(rule)) {
37804
+ const start = now();
37805
+ const corroborateStart = corroborate?.();
37806
+ scan(text, [rule]);
37807
+ const elapsed = now() - start;
37808
+ const corroborateEnd = corroborate?.();
37809
+ if (elapsed > ms) {
37810
+ ms = elapsed;
37811
+ probe = text;
37812
+ corroboratedMs = corroborateStart === void 0 || corroborateEnd === void 0 ? void 0 : corroborateEnd - corroborateStart;
37813
+ }
37814
+ if (ms >= BUDGET_MS) break;
37815
+ }
37816
+ return { ms, probe, corroboratedMs };
37817
+ }
37782
37818
  var CPU_CORROBORATION_SHARE = 0.2;
37783
37819
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
37820
+ function checkRuleTiming(rule, corroborate) {
37821
+ const { ms, probe, corroboratedMs } = worstProbeMs(rule, wallClock, corroborate);
37822
+ const work = corroboratedMs ?? 0;
37823
+ const verdict = ms < BUDGET_MS ? "safe" : work >= CORROBORATION_FLOOR_MS ? "over-budget" : "uncorroborated";
37824
+ return { verdict, worstMs: ms, corroboratedMs: work, probe };
37825
+ }
37784
37826
 
37785
37827
  // ../../packages/plugin-sdk/src/raw-egress.ts
37786
37828
  var RawEgressError = class extends Error {
@@ -37801,7 +37843,12 @@ var MIN_RAW_LEN = 4;
37801
37843
  var RAW_RUN_LEN = 8;
37802
37844
  function carriesRawRun(text, rawValues) {
37803
37845
  let windows = null;
37804
- for (const raw of new Set(rawValues)) {
37846
+ const values = /* @__PURE__ */ new Set();
37847
+ for (const raw of rawValues) {
37848
+ values.add(raw);
37849
+ values.add(stripInvisiblePadding(raw));
37850
+ }
37851
+ for (const raw of values) {
37805
37852
  if (raw.length < MIN_RAW_LEN) continue;
37806
37853
  if (raw.length < RAW_RUN_LEN) {
37807
37854
  if (text.includes(raw)) return true;
@@ -37825,11 +37872,16 @@ function carriesRawRun(text, rawValues) {
37825
37872
  return false;
37826
37873
  }
37827
37874
  function safeMaskedMatch(rawMatch) {
37828
- const masked = maskMatch(rawMatch);
37829
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37830
- return "***";
37875
+ const visible = stripInvisiblePadding(rawMatch);
37876
+ const masked = maskMatch(visible);
37877
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
37878
+ if (!reveals(masked)) return masked;
37879
+ const atIndex = masked.indexOf("@");
37880
+ if (atIndex > 0 && atIndex < masked.length - 1) {
37881
+ const emailFallback = `*${masked.slice(atIndex)}`;
37882
+ if (!reveals(emailFallback)) return emailFallback;
37831
37883
  }
37832
- return masked;
37884
+ return "***";
37833
37885
  }
37834
37886
  function assertRawFree(text, rawValues) {
37835
37887
  if (carriesRawRun(text, rawValues)) {
@@ -40271,6 +40323,11 @@ function bundledDetections() {
40271
40323
  }));
40272
40324
  return cachedDetections;
40273
40325
  }
40326
+ function shippedRegexMatchers() {
40327
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
40328
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
40329
+ );
40330
+ }
40274
40331
 
40275
40332
  // ../../packages/plugin-sdk/src/mask.ts
40276
40333
  var packsReady = false;
@@ -40346,8 +40403,9 @@ function resolveRepoIdentity(cwd) {
40346
40403
  var ATTRIBUTION_MEMO_LIMIT = 64;
40347
40404
  var attributionMemo = /* @__PURE__ */ new Map();
40348
40405
  var NO_ATTRIBUTION = Object.freeze({});
40349
- function resolveRepoAttribution(cwd) {
40406
+ function resolveRepoAttribution(cwd, options) {
40350
40407
  try {
40408
+ if (options?.cache === false) return attributeRepo(cwd);
40351
40409
  const remembered = attributionMemo.get(cwd);
40352
40410
  if (remembered !== void 0) return remembered;
40353
40411
  const attribution = attributeRepo(cwd);
@@ -40662,7 +40720,7 @@ function collectUserClaudeJson(scan2, path, cwd, repoIdentity) {
40662
40720
  }
40663
40721
  function projectEntryFor(projects, cwd) {
40664
40722
  const candidates = /* @__PURE__ */ new Set([cwd]);
40665
- const trimmed = cwd.replace(/\/+$/, "");
40723
+ const trimmed = withoutTrailingSlashes2(cwd);
40666
40724
  if (trimmed.length > 0) candidates.add(trimmed);
40667
40725
  try {
40668
40726
  candidates.add(realpathSync2(cwd));
@@ -40674,6 +40732,12 @@ function projectEntryFor(projects, cwd) {
40674
40732
  }
40675
40733
  return void 0;
40676
40734
  }
40735
+ var SLASH2 = "/".charCodeAt(0);
40736
+ function withoutTrailingSlashes2(path) {
40737
+ let end = path.length;
40738
+ while (end > 0 && path.charCodeAt(end - 1) === SLASH2) end -= 1;
40739
+ return path.slice(0, end);
40740
+ }
40677
40741
  function collectPluginManifestMcp(scan2, installPath, origin) {
40678
40742
  const manifestPath = join19(installPath, ".claude-plugin", "plugin.json");
40679
40743
  const raw = readOptional(manifestPath);
@@ -40823,10 +40887,10 @@ function parseFrontmatter(raw) {
40823
40887
  if (lines[0]?.trim() !== "---") return out;
40824
40888
  for (const line of lines.slice(1)) {
40825
40889
  if (line.trim() === "---") break;
40826
- const sep4 = line.indexOf(":");
40827
- if (sep4 === -1) continue;
40828
- const key = line.slice(0, sep4).trim();
40829
- const value = line.slice(sep4 + 1).trim().replace(/^['"]|['"]$/g, "");
40890
+ const sep3 = line.indexOf(":");
40891
+ if (sep3 === -1) continue;
40892
+ const key = line.slice(0, sep3).trim();
40893
+ const value = line.slice(sep3 + 1).trim().replace(/^['"]|['"]$/g, "");
40830
40894
  if (value === "") continue;
40831
40895
  if (key === "name") out.name = value;
40832
40896
  else if (key === "description") out.description = value;
@@ -40985,12 +41049,402 @@ function offersMaintenance(gateway, member) {
40985
41049
  }
40986
41050
 
40987
41051
  // ../../packages/plugin-sdk/src/events.ts
40988
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
41052
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
41053
+ function contentHashOf(text) {
41054
+ return createHash6("sha256").update(text).digest("hex");
41055
+ }
40989
41056
 
40990
41057
  // ../../packages/plugin-sdk/src/isolated-scan.ts
40991
41058
  import { existsSync as existsSync10 } from "fs";
40992
41059
  import { fileURLToPath } from "url";
40993
41060
  import { Worker } from "worker_threads";
41061
+ var ISOLATED_SCAN_BUDGET_MS = 2e3;
41062
+ var ISOLATED_PROBE_BUDGET_MS = 1e3;
41063
+ var ISOLATED_START_BUDGET_MS = 5e3;
41064
+ var ATTRIBUTION_MIN_RULE_MS = 500;
41065
+ var ATTRIBUTION_MIN_SHARE = 0.5;
41066
+ var resolvedWorkerUrl;
41067
+ function resolveWorkerUrl() {
41068
+ if (resolvedWorkerUrl !== void 0) return resolvedWorkerUrl ?? void 0;
41069
+ resolvedWorkerUrl = null;
41070
+ try {
41071
+ const built = new URL(
41072
+ /* webpackIgnore: true */
41073
+ "./scan-worker.js",
41074
+ import.meta.url
41075
+ );
41076
+ for (const candidate of [built, sourceTwin(built)]) {
41077
+ if (existsSync10(fileURLToPath(candidate))) {
41078
+ resolvedWorkerUrl = candidate;
41079
+ break;
41080
+ }
41081
+ }
41082
+ } catch {
41083
+ }
41084
+ return resolvedWorkerUrl ?? void 0;
41085
+ }
41086
+ function sourceTwin(url2) {
41087
+ const twin = new URL(url2);
41088
+ twin.pathname = twin.pathname.replace(/\.js$/, ".ts");
41089
+ return twin;
41090
+ }
41091
+ function messageOf(error62) {
41092
+ return error62 instanceof Error ? error62.message : String(error62);
41093
+ }
41094
+ function createIsolatedScanner(data, opts = {}) {
41095
+ const budgetMs = opts.budgetMs ?? ISOLATED_SCAN_BUDGET_MS;
41096
+ const probeBudgetMs = opts.probeBudgetMs ?? ISOLATED_PROBE_BUDGET_MS;
41097
+ const startBudgetMs = opts.startBudgetMs ?? ISOLATED_START_BUDGET_MS;
41098
+ const minAttributionMs = opts.minAttributionMs ?? ATTRIBUTION_MIN_RULE_MS;
41099
+ let worker;
41100
+ let readyWorker;
41101
+ let broken;
41102
+ let closed = false;
41103
+ let nextJobId = 1;
41104
+ let pending;
41105
+ const terminating = /* @__PURE__ */ new Set();
41106
+ let chain = Promise.resolve();
41107
+ function clearTimers(job) {
41108
+ if (job.startupTimer !== void 0) clearTimeout(job.startupTimer);
41109
+ if (job.timer !== void 0) clearTimeout(job.timer);
41110
+ }
41111
+ function take() {
41112
+ const job = pending;
41113
+ if (!job) return void 0;
41114
+ pending = void 0;
41115
+ clearTimers(job);
41116
+ worker?.unref();
41117
+ return job;
41118
+ }
41119
+ function failPending(outcome) {
41120
+ take()?.fail(outcome);
41121
+ }
41122
+ function kill(dead) {
41123
+ if (worker === dead) worker = void 0;
41124
+ if (readyWorker === dead) readyWorker = void 0;
41125
+ const done = dead.terminate().catch(() => void 0);
41126
+ terminating.add(done);
41127
+ void done.finally(() => terminating.delete(done));
41128
+ }
41129
+ function onDeadline(job) {
41130
+ if (pending !== job) return;
41131
+ const now = performance.now();
41132
+ const runningMs = now - job.progressAt;
41133
+ const elapsedMs = now - job.startedAt;
41134
+ const blamed = job.progressIndex >= 0 && runningMs >= minAttributionMs && runningMs >= elapsedMs * ATTRIBUTION_MIN_SHARE;
41135
+ const culpritIndex = blamed ? job.progressIndex : void 0;
41136
+ kill(job.worker);
41137
+ failPending({ status: "timeout", culpritIndex, elapsedMs });
41138
+ }
41139
+ function ensureWorker() {
41140
+ if (worker) return worker;
41141
+ const url2 = opts.workerUrl ?? resolveWorkerUrl();
41142
+ if (!url2) {
41143
+ return {
41144
+ error: "the scan worker script was not found next to this bundle"
41145
+ };
41146
+ }
41147
+ let started;
41148
+ try {
41149
+ started = new Worker(url2, { workerData: data });
41150
+ } catch (error62) {
41151
+ return { error: `could not start the scan worker: ${messageOf(error62)}` };
41152
+ }
41153
+ opts.onWorkerStart?.(started.threadId);
41154
+ started.on("message", (message2) => {
41155
+ if (worker !== started) return;
41156
+ if (message2.kind === "ready") {
41157
+ readyWorker = started;
41158
+ if (pending?.worker === started) beginDeadline(pending);
41159
+ return;
41160
+ }
41161
+ if (message2.kind === "progress") {
41162
+ if (pending?.worker === started) {
41163
+ pending.progressIndex = message2.index;
41164
+ pending.progressAt = performance.now();
41165
+ }
41166
+ return;
41167
+ }
41168
+ if (pending?.id !== message2.id) return;
41169
+ if (message2.kind === "failed") {
41170
+ failPending({
41171
+ status: "unavailable",
41172
+ reason: `the scan worker failed: ${message2.message}`
41173
+ });
41174
+ return;
41175
+ }
41176
+ const job = take();
41177
+ if (job && !job.reply(message2)) {
41178
+ job.fail({ status: "unavailable", reason: "the scan worker answered the wrong job" });
41179
+ }
41180
+ });
41181
+ started.on("error", (error62) => {
41182
+ if (worker !== started) return;
41183
+ broken = messageOf(error62);
41184
+ worker = void 0;
41185
+ if (readyWorker === started) readyWorker = void 0;
41186
+ failPending({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
41187
+ });
41188
+ started.on("exit", () => {
41189
+ if (worker !== started) return;
41190
+ broken ??= "the scan worker exited before answering";
41191
+ worker = void 0;
41192
+ if (readyWorker === started) readyWorker = void 0;
41193
+ failPending({ status: "unavailable", reason: "the scan worker exited before answering" });
41194
+ });
41195
+ started.unref();
41196
+ worker = started;
41197
+ return started;
41198
+ }
41199
+ function beginDeadline(job) {
41200
+ if (job.startupTimer !== void 0) {
41201
+ clearTimeout(job.startupTimer);
41202
+ job.startupTimer = void 0;
41203
+ }
41204
+ if (job.timer !== void 0) return;
41205
+ job.startedAt = performance.now();
41206
+ job.progressAt = job.startedAt;
41207
+ job.timer = setTimeout(() => {
41208
+ onDeadline(job);
41209
+ }, job.budgetMs);
41210
+ }
41211
+ function runOne(spec, fail) {
41212
+ if (closed) {
41213
+ fail({ status: "unavailable", reason: "the scan worker is closed" });
41214
+ return;
41215
+ }
41216
+ if (broken !== void 0) {
41217
+ fail({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
41218
+ return;
41219
+ }
41220
+ const started = ensureWorker();
41221
+ if (!(started instanceof Worker)) {
41222
+ broken = started.error;
41223
+ fail({ status: "unavailable", reason: started.error });
41224
+ return;
41225
+ }
41226
+ const id = nextJobId++;
41227
+ const now = performance.now();
41228
+ const job = {
41229
+ id,
41230
+ worker: started,
41231
+ budgetMs: spec.budgetMs,
41232
+ startedAt: now,
41233
+ progressIndex: -1,
41234
+ progressAt: now,
41235
+ startupTimer: void 0,
41236
+ timer: void 0,
41237
+ reply: spec.reply,
41238
+ fail
41239
+ };
41240
+ pending = job;
41241
+ started.ref();
41242
+ if (readyWorker === started) {
41243
+ beginDeadline(job);
41244
+ } else {
41245
+ job.startupTimer = setTimeout(() => {
41246
+ if (pending !== job) return;
41247
+ kill(job.worker);
41248
+ failPending({
41249
+ status: "unavailable",
41250
+ reason: `the scan worker did not start within ${String(startBudgetMs)}ms`
41251
+ });
41252
+ }, startBudgetMs);
41253
+ }
41254
+ try {
41255
+ started.postMessage(spec.build(id));
41256
+ } catch (error62) {
41257
+ failPending({
41258
+ // The thread went away between the ref and the post.
41259
+ status: "unavailable",
41260
+ reason: `could not reach the scan worker: ${messageOf(error62)}`
41261
+ });
41262
+ }
41263
+ }
41264
+ function enqueue(spec) {
41265
+ const next = chain.then(
41266
+ () => new Promise((resolve3) => {
41267
+ spec(resolve3);
41268
+ })
41269
+ );
41270
+ chain = next.then(
41271
+ () => void 0,
41272
+ () => void 0
41273
+ );
41274
+ return next;
41275
+ }
41276
+ return {
41277
+ scan(text, context, scanOpts) {
41278
+ return enqueue((resolve3) => {
41279
+ runOne(
41280
+ {
41281
+ budgetMs,
41282
+ build: (id) => ({
41283
+ kind: "scan",
41284
+ id,
41285
+ text,
41286
+ filePath: context?.filePath,
41287
+ eventKind: context?.eventKind,
41288
+ attribute: scanOpts?.attribute === true
41289
+ }),
41290
+ reply: (message2) => {
41291
+ if (message2.kind !== "result") return false;
41292
+ resolve3({ status: "ok", findings: message2.findings });
41293
+ return true;
41294
+ }
41295
+ },
41296
+ resolve3
41297
+ );
41298
+ });
41299
+ },
41300
+ probe(rule) {
41301
+ return enqueue((resolve3) => {
41302
+ runOne(
41303
+ {
41304
+ budgetMs: probeBudgetMs,
41305
+ build: (id) => ({ kind: "probe", id, rule }),
41306
+ reply: (message2) => {
41307
+ if (message2.kind !== "probed") return false;
41308
+ resolve3({
41309
+ status: "ok",
41310
+ verdict: message2.verdict,
41311
+ worstMs: message2.worstMs,
41312
+ corroboratedMs: message2.corroboratedMs
41313
+ });
41314
+ return true;
41315
+ }
41316
+ },
41317
+ resolve3
41318
+ );
41319
+ });
41320
+ },
41321
+ async close() {
41322
+ closed = true;
41323
+ const live = worker;
41324
+ worker = void 0;
41325
+ readyWorker = void 0;
41326
+ failPending({ status: "unavailable", reason: "the scan worker is closed" });
41327
+ if (live) kill(live);
41328
+ await Promise.all([...terminating]);
41329
+ }
41330
+ };
41331
+ }
41332
+
41333
+ // ../../packages/plugin-sdk/src/work-clock.ts
41334
+ function workClockMs() {
41335
+ const usage = typeof process.threadCpuUsage === "function" ? process.threadCpuUsage() : process.cpuUsage();
41336
+ return (usage.user + usage.system) / 1e3;
41337
+ }
41338
+
41339
+ // ../../packages/plugin-sdk/src/rule-quarantine.ts
41340
+ var PASS_BUDGET_MS = 2e3;
41341
+ var UNQUARANTINE_HINT = "clear it with `aka detections unquarantine`";
41342
+ function ruleProbeKey(rule) {
41343
+ if (rule.matcher.type !== "regex") return void 0;
41344
+ return contentHashOf(`${rule.matcher.pattern} ${rule.matcher.flags}`);
41345
+ }
41346
+ function warn(rule, verb, detail, recoverable) {
41347
+ const hint = recoverable ? ` (${UNQUARANTINE_HINT})` : "";
41348
+ process.stderr.write(`[aka] ${verb} rule "${rule.id}": ${detail}${hint}
41349
+ `);
41350
+ }
41351
+ function warnQuarantined(rule, worstMs, cached2) {
41352
+ warn(
41353
+ rule,
41354
+ "quarantined",
41355
+ Number.isFinite(worstMs) ? `regex matcher exceeded the ReDoS timing budget (${worstMs.toFixed(1)}ms); excluded from this scan.` : "the timing battery failed while measuring its regex matcher; excluded from this scan.",
41356
+ cached2
41357
+ );
41358
+ }
41359
+ function warnUnmeasured(rule) {
41360
+ warn(
41361
+ rule,
41362
+ "skipped",
41363
+ "the timing pre-flight ran out of time before this rule could be measured; excluded for the rest of this run, and measured again next time.",
41364
+ false
41365
+ );
41366
+ }
41367
+ function warnUncorroborated(rule, worstMs, corroboratedMs) {
41368
+ warn(
41369
+ rule,
41370
+ "deferred",
41371
+ `its regex matcher ran past the ReDoS timing budget (${worstMs.toFixed(1)}ms) but spent only ${corroboratedMs.toFixed(1)}ms of CPU doing it, which is a busy machine rather than a slow pattern; excluded from this run and measured again next time, with nothing recorded against it.`,
41372
+ false
41373
+ );
41374
+ }
41375
+ function warnUnmeasurable(reason, count) {
41376
+ process.stderr.write(
41377
+ `[aka] ${String(count)} pulled/custom-pack rule(s) could not be time-checked: ${reason}. That is a problem with this install, not with the rules \u2014 until it is fixed they are excluded from every scan on this machine. Nothing was quarantined, so reinstalling AKA brings them straight back.
41378
+ `
41379
+ );
41380
+ }
41381
+ async function filterUnsafeRules(rules, gateway, opts) {
41382
+ const passBudgetMs = opts?.passBudgetMs ?? PASS_BUDGET_MS;
41383
+ const prober = opts?.prober;
41384
+ const passStart = performance.now();
41385
+ const safe = [];
41386
+ const unmeasurable = /* @__PURE__ */ new Map();
41387
+ try {
41388
+ for (const rule of rules) {
41389
+ const key = ruleProbeKey(rule);
41390
+ if (key === void 0) {
41391
+ safe.push(rule);
41392
+ continue;
41393
+ }
41394
+ let cached2;
41395
+ try {
41396
+ cached2 = await gateway.getRuleProbeVerdict(key);
41397
+ } catch {
41398
+ cached2 = void 0;
41399
+ }
41400
+ if (cached2) {
41401
+ if (cached2.verdict === "safe") safe.push(rule);
41402
+ else warnQuarantined(rule, cached2.worstProbeMs, true);
41403
+ continue;
41404
+ }
41405
+ if (performance.now() - passStart >= passBudgetMs) {
41406
+ warnUnmeasured(rule);
41407
+ continue;
41408
+ }
41409
+ let verdict;
41410
+ let worstMs;
41411
+ let corroboratedMs = 0;
41412
+ if (prober) {
41413
+ const outcome = await prober.probe(rule);
41414
+ if (outcome.status === "unavailable") {
41415
+ unmeasurable.set(outcome.reason, (unmeasurable.get(outcome.reason) ?? 0) + 1);
41416
+ continue;
41417
+ }
41418
+ verdict = outcome.status === "ok" ? outcome.verdict : "over-budget";
41419
+ worstMs = outcome.status === "ok" ? outcome.worstMs : outcome.elapsedMs;
41420
+ if (outcome.status === "ok") corroboratedMs = outcome.corroboratedMs;
41421
+ } else {
41422
+ try {
41423
+ ({ verdict, worstMs, corroboratedMs } = checkRuleTiming(rule, workClockMs));
41424
+ } catch {
41425
+ verdict = "over-budget";
41426
+ worstMs = Number.POSITIVE_INFINITY;
41427
+ }
41428
+ }
41429
+ if (verdict === "uncorroborated") {
41430
+ warnUncorroborated(rule, worstMs, corroboratedMs);
41431
+ continue;
41432
+ }
41433
+ const isSafe = verdict === "safe";
41434
+ let persisted = false;
41435
+ try {
41436
+ await gateway.setRuleProbeVerdict(key, isSafe ? "safe" : "quarantined", worstMs);
41437
+ persisted = true;
41438
+ } catch {
41439
+ }
41440
+ if (isSafe) safe.push(rule);
41441
+ else warnQuarantined(rule, worstMs, persisted);
41442
+ }
41443
+ } finally {
41444
+ for (const [reason, count] of unmeasurable) warnUnmeasurable(reason, count);
41445
+ }
41446
+ return safe;
41447
+ }
40994
41448
 
40995
41449
  // ../../packages/plugin-sdk/src/hook-fail-opens.ts
40996
41450
  import { readFileSync as readFileSync13 } from "fs";
@@ -41030,58 +41484,13 @@ function isPositiveSafeInteger(value) {
41030
41484
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
41031
41485
  }
41032
41486
 
41033
- // ../../packages/plugin-sdk/src/host-floor.ts
41034
- import { readFileSync as readFileSync15 } from "fs";
41035
- import { join as join22 } from "path";
41036
-
41037
- // ../../packages/plugin-sdk/src/model-governance.ts
41038
- import {
41039
- closeSync as closeSync2,
41040
- fstatSync,
41041
- mkdirSync as mkdirSync2,
41042
- openSync as openSync2,
41043
- readFileSync as readFileSync14,
41044
- readSync,
41045
- writeFileSync as writeFileSync5
41046
- } from "fs";
41047
- import { join as join21 } from "path";
41048
- var TAIL_BYTES = 256 * 1024;
41049
-
41050
- // ../../packages/plugin-sdk/src/host-floor.ts
41051
- var HOST_FEATURE = {
41052
- ModelSwitch: "model-switch",
41053
- VaultPointerDisplay: "vault-pointer-display"
41054
- };
41055
- var HOST_FLOORS = {
41056
- [HOST_FEATURE.ModelSwitch]: {
41057
- label: "model-switch protection",
41058
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
41059
- since: "2.1.251"
41060
- },
41061
- [HOST_FEATURE.VaultPointerDisplay]: {
41062
- label: "vault pointer display",
41063
- hookEvents: ["MessageDisplay"],
41064
- since: "2.1.152"
41065
- }
41066
- };
41067
- var ANTIGRAVITY_HOST_FEATURE = {
41068
- EndOfTurnCapture: "end-of-turn-capture"
41069
- };
41070
- var ANTIGRAVITY_HOST_FLOORS = {
41071
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
41072
- label: "end-of-turn history capture",
41073
- hookEvents: ["Stop"],
41074
- since: "1.1.10"
41075
- }
41076
- };
41077
-
41078
41487
  // ../../packages/plugin-sdk/src/ignore-layers.ts
41079
41488
  var import_ignore = __toESM(require_ignore(), 1);
41080
- import { readFileSync as readFileSync16 } from "fs";
41081
- import { join as join23 } from "path";
41489
+ import { readFileSync as readFileSync14 } from "fs";
41490
+ import { join as join21 } from "path";
41082
41491
  function readIgnoreLayer(dir, filename, anchorLen) {
41083
41492
  try {
41084
- return { matcher: (0, import_ignore.default)().add(readFileSync16(join23(dir, filename), "utf8")), anchorLen };
41493
+ return { matcher: (0, import_ignore.default)().add(readFileSync14(join21(dir, filename), "utf8")), anchorLen };
41085
41494
  } catch {
41086
41495
  return void 0;
41087
41496
  }
@@ -41138,31 +41547,27 @@ function resolveInventoryContext(input2) {
41138
41547
  }
41139
41548
 
41140
41549
  // ../../packages/plugin-sdk/src/nudge.ts
41141
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "fs";
41142
- import { join as join24 } from "path";
41550
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync15, writeFileSync as writeFileSync5 } from "fs";
41551
+ import { join as join22 } from "path";
41143
41552
  var SESSION_START_MARKER = "session-start-last";
41144
41553
  function claimSessionStart(dataDir2, sessionId) {
41145
41554
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
41146
41555
  }
41147
41556
  function claimOncePerSession(dataDir2, marker, sessionId) {
41148
41557
  if (!sessionId) return true;
41149
- const path = join24(dataDir2, marker);
41558
+ const path = join22(dataDir2, marker);
41150
41559
  try {
41151
- if (readFileSync17(path, "utf8") === sessionId) return false;
41560
+ if (readFileSync15(path, "utf8") === sessionId) return false;
41152
41561
  } catch {
41153
41562
  }
41154
41563
  try {
41155
- mkdirSync3(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
41156
- writeFileSync6(path, sessionId, { mode: DATA_FILE_MODE });
41564
+ mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
41565
+ writeFileSync5(path, sessionId, { mode: DATA_FILE_MODE });
41157
41566
  } catch {
41158
41567
  }
41159
41568
  return true;
41160
41569
  }
41161
41570
 
41162
- // ../../packages/plugin-sdk/src/paths.ts
41163
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
41164
- import { basename as basename5, dirname as dirname5, sep as sep3 } from "path";
41165
-
41166
41571
  // ../../packages/plugin-sdk/src/policy-resolver.ts
41167
41572
  import { randomUUID as randomUUID14 } from "crypto";
41168
41573
  function assignedRulePolicies(installed) {
@@ -41175,8 +41580,8 @@ function assignedRulePolicies(installed) {
41175
41580
  }
41176
41581
 
41177
41582
  // ../../packages/plugin-sdk/src/project-files.ts
41178
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
41179
- import { basename as basename6, join as join25 } from "path";
41583
+ import { existsSync as existsSync11, readdirSync as readdirSync3 } from "fs";
41584
+ import { basename as basename5, join as join23 } from "path";
41180
41585
  var SKIP_DIRS = /* @__PURE__ */ new Set([
41181
41586
  ".git",
41182
41587
  "node_modules",
@@ -41255,7 +41660,7 @@ function resolveProjectFiles(cwd, opts = {}) {
41255
41660
  let visit3 = function(dir, dirRel, layers, depth) {
41256
41661
  let dirents;
41257
41662
  try {
41258
- dirents = readdirSync4(dir, { withFileTypes: true, encoding: "utf8" });
41663
+ dirents = readdirSync3(dir, { withFileTypes: true, encoding: "utf8" });
41259
41664
  } catch {
41260
41665
  walk.lostSubtree = true;
41261
41666
  return false;
@@ -41273,8 +41678,8 @@ function resolveProjectFiles(cwd, opts = {}) {
41273
41678
  }
41274
41679
  if (entry.isDirectory()) {
41275
41680
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
41276
- const fullPath = join25(dir, entry.name);
41277
- if (existsSync11(join25(fullPath, ".git"))) continue;
41681
+ const fullPath = join23(dir, entry.name);
41682
+ if (existsSync11(join23(fullPath, ".git"))) continue;
41278
41683
  if (depth >= bounds.maxDepth) {
41279
41684
  walk.omitted = true;
41280
41685
  continue;
@@ -41289,7 +41694,7 @@ function resolveProjectFiles(cwd, opts = {}) {
41289
41694
  const relPath = childRel(dirRel, entry.name);
41290
41695
  files.push({
41291
41696
  path: relPath,
41292
- name: basename6(entry.name),
41697
+ name: basename5(entry.name),
41293
41698
  origin: classifyOrigin(relPath, entry.name),
41294
41699
  defaultAccess: "approved"
41295
41700
  });
@@ -41313,30 +41718,14 @@ function resolveProjectFiles(cwd, opts = {}) {
41313
41718
  }
41314
41719
  }
41315
41720
 
41316
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
41317
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
41318
- if (typeof v === "string" && v.trim() === "") return void 0;
41319
- return v;
41320
- }, external_exports.string().optional()).catch(void 0);
41321
- var optionalFlag = external_exports.preprocess((v) => {
41322
- if (typeof v !== "string") return false;
41323
- const normalized = v.trim().toLowerCase();
41324
- return normalized !== "" && normalized !== "0" && normalized !== "false";
41325
- }, external_exports.boolean()).catch(false);
41326
- var antigravityProviderEnvShape = {
41327
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
41328
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
41329
- };
41330
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
41331
-
41332
41721
  // ../../packages/plugin-sdk/src/provider-env-codex.ts
41333
41722
  var DEFAULT_OPENAI_HOST = "api.openai.com";
41334
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
41723
+ var optionalBaseUrl2 = external_exports.preprocess((v) => {
41335
41724
  if (typeof v === "string" && v.trim() === "") return void 0;
41336
41725
  return v;
41337
41726
  }, external_exports.string().optional()).catch(void 0);
41338
41727
  var codexProviderEnvShape = {
41339
- OPENAI_BASE_URL: optionalBaseUrl3
41728
+ OPENAI_BASE_URL: optionalBaseUrl2
41340
41729
  };
41341
41730
  var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
41342
41731
 
@@ -41367,37 +41756,448 @@ function resolveCodexProvider() {
41367
41756
  return { provider: "openai" };
41368
41757
  }
41369
41758
 
41370
- // ../../packages/plugin-sdk/src/runtime.ts
41371
- import { randomUUID as randomUUID15 } from "crypto";
41372
-
41373
41759
  // ../../packages/plugin-sdk/src/scope-key.ts
41374
41760
  import { existsSync as existsSync12 } from "fs";
41375
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
41761
+ import { dirname as dirname5, isAbsolute as isAbsolute2, join as join24, normalize } from "path";
41376
41762
  function sessionRootScopeKey(cwd) {
41377
41763
  return cwd === void 0 ? void 0 : resolveRepoAttribution(cwd).scopeKey;
41378
41764
  }
41379
41765
 
41380
- // ../../packages/plugin-sdk/src/suppressions.ts
41381
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
41382
-
41383
41766
  // ../../packages/plugin-sdk/src/throttle.ts
41384
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
41385
- import { join as join27 } from "path";
41767
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
41768
+ import { join as join25 } from "path";
41386
41769
  function throttled(dataDir2, markerName, windowMs) {
41387
- const marker = join27(dataDir2, markerName);
41770
+ const marker = join25(dataDir2, markerName);
41388
41771
  try {
41389
41772
  if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
41390
41773
  } catch {
41391
41774
  }
41392
41775
  try {
41393
- mkdirSync4(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
41394
- writeFileSync7(marker, String(Date.now()), { mode: DATA_FILE_MODE });
41776
+ mkdirSync3(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
41777
+ writeFileSync6(marker, String(Date.now()), { mode: DATA_FILE_MODE });
41395
41778
  } catch {
41396
41779
  }
41397
41780
  return false;
41398
41781
  }
41399
41782
 
41783
+ // ../../packages/remote/src/http.ts
41784
+ import { request as httpRequest } from "http";
41785
+ import { request as httpsRequest } from "https";
41786
+ var DEFAULT_TIMEOUT_MS = 1e4;
41787
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
41788
+ var RemoteRequestError = class extends Error {
41789
+ constructor(status) {
41790
+ super(`control-plane request failed with status ${String(status)}`);
41791
+ this.status = status;
41792
+ this.name = "RemoteRequestError";
41793
+ }
41794
+ status;
41795
+ };
41796
+ var RemoteRouteAbsent = class extends Error {
41797
+ constructor(route) {
41798
+ super(`control plane does not serve ${route}`);
41799
+ this.route = route;
41800
+ this.name = "RemoteRouteAbsent";
41801
+ }
41802
+ route;
41803
+ };
41804
+ var RemoteRequestInvalid = class extends Error {
41805
+ constructor(route, cause) {
41806
+ super(`refusing to send a malformed body to ${route}`);
41807
+ this.cause = cause;
41808
+ this.name = "RemoteRequestInvalid";
41809
+ }
41810
+ cause;
41811
+ };
41812
+ var RemoteEndpointRefused = class extends Error {
41813
+ constructor(endpoint) {
41814
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
41815
+ this.name = "RemoteEndpointRefused";
41816
+ }
41817
+ };
41818
+ var RemoteResponseInvalid = class extends Error {
41819
+ constructor(route, detail) {
41820
+ super(`control plane answered ${route} with ${detail}`);
41821
+ this.name = "RemoteResponseInvalid";
41822
+ }
41823
+ };
41824
+ var RemoteTransportError = class extends Error {
41825
+ /**
41826
+ * The status the peer sent, when headers arrived and only the BODY was
41827
+ * refused.
41828
+ *
41829
+ * Undefined for the ordinary case this class was written for — no answer at
41830
+ * all. It exists because two paths reject after a status has already been
41831
+ * delivered: an oversized body and an aborted response. Discarding it there
41832
+ * reported a deployment answering 401 with a verbose body as a network
41833
+ * outage, which sends the reader to look at their network instead of their
41834
+ * credential.
41835
+ */
41836
+ constructor(reason, status) {
41837
+ super(`control-plane request did not complete: ${reason}`);
41838
+ this.status = status;
41839
+ this.name = "RemoteTransportError";
41840
+ }
41841
+ status;
41842
+ };
41843
+ async function send(options) {
41844
+ const url2 = new URL(options.url);
41845
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
41846
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
41847
+ const requestOptions = {
41848
+ method: options.method,
41849
+ headers: {
41850
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
41851
+ // last they win, and two of the values below are ones no caller may
41852
+ // replace: `x-api-key` is the credential, and `content-length` is the
41853
+ // byte count that stops a multi-byte body being truncated by the
41854
+ // receiver. `SendOptions.headers` is a free-form record on an exported
41855
+ // function, so "no caller does that today" is not the guarantee to rely
41856
+ // on. The one header any caller actually passes — `if-none-match` on the
41857
+ // conditional GET — is untouched by this order.
41858
+ ...options.headers,
41859
+ // The credential. One header, matching what the deployment authenticates
41860
+ // on; a second copy in an `Authorization` header would be one more place
41861
+ // it can be logged by an intermediary for no gain.
41862
+ //
41863
+ // Spread conditionally rather than assigned as `undefined`: Node's header
41864
+ // handling and `content-length` bookkeeping treat a present-but-undefined
41865
+ // key differently from an absent one, and "the header is not there" is
41866
+ // the property the attach flow needs.
41867
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
41868
+ accept: "application/json",
41869
+ ...options.body === void 0 ? {} : {
41870
+ "content-type": "application/json",
41871
+ // Byte length, not string length: a multi-byte body sent with a
41872
+ // character count is truncated by the receiver.
41873
+ "content-length": String(Buffer.byteLength(options.body))
41874
+ }
41875
+ }
41876
+ };
41877
+ return new Promise((resolve3, reject) => {
41878
+ let settled = false;
41879
+ const fail = (reason, status) => {
41880
+ if (settled) return;
41881
+ settled = true;
41882
+ reject(new RemoteTransportError(reason, status));
41883
+ };
41884
+ const req = send_(url2, requestOptions, (res) => {
41885
+ const chunks = [];
41886
+ let size = 0;
41887
+ res.on("data", (chunk) => {
41888
+ size += chunk.length;
41889
+ if (size > MAX_RESPONSE_BYTES) {
41890
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
41891
+ res.destroy();
41892
+ req.destroy();
41893
+ return;
41894
+ }
41895
+ chunks.push(chunk);
41896
+ });
41897
+ res.on("aborted", () => {
41898
+ fail("the response was aborted", res.statusCode);
41899
+ });
41900
+ res.on("end", () => {
41901
+ if (settled) return;
41902
+ settled = true;
41903
+ resolve3({
41904
+ status: res.statusCode ?? 0,
41905
+ headers: res.headers,
41906
+ body: Buffer.concat(chunks).toString("utf8")
41907
+ });
41908
+ });
41909
+ });
41910
+ const deadline = setTimeout(() => {
41911
+ fail(`no response within ${String(timeoutMs)}ms`);
41912
+ req.destroy();
41913
+ }, timeoutMs);
41914
+ deadline.unref();
41915
+ req.on("upgrade", (_res, socket) => {
41916
+ fail("the deployment answered with a protocol upgrade");
41917
+ socket.destroy();
41918
+ });
41919
+ req.on("close", () => {
41920
+ fail("the connection closed before a response was read");
41921
+ clearTimeout(deadline);
41922
+ });
41923
+ req.on("error", (err) => {
41924
+ fail(err.message);
41925
+ });
41926
+ if (options.body !== void 0) req.write(options.body);
41927
+ req.end();
41928
+ });
41929
+ }
41930
+
41931
+ // ../../packages/remote/src/client.ts
41932
+ var ROUTES = {
41933
+ events: "/v1/events",
41934
+ auditEvents: "/v1/audit-events",
41935
+ auditEventsBatch: "/v1/audit-events/batch",
41936
+ inventory: "/v1/inventory",
41937
+ storePosture: "/v1/store-posture",
41938
+ policyBundle: "/v1/policy-bundle",
41939
+ whoami: "/v1/plugin/whoami",
41940
+ shares: "/v1/shares",
41941
+ commands: "/v1/plugin/commands"
41942
+ };
41943
+ function ackRoute(id) {
41944
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
41945
+ }
41946
+ function headerValue(response, name) {
41947
+ const raw = response.headers[name];
41948
+ if (raw === void 0) return void 0;
41949
+ return Array.isArray(raw) ? raw[0] : raw;
41950
+ }
41951
+ function okBody(response) {
41952
+ if (response.status < 200 || response.status >= 300) {
41953
+ throw new RemoteRequestError(response.status);
41954
+ }
41955
+ return response.body;
41956
+ }
41957
+ function parsed(schema, body, route) {
41958
+ let json2;
41959
+ try {
41960
+ json2 = JSON.parse(body);
41961
+ } catch {
41962
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
41963
+ }
41964
+ const result = schema.safeParse(json2);
41965
+ if (!result.success) {
41966
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
41967
+ }
41968
+ return result.data;
41969
+ }
41970
+ function resolveBaseUrl(endpoint) {
41971
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
41972
+ let end = endpoint.length;
41973
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH3) end -= 1;
41974
+ return endpoint.slice(0, end);
41975
+ }
41976
+ var SLASH3 = "/".charCodeAt(0);
41977
+ function createRemoteClient(options) {
41978
+ const base = resolveBaseUrl(options.endpoint);
41979
+ const url2 = (route) => `${base}${route}`;
41980
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
41981
+ const sendOne = async (event) => {
41982
+ const validated = RecordAuditEventRequest.safeParse(event);
41983
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
41984
+ const response = await send({
41985
+ ...common,
41986
+ method: "POST",
41987
+ url: url2(ROUTES.auditEvents),
41988
+ body: JSON.stringify(validated.data)
41989
+ });
41990
+ okBody(response);
41991
+ };
41992
+ return {
41993
+ async ingestEvents(batch) {
41994
+ const response = await send({
41995
+ ...common,
41996
+ method: "POST",
41997
+ url: url2(ROUTES.events),
41998
+ body: JSON.stringify(batch)
41999
+ });
42000
+ return parsed(IngestAck, okBody(response), ROUTES.events);
42001
+ },
42002
+ async ingestInventory(context) {
42003
+ const response = await send({
42004
+ ...common,
42005
+ method: "POST",
42006
+ url: url2(ROUTES.inventory),
42007
+ body: JSON.stringify(context)
42008
+ });
42009
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
42010
+ },
42011
+ async recordAuditEvent(event) {
42012
+ await sendOne(event);
42013
+ },
42014
+ async recordAuditEvents(events, opts) {
42015
+ const validated = RecordAuditEventBatch.safeParse({ events });
42016
+ if (!validated.success) {
42017
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
42018
+ }
42019
+ const response = await send({
42020
+ ...common,
42021
+ method: "POST",
42022
+ url: url2(ROUTES.auditEventsBatch),
42023
+ body: JSON.stringify(validated.data)
42024
+ });
42025
+ if (response.status === 404) {
42026
+ if (opts?.fallbackToSingleEvents !== true) {
42027
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
42028
+ }
42029
+ for (const event of validated.data.events) await sendOne(event);
42030
+ return { accepted: validated.data.events.length };
42031
+ }
42032
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
42033
+ },
42034
+ async reportStorePosture(snapshot) {
42035
+ const response = await send({
42036
+ ...common,
42037
+ method: "POST",
42038
+ url: url2(ROUTES.storePosture),
42039
+ body: JSON.stringify(snapshot)
42040
+ });
42041
+ okBody(response);
42042
+ },
42043
+ async getPolicyBundle(etag) {
42044
+ const response = await send({
42045
+ ...common,
42046
+ method: "GET",
42047
+ url: url2(ROUTES.policyBundle),
42048
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
42049
+ });
42050
+ if (response.status === 304) {
42051
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
42052
+ }
42053
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
42054
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
42055
+ },
42056
+ async whoami() {
42057
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
42058
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
42059
+ },
42060
+ async recordProjectEgress(request) {
42061
+ const validated = EgressIngestRequest.safeParse(request);
42062
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
42063
+ const response = await send({
42064
+ ...common,
42065
+ method: "POST",
42066
+ url: url2(ROUTES.shares),
42067
+ body: JSON.stringify(validated.data)
42068
+ });
42069
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
42070
+ okBody(response);
42071
+ },
42072
+ async pollCommand() {
42073
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
42074
+ if (response.status === 404) return null;
42075
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
42076
+ },
42077
+ async ackCommand(id, body) {
42078
+ const validated = DeviceCommandAckBody.safeParse(body);
42079
+ const route = ackRoute(id);
42080
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
42081
+ const response = await send({
42082
+ ...common,
42083
+ method: "POST",
42084
+ url: url2(route),
42085
+ body: JSON.stringify(validated.data)
42086
+ });
42087
+ okBody(response);
42088
+ }
42089
+ };
42090
+ }
42091
+
42092
+ // ../../packages/remote/src/failure-kind.ts
42093
+ function statusOf(err) {
42094
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
42095
+ const { status } = err;
42096
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
42097
+ return status >= 100 && status <= 599 ? status : null;
42098
+ }
42099
+ function nameOf(err) {
42100
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
42101
+ return typeof err.name === "string" ? err.name : null;
42102
+ }
42103
+ function classifyRemoteFailure(err) {
42104
+ switch (nameOf(err)) {
42105
+ case "RemoteRouteAbsent":
42106
+ return "route-absent";
42107
+ case "RemoteRequestInvalid":
42108
+ case "RemoteEndpointRefused":
42109
+ return "invalid-request";
42110
+ case "RemoteResponseInvalid":
42111
+ return "rejected";
42112
+ default:
42113
+ break;
42114
+ }
42115
+ const status = statusOf(err);
42116
+ if (status === null) return "unreachable";
42117
+ switch (status) {
42118
+ case 401:
42119
+ return "unauthorized";
42120
+ case 403:
42121
+ return "forbidden";
42122
+ case 429:
42123
+ return "unreachable";
42124
+ case 404:
42125
+ return "unreachable";
42126
+ default:
42127
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
42128
+ }
42129
+ }
42130
+
42131
+ // ../../packages/plugin-runtime/src/attached/failure.ts
42132
+ function classifyFailure(err) {
42133
+ switch (classifyRemoteFailure(err)) {
42134
+ case "unauthorized":
42135
+ return "unauthorized";
42136
+ case "forbidden":
42137
+ return "forbidden";
42138
+ default:
42139
+ return "unreachable";
42140
+ }
42141
+ }
42142
+
42143
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
42144
+ var REQUEST_TIMEOUT_MS = 2e3;
42145
+ function withTimeout(promise2, ms) {
42146
+ let timer;
42147
+ const timeout = new Promise((_, reject) => {
42148
+ timer = setTimeout(() => {
42149
+ reject(new Error("attached gateway request timed out"));
42150
+ }, ms);
42151
+ });
42152
+ promise2.catch(() => void 0);
42153
+ return Promise.race([promise2, timeout]).finally(() => {
42154
+ clearTimeout(timer);
42155
+ });
42156
+ }
42157
+
42158
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
42159
+ import { readFileSync as readFileSync16 } from "fs";
42160
+ import { join as join26 } from "path";
42161
+ var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
42162
+ function forwardDropsPath(dataDir2) {
42163
+ return join26(dataDir2, FORWARD_DROPS_FILENAME);
42164
+ }
42165
+ function recordForwardDrops(dataDir2, count, nowMs) {
42166
+ if (count <= 0) return;
42167
+ try {
42168
+ ensureDataDirSync(dataDir2);
42169
+ const previous = readForwardDrops(dataDir2);
42170
+ const next = {
42171
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
42172
+ lastDropAtMs: nowMs
42173
+ };
42174
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
42175
+ `);
42176
+ } catch {
42177
+ }
42178
+ }
42179
+ function readForwardDrops(dataDir2) {
42180
+ try {
42181
+ const parsed2 = JSON.parse(readFileSync16(forwardDropsPath(dataDir2), "utf8"));
42182
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
42183
+ const record2 = parsed2;
42184
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
42185
+ return null;
42186
+ }
42187
+ if (record2.droppedForwards <= 0) return null;
42188
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
42189
+ return null;
42190
+ }
42191
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
42192
+ } catch {
42193
+ return null;
42194
+ }
42195
+ }
42196
+
41400
42197
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
42198
+ import { randomUUID as randomUUID15 } from "crypto";
42199
+ import { readFile, rename, writeFile } from "fs/promises";
42200
+ import { join as join27 } from "path";
41401
42201
  function isInvalidRequest(err) {
41402
42202
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
41403
42203
  }
@@ -41416,7 +42216,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
41416
42216
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
41417
42217
  function createForwardPolicy(deps) {
41418
42218
  const now = deps.now ?? (() => Date.now());
41419
- const file2 = join28(deps.dir, STATE_FILENAME);
42219
+ const file2 = join27(deps.dir, STATE_FILENAME);
41420
42220
  let state = null;
41421
42221
  let loading = null;
41422
42222
  async function readState() {
@@ -41441,7 +42241,7 @@ function createForwardPolicy(deps) {
41441
42241
  state = next;
41442
42242
  try {
41443
42243
  await ensureDataDir(deps.dir);
41444
- const tmp = `${file2}.${randomUUID16()}.tmp`;
42244
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
41445
42245
  await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
41446
42246
  await rename(tmp, file2);
41447
42247
  } catch {
@@ -41582,6 +42382,9 @@ var AttachedDataGateway = class {
41582
42382
  *
41583
42383
  * Machine mode answers before any key is read, so a machine attachment pays
41584
42384
  * nothing for scoping and forwards exactly what it always has.
42385
+ *
42386
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
42387
+ * forwarding key for key.
41585
42388
  */
41586
42389
  verdictFor(keyOf) {
41587
42390
  try {
@@ -41598,24 +42401,27 @@ var AttachedDataGateway = class {
41598
42401
  * the key its row holds in the local store, recorded per root (see
41599
42402
  * `rootVerdict`), not the key on the root event just handed in: roots are
41600
42403
  * first-write-wins in the store, so when two producers record a root for one
41601
- * session (the session-start hook, then a reconcile pass) the second leaves
41602
- * the stored row as it was, and the history drain decides that row, not this
41603
- * event. Whether this root EVENT is itself sent takes both keys: the stored
41604
- * one AND its own. The event's attributes (cwd, project, repo) describe where
41605
- * it was recorded from, so a root event keyed to a personal directory is never
41606
- * sent under an enrolled stored root, though the enrolled leaves still forward
41607
- * under it: the instance that wrote the stored root is expected to have
41608
- * forwarded it. If it did not (the root was written while standalone or under
41609
- * another attachment, or its forward failed), the plane refuses those leaves
41610
- * and the history drain ships the root first. Any other row with a root
41611
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
41612
- * is in scope AND this instance recorded an in-scope verdict for that root.
41613
- * The audit-event route has real foreign keys on both columns and stubs no
41614
- * missing root, so a leaf sent after its root was kept local is refused
41615
- * there, and a refused forward counts toward the breaker that guards every
41616
- * other one. A root this instance never recorded is therefore `'local'`: the
41617
- * only answer that cannot orphan a row. A row with no root reference at all
41618
- * has nothing to orphan, and is decided by its own key.
42404
+ * session (the session-start hook, then a reconcile pass) the second leaves the
42405
+ * stored row as it was. That stored row, not this event, is what a history
42406
+ * drain pass would decide, if the root started before the attach; the drain
42407
+ * never offers one that started after it (`started_at < backlogBefore`).
42408
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
42409
+ * its own. The event's attributes (cwd, project, repo) describe where it was
42410
+ * recorded from, so a root event keyed to a personal directory is never sent
42411
+ * under an enrolled stored root, though the enrolled leaves still forward under
42412
+ * it: the instance that wrote the stored root is expected to have forwarded it.
42413
+ * If it did not (the root was written while standalone or under another
42414
+ * attachment, or its forward failed), the plane refuses those leaves. A root
42415
+ * that started before the attach is shipped, ahead of its leaves, by the
42416
+ * history drain; one that started after it is never offered by the drain. Any
42417
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
42418
+ * only when its own key is in scope AND this instance recorded an in-scope
42419
+ * verdict for that root. The audit-event route has real foreign keys on both
42420
+ * columns and stubs no missing root, so a leaf sent after its root was kept
42421
+ * local is refused there, and a refused forward counts toward the breaker that
42422
+ * guards every other one. A root this instance never recorded is therefore
42423
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
42424
+ * reference at all has nothing to orphan, and is decided by its own key.
41619
42425
  *
41620
42426
  * What this costs is stated rather than discovered. A session whose stored
41621
42427
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -41686,6 +42492,87 @@ var AttachedDataGateway = class {
41686
42492
  return [];
41687
42493
  }
41688
42494
  }
42495
+ /**
42496
+ * The verdict for the repositories nested in a scanned project, answered
42497
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
42498
+ *
42499
+ * A walk descends into a nested clone or submodule and folds its files into
42500
+ * the project it is walking, so one register can carry several
42501
+ * repositories' call sites under one project key. Each of them must be in
42502
+ * scope for it to forward. One key out of scope, or a nested repository with
42503
+ * no remote (an `undefined` key), keeps the whole register local.
42504
+ *
42505
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
42506
+ * what is nested in it, and every scan passes the list, empty when nothing
42507
+ * is nested. A register nobody vouched for is not one a scoped attachment
42508
+ * may send.
42509
+ *
42510
+ * Machine mode answers before reading the context, so a machine attachment
42511
+ * forwards exactly what it always has.
42512
+ */
42513
+ nestedVerdict(context) {
42514
+ try {
42515
+ if (this.deps.attachment.mode === "machine") return "forward";
42516
+ const keys = context?.nestedScopeKeys;
42517
+ if (keys === void 0) return "local";
42518
+ for (const key of keys) {
42519
+ if (this.verdictFor(() => key) === "local") return "local";
42520
+ }
42521
+ return "forward";
42522
+ } catch {
42523
+ return "local";
42524
+ }
42525
+ }
42526
+ /**
42527
+ * The register a scoped attachment sends, once the project and the repositories
42528
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
42529
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
42530
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
42531
+ *
42532
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
42533
+ * and the ledger holds every file the scanner ever read under the root, nested
42534
+ * clones' included. So a clone that was removed, or one an ignore file now
42535
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
42536
+ * paths come back as deleted. The scan names the repository of each deleted
42537
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
42538
+ * and each is held to the same verdict as any other key. A path whose key is
42539
+ * absent, or out of scope, is not sent.
42540
+ *
42541
+ * The list is asked for here, and only here: it is an async read of the scan
42542
+ * ledger that the scan makes on being called, so a machine attachment, which
42543
+ * returns before this, and a register already kept local never cause it.
42544
+ *
42545
+ * Anything the scan did not vouch for sends no deleted path, and the register
42546
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
42547
+ * list whose length is not the register's. Deleting is the only thing a dropped
42548
+ * path could have done on the server, so the cost of a refusal is a stored row
42549
+ * that stays, never a path that leaves.
42550
+ *
42551
+ * Machine mode returns `input` itself, the same object and unread, so a machine
42552
+ * attachment's request is exactly what it was. A register that lists no deleted
42553
+ * path, or that is not a ledger register, has nothing to cut and is returned
42554
+ * as it came, with the list unread.
42555
+ */
42556
+ async registerForWire(input2, context) {
42557
+ try {
42558
+ if (this.deps.attachment.mode === "machine") return input2;
42559
+ const { reconcile } = input2;
42560
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
42561
+ const deleted = reconcile.deletedFiles;
42562
+ let kept = [];
42563
+ try {
42564
+ const keys = await context?.deletedFileKeys?.();
42565
+ if (keys?.length === deleted.length) {
42566
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
42567
+ }
42568
+ } catch {
42569
+ kept = [];
42570
+ }
42571
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
42572
+ } catch {
42573
+ return void 0;
42574
+ }
42575
+ }
41689
42576
  /**
41690
42577
  * The event `recordCapture` sends for a capture the verdict let through, or
41691
42578
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -42011,12 +42898,24 @@ var AttachedDataGateway = class {
42011
42898
  * payload onto the wire-boundary-safe shape (no snippet, hashed
42012
42899
  * projectKey), and its result is discarded: `forward.run` never throws or
42013
42900
  * rejects, so there is nothing here to act on.
42901
+ *
42902
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
42903
+ * not say: the key of every repository nested below the scan root, whose
42904
+ * files the walk folded into this register. On a scoped attachment the
42905
+ * register is forwarded only when the project's own key AND every one of
42906
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
42907
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
42908
+ * `registerForWire`). Machine mode never reads either, and the local write
42909
+ * never receives the context and gets the register whole.
42014
42910
  */
42015
- async recordProjectEgress(input2) {
42911
+ async recordProjectEgress(input2, context) {
42016
42912
  const summary = await this.deps.local.recordProjectEgress(input2);
42017
42913
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
42914
+ if (this.nestedVerdict(context) === "local") return summary;
42915
+ const register = await this.registerForWire(input2, context);
42916
+ if (register === void 0) return summary;
42018
42917
  await this.deps.forward.run(
42019
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
42918
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
42020
42919
  );
42021
42920
  return summary;
42022
42921
  }
@@ -42070,14 +42969,19 @@ var AttachedDataGateway = class {
42070
42969
  async scanLedgerPaths() {
42071
42970
  return this.deps.local.scanLedgerPaths();
42072
42971
  }
42972
+ // Delegated, like the path list. An inner gateway that cannot say answers an
42973
+ // empty map, which gives every deleted path no key.
42974
+ async scanLedgerPathKeys() {
42975
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
42976
+ }
42073
42977
  async recordScanned(entries) {
42074
42978
  return this.deps.local.recordScanned(entries);
42075
42979
  }
42076
42980
  async getRuleProbeVerdict(ruleKey) {
42077
42981
  return this.deps.local.getRuleProbeVerdict(ruleKey);
42078
42982
  }
42079
- async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs) {
42080
- return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs);
42983
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
42984
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2);
42081
42985
  }
42082
42986
  async openAtRestKeysForPath(path) {
42083
42987
  return this.deps.local.openAtRestKeysForPath(path);
@@ -42136,6 +43040,12 @@ var AttachedDataGateway = class {
42136
43040
  // and the spread above would otherwise drop the field silently — which is
42137
43041
  // exactly what it did, leaving the whole control inert on every device
42138
43042
  // while every test around it stayed green.
43043
+ //
43044
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
43045
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
43046
+ // reads this bundle once to build detection, so the detections it carries
43047
+ // apply to every event on the machine. Where a prohibition applies is
43048
+ // answered per event by `governanceAppliesTo` below.
42139
43049
  prohibitedModels: cached2.prohibitedModels,
42140
43050
  // NAMED for the same reason as the line above, and it is the same defect
42141
43051
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -42195,6 +43105,30 @@ var AttachedDataGateway = class {
42195
43105
  };
42196
43106
  }
42197
43107
  // ---------------------------------------------------------------------
43108
+ // GovernanceScope — where the organization's model policy applies
43109
+ // ---------------------------------------------------------------------
43110
+ /**
43111
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
43112
+ * the question a model-guard site asks once it has decided to refuse.
43113
+ *
43114
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
43115
+ * with the same key would be forwarded. A machine-wide attachment governs
43116
+ * every event, keyless included, exactly as before. A scoped one governs an
43117
+ * event only when its key names an enrolled repository. An event in a
43118
+ * personal repository, in no repository, with an empty key, or met by a fault
43119
+ * is not governed.
43120
+ *
43121
+ * The event's OWN key, never its session root's. The root rule in
43122
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
43123
+ * this decides whether a refusal applies, which is a question about where the
43124
+ * event happened.
43125
+ *
43126
+ * Answered from memory: no store read, no bundle read, nothing sent.
43127
+ */
43128
+ governanceAppliesTo(scopeKey) {
43129
+ return this.verdictFor(() => scopeKey) === "forward";
43130
+ }
43131
+ // ---------------------------------------------------------------------
42198
43132
  // LocalStoreMaintenance — by delegation (D3).
42199
43133
  //
42200
43134
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -42303,7 +43237,7 @@ function toWireInspection(insp) {
42303
43237
  }
42304
43238
 
42305
43239
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42306
- import { createHash as createHash6 } from "crypto";
43240
+ import { createHash as createHash7 } from "crypto";
42307
43241
  import { hostname as hostname5 } from "os";
42308
43242
 
42309
43243
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
@@ -42346,17 +43280,17 @@ function spawnDetached(scriptPath) {
42346
43280
 
42347
43281
  // ../../packages/plugin-runtime/src/attached/install-record.ts
42348
43282
  import { readFile as readFile2, stat } from "fs/promises";
42349
- import { basename as basename7, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
43283
+ import { basename as basename6, dirname as dirname6, join as join28, resolve as resolve2 } from "path";
42350
43284
  async function readInstalledVersion(installRoot) {
42351
43285
  try {
42352
43286
  const versionDir = resolve2(installRoot);
42353
- const pluginDir = dirname7(versionDir);
42354
- const marketplaceDir = dirname7(pluginDir);
42355
- const cacheDir = dirname7(marketplaceDir);
42356
- if (basename7(cacheDir) !== "cache") return null;
42357
- const key = `${basename7(pluginDir)}@${basename7(marketplaceDir)}`;
43287
+ const pluginDir = dirname6(versionDir);
43288
+ const marketplaceDir = dirname6(pluginDir);
43289
+ const cacheDir = dirname6(marketplaceDir);
43290
+ if (basename6(cacheDir) !== "cache") return null;
43291
+ const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
42358
43292
  const record2 = JSON.parse(
42359
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
43293
+ await readFile2(join28(dirname6(cacheDir), "installed_plugins.json"), "utf8")
42360
43294
  );
42361
43295
  const plugins = record2?.plugins;
42362
43296
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -42388,7 +43322,7 @@ async function exists(path) {
42388
43322
  }
42389
43323
 
42390
43324
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
42391
- import { readFileSync as readFileSync18 } from "fs";
43325
+ import { readFileSync as readFileSync17 } from "fs";
42392
43326
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
42393
43327
  var manifestBuildCache = /* @__PURE__ */ new Map();
42394
43328
  function readManifestBuild(manifestUrl, packageName) {
@@ -42396,7 +43330,7 @@ function readManifestBuild(manifestUrl, packageName) {
42396
43330
  if (!manifestBuildCache.has(key)) {
42397
43331
  let build;
42398
43332
  try {
42399
- const manifest = JSON.parse(readFileSync18(manifestUrl, "utf8"));
43333
+ const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
42400
43334
  build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
42401
43335
  } catch {
42402
43336
  build = void 0;
@@ -42431,9 +43365,9 @@ async function readInstalledVersionBounded(installRoot) {
42431
43365
  }
42432
43366
 
42433
43367
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42434
- import { randomUUID as randomUUID17 } from "crypto";
43368
+ import { randomUUID as randomUUID16 } from "crypto";
42435
43369
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42436
- import { join as join30 } from "path";
43370
+ import { join as join29 } from "path";
42437
43371
 
42438
43372
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
42439
43373
  import { rename as rename2 } from "fs/promises";
@@ -42462,7 +43396,7 @@ async function publishByRename(tmp, file2, move = rename2) {
42462
43396
 
42463
43397
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42464
43398
  function createPolicyStore(dir = dataDir()) {
42465
- const file2 = join30(dir, "policy-cache.json");
43399
+ const file2 = join29(dir, "policy-cache.json");
42466
43400
  async function read() {
42467
43401
  try {
42468
43402
  const raw = await readFile3(file2, "utf8");
@@ -42494,7 +43428,7 @@ function createPolicyStore(dir = dataDir()) {
42494
43428
  }
42495
43429
  }
42496
43430
  async function publishRecord(record2) {
42497
- const tmp = `${file2}.${randomUUID17()}.tmp`;
43431
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
42498
43432
  try {
42499
43433
  await writeFile2(tmp, JSON.stringify(record2), {
42500
43434
  encoding: "utf8",
@@ -42532,8 +43466,8 @@ function createPolicyStore(dir = dataDir()) {
42532
43466
  }
42533
43467
 
42534
43468
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
42535
- import { readFileSync as readFileSync19 } from "fs";
42536
- import { join as join31 } from "path";
43469
+ import { readFileSync as readFileSync18 } from "fs";
43470
+ import { join as join30 } from "path";
42537
43471
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
42538
43472
  var OUTCOME_KEYS = {
42539
43473
  ok: true,
@@ -42547,7 +43481,7 @@ var OUTCOME_KEYS = {
42547
43481
  };
42548
43482
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
42549
43483
  function postureReportStatePath(dataDir2) {
42550
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
43484
+ return join30(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42551
43485
  }
42552
43486
  function writePostureReportState(dataDir2, state) {
42553
43487
  try {
@@ -42588,10 +43522,19 @@ function createPostureReporter(deps) {
42588
43522
  hostname: deps.hostname(),
42589
43523
  capturedAt: nowMs,
42590
43524
  ...measurement,
42591
- // Omit the key rather than spread an explicit `undefined` —
42592
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
42593
- // factory.ts keys on presence.
42594
- ...plugin === void 0 ? {} : { plugin }
43525
+ // Omit the key rather than spread an explicit `undefined`. The type
43526
+ // admits `undefined` here (the schema's optional member), and
43527
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
43528
+ // in-memory object free of an explicit `undefined` member, which the
43529
+ // tests pin by key presence.
43530
+ ...plugin === void 0 ? {} : { plugin },
43531
+ // LAST, and only for a scoped attachment. A machine attachment omits
43532
+ // the key the same way, so its body is byte for byte the one it sent
43533
+ // before the member existed. Anything but exactly `machine` reports the
43534
+ // constant `scoped`, never the raw value: that is resolveScope's own
43535
+ // fail direction, and a value outside the wire's vocabulary would fail
43536
+ // the whole snapshot at the receiver, the wipe signal with it.
43537
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
42595
43538
  };
42596
43539
  } catch {
42597
43540
  return null;
@@ -42615,7 +43558,7 @@ function createPostureReporter(deps) {
42615
43558
 
42616
43559
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
42617
43560
  import { statSync as statSync9 } from "fs";
42618
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
43561
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
42619
43562
 
42620
43563
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
42621
43564
  function emptyActionCounts() {
@@ -42673,7 +43616,7 @@ function readStorePosture(dbPath2) {
42673
43616
  readError: false
42674
43617
  });
42675
43618
  try {
42676
- db = new DatabaseSync4(dbPath2, { readOnly: true });
43619
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
42677
43620
  db.exec("PRAGMA busy_timeout = 2000");
42678
43621
  version2 = db.prepare("PRAGMA user_version").get().user_version;
42679
43622
  try {
@@ -42725,16 +43668,16 @@ function readStorePosture(dbPath2) {
42725
43668
  }
42726
43669
 
42727
43670
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42728
- import { randomUUID as randomUUID18 } from "crypto";
43671
+ import { randomUUID as randomUUID17 } from "crypto";
42729
43672
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42730
- import { join as join32 } from "path";
43673
+ import { join as join31 } from "path";
42731
43674
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42732
43675
  function createPostureStore(dir = settingsDir(), legacyDir) {
42733
- const file2 = join32(dir, "posture-state.json");
42734
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
43676
+ const file2 = join31(dir, "posture-state.json");
43677
+ const legacyFile = legacyDir === void 0 ? null : join31(legacyDir, "posture-state.json");
42735
43678
  async function persist(state) {
42736
43679
  await ensureDataDir(dir);
42737
- const tmp = `${file2}.${randomUUID18()}.tmp`;
43680
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
42738
43681
  try {
42739
43682
  await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
42740
43683
  await publishByRename(tmp, file2);
@@ -42776,7 +43719,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42776
43719
  }
42777
43720
  return legacy;
42778
43721
  }
42779
- const fresh = { deviceId: randomUUID18(), lastAttemptedAtMs: 0 };
43722
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
42780
43723
  try {
42781
43724
  await ensureDataDir(dir);
42782
43725
  if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
@@ -42799,8 +43742,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42799
43742
  }
42800
43743
 
42801
43744
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42802
- import { readFileSync as readFileSync20 } from "fs";
42803
- import { join as join33 } from "path";
43745
+ import { readFileSync as readFileSync19 } from "fs";
43746
+ import { join as join32 } from "path";
42804
43747
 
42805
43748
  // ../../packages/plugin-runtime/src/attached/status.ts
42806
43749
  var REFUSAL_LINES = {
@@ -42887,7 +43830,7 @@ var StandaloneDataGateway = class {
42887
43830
  // One notice per gateway — see warnRulesetDiscarded.
42888
43831
  warnedRulesetDiscarded = false;
42889
43832
  constructor(dataDir2, detections = [], meta4) {
42890
- this.db = openLocalDatabase(dataDir2);
43833
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
42891
43834
  this.dataDir = dataDir2;
42892
43835
  this.db.installedPacks.recordInventory(detections, meta4);
42893
43836
  }
@@ -43236,6 +44179,9 @@ var StandaloneDataGateway = class {
43236
44179
  scanLedgerPaths() {
43237
44180
  return Promise.resolve(this.db.scanLedger.allPaths());
43238
44181
  }
44182
+ scanLedgerPathKeys() {
44183
+ return Promise.resolve(this.db.scanLedger.pathKeys());
44184
+ }
43239
44185
  recordScanned(entries) {
43240
44186
  this.db.scanLedger.upsertEntries(entries);
43241
44187
  return Promise.resolve();
@@ -43243,8 +44189,8 @@ var StandaloneDataGateway = class {
43243
44189
  getRuleProbeVerdict(ruleKey) {
43244
44190
  return Promise.resolve(this.db.ruleProbeCache.getVerdict(ruleKey));
43245
44191
  }
43246
- setRuleProbeVerdict(ruleKey, verdict, worstProbeMs) {
43247
- this.db.ruleProbeCache.setVerdict(ruleKey, verdict, worstProbeMs);
44192
+ setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
44193
+ this.db.ruleProbeCache.setVerdict(ruleKey, verdict, worstProbeMs2);
43248
44194
  return Promise.resolve();
43249
44195
  }
43250
44196
  openAtRestKeysForPath(path) {
@@ -43323,11 +44269,15 @@ function resolveGatewayForConfig(config2, meta4) {
43323
44269
  readStore: () => readStorePosture(config2.dbPath),
43324
44270
  hostname: () => hostname6(),
43325
44271
  now: () => Date.now(),
44272
+ // The mode THIS gateway enforces, from the attachment resolved above,
44273
+ // so the report cannot name a mode the forward paths are not using.
44274
+ attachmentMode: attachment.mode,
43326
44275
  // The reporting build's identity, when the caller knows it (the plugin
43327
44276
  // adapters do; an embedder or a test may not). Composed with the SAME
43328
44277
  // policy store the sync child writes, so the block names the bundle
43329
- // actually in force. Key omitted rather than set undefined — the
43330
- // reporter keys on presence.
44278
+ // actually in force. The dependency key is omitted when no build is
44279
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
44280
+ // then adds no block.
43331
44281
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
43332
44282
  })
43333
44283
  });
@@ -43344,7 +44294,57 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
43344
44294
  }
43345
44295
 
43346
44296
  // ../../packages/plugin-runtime/src/handle-session-start.ts
43347
- import { randomUUID as randomUUID19 } from "crypto";
44297
+ import { randomUUID as randomUUID18 } from "crypto";
44298
+
44299
+ // ../../packages/plugin-runtime/src/mod-policy-sync.ts
44300
+ function modPolicyInputFromBundle(bundle) {
44301
+ const extra = bundle.rules ?? [];
44302
+ const rules = bundle.rulesComplete ? extra : extra.length > 0 ? [...bundledDetections().flatMap((pack) => pack.rules), ...extra] : void 0;
44303
+ return {
44304
+ rules,
44305
+ policies: bundle.policies,
44306
+ exceptionRuleIds: (bundle.exceptions ?? []).map((entry) => entry.ruleId)
44307
+ };
44308
+ }
44309
+ async function vetRulesForModFromGateway(rules, gateway, prober) {
44310
+ const bundledKeys = new Set(
44311
+ bundledDetections().flatMap((pack) => pack.rules).map(ruleProbeKey)
44312
+ );
44313
+ const shipped = [];
44314
+ const unproven = [];
44315
+ for (const rule of rules) {
44316
+ const key = ruleProbeKey(rule);
44317
+ if (key === void 0) shipped.push(rule);
44318
+ else if (bundledKeys.has(key)) {
44319
+ const verdict = await gateway.getRuleProbeVerdict(key).catch(() => void 0);
44320
+ if (verdict?.verdict !== "quarantined") shipped.push(rule);
44321
+ } else unproven.push(rule);
44322
+ }
44323
+ let isolated;
44324
+ const passed = new Set(
44325
+ await filterUnsafeRules(unproven, gateway, {
44326
+ prober: prober ?? {
44327
+ probe: (rule) => {
44328
+ isolated ??= createIsolatedScanner({ verified: [], unverified: [] });
44329
+ return isolated.probe(rule);
44330
+ }
44331
+ }
44332
+ })
44333
+ );
44334
+ await isolated?.close();
44335
+ const keep = /* @__PURE__ */ new Set([...shipped, ...passed]);
44336
+ return rules.filter((rule) => keep.has(rule));
44337
+ }
44338
+ async function syncModPolicySnapshot(gateway, dataDir2, prober) {
44339
+ try {
44340
+ const input2 = modPolicyInputFromBundle(await gateway.getPolicyBundle());
44341
+ const rules = input2.rules === void 0 ? void 0 : await vetRulesForModFromGateway(input2.rules, gateway, prober);
44342
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot({ ...input2, rules }));
44343
+ } catch {
44344
+ }
44345
+ }
44346
+
44347
+ // ../../packages/plugin-runtime/src/handle-session-start.ts
43348
44348
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
43349
44349
  async function handleSessionStart(input2, config2 = loadConfig()) {
43350
44350
  const silent = { staleBinaryNotice: null };
@@ -43386,6 +44386,9 @@ async function handleSessionStart(input2, config2 = loadConfig()) {
43386
44386
  } catch {
43387
44387
  }
43388
44388
  }
44389
+ if (input2.tool === SOURCE_TOOL.ClaudeCode) {
44390
+ await syncModPolicySnapshot(gateway, config2.dataDir);
44391
+ }
43389
44392
  if (offersMaintenance(gateway, "recordProjectFiles")) {
43390
44393
  try {
43391
44394
  if (resolved.sourceProjectId) {
@@ -43437,7 +44440,7 @@ async function recordConfigInventory(gateway, sessionId, cwd, homeDir) {
43437
44440
  }
43438
44441
  function buildConfigScanEvent(sessionId, scan2) {
43439
44442
  return {
43440
- id: randomUUID19(),
44443
+ id: randomUUID18(),
43441
44444
  eventType: "config_scan",
43442
44445
  startedAt: scan2.scannedAt,
43443
44446
  parentId: sessionId,
@@ -43496,27 +44499,27 @@ function pluginBuild() {
43496
44499
 
43497
44500
  // src/history/reconcile-trigger.ts
43498
44501
  import { spawn as spawn4 } from "child_process";
43499
- import { dirname as dirname8, join as join35 } from "path";
44502
+ import { dirname as dirname7, join as join34 } from "path";
43500
44503
  import { fileURLToPath as fileURLToPath5 } from "url";
43501
44504
 
43502
44505
  // src/history/tail.ts
43503
- import { createHash as createHash7 } from "crypto";
44506
+ import { createHash as createHash8 } from "crypto";
43504
44507
  import {
43505
- closeSync as closeSync3,
43506
- fstatSync as fstatSync2,
43507
- mkdirSync as mkdirSync5,
43508
- openSync as openSync3,
43509
- readFileSync as readFileSync21,
43510
- readSync as readSync2,
43511
- writeFileSync as writeFileSync8
44508
+ closeSync as closeSync2,
44509
+ fstatSync,
44510
+ mkdirSync as mkdirSync4,
44511
+ openSync as openSync2,
44512
+ readFileSync as readFileSync20,
44513
+ readSync,
44514
+ writeFileSync as writeFileSync7
43512
44515
  } from "fs";
43513
- import { join as join34 } from "path";
44516
+ import { join as join33 } from "path";
43514
44517
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
43515
44518
  function safeSessionId(sessionId) {
43516
44519
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
43517
44520
  return sessionId;
43518
44521
  }
43519
- return createHash7("sha256").update(sessionId).digest("hex");
44522
+ return createHash8("sha256").update(sessionId).digest("hex");
43520
44523
  }
43521
44524
 
43522
44525
  // src/history/reconcile-trigger.ts
@@ -43526,8 +44529,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
43526
44529
  try {
43527
44530
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
43528
44531
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
43529
- const here = dirname8(fileURLToPath5(import.meta.url));
43530
- const child = spawn4(process.execPath, [join35(here, "reconcile.js"), sessionId, transcriptPath], {
44532
+ const here = dirname7(fileURLToPath5(import.meta.url));
44533
+ const child = spawn4(process.execPath, [join34(here, "reconcile.js"), sessionId, transcriptPath], {
43531
44534
  detached: true,
43532
44535
  stdio: "ignore"
43533
44536
  });
@@ -43537,9 +44540,9 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
43537
44540
  }
43538
44541
 
43539
44542
  // src/history/transcripts.ts
43540
- import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync22, readSync as readSync3, statSync as statSync10 } from "fs";
44543
+ import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync4, readFileSync as readFileSync21, readSync as readSync2, statSync as statSync10 } from "fs";
43541
44544
  import { homedir as homedir3 } from "os";
43542
- import { join as join36 } from "path";
44545
+ import { join as join35 } from "path";
43543
44546
  function isRecord(value) {
43544
44547
  return typeof value === "object" && value !== null;
43545
44548
  }
@@ -43550,13 +44553,13 @@ var SESSION_META_PEEK_BYTES = 4096;
43550
44553
  function peekSessionOriginator(transcriptPath) {
43551
44554
  let head;
43552
44555
  try {
43553
- const fd = openSync4(transcriptPath, "r");
44556
+ const fd = openSync3(transcriptPath, "r");
43554
44557
  try {
43555
44558
  const buf = Buffer.allocUnsafe(SESSION_META_PEEK_BYTES);
43556
- const bytesRead = readSync3(fd, buf, 0, SESSION_META_PEEK_BYTES, 0);
44559
+ const bytesRead = readSync2(fd, buf, 0, SESSION_META_PEEK_BYTES, 0);
43557
44560
  head = buf.subarray(0, bytesRead).toString("utf8");
43558
44561
  } finally {
43559
- closeSync4(fd);
44562
+ closeSync3(fd);
43560
44563
  }
43561
44564
  } catch {
43562
44565
  return void 0;
@@ -43578,17 +44581,17 @@ var DAY_MS5 = 24 * 60 * 60 * 1e3;
43578
44581
 
43579
44582
  // src/protocol/marker.ts
43580
44583
  import { randomBytes as randomBytes4 } from "crypto";
43581
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync23, renameSync as renameSync5, writeFileSync as writeFileSync9 } from "fs";
43582
- import { join as join37 } from "path";
44584
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync22, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "fs";
44585
+ import { join as join36 } from "path";
43583
44586
  var MARKER_FILE = "protocol-marker";
43584
44587
  function mintMarker() {
43585
44588
  return randomBytes4(8).toString("hex");
43586
44589
  }
43587
44590
  function sessionProtocolMarker(dataDir2, sessionId) {
43588
44591
  if (!sessionId) return mintMarker();
43589
- const path = join37(dataDir2, MARKER_FILE);
44592
+ const path = join36(dataDir2, MARKER_FILE);
43590
44593
  try {
43591
- const stored = JSON.parse(readFileSync23(path, "utf8"));
44594
+ const stored = JSON.parse(readFileSync22(path, "utf8"));
43592
44595
  if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
43593
44596
  return stored.marker;
43594
44597
  }
@@ -43596,9 +44599,9 @@ function sessionProtocolMarker(dataDir2, sessionId) {
43596
44599
  }
43597
44600
  const marker = mintMarker();
43598
44601
  try {
43599
- mkdirSync6(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
43600
- const tmp = join37(dataDir2, `${MARKER_FILE}.tmp`);
43601
- writeFileSync9(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
44602
+ mkdirSync5(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
44603
+ const tmp = join36(dataDir2, `${MARKER_FILE}.tmp`);
44604
+ writeFileSync8(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
43602
44605
  renameSync5(tmp, path);
43603
44606
  } catch {
43604
44607
  }
@@ -43667,16 +44670,16 @@ function countFailOpen(base) {
43667
44670
  }
43668
44671
 
43669
44672
  // src/hooks/store-health.ts
43670
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync24, writeFileSync as writeFileSync10 } from "fs";
43671
- import { dirname as dirname9, join as join38 } from "path";
44673
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync23, writeFileSync as writeFileSync9 } from "fs";
44674
+ import { dirname as dirname8, join as join37 } from "path";
43672
44675
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
43673
44676
  function markerDirs(dataDir2) {
43674
- return [dataDir2, dirname9(dataDir2)];
44677
+ return [dataDir2, dirname8(dataDir2)];
43675
44678
  }
43676
44679
  function alreadyClaimed(dirs, marker, sessionId) {
43677
44680
  return dirs.some((dir) => {
43678
44681
  try {
43679
- return readFileSync24(join38(dir, marker), "utf8") === sessionId;
44682
+ return readFileSync23(join37(dir, marker), "utf8") === sessionId;
43680
44683
  } catch {
43681
44684
  return false;
43682
44685
  }
@@ -43685,8 +44688,8 @@ function alreadyClaimed(dirs, marker, sessionId) {
43685
44688
  function recordClaim(dirs, marker, sessionId) {
43686
44689
  for (const dir of dirs) {
43687
44690
  try {
43688
- mkdirSync7(dir, { recursive: true, mode: DATA_DIR_MODE });
43689
- writeFileSync10(join38(dir, marker), sessionId, { mode: DATA_FILE_MODE });
44691
+ mkdirSync6(dir, { recursive: true, mode: DATA_DIR_MODE });
44692
+ writeFileSync9(join37(dir, marker), sessionId, { mode: DATA_FILE_MODE });
43690
44693
  return;
43691
44694
  } catch {
43692
44695
  }
@@ -43711,7 +44714,7 @@ function formatMode(mode) {
43711
44714
  }
43712
44715
  function warnIfStoreRedirected(config2, sessionId, write = (message2) => void process.stderr.write(message2)) {
43713
44716
  try {
43714
- const paths = symlinkedStorePaths(dirname9(config2.dataDir));
44717
+ const paths = symlinkedStorePaths(dirname8(config2.dataDir));
43715
44718
  if (paths.length === 0) return;
43716
44719
  if (!sessionId) {
43717
44720
  write(storeRedirectedMessage(paths));
@@ -43730,7 +44733,7 @@ function harnessVersion() {
43730
44733
  const manifestPath = process.argv[2];
43731
44734
  if (!manifestPath) return void 0;
43732
44735
  try {
43733
- const manifest = JSON.parse(readFileSync25(manifestPath, "utf8"));
44736
+ const manifest = JSON.parse(readFileSync24(manifestPath, "utf8"));
43734
44737
  return typeof manifest.version === "string" ? manifest.version : void 0;
43735
44738
  } catch {
43736
44739
  return void 0;