@akasecurity/ai-tc-codex 0.9.14 → 0.9.16

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.
@@ -32,9 +32,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
  mod
33
33
  ));
34
34
 
35
- // ../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js
35
+ // ../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js
36
36
  var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js"(exports, module) {
37
+ "../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js"(exports, module) {
38
38
  "use strict";
39
39
  function makeArray(subject) {
40
40
  return Array.isArray(subject) ? subject : [subject];
@@ -169,6 +169,7 @@ var require_ignore = __commonJS({
169
169
  "g"
170
170
  );
171
171
  var TRAILING_WILDCARD = "\uE000";
172
+ var TRAILING_DOUBLESTAR = "\uE001";
172
173
  var extractBrackets = (pattern) => {
173
174
  const sources = [];
174
175
  const hold = (source) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
@@ -329,7 +330,7 @@ var require_ignore = __commonJS({
329
330
  // Zero, one or several directories
330
331
  // should not use '*', or it will be replaced by the next replacer
331
332
  // Check if it is not the last `'/**'`
332
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : "\\/.+",
333
+ (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
333
334
  "*"
334
335
  ],
335
336
  // normal intermediate wildcards
@@ -407,7 +408,7 @@ var require_ignore = __commonJS({
407
408
  // 'js' will match 'a.js' and 'a.js/'
408
409
  (source) => {
409
410
  const last = source[source.length - 1];
410
- if (!last || last === TRAILING_WILDCARD) {
411
+ if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
411
412
  return source;
412
413
  }
413
414
  return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
@@ -418,17 +419,20 @@ var require_ignore = __commonJS({
418
419
  var MODE_IGNORE = "regex";
419
420
  var MODE_CHECK_IGNORE = "checkRegex";
420
421
  var UNDERSCORE = "_";
421
- var TRAILING_WILD_CARD_REPLACERS = {
422
- [MODE_IGNORE](_, p1) {
423
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
- return `${prefix}(?=$|\\/$)`;
425
- },
426
- [MODE_CHECK_IGNORE](_, p1) {
427
- const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
428
- return `${prefix}(?=$|\\/$)`;
429
- }
422
+ var replaceTrailingWildcard = (_, p1) => {
423
+ const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
+ return `${prefix}(?=$|\\/$)`;
430
425
  };
426
+ var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
427
+ var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
431
428
  var WILDCARD = "[^\\/]*";
429
+ var separatorAfter = (run, at) => {
430
+ let separator = EMPTY;
431
+ for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
432
+ separator += run[index].single;
433
+ }
434
+ return separator;
435
+ };
432
436
  var pinWildcards = (source) => {
433
437
  if (source.indexOf(WILDCARD) < 0) {
434
438
  return source;
@@ -498,7 +502,7 @@ var require_ignore = __commonJS({
498
502
  out += token.single;
499
503
  return;
500
504
  }
501
- out += at === lastWildcard ? WILDCARD : `(?:(?!${run[at + 1].single})[^\\/])*`;
505
+ out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
502
506
  });
503
507
  run = [];
504
508
  };
@@ -536,6 +540,14 @@ var require_ignore = __commonJS({
536
540
  (match, index) => sources[index]
537
541
  ) : replaced;
538
542
  };
543
+ var checkSourceOf = (body, prefix) => {
544
+ if (body[body.length - 1] === SLASH3) {
545
+ prefix = makeRegexPrefix(body.slice(0, -1));
546
+ }
547
+ const head = prefix.slice(0, -1);
548
+ const last = prefix[prefix.length - 1];
549
+ return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
+ };
539
551
  var matchesBasename = (body) => {
540
552
  const index = body.indexOf(SLASH3);
541
553
  return index < 0 || index === body.length - 1;
@@ -596,11 +608,9 @@ var require_ignore = __commonJS({
596
608
  return this._make(MODE_CHECK_IGNORE, key);
597
609
  }
598
610
  _make(mode, key) {
599
- const str2 = pinWildcards(this.regexPrefix.replace(
600
- REGEX_REPLACE_TRAILING_WILDCARD,
601
- // It does not need to bind pattern
602
- TRAILING_WILD_CARD_REPLACERS[mode]
603
- ));
611
+ const str2 = pinWildcards(
612
+ mode === MODE_IGNORE ? this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar) : checkSourceOf(this.body, this.regexPrefix)
613
+ );
604
614
  const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
605
615
  return define(this, key, regex);
606
616
  }
@@ -659,8 +669,39 @@ var require_ignore = __commonJS({
659
669
  makeArray(
660
670
  isString(pattern) ? splitPattern(pattern) : pattern
661
671
  ).forEach(this._add, this);
672
+ if (this._added) {
673
+ this._literalRules = UNDEFINED;
674
+ }
662
675
  return this._added;
663
676
  }
677
+ // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule
678
+ // ending in a wildcard can match it (see `checkSourceOf`), so the rest
679
+ // are left out once, rather than tested or compiled for every path.
680
+ testLiteral(path) {
681
+ const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
+ ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
683
+ ));
684
+ let ignored = false;
685
+ let unignored = false;
686
+ let matchedRule;
687
+ for (let index = rules.length - 1; index >= 0; index--) {
688
+ const rule = rules[index];
689
+ if (rule.checkRegex.test(path)) {
690
+ ignored = !rule.negative;
691
+ unignored = rule.negative;
692
+ matchedRule = rule.negative ? UNDEFINED : rule;
693
+ break;
694
+ }
695
+ }
696
+ const ret = {
697
+ ignored,
698
+ unignored
699
+ };
700
+ if (matchedRule) {
701
+ ret.rule = matchedRule;
702
+ }
703
+ return ret;
704
+ }
664
705
  // Test one single path without recursively checking parent directories
665
706
  //
666
707
  // - checkUnignored `boolean` whether should check if the path is unignored,
@@ -675,13 +716,13 @@ var require_ignore = __commonJS({
675
716
  const rules = this._rules;
676
717
  const { length } = rules;
677
718
  const shortcut = this._basenameCount * 2 >= length;
678
- const basename6 = shortcut ? basenameOf(path) : path;
719
+ const basename7 = shortcut ? basenameOf(path) : path;
679
720
  for (let index = 0; index < length; index++) {
680
721
  const rule = rules[index];
681
722
  const { negative } = rule;
682
723
  const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
683
724
  if (!skip && rule[mode].test(
684
- shortcut && rule._basenameOnly ? basename6 : path
725
+ shortcut && rule._basenameOnly ? basename7 : path
685
726
  )) {
686
727
  ignored = !negative;
687
728
  unignored = negative;
@@ -781,14 +822,12 @@ var require_ignore = __commonJS({
781
822
  if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {
782
823
  return this.test(path);
783
824
  }
784
- const parentPath = parentOf(path);
785
- if (parentPath) {
786
- const parent = this._t(parentPath, this._testCache, true);
787
- if (parent.ignored) {
788
- return parent;
789
- }
825
+ const dir = this._t(path, this._testCache, true);
826
+ if (dir.ignored) {
827
+ return dir;
790
828
  }
791
- return this._rules.test(path, false, MODE_CHECK_IGNORE);
829
+ const literal2 = this._rules.testLiteral(path);
830
+ return literal2.ignored || literal2.unignored ? literal2 : dir;
792
831
  }
793
832
  _t(path, cache, checkUnignored) {
794
833
  if (path in cache) {
@@ -997,6 +1036,14 @@ var SQLITE_MIGRATIONS = [
997
1036
  {
998
1037
  tag: "0035_share_destination_provider_id",
999
1038
  sql: "ALTER TABLE `share_destination` ADD `provider_id` text;"
1039
+ },
1040
+ {
1041
+ tag: "0036_secret_vault_identity_fingerprint",
1042
+ sql: "ALTER TABLE `secret_vault` ADD `value_identity_fingerprint` text DEFAULT '' NOT NULL;--> statement-breakpoint\nUPDATE `secret_vault` SET `value_identity_fingerprint` = `value_fingerprint`;\n"
1043
+ },
1044
+ {
1045
+ tag: "0037_finding_location",
1046
+ sql: "ALTER TABLE `inspection_findings` ADD `line` integer;--> statement-breakpoint\nALTER TABLE `inspection_findings` ADD `col` integer;--> statement-breakpoint\nALTER TABLE `inspection_findings` ADD `context` text;--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_context` ON `inspection_findings` (`first_detected_at`) WHERE context IS NOT NULL;"
1000
1047
  }
1001
1048
  ];
1002
1049
 
@@ -6032,7 +6079,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6032
6079
  var NONE = 0;
6033
6080
  var ASSUMED = 1;
6034
6081
  var PROVEN = 2;
6035
- function isRecursive(inst, stack, resolve2) {
6082
+ function isRecursive(inst, stack, resolve3) {
6036
6083
  const cached2 = recursive.get(inst);
6037
6084
  if (cached2 !== void 0)
6038
6085
  return cached2 ? PROVEN : NONE;
@@ -6042,7 +6089,7 @@ function isRecursive(inst, stack, resolve2) {
6042
6089
  let result = NONE;
6043
6090
  const check2 = (child) => {
6044
6091
  if (result !== PROVEN && child?._zod) {
6045
- const answer = isRecursive(child, stack, resolve2);
6092
+ const answer = isRecursive(child, stack, resolve3);
6046
6093
  if (answer > result)
6047
6094
  result = answer;
6048
6095
  }
@@ -6053,7 +6100,7 @@ function isRecursive(inst, stack, resolve2) {
6053
6100
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6054
6101
  if (spread && !desc.enumerable)
6055
6102
  continue;
6056
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
6103
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6057
6104
  if (child > answer)
6058
6105
  answer = child;
6059
6106
  }
@@ -6117,7 +6164,7 @@ function isRecursive(inst, stack, resolve2) {
6117
6164
  break;
6118
6165
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6119
6166
  case "lazy": {
6120
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
6167
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6121
6168
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6122
6169
  break;
6123
6170
  }
@@ -21890,11 +21937,33 @@ var ResolutionMethod = external_exports.enum([
21890
21937
  "false-positive",
21891
21938
  "redetected"
21892
21939
  ]).meta({ id: "ResolutionMethod" });
21940
+ var FindingContextBasis = external_exports.enum(["file", "excerpt"]).meta({ id: "FindingContextBasis" });
21941
+ var FindingContext = external_exports.object({
21942
+ basis: FindingContextBasis,
21943
+ // 1-based line number of `lines[0]`.
21944
+ firstLine: external_exports.number().int().positive(),
21945
+ lines: external_exports.array(external_exports.string()).min(1).max(5),
21946
+ match: external_exports.object({
21947
+ // 1-based line number, within [firstLine, firstLine + lines.length).
21948
+ line: external_exports.number().int().positive(),
21949
+ // Offsets into that entry of `lines`, end exclusive.
21950
+ start: external_exports.number().int().nonnegative(),
21951
+ end: external_exports.number().int().nonnegative()
21952
+ }).nullable()
21953
+ }).meta({ id: "FindingContext" });
21954
+ var FindingLocation = external_exports.object({
21955
+ line: external_exports.number().int().positive(),
21956
+ col: external_exports.number().int().positive(),
21957
+ context: FindingContext.nullable()
21958
+ });
21893
21959
  var FindingMatch = external_exports.object({
21894
21960
  // Masked preview of the matched value. Never raw content.
21895
21961
  maskedValue: external_exports.string(),
21896
- // Redacted source-line prefix. Currently empty (pending privacy review).
21897
- contextPrefix: external_exports.string()
21962
+ // Deprecated: always empty. Superseded by `context`.
21963
+ contextPrefix: external_exports.string(),
21964
+ // The masked lines around the match. Absent when the finding predates
21965
+ // context capture or none could be built safely.
21966
+ context: FindingContext.optional()
21898
21967
  }).meta({ id: "FindingMatch" });
21899
21968
  var FindingDetectionRef = external_exports.object({
21900
21969
  id: external_exports.string(),
@@ -21914,6 +21983,11 @@ var FindingInstance = external_exports.object({
21914
21983
  provider: FindingProvider,
21915
21984
  repo: external_exports.string(),
21916
21985
  file: external_exports.string(),
21986
+ // 1-based line and column of the match start in the scanned text (the
21987
+ // column in UTF-16 code units). Absent for findings that predate location
21988
+ // capture or have no source text.
21989
+ line: external_exports.number().int().positive().optional(),
21990
+ col: external_exports.number().int().positive().optional(),
21917
21991
  // Who the capturing event is attributed to. Optional: a single-user store
21918
21992
  // has no one to attribute a finding to and never sets it.
21919
21993
  user: FindingUser.optional(),
@@ -21975,6 +22049,13 @@ var FindingStats = external_exports.object({
21975
22049
  low: external_exports.number().int().nonnegative()
21976
22050
  })
21977
22051
  }).meta({ id: "FindingStats" });
22052
+ var FindingsOverview = external_exports.object({
22053
+ findings: external_exports.number().int().nonnegative(),
22054
+ open: external_exports.number().int().nonnegative(),
22055
+ handled: external_exports.number().int().nonnegative(),
22056
+ resolved: external_exports.number().int().nonnegative(),
22057
+ dismissed: external_exports.number().int().nonnegative()
22058
+ }).meta({ id: "FindingsOverview" });
21978
22059
  var FindingFacetItem = external_exports.object({
21979
22060
  value: external_exports.string(),
21980
22061
  count: external_exports.number().int().nonnegative()
@@ -22094,6 +22175,7 @@ var FindingInstanceDetail = FindingInstance.extend({
22094
22175
  }).meta({ id: "FindingInstanceDetail" });
22095
22176
  var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
22096
22177
  var MAX_FLAT_FINDINGS_LIMIT = 200;
22178
+ var FindingContextQuery = external_exports.object({ id: external_exports.string().min(1).max(256) });
22097
22179
  var ListFindingInstancesQuery = external_exports.object({
22098
22180
  severity: external_exports.array(Severity).optional(),
22099
22181
  // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
@@ -22426,7 +22508,23 @@ var CaptureAttributes = external_exports.object({
22426
22508
  // capture denied by another finding's own Block policy carries `block`
22427
22509
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22428
22510
  // repeated rather than referenced because a store reader opens this file.
22429
- redact_degraded_to: ActionTaken.optional()
22511
+ redact_degraded_to: ActionTaken.optional(),
22512
+ // The scope key this capture was stamped with: the canonical repository
22513
+ // (`host/owner/repo`) of the path the capture names (a relative path is read
22514
+ // against its working directory), else of its own working directory, or a
22515
+ // chat account's identity. The store's local `scope_key` column reads it, so
22516
+ // a scoped attachment has a per-row key to work from. Absent when no key
22517
+ // could be derived.
22518
+ //
22519
+ // LOCAL ONLY. That is the contract for every path that sends a row. Producers
22520
+ // stamp it in every attachment mode, and the two structural choke points strip
22521
+ // it: the attached gateway's `reKeyForForward` on the live path, and the
22522
+ // history drain's `rebuildAuditEvent`, which drops it through `withoutScopeKey`.
22523
+ // A capture row's bag reaches the wire through `rebuildCapture`, which builds
22524
+ // the metadata from named keys and never names this one; `toCaptureAttributes`,
22525
+ // which builds the bag from a wire event, never emits it. What a scoped
22526
+ // attachment does with the key is not part of this shape's contract.
22527
+ scope_key: external_exports.string().optional()
22430
22528
  }).catchall(external_exports.unknown());
22431
22529
  var CaptureStatusAttributes = external_exports.object({
22432
22530
  source_tool: external_exports.string().optional(),
@@ -22456,6 +22554,12 @@ var ToolCallInspection = external_exports.object({
22456
22554
  actionTaken: ActionTaken,
22457
22555
  confidence: external_exports.number().min(0).max(1)
22458
22556
  });
22557
+ var findingLocationFields = {
22558
+ line: external_exports.number().int().positive().optional(),
22559
+ col: external_exports.number().int().positive().optional(),
22560
+ context: FindingContext.nullable().optional()
22561
+ };
22562
+ var ToolCallInspectionInput = ToolCallInspection.extend(findingLocationFields);
22459
22563
  var ToolCallInput = external_exports.object({
22460
22564
  sessionId: external_exports.string().min(1),
22461
22565
  toolUseId: external_exports.string().min(1),
@@ -22465,7 +22569,7 @@ var ToolCallInput = external_exports.object({
22465
22569
  attributes: ToolCallAttributes,
22466
22570
  // Secrets detected in the tool's (masked) target — written as linked
22467
22571
  // `inspection_findings`. Empty for a clean tool call.
22468
- inspections: external_exports.array(ToolCallInspection).default([])
22572
+ inspections: external_exports.array(ToolCallInspectionInput).default([])
22469
22573
  });
22470
22574
  var InventoryInput = external_exports.object({
22471
22575
  objectType: InventoryObjectType,
@@ -22539,7 +22643,8 @@ var InspectionFindingInput = external_exports.object({
22539
22643
  // same findingKey — mirrors the legacy `findings.first_detected_at`.
22540
22644
  // Optional: when omitted, the writer derives it from the referenced audit
22541
22645
  // event's startedAt on first insert (see SqliteInspectionFindingsRepository).
22542
- firstDetectedAt: external_exports.iso.datetime().optional()
22646
+ firstDetectedAt: external_exports.iso.datetime().optional(),
22647
+ ...findingLocationFields
22543
22648
  });
22544
22649
  var InventoryContext = external_exports.object({
22545
22650
  host: InventoryInput.optional(),
@@ -23318,6 +23423,17 @@ var AttachedCredential = external_exports.object({
23318
23423
  keyPrefix: external_exports.string().min(1).max(16).optional(),
23319
23424
  mintedAt: external_exports.iso.datetime().optional()
23320
23425
  });
23426
+ var AttachmentMode = external_exports.enum(["machine", "scoped"]);
23427
+ var ATTACHED_CREDENTIAL_SCOPED_SPEC_VERSION = 2;
23428
+ var AttachedCredentialV1 = AttachedCredential;
23429
+ var AttachedCredentialV2 = AttachedCredential.extend({
23430
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SCOPED_SPEC_VERSION),
23431
+ mode: external_exports.literal("scoped")
23432
+ });
23433
+ var AttachedCredentialAny = external_exports.discriminatedUnion("specVersion", [
23434
+ AttachedCredentialV1,
23435
+ AttachedCredentialV2
23436
+ ]);
23321
23437
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
23322
23438
  function unsafeEndpointReason(endpoint) {
23323
23439
  let parsed2;
@@ -23398,7 +23514,29 @@ var StorePosturePlugin = external_exports.object({
23398
23514
  */
23399
23515
  policyBundleVersion: external_exports.string().max(200).nullable(),
23400
23516
  /** Epoch millis, on the CLIENT clock, of that fetch. */
23401
- policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
23517
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
23518
+ /**
23519
+ * The newest version the host's own install record holds for this plugin —
23520
+ * what is on disk. After an update it leads `version` (the running copy) by
23521
+ * one launch. Null when no usable version can be read: no install record
23522
+ * (a plugin run from a checkout), no entry with a valid version, or every
23523
+ * such entry names an `installPath` that no longer exists; OPTIONAL, not
23524
+ * required, so a build that predates the member keeps getting its 200.
23525
+ * Bounded like `version`.
23526
+ */
23527
+ installedVersion: external_exports.string().max(64).nullable().optional(),
23528
+ /**
23529
+ * The local-store schema version this running build migrates a store to:
23530
+ * the number of store migrations it carries, the count it stamps into
23531
+ * `PRAGMA user_version`. A snapshot whose `schemaVersion` is above it
23532
+ * usually describes a store a newer build migrated. It is a hint, not a
23533
+ * verdict: the stamp is write-only, so a store whose count ran past this
23534
+ * build's while this build knows every migration in its ledger reads above
23535
+ * it too, which is why describeStoreSkew decides skew on ledger tags and
23536
+ * never on the count. OPTIONAL for the same reason as `installedVersion`;
23537
+ * bounded like `schemaVersion`.
23538
+ */
23539
+ buildSchemaVersion: external_exports.number().int().min(0).max(MAX_INT4).optional()
23402
23540
  }).meta({ id: "StorePosturePlugin" });
23403
23541
  var StorePostureSnapshot = external_exports.object({
23404
23542
  deviceId: external_exports.guid(),
@@ -23601,6 +23739,130 @@ var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
23601
23739
  var SemVer = external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/);
23602
23740
  var PublisherKind = external_exports.enum(["labs", "user", "org"]);
23603
23741
 
23742
+ // ../../packages/schema/src/zod/builtin-policy-id.ts
23743
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23744
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23745
+
23746
+ // ../../packages/schema/src/zod/event.ts
23747
+ var EventKind = external_exports.enum(["prompt", "response", "code_change", "tool_use"]).meta({ id: "EventKind" });
23748
+ var CAPTURE_EVENT_TYPES_SQL = EventKind.options.map((k) => `'${k}'`).join(",");
23749
+ var EventMetadata = external_exports.object({
23750
+ sessionId: external_exports.string().optional(),
23751
+ repo: external_exports.string().optional(),
23752
+ filePath: external_exports.string().optional(),
23753
+ // The host tool whose input/output was scanned (e.g. 'Bash', 'WebFetch'),
23754
+ // set by the tool-scanning hooks. The tool NAME only — never the tool's
23755
+ // arguments or output, which can carry the very value a finding masked
23756
+ // (metadata is stored unredacted). Gives findings on non-file captures a
23757
+ // display location ("via Bash") when no filePath exists.
23758
+ toolName: external_exports.string().optional(),
23759
+ // Set (true) by the worktree scanner when the file is excluded by the
23760
+ // repo's .gitignore. Gitignored files ARE still scanned — local scratch and
23761
+ // generated code can leak real secrets — but the provenance is recorded so
23762
+ // policy/dashboards can treat those findings as informational rather than
23763
+ // blocking. Omitted (not false) for tracked files and non-scan events.
23764
+ gitignored: external_exports.boolean().optional(),
23765
+ // Set (true) ONLY when the event's `content` is the COMPLETE file at
23766
+ // capture time (a worktree scan reading from disk). Hook-captured edits
23767
+ // (e.g. an Edit tool's new_string) are partial fragments and MUST NOT set
23768
+ // this. The resolver-on-ingest keys its fixed-at-source dropout
23769
+ // diff on this marker: only a whole-file snapshot can prove a previously
23770
+ // open finding is gone; a fragment's absence proves nothing (the secret
23771
+ // may live outside the hunk). Omitted (not false) for fragments and
23772
+ // non-scan events, so pre-marker clients safely default to the
23773
+ // non-authoritative path.
23774
+ wholeFile: external_exports.boolean().optional(),
23775
+ model: external_exports.string().optional(),
23776
+ turnIndex: external_exports.number().int().nonnegative().optional(),
23777
+ // Distributed-tracing correlation. `correlationId` ties a recorded event back
23778
+ // to the request that captured/ingested it (a UUID, generated independently of
23779
+ // the trace id); `traceId` is the W3C trace id (32 lowercase hex chars) of the
23780
+ // originating span when telemetry is enabled. Both optional + backward
23781
+ // compatible — populated by the plugin (see @akasecurity/plugin-sdk).
23782
+ correlationId: external_exports.uuid().optional(),
23783
+ traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).optional(),
23784
+ // Ids of the detection exceptions that downgraded findings in this capture
23785
+ // to 'allow' — the enforcement audit trail's link back to the grant that
23786
+ // authorized the bypass. Absent on captures where no exception applied.
23787
+ exceptionIds: external_exports.array(external_exports.guid()).optional(),
23788
+ // The assistant message this capture belongs to, and the conversation it sits
23789
+ // in — set by the browser extension's network capture so a stored `response`
23790
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
23791
+ // on every other capture path, which has no such id.
23792
+ //
23793
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
23794
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
23795
+ // places an event is PARSED; the local write path types the event and parses
23796
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
23797
+ messageId: external_exports.string().min(1).optional(),
23798
+ conversationId: external_exports.string().optional(),
23799
+ // How long THIS capture's inspection blocked its caller, in whole
23800
+ // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
23801
+ // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
23802
+ // detection + redaction, the work the host session actually waits on.
23803
+ //
23804
+ // Stamped ONLY on live in-flight captures. A capture that carries its own
23805
+ // `occurredAt` is replaying past work (the transcript backfill, the worktree
23806
+ // scan), and its scan duration is not latency any host session experienced,
23807
+ // so those rows leave this ABSENT rather than reporting a misleading number.
23808
+ // Absent is also what every pre-measurement client writes, and what a
23809
+ // clock failure degrades to — a reader must treat absence as "not measured"
23810
+ // and never as a zero, which would read as "inspection is free".
23811
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
23812
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
23813
+ // workspace's `redactFallback`, applied because the field could not be
23814
+ // masked in place (a shell command, a URL, or any argument on a host whose
23815
+ // hook contract offers no rewrite channel).
23816
+ //
23817
+ // It exists because the action alone cannot say why. A finding recorded as
23818
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
23819
+ // assigned Redact on a field that could not take one — and those are
23820
+ // different facts about the same row: the first is a policy the user chose,
23821
+ // the second is a masking the host could not perform. Absent means no
23822
+ // degrade happened, which is every ordinary capture.
23823
+ //
23824
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
23825
+ // is the CAPTURE while `actionTaken` is per FINDING:
23826
+ //
23827
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
23828
+ // `redact` alongside a finding ASSIGNED the same action stores both
23829
+ // identically and one reason for the pair; attributing it to both
23830
+ // describes the assigned one wrongly, and to neither loses the degrade.
23831
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
23832
+ // became, not the reason the capture ended as it did — a capture denied
23833
+ // by some other finding's own Block policy still carries `block` here,
23834
+ // and clearing the workspace's fallback would not have let it through.
23835
+ // Gate on the value against what a fallback can produce; never read the
23836
+ // field's presence as "this was the fallback's doing".
23837
+ //
23838
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23839
+ // Closing either means moving the reason onto the finding row, which
23840
+ // already carries its own action.
23841
+ redactDegradedTo: ActionTaken.optional()
23842
+ }).meta({ id: "EventMetadata" });
23843
+ var Event = external_exports.object({
23844
+ id: external_exports.guid(),
23845
+ sourceTool: SourceTool,
23846
+ kind: EventKind,
23847
+ occurredAt: external_exports.iso.datetime(),
23848
+ contentHash: external_exports.string(),
23849
+ content: external_exports.string(),
23850
+ metadata: EventMetadata.optional()
23851
+ }).meta({ id: "Event" });
23852
+ var IngestEvent = Event.meta({ id: "IngestEvent" });
23853
+ var INGEST_BATCH_MAX = 100;
23854
+ var IngestBatch = external_exports.object({
23855
+ events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
23856
+ // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
23857
+ // additionally rejects any event whose contentHash the store has already
23858
+ // recorded — for re-runnable bulk ingest (worktree scan, transcript
23859
+ // backfill), where a re-run mints fresh event ids for identical content and
23860
+ // would otherwise accumulate duplicates. Live hook traffic must NOT set it:
23861
+ // two genuinely separate prompts can be byte-identical and both belong on
23862
+ // the timeline.
23863
+ dedupe: external_exports.literal("content-hash").optional()
23864
+ }).meta({ id: "IngestBatch" });
23865
+
23604
23866
  // ../../packages/schema/src/zod/rule.ts
23605
23867
  var MatcherType = external_exports.enum(["keyword", "regex"]).meta({ id: "MatcherType" });
23606
23868
  var RuleProbeVerdict = external_exports.enum(["safe", "quarantined"]).meta({ id: "RuleProbeVerdict" });
@@ -23669,7 +23931,10 @@ var Matcher = external_exports.discriminatedUnion("type", [KeywordMatcher, Regex
23669
23931
  var MATCHER_TYPES = MatcherType.options;
23670
23932
  var AppliesTo = external_exports.strictObject({
23671
23933
  // Dot-prefixed, e.g. ".py" — matches the scanner's SOURCE_EXTENSIONS shape.
23672
- extensions: external_exports.array(external_exports.string().regex(/^\.[A-Za-z0-9]+$/)).min(1)
23934
+ extensions: external_exports.array(external_exports.string().regex(/^\.[A-Za-z0-9]+$/)).min(1).optional(),
23935
+ eventKinds: external_exports.array(EventKind).min(1).optional()
23936
+ }).refine((v) => v.extensions !== void 0 || v.eventKinds !== void 0, {
23937
+ message: "appliesTo needs extensions, eventKinds, or both"
23673
23938
  }).meta({ id: "AppliesTo" });
23674
23939
  var PostValidatorName = external_exports.enum(["entropy", "luhn"]).meta({ id: "PostValidatorName" });
23675
23940
  var PostValidatorRef = external_exports.union(
@@ -23692,6 +23957,7 @@ var PostValidatorRef = external_exports.union(
23692
23957
  )}) or { "name": ..., "config": { ... } }. An unrecognized name would be a false-positive guard that never runs.`
23693
23958
  }
23694
23959
  ).meta({ id: "PostValidatorRef" });
23960
+ var RuleEvidence = external_exports.enum(["code", "value"]).meta({ id: "RuleEvidence" });
23695
23961
  var RequiresNearby = external_exports.strictObject({
23696
23962
  // Each array, when present, must be non-empty and contain non-empty strings —
23697
23963
  // an empty/blank criterion would either never fire or (for labels) match
@@ -23714,6 +23980,8 @@ var RuleFixture = external_exports.strictObject({
23714
23980
  // Simulated file context for the scan, so fixtures can assert `appliesTo`
23715
23981
  // gating (e.g. a Python-only pattern must NOT fire in a .ts file).
23716
23982
  filePath: external_exports.string().optional(),
23983
+ // Simulated capture kind, so fixtures can assert `appliesTo.eventKinds`.
23984
+ eventKind: EventKind.optional(),
23717
23985
  expectedSpans: external_exports.array(external_exports.strictObject({ start: external_exports.number(), end: external_exports.number() })).optional()
23718
23986
  }).meta({ id: "RuleFixture" });
23719
23987
  var Rule = external_exports.strictObject({
@@ -23739,7 +24007,9 @@ var Rule = external_exports.strictObject({
23739
24007
  appliesTo: AppliesTo.optional(),
23740
24008
  postValidators: external_exports.array(PostValidatorRef).optional(),
23741
24009
  requiresNearby: RequiresNearby.optional(),
23742
- examples: external_exports.array(external_exports.string()).optional()
24010
+ examples: external_exports.array(external_exports.string()).optional(),
24011
+ // Whether the matched text is itself sensitive. Absent means 'value'.
24012
+ evidence: RuleEvidence.optional()
23743
24013
  }).meta({ id: "Rule" });
23744
24014
  var Author = external_exports.object({
23745
24015
  name: external_exports.string(),
@@ -23756,7 +24026,11 @@ var PackManifest = external_exports.object({
23756
24026
  description: external_exports.string().optional(),
23757
24027
  author: Author.optional(),
23758
24028
  license: external_exports.string().optional(),
23759
- sourceUrl: external_exports.url().optional()
24029
+ sourceUrl: external_exports.url().optional(),
24030
+ // The built-in policy a FIRST install of this pack assigns
24031
+ // (installed_packs.policy_id). Absent leaves the pack unassigned, so its
24032
+ // rules follow the category policies. An existing install never takes it.
24033
+ defaultPolicy: BuiltinPolicyId.optional()
23760
24034
  }).meta({ id: "PackManifest" });
23761
24035
 
23762
24036
  // ../../packages/schema/src/zod/detection.ts
@@ -23784,10 +24058,12 @@ var DetectionListItem = external_exports.object({
23784
24058
  // Per-pack enforcement-policy assignment. Holds a BuiltinPolicyId ARCHETYPE
23785
24059
  // (monitor|warn|redact|block) — NOT a policies-table Policy.id guid; a
23786
24060
  // detection is a PACK, and its policy is the archetype applied to all its
23787
- // rules. Absent == unassigned, which resolves to Monitor everywhere
23788
- // (DEFAULT_PACK_POLICY_ID). Every enforcement surface expands it into
23789
- // per-rule policies (see policyIdToAction). Typed z.string() (not
23790
- // the enum) to keep the OpenAPI response tolerant of a future custom id.
24061
+ // rules. Absent == unassigned, which resolves to Monitor by default
24062
+ // (DEFAULT_PACK_POLICY_ID); a host may resolve it to a policy of its own
24063
+ // (see the dashboard's `unassignedPolicy`). Every enforcement surface
24064
+ // expands it into per-rule policies (see policyIdToAction). Typed
24065
+ // z.string() (not the enum) to keep the OpenAPI response tolerant of a
24066
+ // future custom id.
23791
24067
  policyId: external_exports.string().optional(),
23792
24068
  // Set ONLY when a newer snapshot is available for this pack (OSS: the
23793
24069
  // bundled inventory recorded in available_packs differs from the installed
@@ -23856,10 +24132,12 @@ var DetectionDetail = external_exports.object({
23856
24132
  // Per-pack enforcement-policy assignment. Holds a BuiltinPolicyId ARCHETYPE
23857
24133
  // (monitor|warn|redact|block) — NOT a policies-table Policy.id guid; a
23858
24134
  // detection is a PACK, and its policy is the archetype applied to all its
23859
- // rules. Absent == unassigned, which resolves to Monitor everywhere
23860
- // (DEFAULT_PACK_POLICY_ID). Every enforcement surface expands it into
23861
- // per-rule policies (see policyIdToAction). Typed z.string() (not
23862
- // the enum) to keep the OpenAPI response tolerant of a future custom id.
24135
+ // rules. Absent == unassigned, which resolves to Monitor by default
24136
+ // (DEFAULT_PACK_POLICY_ID); a host may resolve it to a policy of its own
24137
+ // (see the dashboard's `unassignedPolicy`). Every enforcement surface
24138
+ // expands it into per-rule policies (see policyIdToAction). Typed
24139
+ // z.string() (not the enum) to keep the OpenAPI response tolerant of a
24140
+ // future custom id.
23863
24141
  policyId: external_exports.string().optional()
23864
24142
  }).meta({ id: "DetectionDetail" });
23865
24143
  var LibraryItem = external_exports.object({
@@ -24006,126 +24284,6 @@ function buildDetectionsList(summaries, query) {
24006
24284
  return { counts, items: filtered.map(summaryToDetectionListItem) };
24007
24285
  }
24008
24286
 
24009
- // ../../packages/schema/src/zod/event.ts
24010
- var EventKind = external_exports.enum(["prompt", "response", "code_change", "tool_use"]).meta({ id: "EventKind" });
24011
- var CAPTURE_EVENT_TYPES_SQL = EventKind.options.map((k) => `'${k}'`).join(",");
24012
- var EventMetadata = external_exports.object({
24013
- sessionId: external_exports.string().optional(),
24014
- repo: external_exports.string().optional(),
24015
- filePath: external_exports.string().optional(),
24016
- // The host tool whose input/output was scanned (e.g. 'Bash', 'WebFetch'),
24017
- // set by the tool-scanning hooks. The tool NAME only — never the tool's
24018
- // arguments or output, which can carry the very value a finding masked
24019
- // (metadata is stored unredacted). Gives findings on non-file captures a
24020
- // display location ("via Bash") when no filePath exists.
24021
- toolName: external_exports.string().optional(),
24022
- // Set (true) by the worktree scanner when the file is excluded by the
24023
- // repo's .gitignore. Gitignored files ARE still scanned — local scratch and
24024
- // generated code can leak real secrets — but the provenance is recorded so
24025
- // policy/dashboards can treat those findings as informational rather than
24026
- // blocking. Omitted (not false) for tracked files and non-scan events.
24027
- gitignored: external_exports.boolean().optional(),
24028
- // Set (true) ONLY when the event's `content` is the COMPLETE file at
24029
- // capture time (a worktree scan reading from disk). Hook-captured edits
24030
- // (e.g. an Edit tool's new_string) are partial fragments and MUST NOT set
24031
- // this. The resolver-on-ingest keys its fixed-at-source dropout
24032
- // diff on this marker: only a whole-file snapshot can prove a previously
24033
- // open finding is gone; a fragment's absence proves nothing (the secret
24034
- // may live outside the hunk). Omitted (not false) for fragments and
24035
- // non-scan events, so pre-marker clients safely default to the
24036
- // non-authoritative path.
24037
- wholeFile: external_exports.boolean().optional(),
24038
- model: external_exports.string().optional(),
24039
- turnIndex: external_exports.number().int().nonnegative().optional(),
24040
- // Distributed-tracing correlation. `correlationId` ties a recorded event back
24041
- // to the request that captured/ingested it (a UUID, generated independently of
24042
- // the trace id); `traceId` is the W3C trace id (32 lowercase hex chars) of the
24043
- // originating span when telemetry is enabled. Both optional + backward
24044
- // compatible — populated by the plugin (see @akasecurity/plugin-sdk).
24045
- correlationId: external_exports.uuid().optional(),
24046
- traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).optional(),
24047
- // Ids of the detection exceptions that downgraded findings in this capture
24048
- // to 'allow' — the enforcement audit trail's link back to the grant that
24049
- // authorized the bypass. Absent on captures where no exception applied.
24050
- exceptionIds: external_exports.array(external_exports.guid()).optional(),
24051
- // The assistant message this capture belongs to, and the conversation it sits
24052
- // in — set by the browser extension's network capture so a stored `response`
24053
- // row can be joined to the `llm_call` leaf describing the same turn. Absent
24054
- // on every other capture path, which has no such id.
24055
- //
24056
- // Non-empty for the reason WebExchange.messageId is: it is the join key, and
24057
- // a blank one matches no `llm_call` leaf. That refusal reaches only the
24058
- // places an event is PARSED; the local write path types the event and parses
24059
- // nothing, which is why `toCaptureAttributes` omits a blank one separately.
24060
- messageId: external_exports.string().min(1).optional(),
24061
- conversationId: external_exports.string().optional(),
24062
- // How long THIS capture's inspection blocked its caller, in whole
24063
- // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
24064
- // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
24065
- // detection + redaction, the work the host session actually waits on.
24066
- //
24067
- // Stamped ONLY on live in-flight captures. A capture that carries its own
24068
- // `occurredAt` is replaying past work (the transcript backfill, the worktree
24069
- // scan), and its scan duration is not latency any host session experienced,
24070
- // so those rows leave this ABSENT rather than reporting a misleading number.
24071
- // Absent is also what every pre-measurement client writes, and what a
24072
- // clock failure degrades to — a reader must treat absence as "not measured"
24073
- // and never as a zero, which would read as "inspection is free".
24074
- inspectionMs: external_exports.number().int().nonnegative().optional(),
24075
- // What a `redact` this capture COULD NOT CARRY OUT became instead — the
24076
- // workspace's `redactFallback`, applied because the field could not be
24077
- // masked in place (a shell command, a URL, or any argument on a host whose
24078
- // hook contract offers no rewrite channel).
24079
- //
24080
- // It exists because the action alone cannot say why. A finding recorded as
24081
- // `warn` reads identically whether its detection was ASSIGNED Warn or was
24082
- // assigned Redact on a field that could not take one — and those are
24083
- // different facts about the same row: the first is a policy the user chose,
24084
- // the second is a masking the host could not perform. Absent means no
24085
- // degrade happened, which is every ordinary capture.
24086
- //
24087
- // TWO LIMITS a reader of a stored row has to know, because the grain here
24088
- // is the CAPTURE while `actionTaken` is per FINDING:
24089
- //
24090
- // - It does not say WHICH finding degraded. A capture carrying a degraded
24091
- // `redact` alongside a finding ASSIGNED the same action stores both
24092
- // identically and one reason for the pair; attributing it to both
24093
- // describes the assigned one wrongly, and to neither loses the degrade.
24094
- // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
24095
- // became, not the reason the capture ended as it did — a capture denied
24096
- // by some other finding's own Block policy still carries `block` here,
24097
- // and clearing the workspace's fallback would not have let it through.
24098
- // Gate on the value against what a fallback can produce; never read the
24099
- // field's presence as "this was the fallback's doing".
24100
- //
24101
- // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
24102
- // Closing either means moving the reason onto the finding row, which
24103
- // already carries its own action.
24104
- redactDegradedTo: ActionTaken.optional()
24105
- }).meta({ id: "EventMetadata" });
24106
- var Event = external_exports.object({
24107
- id: external_exports.guid(),
24108
- sourceTool: SourceTool,
24109
- kind: EventKind,
24110
- occurredAt: external_exports.iso.datetime(),
24111
- contentHash: external_exports.string(),
24112
- content: external_exports.string(),
24113
- metadata: EventMetadata.optional()
24114
- }).meta({ id: "Event" });
24115
- var IngestEvent = Event.meta({ id: "IngestEvent" });
24116
- var INGEST_BATCH_MAX = 100;
24117
- var IngestBatch = external_exports.object({
24118
- events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
24119
- // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
24120
- // additionally rejects any event whose contentHash the store has already
24121
- // recorded — for re-runnable bulk ingest (worktree scan, transcript
24122
- // backfill), where a re-run mints fresh event ids for identical content and
24123
- // would otherwise accumulate duplicates. Live hook traffic must NOT set it:
24124
- // two genuinely separate prompts can be byte-identical and both belong on
24125
- // the timeline.
24126
- dedupe: external_exports.literal("content-hash").optional()
24127
- }).meta({ id: "IngestBatch" });
24128
-
24129
24287
  // ../../packages/schema/src/zod/exception.ts
24130
24288
  var ExceptionScope = external_exports.enum(["once", "temporary", "permanent"]);
24131
24289
  var ExceptionConditions = external_exports.object({
@@ -24593,6 +24751,8 @@ function toInstanceDetail(row) {
24593
24751
  provider: toApiProvider(row.sourceTool),
24594
24752
  repo: row.repo,
24595
24753
  file: row.file,
24754
+ ...row.line === void 0 ? {} : { line: row.line },
24755
+ ...row.col === void 0 ? {} : { col: row.col },
24596
24756
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
24597
24757
  eventId: row.eventId,
24598
24758
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
@@ -24606,7 +24766,11 @@ function toInstanceDetail(row) {
24606
24766
  category,
24607
24767
  subtype: row.ruleId,
24608
24768
  severity: row.severity,
24609
- match: { maskedValue: row.maskedMatch, contextPrefix: "" },
24769
+ match: {
24770
+ maskedValue: row.maskedMatch,
24771
+ contextPrefix: "",
24772
+ ...row.context === void 0 ? {} : { context: row.context }
24773
+ },
24610
24774
  detection: { id: row.ruleId, name: null },
24611
24775
  policy: { id: `category:${category}`, name: category }
24612
24776
  };
@@ -24718,8 +24882,6 @@ var Policy = external_exports.object({
24718
24882
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
24719
24883
  provenance: PolicyProvenance.optional()
24720
24884
  }).meta({ id: "Policy" });
24721
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
24722
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
24723
24885
  var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
24724
24886
  id: "RedactFallback"
24725
24887
  });
@@ -24954,10 +25116,15 @@ var ParsedPointer = external_exports.object({
24954
25116
  });
24955
25117
  var VaultEntry = external_exports.object({
24956
25118
  pointerId: external_exports.string(),
24957
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
24958
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
24959
- // independently of the vault encryption key below.
25119
+ // The keyed HMAC of the EXACT raw bytes under `exception.key`, and the epoch it
25120
+ // was derived under. The vault's own dedupe key: a value and its invisibly
25121
+ // padded twin are two rows. It rotates independently of the vault encryption
25122
+ // key below. Never matched against an exception or grant.
24960
25123
  valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25124
+ // The same HMAC over the raw with invisible padding removed: the identity a
25125
+ // reveal-to-model grant and every exception match on. Shared by a value and
25126
+ // its padded twin.
25127
+ valueIdentityFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
24961
25128
  fingerprintKeyVersion: external_exports.number().int().positive(),
24962
25129
  // The vault-key epoch this row's ciphertext was sealed under.
24963
25130
  keyVersion: external_exports.number().int().positive(),
@@ -25101,7 +25268,7 @@ var VaultConsent = external_exports.object({
25101
25268
  });
25102
25269
 
25103
25270
  // ../../packages/schema/src/zod/local.ts
25104
- var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
25271
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 9;
25105
25272
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
25106
25273
  var HISTORY_SYNC_PAYLOAD_VERSION = 3;
25107
25274
  var RunMode = external_exports.enum(["standalone", "attached"]);
@@ -25126,6 +25293,18 @@ function isHistorySyncConsentValid(consent, endpoint) {
25126
25293
  if (consent === void 0 || endpoint === void 0) return false;
25127
25294
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
25128
25295
  }
25296
+ var ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH = 512;
25297
+ var AttachmentScopeEntry = external_exports.object({
25298
+ kind: external_exports.enum(["repo", "account"]),
25299
+ identity: printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH).min(1),
25300
+ label: printable(80).optional(),
25301
+ enrolledAt: external_exports.iso.datetime()
25302
+ });
25303
+ var AttachmentScope = external_exports.object({
25304
+ endpoint: external_exports.string().min(1),
25305
+ entries: external_exports.array(AttachmentScopeEntry)
25306
+ });
25307
+ var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
25129
25308
  var WebChatCaptureConsent = external_exports.object({
25130
25309
  acknowledgedAt: external_exports.iso.datetime(),
25131
25310
  version: external_exports.number().int().positive()
@@ -25196,6 +25375,23 @@ var WorkspaceSettings = external_exports.object({
25196
25375
  // both widenings. Absent until granted, and a grant for a different endpoint
25197
25376
  // or an older payload no longer counts.
25198
25377
  historySyncConsent: HistorySyncConsent.optional(),
25378
+ // The identities a SCOPED attachment forwards and the deployment they were
25379
+ // enrolled for (see AttachmentScope). Absent until something is enrolled.
25380
+ //
25381
+ // `z.unknown()`, NOT `AttachmentScope`, and the difference is this field's
25382
+ // whole failure mode. A settings.json that fails this schema reads as the
25383
+ // unonboarded defaults (readUserSettings in @akasecurity/persistence), and the
25384
+ // next save writes those defaults back over it. Typed, one entry with an
25385
+ // unknown `kind`, a control character or a bad timestamp would cost the
25386
+ // attachment, every consent and onboardedAt, permanently. Untyped, the value
25387
+ // is kept exactly as found and validated where it is used: parseAttachmentScope
25388
+ // drops a bad entry by itself, and on a scoped attachment resolveScope reads a
25389
+ // bad envelope as no entries, which keeps every event local.
25390
+ //
25391
+ // No default: absent must stay absent, so defaultWorkspaceSettings() and a
25392
+ // fresh settings.json do not change. No `.meta({ id })`, like every field
25393
+ // here. Not a ManagedSettingKey.
25394
+ attachmentScope: external_exports.unknown().optional(),
25199
25395
  // What the browser extension may record from a web chat, and the grant that
25200
25396
  // authorizes it. Absent until the user answers: recording something that was
25201
25397
  // never recorded before is never an assumed grant on upgrade, so the whole
@@ -25290,7 +25486,10 @@ function toInspectionFindingRow(input2) {
25290
25486
  actionTaken: input2.actionTaken,
25291
25487
  confidence: input2.confidence,
25292
25488
  findingKey: input2.findingKey ?? null,
25293
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
25489
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null,
25490
+ line: input2.line ?? null,
25491
+ col: input2.col ?? null,
25492
+ context: input2.context ? JSON.stringify(input2.context) : null
25294
25493
  };
25295
25494
  }
25296
25495
  function toCaptureAttributes(event) {
@@ -25535,10 +25734,18 @@ var SeveritySummaryItem = external_exports.object({
25535
25734
  count: external_exports.number().int().nonnegative(),
25536
25735
  // Resolution-aware breakdown (optional, additive). Populated once findings
25537
25736
  // carry lifecycle state: `caught` = handled in-flight (enforced); `openAtRest`
25538
- // = still open with no in-flight enforcement (needs remediation). Absent on the
25539
- // legacy count-only response until the resolution feature lands.
25737
+ // = still open with no in-flight enforcement (needs remediation); `dismissed`
25738
+ // = closed by a human judgement rather than a fix — visible, but not counted as
25739
+ // needing remediation. The three are disjoint. Absent on the legacy count-only
25740
+ // response until the resolution feature lands.
25540
25741
  caught: external_exports.number().int().nonnegative().optional(),
25541
- openAtRest: external_exports.number().int().nonnegative().optional()
25742
+ openAtRest: external_exports.number().int().nonnegative().optional(),
25743
+ dismissed: external_exports.number().int().nonnegative().optional(),
25744
+ // The two halves of `caught`, for a reader that wants them apart: `handled` =
25745
+ // in-flight findings an enforcement action already contained; `resolved` =
25746
+ // at-rest findings closed out by fixing them. `handled + resolved === caught`.
25747
+ handled: external_exports.number().int().nonnegative().optional(),
25748
+ resolved: external_exports.number().int().nonnegative().optional()
25542
25749
  }).meta({ id: "SeveritySummaryItem" });
25543
25750
  var SeveritySummaryResponse = external_exports.object({
25544
25751
  // Sum of bySeverity[].count.
@@ -25546,6 +25753,9 @@ var SeveritySummaryResponse = external_exports.object({
25546
25753
  // Findings still open at rest (sum of bySeverity[].openAtRest). Optional and
25547
25754
  // additive — absent on the legacy response until the resolution feature lands.
25548
25755
  needsRemediation: external_exports.number().int().nonnegative().optional(),
25756
+ // Findings a user dismissed (sum of bySeverity[].dismissed). Excluded from
25757
+ // needsRemediation, and kept visible here so an accepted risk is not erased.
25758
+ dismissed: external_exports.number().int().nonnegative().optional(),
25549
25759
  // All four severity levels are always present (count may be 0).
25550
25760
  bySeverity: external_exports.array(SeveritySummaryItem)
25551
25761
  }).meta({ id: "SeveritySummaryResponse" });
@@ -26106,11 +26316,11 @@ function repairOrRefuseMode(file2) {
26106
26316
  const link = lstatSync2(file2, { throwIfNoEntry: false });
26107
26317
  if (link === void 0) return "absent";
26108
26318
  if (link.isSymbolicLink()) return "untrusted";
26109
- const stat = statSync(file2, { throwIfNoEntry: false });
26110
- if (stat === void 0) return "absent";
26319
+ const stat2 = statSync(file2, { throwIfNoEntry: false });
26320
+ if (stat2 === void 0) return "absent";
26111
26321
  const uid = process.getuid?.();
26112
- if (uid !== void 0 && stat.uid !== uid) return "untrusted";
26113
- if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
26322
+ if (uid !== void 0 && stat2.uid !== uid) return "untrusted";
26323
+ if (process.platform !== "win32" && (stat2.mode & 511) !== DATA_FILE_MODE) {
26114
26324
  try {
26115
26325
  chmodSync2(file2, DATA_FILE_MODE);
26116
26326
  } catch {
@@ -26516,6 +26726,15 @@ var COUNTED_SCOPE = `
26516
26726
  OR outbox_owed = 1
26517
26727
  )`;
26518
26728
  var SKIPPED = -1;
26729
+ function inScope(column) {
26730
+ return `${column} IN (SELECT value FROM json_each(:scopeKeys))`;
26731
+ }
26732
+ function scopeKeysParam(scopeKeys) {
26733
+ return JSON.stringify(scopeKeys);
26734
+ }
26735
+ var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26736
+ FROM audit_events AS session_root
26737
+ WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26519
26738
  var HISTORY_SYNC_LEASE_STALE_MS = 6e4;
26520
26739
  var ROW_COLUMNS = `id,
26521
26740
  parent_id AS parentId,
@@ -26545,6 +26764,18 @@ var SqliteHistorySyncRepository = class {
26545
26764
  ORDER BY earliest
26546
26765
  LIMIT :limit`
26547
26766
  );
26767
+ this.scopedSessionsStmt = db.prepare(
26768
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
26769
+ FROM audit_events
26770
+ WHERE synced_at IS NULL
26771
+ AND event_type IN (${TYPE_LIST})
26772
+ AND started_at < :before
26773
+ AND ${inScope("scope_key")}
26774
+ AND ${inScope(ROOT_SCOPE_KEY)}
26775
+ GROUP BY sessionId
26776
+ ORDER BY earliest
26777
+ LIMIT :limit`
26778
+ );
26548
26779
  this.rowsStmt = db.prepare(
26549
26780
  `SELECT ${ROW_COLUMNS}
26550
26781
  FROM audit_events
@@ -26555,6 +26786,18 @@ var SqliteHistorySyncRepository = class {
26555
26786
  ORDER BY (event_type = 'session') DESC, started_at
26556
26787
  LIMIT :limit`
26557
26788
  );
26789
+ this.scopedRowsStmt = db.prepare(
26790
+ `SELECT ${ROW_COLUMNS}
26791
+ FROM audit_events
26792
+ WHERE synced_at IS NULL
26793
+ AND event_type IN (${TYPE_LIST})
26794
+ AND started_at < :before
26795
+ AND COALESCE(root_session_id, id) = :sessionId
26796
+ AND ${inScope("scope_key")}
26797
+ AND ${inScope(ROOT_SCOPE_KEY)}
26798
+ ORDER BY (event_type = 'session') DESC, started_at
26799
+ LIMIT :limit`
26800
+ );
26558
26801
  this.captureRowsStmt = db.prepare(
26559
26802
  `SELECT ${ROW_COLUMNS}
26560
26803
  FROM audit_events
@@ -26566,6 +26809,18 @@ var SqliteHistorySyncRepository = class {
26566
26809
  ORDER BY started_at
26567
26810
  LIMIT :limit`
26568
26811
  );
26812
+ this.scopedCaptureRowsStmt = db.prepare(
26813
+ `SELECT ${ROW_COLUMNS}
26814
+ FROM audit_events
26815
+ WHERE synced_at IS NULL
26816
+ AND sync_claimed_at IS NULL
26817
+ AND outbox_owed = 1
26818
+ AND event_type IN (${CAPTURE_TYPE_LIST})
26819
+ AND started_at < :before
26820
+ AND ${inScope("scope_key")}
26821
+ ORDER BY started_at
26822
+ LIMIT :limit`
26823
+ );
26569
26824
  this.markOwedStmt = db.prepare(
26570
26825
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
26571
26826
  );
@@ -26575,6 +26830,20 @@ var SqliteHistorySyncRepository = class {
26575
26830
  AND event_type IN (${CAPTURE_TYPE_LIST})
26576
26831
  AND started_at < :before`
26577
26832
  );
26833
+ this.scopedCaptureBacklogOwedStmt = db.prepare(
26834
+ `UPDATE audit_events SET outbox_owed = 1
26835
+ WHERE synced_at IS NULL
26836
+ AND event_type IN (${CAPTURE_TYPE_LIST})
26837
+ AND started_at < :before
26838
+ AND ${inScope("scope_key")}`
26839
+ );
26840
+ this.markScopeCapturesOwedStmt = db.prepare(
26841
+ `UPDATE audit_events SET outbox_owed = 1
26842
+ WHERE synced_at IS NULL
26843
+ AND outbox_owed IS NULL
26844
+ AND event_type IN (${CAPTURE_TYPE_LIST})
26845
+ AND ${inScope("scope_key")}`
26846
+ );
26578
26847
  this.stampStmt = db.prepare(
26579
26848
  `UPDATE audit_events
26580
26849
  SET synced_at = :at,
@@ -26733,6 +27002,15 @@ var SqliteHistorySyncRepository = class {
26733
27002
  claimRowStmt;
26734
27003
  releaseRowStmt;
26735
27004
  releaseStaleClaimsStmt;
27005
+ // The SCOPED twins, for a scoped attachment: the same reads and seeds with the
27006
+ // scope clause added, prepared once here beside the machine statements, so a
27007
+ // machine attachment's statements are untouched and neither form is compiled
27008
+ // per call.
27009
+ scopedSessionsStmt;
27010
+ scopedRowsStmt;
27011
+ scopedCaptureRowsStmt;
27012
+ scopedCaptureBacklogOwedStmt;
27013
+ markScopeCapturesOwedStmt;
26736
27014
  /**
26737
27015
  * The masked detections recorded against one tool call.
26738
27016
  *
@@ -26752,15 +27030,33 @@ var SqliteHistorySyncRepository = class {
26752
27030
  * path's to deliver; this drain exists for what was recorded before it, and a
26753
27031
  * row both paths send is at best a duplicate request and at worst — for a
26754
27032
  * session root — an overwrite of the inventory ids the live path resolved.
27033
+ *
27034
+ * `scopeKeys` is a scoped attachment's filter: a session is offered only while
27035
+ * its root's key is one of them AND at least one of its unsent rows' keys is
27036
+ * (see scopedSessionsStmt). Omitted, this runs the machine statement,
27037
+ * unchanged; an empty list offers nothing.
26755
27038
  */
26756
- pendingSessions(limit, before) {
26757
- return allRows(this.sessionsStmt, { limit, before }).map(
26758
- (r) => r.sessionId
26759
- );
27039
+ pendingSessions(limit, before, scopeKeys) {
27040
+ const rows = scopeKeys === void 0 ? allRows(this.sessionsStmt, { limit, before }) : allRows(this.scopedSessionsStmt, {
27041
+ limit,
27042
+ before,
27043
+ scopeKeys: scopeKeysParam(scopeKeys)
27044
+ });
27045
+ return rows.map((r) => r.sessionId);
26760
27046
  }
26761
- /** One session's undelivered structural rows within the backlog, root first. */
26762
- pendingRows(sessionId, limit, before) {
26763
- return allRows(this.rowsStmt, { sessionId, limit, before });
27047
+ /**
27048
+ * One session's undelivered structural rows within the backlog, root first.
27049
+ *
27050
+ * With `scopeKeys`, only the rows whose own key AND whose session root's key
27051
+ * are among them, whichever session id is passed.
27052
+ */
27053
+ pendingRows(sessionId, limit, before, scopeKeys) {
27054
+ return scopeKeys === void 0 ? allRows(this.rowsStmt, { sessionId, limit, before }) : allRows(this.scopedRowsStmt, {
27055
+ sessionId,
27056
+ limit,
27057
+ before,
27058
+ scopeKeys: scopeKeysParam(scopeKeys)
27059
+ });
26764
27060
  }
26765
27061
  /**
26766
27062
  * Captures this machine still owes the deployment, oldest first.
@@ -26769,9 +27065,17 @@ var SqliteHistorySyncRepository = class {
26769
27065
  * by a time window — see captureRowsStmt for why a window could not express
26770
27066
  * this. `before` is the grace window that leaves a just-recorded capture to
26771
27067
  * the live path.
27068
+ *
27069
+ * With `scopeKeys`, only captures stamped with one of them, decided per
27070
+ * capture: /v1/events stubs a missing root, so a capture never waits on its
27071
+ * session's scope. An empty list reads nothing.
26772
27072
  */
26773
- pendingCaptureRows(limit, before) {
26774
- return allRows(this.captureRowsStmt, { limit, before });
27073
+ pendingCaptureRows(limit, before, scopeKeys) {
27074
+ return scopeKeys === void 0 ? allRows(this.captureRowsStmt, { limit, before }) : allRows(this.scopedCaptureRowsStmt, {
27075
+ limit,
27076
+ before,
27077
+ scopeKeys: scopeKeysParam(scopeKeys)
27078
+ });
26775
27079
  }
26776
27080
  /**
26777
27081
  * Record that a capture is OWED to the deployment.
@@ -26803,9 +27107,37 @@ var SqliteHistorySyncRepository = class {
26803
27107
  * Returns how many rows matched, for the caller to log or test against. Not a
26804
27108
  * count of NEWLY marked rows — a row still unsynced from an earlier call
26805
27109
  * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27110
+ *
27111
+ * `scopeKeys` scopes it for a scoped attachment: only captures stamped with one
27112
+ * of the keys are marked, and an empty list marks none. The scoped capture read
27113
+ * is what keeps a personal capture out of a batch; this keeps the marker to
27114
+ * what the grant covers. Omitted, it runs the machine statement, unchanged.
27115
+ */
27116
+ markCaptureBacklogOwed(before, scopeKeys) {
27117
+ const result = scopeKeys === void 0 ? this.markCaptureBacklogOwedStmt.run({ before }) : this.scopedCaptureBacklogOwedStmt.run({ before, scopeKeys: scopeKeysParam(scopeKeys) });
27118
+ return Number(result.changes);
27119
+ }
27120
+ /**
27121
+ * Mark owed every unsent capture stamped with one of `scopeKeys`: the re-seed
27122
+ * an enrollment runs.
27123
+ *
27124
+ * This ASSUMES the contract a scoped caller keeps, and cannot check it: nothing
27125
+ * else marks an out-of-scope capture owed (the live forward must refuse it
27126
+ * before its owed branch, and the consent-time seed must be handed the key
27127
+ * list). Under that contract, an enrolled repository's unsent captures are
27128
+ * reachable only if this runs when the repository is enrolled. Like the
27129
+ * consent seed it is one explicit human action, never something a pass infers,
27130
+ * and its caller must know the history grant is in force: this method cannot
27131
+ * check consent and must not be called without it.
27132
+ *
27133
+ * No time bound. Delivered and skipped rows are never re-opened, and a row
27134
+ * already owed is not counted, so the return value is how many rows this call
27135
+ * newly marked. An empty list marks nothing.
26806
27136
  */
26807
- markCaptureBacklogOwed(before) {
26808
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27137
+ markScopeCapturesOwed(scopeKeys) {
27138
+ return Number(
27139
+ this.markScopeCapturesOwedStmt.run({ scopeKeys: scopeKeysParam(scopeKeys) }).changes
27140
+ );
26809
27141
  }
26810
27142
  /**
26811
27143
  * Record delivery. Called only AFTER the far side has accepted the rows.
@@ -27010,8 +27342,12 @@ var SqliteHistorySyncRepository = class {
27010
27342
  * disown from eating THIS SAME CALL's own re-mark is the order, not the
27011
27343
  * bound — disown runs first, re-mark second, both inside the one
27012
27344
  * transaction above.
27345
+ *
27346
+ * `scopeKeys` scopes the re-mark exactly as `markCaptureBacklogOwed` is scoped.
27347
+ * The disown before it is not scoped, and must not be: it clears the previous
27348
+ * deployment's markers whatever their scope.
27013
27349
  */
27014
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
27350
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore, scopeKeys) {
27015
27351
  this.ensureRowStmt.run();
27016
27352
  withTransaction(
27017
27353
  this.db,
@@ -27022,7 +27358,7 @@ var SqliteHistorySyncRepository = class {
27022
27358
  this.disownCapturesStmt.run({ attachedAt: backlogBefore });
27023
27359
  }
27024
27360
  if (backfillCapturesBefore !== void 0) {
27025
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
27361
+ this.markCaptureBacklogOwed(backfillCapturesBefore, scopeKeys);
27026
27362
  }
27027
27363
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27028
27364
  },
@@ -27188,6 +27524,7 @@ function applyMigrations(db, file2, options = {}) {
27188
27524
  db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
27189
27525
  }
27190
27526
  ensureSyncedAtColumn(db, "audit_events");
27527
+ ensureScopeKeyColumn(db);
27191
27528
  ensureScanLedgerTable(db);
27192
27529
  ensureHistorySyncTable(db);
27193
27530
  ensureBlockedDetectionsTable(db);
@@ -27613,6 +27950,21 @@ function ensureSyncedAtColumn(db, table) {
27613
27950
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
27614
27951
  );
27615
27952
  }
27953
+ var SCOPE_KEY_COLUMN_DDL = "ALTER TABLE audit_events ADD COLUMN scope_key text GENERATED ALWAYS AS (CASE WHEN json_valid(attributes) THEN json_extract(attributes, '$.scope_key') END) VIRTUAL";
27954
+ function ensureScopeKeyColumn(db) {
27955
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27956
+ if (hasScopeKeyColumn(db)) return;
27957
+ withTransaction(
27958
+ db,
27959
+ () => {
27960
+ if (!hasScopeKeyColumn(db)) db.exec(SCOPE_KEY_COLUMN_DDL);
27961
+ },
27962
+ "IMMEDIATE"
27963
+ );
27964
+ }
27965
+ function hasScopeKeyColumn(db) {
27966
+ return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
27967
+ }
27616
27968
  function ensureScanLedgerTable(db) {
27617
27969
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27618
27970
  path TEXT PRIMARY KEY,
@@ -28490,6 +28842,19 @@ var SqliteAuditEventsRepository = class {
28490
28842
  if (typeof provider === "string") return provider;
28491
28843
  return void 0;
28492
28844
  }
28845
+ // The `scope_key` stored on a session root's attributes: the key the history
28846
+ // drain decides that root by. It is NOT necessarily the key of the root event a
28847
+ // caller just wrote, because roots are first-write-wins (see the session-root
28848
+ // upsert above) and the root event that arrives second leaves the stored row as
28849
+ // it was. Returns undefined when the id is not a session root, when the root is
28850
+ // a stub or carries no key, and when the stored value is not a string, which is
28851
+ // what the drain's scoped reads would not match either.
28852
+ sessionScopeKey(sessionId) {
28853
+ const row = this.findById(sessionId);
28854
+ if (row?.event_type !== "session" || !row.attributes) return void 0;
28855
+ const key = parseJsonObject(row.attributes)?.scope_key;
28856
+ return typeof key === "string" ? key : void 0;
28857
+ }
28493
28858
  // Every `llm_call` leaf's session id + raw attribute bag, for the read-time token
28494
28859
  // rollups. The caller parses each bag and prices it via the
28495
28860
  // cost model — we stay a thin reader here (no business logic, no cost). `root_session_id`
@@ -28510,6 +28875,8 @@ var SqliteAuditEventsRepository = class {
28510
28875
  var DEFAULT_BATCH_SIZE = 500;
28511
28876
  var DEFAULT_MAX_ROWS = 5e4;
28512
28877
  var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
28878
+ var SWEEP = { kind: "sweep" };
28879
+ var HOLD_ALL = { kind: "hold-all" };
28513
28880
  var SqliteBodyRetentionRepository = class {
28514
28881
  constructor(db) {
28515
28882
  this.db = db;
@@ -28526,6 +28893,14 @@ var SqliteBodyRetentionRepository = class {
28526
28893
  this.candidatesSyncSafeStmt = this.db.prepare(
28527
28894
  select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
28528
28895
  );
28896
+ this.candidatesScopedStmt = this.db.prepare(
28897
+ select(
28898
+ `AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL
28899
+ OR (outbox_owed IS NOT 1
28900
+ AND (scope_key IS NULL
28901
+ OR scope_key NOT IN (SELECT value FROM json_each(:scopeKeys)))))`
28902
+ )
28903
+ );
28529
28904
  this.heldBySyncStmt = this.db.prepare(`
28530
28905
  SELECT COUNT(*) AS n
28531
28906
  FROM audit_events
@@ -28533,37 +28908,63 @@ var SqliteBodyRetentionRepository = class {
28533
28908
  AND started_at < :cutoff
28534
28909
  AND event_type IN (${SYNC_LANE_TYPES_SQL})
28535
28910
  AND synced_at IS NULL`);
28911
+ this.heldByScopeStmt = this.db.prepare(`
28912
+ SELECT COUNT(*) AS n
28913
+ FROM audit_events
28914
+ WHERE content IS NOT NULL
28915
+ AND started_at < :cutoff
28916
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
28917
+ AND synced_at IS NULL
28918
+ AND (outbox_owed = 1
28919
+ OR scope_key IN (SELECT value FROM json_each(:scopeKeys)))`);
28536
28920
  this.expireStmt = this.db.prepare(
28537
28921
  `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
28538
28922
  );
28923
+ this.expireContextsStmt = this.db.prepare(
28924
+ `UPDATE inspection_findings SET context = NULL
28925
+ WHERE id IN (
28926
+ SELECT f.id
28927
+ FROM inspection_findings f INDEXED BY idx_inspection_findings_context
28928
+ JOIN audit_events e ON e.id = f.audit_event_id
28929
+ WHERE f.context IS NOT NULL
28930
+ AND f.first_detected_at < :cutoff
28931
+ AND e.content IS NULL
28932
+ AND e.started_at < :cutoff
28933
+ LIMIT :limit)`
28934
+ );
28539
28935
  }
28540
28936
  db;
28541
28937
  candidatesStmt;
28542
28938
  candidatesSyncSafeStmt;
28939
+ candidatesScopedStmt;
28543
28940
  heldBySyncStmt;
28941
+ heldByScopeStmt;
28544
28942
  expireStmt;
28545
- /** How many bytes a pass with these options would free, changing nothing. */
28943
+ expireContextsStmt;
28944
+ /**
28945
+ * How many body bytes a pass with these options would free, changing
28946
+ * nothing. Finding excerpts are not counted (see `bytesFreed`).
28947
+ */
28546
28948
  preview(opts) {
28547
- const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
28548
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
28549
- const rows = stmt.all({ cutoff: opts.cutoff, limit });
28949
+ const lane = laneOf(opts.sweepSyncLane);
28950
+ const rows = this.candidates(lane, opts.cutoff, opts.maxRows ?? DEFAULT_MAX_ROWS);
28550
28951
  return {
28551
28952
  rowsExpired: rows.length,
28552
28953
  bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
28553
- rowsHeldBySync: this.countHeldBySync(opts)
28954
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff)
28554
28955
  };
28555
28956
  }
28556
28957
  /** Clear eligible bodies, in bounded batches. */
28557
28958
  expire(opts) {
28558
28959
  const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
28559
28960
  const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
28560
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
28961
+ const lane = laneOf(opts.sweepSyncLane);
28561
28962
  let rowsExpired = 0;
28562
28963
  let bytesFreed = 0;
28563
28964
  let done = true;
28564
28965
  while (rowsExpired < maxRows) {
28565
28966
  const remaining = Math.min(batchSize, maxRows - rowsExpired);
28566
- const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
28967
+ const batch = this.candidates(lane, opts.cutoff, remaining);
28567
28968
  if (batch.length === 0) break;
28568
28969
  withTransaction(
28569
28970
  this.db,
@@ -28576,17 +28977,60 @@ var SqliteBodyRetentionRepository = class {
28576
28977
  bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
28577
28978
  if (batch.length < remaining) break;
28578
28979
  if (rowsExpired >= maxRows) {
28579
- done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
28980
+ done = this.candidates(lane, opts.cutoff, 1).length === 0;
28580
28981
  }
28581
28982
  }
28582
- return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
28983
+ this.expireContexts(opts.cutoff, batchSize, maxRows);
28984
+ return {
28985
+ rowsExpired,
28986
+ bytesFreed,
28987
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff),
28988
+ done
28989
+ };
28990
+ }
28991
+ // Clear the excerpts that outlived their body, one bounded transaction per
28992
+ // batch for the same reason the body sweep batches, and at most `maxRows` of
28993
+ // them per pass under the same cap: the next pass picks up the rest.
28994
+ expireContexts(cutoff, batchSize, maxRows) {
28995
+ let total = 0;
28996
+ while (total < maxRows) {
28997
+ const limit = Math.min(batchSize, maxRows - total);
28998
+ let cleared = 0;
28999
+ withTransaction(
29000
+ this.db,
29001
+ () => {
29002
+ cleared = Number(this.expireContextsStmt.run({ cutoff, limit }).changes);
29003
+ },
29004
+ "IMMEDIATE"
29005
+ );
29006
+ total += cleared;
29007
+ if (cleared < limit) return;
29008
+ }
28583
29009
  }
28584
- countHeldBySync(opts) {
28585
- if (opts.sweepSyncLane) return 0;
28586
- const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
29010
+ /**
29011
+ * One batch of candidates under `lane`, bound with exactly the parameters its
29012
+ * statement names — node:sqlite refuses a named parameter a statement does not
29013
+ * declare, so the key list goes to the scoped statements only.
29014
+ *
29015
+ * Anything that is not `sweep` or `hold-keys` takes the hold-all statement.
29016
+ * The type admits no fourth kind, but this decides what is destroyed, and the
29017
+ * direction an unforeseen value falls has to be holding.
29018
+ */
29019
+ candidates(lane, cutoff, limit) {
29020
+ const rows = lane.kind === "sweep" ? this.candidatesStmt.all({ cutoff, limit }) : lane.kind === "hold-keys" ? this.candidatesScopedStmt.all({ cutoff, limit, scopeKeys: JSON.stringify(lane.keys) }) : this.candidatesSyncSafeStmt.all({ cutoff, limit });
29021
+ return rows;
29022
+ }
29023
+ countHeldBySync(lane, cutoff) {
29024
+ if (lane.kind === "sweep") return 0;
29025
+ const row = lane.kind === "hold-keys" ? this.heldByScopeStmt.get({ cutoff, scopeKeys: JSON.stringify(lane.keys) }) : this.heldBySyncStmt.get({ cutoff });
28587
29026
  return row.n;
28588
29027
  }
28589
29028
  };
29029
+ function laneOf(gate) {
29030
+ if (gate === true) return SWEEP;
29031
+ if (gate === false) return HOLD_ALL;
29032
+ return gate;
29033
+ }
28590
29034
 
28591
29035
  // ../../packages/persistence/src/repositories/capture-status.ts
28592
29036
  var STATUS_LOOKBACK_ROWS = 128;
@@ -29495,6 +29939,8 @@ function toFlatFindingRow(r) {
29495
29939
  repo: r.repo ?? "",
29496
29940
  file: r.file ?? "",
29497
29941
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
29942
+ ...r.line === null ? {} : { line: r.line },
29943
+ ...r.col === null ? {} : { col: r.col },
29498
29944
  eventId: r.event_id,
29499
29945
  ...r.session_id === null ? {} : { sessionId: r.session_id },
29500
29946
  status: deriveInstanceStatus(r),
@@ -29572,7 +30018,8 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
29572
30018
  ${latestResolutionStatusSql("f")} AS latest_status,
29573
30019
  e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
29574
30020
  e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
29575
- e.outbox_owed AS outbox_owed`;
30021
+ e.outbox_owed AS outbox_owed,
30022
+ f.line AS line, f.col AS col`;
29576
30023
  var DAY_MS3 = 864e5;
29577
30024
  var SqliteFindingsRepository = class {
29578
30025
  constructor(db) {
@@ -29995,6 +30442,27 @@ var SqliteFindingsRepository = class {
29995
30442
  ).get(id);
29996
30443
  return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
29997
30444
  }
30445
+ /**
30446
+ * One finding's excerpt source (see FindingContextSource). A primary-key
30447
+ * seek, like `findingInstance`, and the only findings read that touches the
30448
+ * event's text — which is why the list never projects the excerpt and the
30449
+ * drawer asks for it here, one finding at a time.
30450
+ */
30451
+ findingContextSource(id) {
30452
+ const row = this.db.prepare(
30453
+ `SELECT f.context AS context, e.content AS content,
30454
+ f.span_start AS spanStart, f.span_end AS spanEnd,
30455
+ d.rule_id AS ruleId, d.category AS category,
30456
+ json_extract(e.attributes, '$.whole_file') AS wholeFile,
30457
+ e.tool_name AS toolName, e.event_type AS eventType
30458
+ FROM inspection_findings f
30459
+ JOIN audit_events e ON e.id = f.audit_event_id
30460
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30461
+ WHERE f.id = ?`
30462
+ ).get(id);
30463
+ if (row === void 0) return null;
30464
+ return { ...row, wholeFile: row.wholeFile === 1 };
30465
+ }
29998
30466
  /**
29999
30467
  * The one statement both instance-level scans run: every finding in scope,
30000
30468
  * joined to its event and definition, newest first.
@@ -30131,6 +30599,61 @@ var SqliteFindingsRepository = class {
30131
30599
  ])
30132
30600
  );
30133
30601
  }
30602
+ /**
30603
+ * The Findings page's summary strip: whole-store counts over exactly the rows
30604
+ * the instance reads list (the four capture kinds), each equal to what
30605
+ * listFindingInstances totals for the same filters — see FindingsOverview.
30606
+ *
30607
+ * ONE grouped aggregate whose keys are the raw classifier inputs, not the
30608
+ * answers: the statement groups by the three inputs deriveFindingStatus
30609
+ * reads, and each group is then classified here by that same function. So
30610
+ * SQL never restates the status rule, and the strip cannot disagree with the
30611
+ * list about which status a finding has. The group count is bounded by a
30612
+ * handful of status inputs, not by the store, so only the scan grows with it
30613
+ * — the same linear cost every other unscoped read on the page already pays.
30614
+ *
30615
+ * The definitions join selects nothing. It is there because the list's scan
30616
+ * joins it too, so a finding whose definition row is missing is left out of
30617
+ * both rather than counted here and absent there.
30618
+ *
30619
+ * The latest-resolution join is the derived-table form, which
30620
+ * resolution-sql.ts recommends for an aggregate over many findings.
30621
+ */
30622
+ findingsOverview() {
30623
+ const rows = allRows(
30624
+ this.db.prepare(
30625
+ `SELECT e.event_type AS kind, (f.finding_key IS NOT NULL) AS keyed,
30626
+ latest.status AS latest_status, count(*) AS c
30627
+ FROM inspection_findings f
30628
+ JOIN audit_events e ON e.id = f.audit_event_id
30629
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30630
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30631
+ ON latest.finding_key = f.finding_key
30632
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30633
+ GROUP BY e.event_type, keyed, latest.status`
30634
+ )
30635
+ );
30636
+ const byStatus = {
30637
+ open: 0,
30638
+ handled: 0,
30639
+ resolved: 0,
30640
+ dismissed: 0
30641
+ };
30642
+ let findings = 0;
30643
+ for (const row of rows) {
30644
+ const status = deriveFindingStatus({
30645
+ kind: row.kind,
30646
+ // The classifier only asks whether a key exists, never what it is. The
30647
+ // stand-in is non-empty so a truthiness test of the key reads it as
30648
+ // present, exactly as it would a real one.
30649
+ findingKey: row.keyed ? "keyed" : null,
30650
+ latestResolutionStatus: row.latest_status
30651
+ });
30652
+ findings += row.c;
30653
+ byStatus[status] += row.c;
30654
+ }
30655
+ return Promise.resolve({ findings, ...byStatus });
30656
+ }
30134
30657
  healthSummary() {
30135
30658
  const total = countScalar(
30136
30659
  this.db,
@@ -30258,12 +30781,13 @@ var SqliteInspectionFindingsRepository = class {
30258
30781
  `INSERT INTO inspection_findings
30259
30782
  (id, audit_event_id, inspection_definition_id, classified_data_id,
30260
30783
  span_start, span_end, masked_match, action_taken, confidence,
30261
- finding_key, first_detected_at)
30784
+ finding_key, first_detected_at, line, col, context)
30262
30785
  VALUES
30263
30786
  (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
30264
30787
  :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
30265
30788
  :findingKey,
30266
- COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
30789
+ COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)),
30790
+ :line, :col, :context)
30267
30791
  ON CONFLICT(id) DO UPDATE SET
30268
30792
  inspection_definition_id = excluded.inspection_definition_id
30269
30793
  ON CONFLICT (finding_key) DO UPDATE SET
@@ -30274,7 +30798,10 @@ var SqliteInspectionFindingsRepository = class {
30274
30798
  span_end = excluded.span_end,
30275
30799
  masked_match = excluded.masked_match,
30276
30800
  action_taken = excluded.action_taken,
30277
- confidence = excluded.confidence`
30801
+ confidence = excluded.confidence,
30802
+ line = excluded.line,
30803
+ col = excluded.col,
30804
+ context = excluded.context`
30278
30805
  );
30279
30806
  this.sessionDupStmt = db.prepare(
30280
30807
  `SELECT 1 FROM inspection_findings f
@@ -30324,7 +30851,10 @@ var SqliteInspectionFindingsRepository = class {
30324
30851
  actionTaken: row.actionTaken,
30325
30852
  confidence: row.confidence,
30326
30853
  findingKey: row.findingKey,
30327
- firstDetectedAt: row.firstDetectedAt
30854
+ firstDetectedAt: row.firstDetectedAt,
30855
+ line: row.line,
30856
+ col: row.col,
30857
+ context: row.context
30328
30858
  })
30329
30859
  );
30330
30860
  }
@@ -30665,8 +31195,8 @@ var SqliteInstalledPacksRepository = class {
30665
31195
  this.db = db;
30666
31196
  this.baseDir = baseDir;
30667
31197
  this.insertMissingStmt = db.prepare(
30668
- `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
30669
- VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
31198
+ `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31199
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
30670
31200
  ON CONFLICT (namespace, pack_id) DO NOTHING`
30671
31201
  );
30672
31202
  this.upsertAvailableStmt = db.prepare(
@@ -30726,7 +31256,10 @@ var SqliteInstalledPacksRepository = class {
30726
31256
  version: pack.version,
30727
31257
  name: pack.name,
30728
31258
  rulesJson: JSON.stringify(pack.rules),
30729
- ruleIds: new Set(pack.rules.map((r) => r.id))
31259
+ ruleIds: new Set(pack.rules.map((r) => r.id)),
31260
+ // Only a first install takes it: an existing row is never modified here,
31261
+ // so a policy the user chose (or cleared) is never overwritten.
31262
+ defaultPolicyId: pack.defaultPolicyId ?? null
30730
31263
  }));
30731
31264
  if (this.storedSignature() === inventorySignature(rows)) return;
30732
31265
  const now = Date.now();
@@ -30755,7 +31288,7 @@ var SqliteInstalledPacksRepository = class {
30755
31288
  } else {
30756
31289
  behind = true;
30757
31290
  }
30758
- this.insertMissingStmt.run(params);
31291
+ this.insertMissingStmt.run({ ...params, policyId: row.defaultPolicyId });
30759
31292
  }
30760
31293
  if (!behind) this.pruneAvailable(rows.map((r) => `${r.namespace}/${r.packId}`));
30761
31294
  },
@@ -30873,7 +31406,8 @@ var SqliteInstalledPacksRepository = class {
30873
31406
  rejectedRules: [],
30874
31407
  ruleActions: /* @__PURE__ */ new Map(),
30875
31408
  ruleVersions: /* @__PURE__ */ new Map(),
30876
- reversibleRules: /* @__PURE__ */ new Set()
31409
+ reversibleRules: /* @__PURE__ */ new Set(),
31410
+ assignedRules: /* @__PURE__ */ new Set()
30877
31411
  };
30878
31412
  const reject = (pack, ruleId, reason) => {
30879
31413
  if (out.rejectedRules.length >= REJECTED_RULE_DETAIL_CAP) return;
@@ -30906,6 +31440,8 @@ var SqliteInstalledPacksRepository = class {
30906
31440
  out.ruleVersions.set(parsed2.data.id, row.version);
30907
31441
  if (reversible) out.reversibleRules.add(parsed2.data.id);
30908
31442
  else out.reversibleRules.delete(parsed2.data.id);
31443
+ if (row.policyId !== null) out.assignedRules.add(parsed2.data.id);
31444
+ else out.assignedRules.delete(parsed2.data.id);
30909
31445
  } else {
30910
31446
  out.invalidRules += 1;
30911
31447
  reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
@@ -31992,6 +32528,7 @@ var SqliteInventoryAssetsRepository = class {
31992
32528
 
31993
32529
  // ../../packages/persistence/src/repositories/policies.ts
31994
32530
  import { randomUUID as randomUUID6 } from "crypto";
32531
+ var SEED_BATCH_WINDOW_MS = 6e4;
31995
32532
  var SqlitePoliciesRepository = class {
31996
32533
  constructor(db) {
31997
32534
  this.db = db;
@@ -32013,39 +32550,123 @@ var SqlitePoliciesRepository = class {
32013
32550
  });
32014
32551
  return Promise.resolve(policies);
32015
32552
  }
32016
- // Seed one policy per bundled category from DEFAULT_ACTIONS so the
32017
- // detection-type config exists from first run. Only when the table is empty,
32018
- // so a user's edits are never clobbered.
32553
+ // Seed one policy per bundled category at Monitor so the detection-type config
32554
+ // exists from first run. An unassigned pack's rules follow these rows, so
32555
+ // Monitor here is the posture of every pack that ships no defaultPolicy; a pack
32556
+ // that ships one carries its own assignment instead. Only when the
32557
+ // table is empty, so a user's edits are never clobbered.
32019
32558
  seedDefaults() {
32020
32559
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32021
- if (count > 0) return;
32560
+ if (count > 0) {
32561
+ this.markEarlierChoices();
32562
+ this.monitorUntouchedSeeds();
32563
+ return;
32564
+ }
32022
32565
  const stmt = this.db.prepare(
32023
32566
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
32024
32567
  VALUES (:id, 'global', :target, :action, 1, :now, :now)`
32025
32568
  );
32026
32569
  failOpenTransaction(this.db, () => {
32027
- for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
32570
+ for (const category of Object.keys(DEFAULT_ACTIONS)) {
32028
32571
  stmt.run({
32029
32572
  id: randomUUID6(),
32030
32573
  target: JSON.stringify({ category }),
32031
- action,
32574
+ action: "log",
32032
32575
  now: Date.now()
32033
32576
  });
32034
32577
  }
32035
32578
  });
32036
32579
  }
32580
+ // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32581
+ // equal to created_at, so a choice made for a category that had no row yet
32582
+ // (one added in a release after the store was seeded) looks exactly like a
32583
+ // seed. Left alone, fill-gaps would overwrite it and monitorUntouchedSeeds
32584
+ // could reset it. This pass marks such rows as chosen (updated_at =
32585
+ // created_at + 1) before either can read them. A row is an earlier build's
32586
+ // choice, not its seed, when either:
32587
+ // - its action is neither the old seed value (DEFAULT_ACTIONS) nor Monitor,
32588
+ // which no seed of any build ever wrote; or
32589
+ // - it was created well after the seed batch. Every build seeds all of its
32590
+ // categories in one transaction, and only into an empty table, so a row
32591
+ // created later came from upsertCategoryAction.
32592
+ // It needs no marker of its own: every row this build writes has updated_at >
32593
+ // created_at, and the seeds it leaves equal (fresh 'log' seeds, and seeds
32594
+ // moved to Monitor below, which keep their created_at) match neither test, so
32595
+ // after one pass it finds nothing and stays a read. What it cannot tell apart
32596
+ // is an earlier build's choice that equals the seed value AND was made within
32597
+ // the seed batch window; that row is read as a seed.
32598
+ markEarlierChoices() {
32599
+ const rows = allRows(
32600
+ this.db.prepare(
32601
+ `SELECT id, json_extract(target, '$.category') AS category, action,
32602
+ created_at AS c, updated_at AS u
32603
+ FROM policies
32604
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL`
32605
+ )
32606
+ );
32607
+ if (rows.length === 0) return;
32608
+ const seedBatchStart = Math.min(...rows.map((row) => row.c));
32609
+ const seeded = DEFAULT_ACTIONS;
32610
+ const choices = rows.filter(
32611
+ (row) => row.u === row.c && (row.action !== "log" && row.action !== seeded[row.category] || row.c > seedBatchStart + SEED_BATCH_WINDOW_MS)
32612
+ );
32613
+ if (choices.length === 0) return;
32614
+ const stmt = this.db.prepare(
32615
+ `UPDATE policies SET updated_at = created_at + 1 WHERE id = :id AND updated_at = created_at`
32616
+ );
32617
+ failOpenTransaction(this.db, () => {
32618
+ for (const row of choices) stmt.run({ id: row.id });
32619
+ });
32620
+ }
32621
+ // Stores seeded by an earlier build hold DEFAULT_ACTIONS in their category
32622
+ // rows. Those rows used to be shadowed by the Monitor every unassigned pack
32623
+ // emitted; now that unassigned packs defer to them, an untouched one would
32624
+ // turn Monitor into Warn on upgrade with nobody having asked. So a row still
32625
+ // exactly as seeded — the seeded action, never updated since it was created —
32626
+ // is moved to Monitor. A row the user, the setup wizard or the warn-era cap
32627
+ // ever wrote has a later updated_at and is left alone. updated_at is NOT
32628
+ // advanced, so a moved row still reads as an untouched seed (see
32629
+ // isCategoryChosen); it never matches again because it is no longer off 'log'.
32630
+ // One knock-on: when the installed snapshot is unusable (corrupt rules_json)
32631
+ // the gateway falls back to the bundled packs with no per-rule policies, so
32632
+ // every rule follows these rows. On an upgraded store that fallback now
32633
+ // monitors where the earlier build warned.
32634
+ monitorUntouchedSeeds() {
32635
+ const untouched = allRows(
32636
+ this.db.prepare(
32637
+ `SELECT json_extract(target, '$.category') AS category, action FROM policies
32638
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL
32639
+ AND action <> 'log' AND updated_at = created_at`
32640
+ )
32641
+ ).filter(
32642
+ (row) => DEFAULT_ACTIONS[row.category] === row.action
32643
+ );
32644
+ if (untouched.length === 0) return;
32645
+ const stmt = this.db.prepare(
32646
+ `UPDATE policies SET action = 'log'
32647
+ WHERE scope = 'global' AND json_extract(target, '$.category') = :category
32648
+ AND action = :seeded AND action <> 'log' AND updated_at = created_at`
32649
+ );
32650
+ failOpenTransaction(this.db, () => {
32651
+ for (const row of untouched) {
32652
+ stmt.run({ category: row.category, seeded: row.action });
32653
+ }
32654
+ });
32655
+ }
32037
32656
  // Insert-or-update the single global per-category policy row, keyed on the
32038
32657
  // existing uq_policies_scope_target unique index (scope, target). `action`
32039
32658
  // uses the SAME vocabulary seedDefaults writes (DEFAULT_ACTIONS' ActionTaken
32040
32659
  // values), so the runtime's resolveAction reads rows written by either path
32041
32660
  // identically. On conflict, `action`, `enabled`, and `updated_at` are updated;
32042
- // `id` and `created_at` are left exactly as they were.
32661
+ // `id` and `created_at` are left exactly as they were. Either way updated_at
32662
+ // ends up later than created_at, which is what marks the row as chosen.
32043
32663
  upsertCategoryAction(category, action) {
32044
32664
  const now = Date.now();
32045
32665
  this.db.prepare(
32046
32666
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
32047
- VALUES (:id, 'global', :target, :action, 1, :now, :now)
32048
- ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
32667
+ VALUES (:id, 'global', :target, :action, 1, :now, :now + 1)
32668
+ ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32669
+ updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32049
32670
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32050
32671
  }
32051
32672
  // Caps every global per-category policy currently set to block/redact down
@@ -32059,6 +32680,16 @@ var SqlitePoliciesRepository = class {
32059
32680
  ).run({ now: Date.now() });
32060
32681
  return Number(info.changes);
32061
32682
  }
32683
+ // Whether the category's row was ever written after it was created — by the
32684
+ // user, the setup wizard or a cap. A row still as seeded (updated_at equal to
32685
+ // created_at) is not a choice, so a posture filling gaps may replace it.
32686
+ isCategoryChosen(category) {
32687
+ const row = this.db.prepare(
32688
+ `SELECT created_at AS c, updated_at AS u FROM policies
32689
+ WHERE scope='global' AND json_extract(target,'$.category') = :category`
32690
+ ).get({ category });
32691
+ return row !== void 0 && row.u !== row.c;
32692
+ }
32062
32693
  // Read the current action for a single global per-category policy row, mirroring
32063
32694
  // upsertCategoryAction's category-lookup predicate. Returns undefined when no
32064
32695
  // row exists yet, so callers can distinguish an unset category from a set one.
@@ -32230,7 +32861,10 @@ var SqliteResolutionsRepository = class {
32230
32861
  * Insert many dispositions as ONE transaction — all of them or none.
32231
32862
  *
32232
32863
  * A dashboard dismissal closes every open finding of a rule, which is one
32233
- * write per key; run loose, a fault partway leaves half a rule closed with
32864
+ * write per key. It reaches this through
32865
+ * `LocalDatabase.dismissOpenFindingsForRule`, which calls it inside the
32866
+ * transaction that selected the keys, so there it runs as a SAVEPOINT of
32867
+ * that transaction. Run loose, a fault partway leaves half a rule closed with
32234
32868
  * nothing recording that the other half was meant to be. The caller then has
32235
32869
  * no way to tell a partial run from a complete one, because the card it
32236
32870
  * refreshes into just shows a smaller number either way.
@@ -32450,6 +33084,7 @@ function toSighting(row) {
32450
33084
  var SELECT_COLUMNS = `
32451
33085
  pointer_id AS pointerId,
32452
33086
  value_fingerprint AS valueFingerprint,
33087
+ value_identity_fingerprint AS valueIdentityFingerprint,
32453
33088
  fingerprint_key_version AS fingerprintKeyVersion,
32454
33089
  key_version AS keyVersion,
32455
33090
  format_version AS formatVersion,
@@ -32474,13 +33109,13 @@ var SqliteSecretVaultRepository = class {
32474
33109
  this.db = db;
32475
33110
  this.insertStmt = db.prepare(
32476
33111
  `INSERT INTO secret_vault (
32477
- pointer_id, value_fingerprint, fingerprint_key_version, key_version,
32478
- format_version, category, rule_id, masked_match, provider,
33112
+ pointer_id, value_fingerprint, value_identity_fingerprint,
33113
+ fingerprint_key_version, key_version, format_version, category, rule_id, masked_match, provider,
32479
33114
  ciphertext, nonce, auth_tag,
32480
33115
  user_authorized, occurrence_count, first_seen, last_seen
32481
33116
  ) VALUES (
32482
- :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
32483
- :formatVersion, :category, :ruleId, :maskedMatch, :provider,
33117
+ :pointerId, :valueFingerprint, :valueIdentityFingerprint,
33118
+ :fingerprintKeyVersion, :keyVersion, :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32484
33119
  :ciphertext, :nonce, :authTag,
32485
33120
  :userAuthorized, 1, :now, :now
32486
33121
  )`
@@ -32505,7 +33140,13 @@ var SqliteSecretVaultRepository = class {
32505
33140
  );
32506
33141
  this.refreshFingerprintStmt = db.prepare(
32507
33142
  `UPDATE secret_vault
32508
- SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
33143
+ SET value_fingerprint = :valueFingerprint,
33144
+ value_identity_fingerprint = :valueIdentityFingerprint,
33145
+ fingerprint_key_version = :fingerprintKeyVersion
33146
+ WHERE pointer_id = :pointerId`
33147
+ );
33148
+ this.setIdentityStmt = db.prepare(
33149
+ `UPDATE secret_vault SET value_identity_fingerprint = :valueIdentityFingerprint
32509
33150
  WHERE pointer_id = :pointerId`
32510
33151
  );
32511
33152
  this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
@@ -32522,6 +33163,7 @@ var SqliteSecretVaultRepository = class {
32522
33163
  listStmt;
32523
33164
  replaceCiphertextStmt;
32524
33165
  refreshFingerprintStmt;
33166
+ setIdentityStmt;
32525
33167
  deleteByPointerStmt;
32526
33168
  derefStmt;
32527
33169
  /**
@@ -32552,6 +33194,7 @@ var SqliteSecretVaultRepository = class {
32552
33194
  bindParams({
32553
33195
  pointerId: input2.pointerId,
32554
33196
  valueFingerprint: input2.valueFingerprint,
33197
+ valueIdentityFingerprint: input2.valueIdentityFingerprint,
32555
33198
  fingerprintKeyVersion: input2.fingerprintKeyVersion,
32556
33199
  keyVersion: input2.keyVersion,
32557
33200
  formatVersion: input2.formatVersion ?? POINTER_FORMAT_VERSION,
@@ -32613,7 +33256,15 @@ var SqliteSecretVaultRepository = class {
32613
33256
  replaceCiphertext(pointerId, next) {
32614
33257
  this.replaceCiphertextStmt.run({ pointerId, ...next });
32615
33258
  }
32616
- /** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
33259
+ /**
33260
+ * Correct an entry's identity fingerprint in place, leaving its exact
33261
+ * fingerprint and key epoch alone. For a row whose identity column still holds
33262
+ * the exact value copied in by the migration that added it.
33263
+ */
33264
+ setIdentityFingerprint(pointerId, valueIdentityFingerprint) {
33265
+ this.setIdentityStmt.run({ pointerId, valueIdentityFingerprint });
33266
+ }
33267
+ /** Re-derive an entry's fingerprints under a new fingerprint-key epoch. */
32617
33268
  refreshFingerprint(pointerId, next) {
32618
33269
  this.refreshFingerprintStmt.run({ pointerId, ...next });
32619
33270
  }
@@ -32744,7 +33395,7 @@ var SqliteSecretVaultRepository = class {
32744
33395
  `SELECT ${INVENTORY_COLUMNS},
32745
33396
  (SELECT e.id FROM exceptions e
32746
33397
  WHERE e.rule_id = v.rule_id
32747
- AND e.value_fingerprint = v.value_fingerprint
33398
+ AND e.value_fingerprint = v.value_identity_fingerprint
32748
33399
  AND e.key_version = v.fingerprint_key_version
32749
33400
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32750
33401
  LIMIT 1) AS grant_id
@@ -32787,7 +33438,7 @@ var SqliteSecretVaultRepository = class {
32787
33438
  `SELECT ${INVENTORY_COLUMNS},
32788
33439
  (SELECT e.id FROM exceptions e
32789
33440
  WHERE e.rule_id = v.rule_id
32790
- AND e.value_fingerprint = v.value_fingerprint
33441
+ AND e.value_fingerprint = v.value_identity_fingerprint
32791
33442
  AND e.key_version = v.fingerprint_key_version
32792
33443
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32793
33444
  LIMIT 1) AS grant_id
@@ -32891,6 +33542,18 @@ var OPEN_AT_REST_FINDINGS_SQL = `FROM inspection_findings f
32891
33542
  OR latest.status IS NULL
32892
33543
  OR latest.status NOT IN ('resolved', 'dismissed')
32893
33544
  )`;
33545
+ function selectOpenFindingKeysForRule(db, ruleId) {
33546
+ const rows = allRows(
33547
+ db.prepare(
33548
+ `SELECT DISTINCT f.finding_key AS finding_key
33549
+ ${OPEN_AT_REST_FINDINGS_SQL}
33550
+ AND d.rule_id = :ruleId
33551
+ AND f.finding_key IS NOT NULL`
33552
+ ),
33553
+ { ruleId }
33554
+ );
33555
+ return rows.map((r) => r.finding_key);
33556
+ }
32894
33557
  var SEVERITIES = ["critical", "high", "medium", "low"];
32895
33558
  var ACTION_TO_KIND = {
32896
33559
  block: "blocked",
@@ -32947,16 +33610,16 @@ var SqliteSecurityRepository = class {
32947
33610
  // findings are caught only once their latest disposition is resolved,
32948
33611
  // otherwise they are open-at-rest.
32949
33612
  //
32950
- // NOTE for future manual-resolution writers: only latest status
32951
- // 'resolved' counts as caught above. When acknowledged/dismissed/
32952
- // false-positive manual dispositions land, this must keep filtering by
32953
- // status/method — 'acknowledged' is accepted risk, not a fix, and must NOT
32954
- // be bucketed as caught alongside 'resolved'.
33613
+ // Only latest status 'resolved' counts as caught above. 'dismissed' is its
33614
+ // own bucket: a judgement rather than a fix, so it is neither caught nor
33615
+ // needing remediation, and stays countable. A further manual disposition
33616
+ // (acknowledged, false-positive) must be placed deliberately — 'acknowledged'
33617
+ // is accepted risk, not a fix, and must NOT be bucketed as caught.
32955
33618
  //
32956
33619
  // Legacy at-rest findings from pre-branch scans carry finding_key = NULL —
32957
33620
  // the resolution lifecycle is keyed by finding_key, so it can never attach a
32958
33621
  // disposition to (or clear) one of these on re-scan. They are excluded from
32959
- // both caught and openAtRest (untracked, not "needs remediation forever"),
33622
+ // all three buckets (untracked, not "needs remediation forever"),
32960
33623
  // but still counted in total/count below — this keeps this predicate
32961
33624
  // consistent with SqliteResolutionsRepository.openAtRestKeysForPath, which
32962
33625
  // already filters `finding_key IS NOT NULL`.
@@ -32979,12 +33642,25 @@ var SqliteSecurityRepository = class {
32979
33642
  WHEN latest.status = 'resolved' THEN 1
32980
33643
  ELSE 0
32981
33644
  END) AS caught,
33645
+ SUM(CASE WHEN e.event_type != 'code_change' THEN 1 ELSE 0 END) AS handled,
32982
33646
  SUM(CASE
32983
33647
  WHEN e.event_type = 'code_change'
32984
33648
  AND f.finding_key IS NOT NULL
32985
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
33649
+ AND latest.status = 'resolved' THEN 1
32986
33650
  ELSE 0
32987
- END) AS open_at_rest
33651
+ END) AS resolved,
33652
+ SUM(CASE
33653
+ WHEN e.event_type = 'code_change'
33654
+ AND f.finding_key IS NOT NULL
33655
+ AND (latest.status IS NULL
33656
+ OR latest.status NOT IN ('resolved', 'dismissed')) THEN 1
33657
+ ELSE 0
33658
+ END) AS open_at_rest,
33659
+ SUM(CASE
33660
+ WHEN e.event_type = 'code_change'
33661
+ AND latest.status = 'dismissed' THEN 1
33662
+ ELSE 0
33663
+ END) AS dismissed
32988
33664
  FROM inspection_findings f
32989
33665
  JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
32990
33666
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -32999,11 +33675,15 @@ var SqliteSecurityRepository = class {
32999
33675
  severity,
33000
33676
  count: byRow.get(severity)?.count ?? 0,
33001
33677
  caught: byRow.get(severity)?.caught ?? 0,
33002
- openAtRest: byRow.get(severity)?.open_at_rest ?? 0
33678
+ handled: byRow.get(severity)?.handled ?? 0,
33679
+ resolved: byRow.get(severity)?.resolved ?? 0,
33680
+ openAtRest: byRow.get(severity)?.open_at_rest ?? 0,
33681
+ dismissed: byRow.get(severity)?.dismissed ?? 0
33003
33682
  }));
33004
33683
  const total = bySeverity.reduce((sum, s) => sum + s.count, 0);
33005
33684
  const needsRemediation = bySeverity.reduce((sum, s) => sum + s.openAtRest, 0);
33006
- return Promise.resolve({ total, needsRemediation, bySeverity });
33685
+ const dismissed = bySeverity.reduce((sum, s) => sum + s.dismissed, 0);
33686
+ return Promise.resolve({ total, needsRemediation, dismissed, bySeverity });
33007
33687
  }
33008
33688
  // Range is echoed but does not change the result today — coverage is a constant
33009
33689
  // business fact (see SCAN_COVERAGE), not a measured per-window metric. Order
@@ -33320,10 +34000,10 @@ var SqliteSecurityRepository = class {
33320
34000
  * machine, and the second reported "no recommendations" over live exposure.
33321
34001
  *
33322
34002
  * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
33323
- * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
33324
- * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
33325
- * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
33326
- * The two answer different questions and only this one has to match a link.
34003
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. It
34004
+ * differs from `severitySummary`'s `openAtRest` only in including untracked
34005
+ * legacy rows, which that bucket leaves out; dismissed is excluded from both.
34006
+ * Only this one has to match a link.
33327
34007
  *
33328
34008
  * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
33329
34009
  * whole-store scope costs a grouped scan rather than a row per finding.
@@ -33351,6 +34031,8 @@ var SqliteSecurityRepository = class {
33351
34031
  /**
33352
34032
  * The distinct `finding_key`s behind ONE rule's {@link recommendationInputs}
33353
34033
  * tally — what a dashboard dismissal of that row writes a disposition for.
34034
+ * The dismissal itself does not call this: it reads the same set through
34035
+ * {@link selectOpenFindingKeysForRule}, inside its own write transaction.
33354
34036
  *
33355
34037
  * It shares {@link OPEN_AT_REST_FINDINGS_SQL} with the count rather than
33356
34038
  * restating the predicate, because a dismissal has to act on exactly the set
@@ -33367,16 +34049,7 @@ var SqliteSecurityRepository = class {
33367
34049
  * this set SMALLER than the tally, never larger.
33368
34050
  */
33369
34051
  openFindingKeysForRule(ruleId) {
33370
- const rows = allRows(
33371
- this.db.prepare(
33372
- `SELECT DISTINCT f.finding_key AS finding_key
33373
- ${OPEN_AT_REST_FINDINGS_SQL}
33374
- AND d.rule_id = :ruleId
33375
- AND f.finding_key IS NOT NULL`
33376
- ),
33377
- { ruleId }
33378
- );
33379
- return Promise.resolve(rows.map((r) => r.finding_key));
34052
+ return Promise.resolve(selectOpenFindingKeysForRule(this.db, ruleId));
33380
34053
  }
33381
34054
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
33382
34055
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
@@ -34262,6 +34935,11 @@ var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
34262
34935
  function linkHost(input2, hostId) {
34263
34936
  return hostId ? { ...input2, hostId } : input2;
34264
34937
  }
34938
+ function captureAttributesOf(event, scopeKey) {
34939
+ const attributes = toCaptureAttributes(event);
34940
+ if (scopeKey === void 0 || scopeKey === "") return attributes;
34941
+ return { ...attributes, scope_key: scopeKey };
34942
+ }
34265
34943
  function closeQuietly(db) {
34266
34944
  try {
34267
34945
  db.close();
@@ -34422,7 +35100,32 @@ function openLocalDatabase(dir, options = {}) {
34422
35100
  );
34423
35101
  });
34424
35102
  }
34425
- function recordCapture(event, detected) {
35103
+ function dismissOpenFindingsForRule(ruleId, disposition) {
35104
+ let dismissed = 0;
35105
+ withTransaction(
35106
+ db,
35107
+ () => {
35108
+ const keys = selectOpenFindingKeysForRule(db, ruleId);
35109
+ resolutions.insertResolutions(
35110
+ keys.map((findingKey) => ({
35111
+ findingKey,
35112
+ status: "dismissed",
35113
+ method: disposition.method,
35114
+ resolvedAt: disposition.resolvedAt,
35115
+ evidence: disposition.evidence
35116
+ }))
35117
+ );
35118
+ dismissed = keys.length;
35119
+ },
35120
+ // IMMEDIATE takes the write lock at BEGIN, before the select, which is
35121
+ // what keeps a concurrent resolve out of the gap. It also makes waiting
35122
+ // on a busy writer an ordinary busy_timeout wait rather than a
35123
+ // read-to-write upgrade SQLite refuses to retry.
35124
+ "IMMEDIATE"
35125
+ );
35126
+ return dismissed;
35127
+ }
35128
+ function recordCapture(event, detected, scopeKey) {
34426
35129
  failOpenTransaction(db, () => {
34427
35130
  const sessionId = event.metadata?.sessionId;
34428
35131
  if (sessionId) {
@@ -34437,7 +35140,7 @@ function openLocalDatabase(dir, options = {}) {
34437
35140
  rootSessionId: sessionId,
34438
35141
  content: event.content,
34439
35142
  contentHash: event.contentHash,
34440
- attributes: toCaptureAttributes(event)
35143
+ attributes: captureAttributesOf(event, scopeKey)
34441
35144
  });
34442
35145
  const definitionIds = /* @__PURE__ */ new Map();
34443
35146
  for (const finding of detected) {
@@ -34467,7 +35170,12 @@ function openLocalDatabase(dir, options = {}) {
34467
35170
  maskedMatch: finding.maskedMatch,
34468
35171
  actionTaken: finding.actionTaken,
34469
35172
  confidence: finding.confidence,
34470
- findingKey: finding.findingKey ?? void 0
35173
+ findingKey: finding.findingKey ?? void 0,
35174
+ ...finding.location === void 0 ? {} : {
35175
+ line: finding.location.line,
35176
+ col: finding.location.col,
35177
+ context: finding.location.context
35178
+ }
34471
35179
  });
34472
35180
  }
34473
35181
  });
@@ -34605,6 +35313,7 @@ function openLocalDatabase(dir, options = {}) {
34605
35313
  inspectionDefinitions,
34606
35314
  inspectionFindings,
34607
35315
  recordCapture,
35316
+ dismissOpenFindingsForRule,
34608
35317
  markCaptureDelivered,
34609
35318
  markCaptureOwed,
34610
35319
  markAuditEventsDelivered,
@@ -34629,6 +35338,7 @@ function openLocalDatabase(dir, options = {}) {
34629
35338
  // ../../packages/persistence/src/egress-wire.ts
34630
35339
  import { createHash as createHash3 } from "crypto";
34631
35340
  var SLASH = "/".charCodeAt(0);
35341
+ var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
34632
35342
 
34633
35343
  // ../../packages/persistence/src/finding-key.ts
34634
35344
  import { createHash as createHash4 } from "crypto";
@@ -34859,7 +35569,7 @@ async function send(options) {
34859
35569
  }
34860
35570
  }
34861
35571
  };
34862
- return new Promise((resolve2, reject) => {
35572
+ return new Promise((resolve3, reject) => {
34863
35573
  let settled = false;
34864
35574
  const fail = (reason, status) => {
34865
35575
  if (settled) return;
@@ -34885,7 +35595,7 @@ async function send(options) {
34885
35595
  res.on("end", () => {
34886
35596
  if (settled) return;
34887
35597
  settled = true;
34888
- resolve2({
35598
+ resolve3({
34889
35599
  status: res.statusCode ?? 0,
34890
35600
  headers: res.headers,
34891
35601
  body: Buffer.concat(chunks).toString("utf8")
@@ -35074,14 +35784,17 @@ function createRemoteClient(options) {
35074
35784
  };
35075
35785
  }
35076
35786
 
35787
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
35788
+ var REQUEST_TIMEOUT_MS = 2e3;
35789
+
35077
35790
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
35078
35791
  import { readFileSync as readFileSync10 } from "fs";
35079
35792
  import { join as join16 } from "path";
35080
35793
 
35081
35794
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35082
- import { randomUUID as randomUUID15 } from "crypto";
35795
+ import { randomUUID as randomUUID16 } from "crypto";
35083
35796
  import { readFile, rename, writeFile } from "fs/promises";
35084
- import { join as join27 } from "path";
35797
+ import { join as join28 } from "path";
35085
35798
 
35086
35799
  // ../../packages/plugin-sdk/src/config.ts
35087
35800
  import { existsSync as existsSync8 } from "fs";
@@ -35706,6 +36419,10 @@ function escapeRegExp2(value) {
35706
36419
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35707
36420
  }
35708
36421
 
36422
+ // ../../packages/detections/src/format-chars.ts
36423
+ var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
36424
+ var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
36425
+
35709
36426
  // ../../packages/detections/src/regex-cache.ts
35710
36427
  var singles = /* @__PURE__ */ new WeakMap();
35711
36428
  var keywordLists = /* @__PURE__ */ new WeakMap();
@@ -35942,6 +36659,7 @@ var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
35942
36659
  // ../../packages/plugin-sdk/src/repo.ts
35943
36660
  import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
35944
36661
  import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36662
+ var NO_ATTRIBUTION = Object.freeze({});
35945
36663
 
35946
36664
  // ../../packages/plugin-sdk/src/events.ts
35947
36665
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -36016,6 +36734,9 @@ import { join as join24 } from "path";
36016
36734
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
36017
36735
  import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36018
36736
 
36737
+ // ../../packages/plugin-sdk/src/policy-resolver.ts
36738
+ import { randomUUID as randomUUID14 } from "crypto";
36739
+
36019
36740
  // ../../packages/plugin-sdk/src/project-files.ts
36020
36741
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36021
36742
  import { basename as basename5, join as join25 } from "path";
@@ -36047,14 +36768,30 @@ var codexProviderEnvShape = {
36047
36768
  var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
36048
36769
 
36049
36770
  // ../../packages/plugin-sdk/src/runtime.ts
36050
- import { randomUUID as randomUUID14 } from "crypto";
36771
+ import { randomUUID as randomUUID15 } from "crypto";
36772
+
36773
+ // ../../packages/plugin-sdk/src/scope-key.ts
36774
+ import { existsSync as existsSync12 } from "fs";
36775
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
36051
36776
 
36052
36777
  // ../../packages/plugin-sdk/src/suppressions.ts
36053
36778
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36054
36779
 
36055
36780
  // ../../packages/plugin-sdk/src/throttle.ts
36056
36781
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36057
- import { join as join26 } from "path";
36782
+ import { join as join27 } from "path";
36783
+
36784
+ // ../../packages/plugin-runtime/src/attached/scope-strip.ts
36785
+ function withoutScopeKey(event) {
36786
+ const attributes = event.attributes;
36787
+ if (attributes == null || !Object.hasOwn(attributes, "scope_key")) return event;
36788
+ const rest = { ...attributes };
36789
+ delete rest.scope_key;
36790
+ if (Object.keys(rest).length > 0) return { ...event, attributes: rest };
36791
+ const bare = { ...event };
36792
+ delete bare.attributes;
36793
+ return bare;
36794
+ }
36058
36795
 
36059
36796
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36060
36797
  import { createHash as createHash6 } from "crypto";
@@ -36223,7 +36960,10 @@ function attributesOf(raw) {
36223
36960
  try {
36224
36961
  const parsed2 = JSON.parse(raw);
36225
36962
  if (typeof parsed2 !== "object" || parsed2 === null || Array.isArray(parsed2)) return {};
36226
- return { attributes: parsed2 };
36963
+ const bag = {
36964
+ attributes: parsed2
36965
+ };
36966
+ return withoutScopeKey(bag);
36227
36967
  } catch {
36228
36968
  return {};
36229
36969
  }
@@ -36726,13 +37466,18 @@ import { spawn } from "child_process";
36726
37466
  import { fileURLToPath as fileURLToPath2 } from "url";
36727
37467
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
36728
37468
 
37469
+ // ../../packages/plugin-runtime/src/attached/install-record.ts
37470
+ import { readFile as readFile2, stat } from "fs/promises";
37471
+ import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
37472
+
36729
37473
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
36730
37474
  import { readFileSync as readFileSync18 } from "fs";
37475
+ var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
36731
37476
 
36732
37477
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36733
- import { randomUUID as randomUUID16 } from "crypto";
36734
- import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36735
- import { join as join28 } from "path";
37478
+ import { randomUUID as randomUUID17 } from "crypto";
37479
+ import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
37480
+ import { join as join30 } from "path";
36736
37481
 
36737
37482
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36738
37483
  import { rename as rename2 } from "fs/promises";
@@ -36742,7 +37487,7 @@ var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
36742
37487
 
36743
37488
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
36744
37489
  import { readFileSync as readFileSync19 } from "fs";
36745
- import { join as join29 } from "path";
37490
+ import { join as join31 } from "path";
36746
37491
  var OUTCOME_KEYS = {
36747
37492
  ok: true,
36748
37493
  unauthorized: true,
@@ -36763,13 +37508,13 @@ import { statSync as statSync9 } from "fs";
36763
37508
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
36764
37509
 
36765
37510
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
36766
- import { randomUUID as randomUUID17 } from "crypto";
36767
- import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
36768
- import { join as join30 } from "path";
37511
+ import { randomUUID as randomUUID18 } from "crypto";
37512
+ import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37513
+ import { join as join32 } from "path";
36769
37514
 
36770
37515
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
36771
37516
  import { readFileSync as readFileSync20 } from "fs";
36772
- import { join as join31 } from "path";
37517
+ import { join as join33 } from "path";
36773
37518
 
36774
37519
  // ../../packages/plugin-runtime/src/attached/status.ts
36775
37520
  var REFUSAL_LINES = {
@@ -36801,9 +37546,6 @@ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
36801
37546
  // ../../packages/plugin-runtime/src/attached/factory.ts
36802
37547
  import { hostname as hostname6 } from "os";
36803
37548
 
36804
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
36805
- import { randomUUID as randomUUID18 } from "crypto";
36806
-
36807
37549
  // ../../packages/plugin-runtime/src/handle-session-start.ts
36808
37550
  import { randomUUID as randomUUID19 } from "crypto";
36809
37551
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;