@akasecurity/ai-tc-codex 0.9.15 → 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.
package/scripts/sync.js CHANGED
@@ -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.10/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.10/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) => `${PLACEHOLDER2}${sources.push(source) - 1}${PLACEHOLDER2}`;
@@ -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,16 +419,12 @@ 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 = "[^\\/]*";
432
429
  var separatorAfter = (run, at) => {
433
430
  let separator = EMPTY;
@@ -543,6 +540,14 @@ var require_ignore = __commonJS({
543
540
  (match, index) => sources[index]
544
541
  ) : replaced;
545
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
+ };
546
551
  var matchesBasename = (body) => {
547
552
  const index = body.indexOf(SLASH3);
548
553
  return index < 0 || index === body.length - 1;
@@ -603,11 +608,9 @@ var require_ignore = __commonJS({
603
608
  return this._make(MODE_CHECK_IGNORE, key);
604
609
  }
605
610
  _make(mode, key) {
606
- const str2 = pinWildcards(this.regexPrefix.replace(
607
- REGEX_REPLACE_TRAILING_WILDCARD,
608
- // It does not need to bind pattern
609
- TRAILING_WILD_CARD_REPLACERS[mode]
610
- ));
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
+ );
611
614
  const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
612
615
  return define(this, key, regex);
613
616
  }
@@ -666,8 +669,39 @@ var require_ignore = __commonJS({
666
669
  makeArray(
667
670
  isString(pattern) ? splitPattern(pattern) : pattern
668
671
  ).forEach(this._add, this);
672
+ if (this._added) {
673
+ this._literalRules = UNDEFINED;
674
+ }
669
675
  return this._added;
670
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
+ }
671
705
  // Test one single path without recursively checking parent directories
672
706
  //
673
707
  // - checkUnignored `boolean` whether should check if the path is unignored,
@@ -788,14 +822,12 @@ var require_ignore = __commonJS({
788
822
  if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {
789
823
  return this.test(path);
790
824
  }
791
- const parentPath = parentOf(path);
792
- if (parentPath) {
793
- const parent = this._t(parentPath, this._testCache, true);
794
- if (parent.ignored) {
795
- return parent;
796
- }
825
+ const dir = this._t(path, this._testCache, true);
826
+ if (dir.ignored) {
827
+ return dir;
797
828
  }
798
- return this._rules.test(path, false, MODE_CHECK_IGNORE);
829
+ const literal2 = this._rules.testLiteral(path);
830
+ return literal2.ignored || literal2.unignored ? literal2 : dir;
799
831
  }
800
832
  _t(path, cache, checkUnignored) {
801
833
  if (path in cache) {
@@ -1010,6 +1042,10 @@ var SQLITE_MIGRATIONS = [
1010
1042
  {
1011
1043
  tag: "0036_secret_vault_identity_fingerprint",
1012
1044
  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"
1045
+ },
1046
+ {
1047
+ tag: "0037_finding_location",
1048
+ 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;"
1013
1049
  }
1014
1050
  ];
1015
1051
 
@@ -6051,7 +6087,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6051
6087
  var NONE = 0;
6052
6088
  var ASSUMED = 1;
6053
6089
  var PROVEN = 2;
6054
- function isRecursive(inst, stack, resolve3) {
6090
+ function isRecursive(inst, stack, resolve4) {
6055
6091
  const cached2 = recursive.get(inst);
6056
6092
  if (cached2 !== void 0)
6057
6093
  return cached2 ? PROVEN : NONE;
@@ -6061,7 +6097,7 @@ function isRecursive(inst, stack, resolve3) {
6061
6097
  let result = NONE;
6062
6098
  const check2 = (child) => {
6063
6099
  if (result !== PROVEN && child?._zod) {
6064
- const answer = isRecursive(child, stack, resolve3);
6100
+ const answer = isRecursive(child, stack, resolve4);
6065
6101
  if (answer > result)
6066
6102
  result = answer;
6067
6103
  }
@@ -6072,7 +6108,7 @@ function isRecursive(inst, stack, resolve3) {
6072
6108
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6073
6109
  if (spread && !desc.enumerable)
6074
6110
  continue;
6075
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6111
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve4) : NONE;
6076
6112
  if (child > answer)
6077
6113
  answer = child;
6078
6114
  }
@@ -6136,7 +6172,7 @@ function isRecursive(inst, stack, resolve3) {
6136
6172
  break;
6137
6173
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6138
6174
  case "lazy": {
6139
- const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6175
+ const inner = def._cachedInner ?? (resolve4 ? inst._zod.innerType : void 0);
6140
6176
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6141
6177
  break;
6142
6178
  }
@@ -21909,11 +21945,33 @@ var ResolutionMethod = external_exports.enum([
21909
21945
  "false-positive",
21910
21946
  "redetected"
21911
21947
  ]).meta({ id: "ResolutionMethod" });
21948
+ var FindingContextBasis = external_exports.enum(["file", "excerpt"]).meta({ id: "FindingContextBasis" });
21949
+ var FindingContext = external_exports.object({
21950
+ basis: FindingContextBasis,
21951
+ // 1-based line number of `lines[0]`.
21952
+ firstLine: external_exports.number().int().positive(),
21953
+ lines: external_exports.array(external_exports.string()).min(1).max(5),
21954
+ match: external_exports.object({
21955
+ // 1-based line number, within [firstLine, firstLine + lines.length).
21956
+ line: external_exports.number().int().positive(),
21957
+ // Offsets into that entry of `lines`, end exclusive.
21958
+ start: external_exports.number().int().nonnegative(),
21959
+ end: external_exports.number().int().nonnegative()
21960
+ }).nullable()
21961
+ }).meta({ id: "FindingContext" });
21962
+ var FindingLocation = external_exports.object({
21963
+ line: external_exports.number().int().positive(),
21964
+ col: external_exports.number().int().positive(),
21965
+ context: FindingContext.nullable()
21966
+ });
21912
21967
  var FindingMatch = external_exports.object({
21913
21968
  // Masked preview of the matched value. Never raw content.
21914
21969
  maskedValue: external_exports.string(),
21915
- // Redacted source-line prefix. Currently empty (pending privacy review).
21916
- contextPrefix: external_exports.string()
21970
+ // Deprecated: always empty. Superseded by `context`.
21971
+ contextPrefix: external_exports.string(),
21972
+ // The masked lines around the match. Absent when the finding predates
21973
+ // context capture or none could be built safely.
21974
+ context: FindingContext.optional()
21917
21975
  }).meta({ id: "FindingMatch" });
21918
21976
  var FindingDetectionRef = external_exports.object({
21919
21977
  id: external_exports.string(),
@@ -21933,6 +21991,11 @@ var FindingInstance = external_exports.object({
21933
21991
  provider: FindingProvider,
21934
21992
  repo: external_exports.string(),
21935
21993
  file: external_exports.string(),
21994
+ // 1-based line and column of the match start in the scanned text (the
21995
+ // column in UTF-16 code units). Absent for findings that predate location
21996
+ // capture or have no source text.
21997
+ line: external_exports.number().int().positive().optional(),
21998
+ col: external_exports.number().int().positive().optional(),
21936
21999
  // Who the capturing event is attributed to. Optional: a single-user store
21937
22000
  // has no one to attribute a finding to and never sets it.
21938
22001
  user: FindingUser.optional(),
@@ -21994,6 +22057,13 @@ var FindingStats = external_exports.object({
21994
22057
  low: external_exports.number().int().nonnegative()
21995
22058
  })
21996
22059
  }).meta({ id: "FindingStats" });
22060
+ var FindingsOverview = external_exports.object({
22061
+ findings: external_exports.number().int().nonnegative(),
22062
+ open: external_exports.number().int().nonnegative(),
22063
+ handled: external_exports.number().int().nonnegative(),
22064
+ resolved: external_exports.number().int().nonnegative(),
22065
+ dismissed: external_exports.number().int().nonnegative()
22066
+ }).meta({ id: "FindingsOverview" });
21997
22067
  var FindingFacetItem = external_exports.object({
21998
22068
  value: external_exports.string(),
21999
22069
  count: external_exports.number().int().nonnegative()
@@ -22113,6 +22183,7 @@ var FindingInstanceDetail = FindingInstance.extend({
22113
22183
  }).meta({ id: "FindingInstanceDetail" });
22114
22184
  var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
22115
22185
  var MAX_FLAT_FINDINGS_LIMIT = 200;
22186
+ var FindingContextQuery = external_exports.object({ id: external_exports.string().min(1).max(256) });
22116
22187
  var ListFindingInstancesQuery = external_exports.object({
22117
22188
  severity: external_exports.array(Severity).optional(),
22118
22189
  // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
@@ -22445,7 +22516,23 @@ var CaptureAttributes = external_exports.object({
22445
22516
  // capture denied by another finding's own Block policy carries `block`
22446
22517
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22447
22518
  // repeated rather than referenced because a store reader opens this file.
22448
- redact_degraded_to: ActionTaken.optional()
22519
+ redact_degraded_to: ActionTaken.optional(),
22520
+ // The scope key this capture was stamped with: the canonical repository
22521
+ // (`host/owner/repo`) of the path the capture names (a relative path is read
22522
+ // against its working directory), else of its own working directory, or a
22523
+ // chat account's identity. The store's local `scope_key` column reads it, so
22524
+ // a scoped attachment has a per-row key to work from. Absent when no key
22525
+ // could be derived.
22526
+ //
22527
+ // LOCAL ONLY. That is the contract for every path that sends a row. Producers
22528
+ // stamp it in every attachment mode, and the two structural choke points strip
22529
+ // it: the attached gateway's `reKeyForForward` on the live path, and the
22530
+ // history drain's `rebuildAuditEvent`, which drops it through `withoutScopeKey`.
22531
+ // A capture row's bag reaches the wire through `rebuildCapture`, which builds
22532
+ // the metadata from named keys and never names this one; `toCaptureAttributes`,
22533
+ // which builds the bag from a wire event, never emits it. What a scoped
22534
+ // attachment does with the key is not part of this shape's contract.
22535
+ scope_key: external_exports.string().optional()
22449
22536
  }).catchall(external_exports.unknown());
22450
22537
  var CaptureStatusAttributes = external_exports.object({
22451
22538
  source_tool: external_exports.string().optional(),
@@ -22475,6 +22562,12 @@ var ToolCallInspection = external_exports.object({
22475
22562
  actionTaken: ActionTaken,
22476
22563
  confidence: external_exports.number().min(0).max(1)
22477
22564
  });
22565
+ var findingLocationFields = {
22566
+ line: external_exports.number().int().positive().optional(),
22567
+ col: external_exports.number().int().positive().optional(),
22568
+ context: FindingContext.nullable().optional()
22569
+ };
22570
+ var ToolCallInspectionInput = ToolCallInspection.extend(findingLocationFields);
22478
22571
  var ToolCallInput = external_exports.object({
22479
22572
  sessionId: external_exports.string().min(1),
22480
22573
  toolUseId: external_exports.string().min(1),
@@ -22484,7 +22577,7 @@ var ToolCallInput = external_exports.object({
22484
22577
  attributes: ToolCallAttributes,
22485
22578
  // Secrets detected in the tool's (masked) target — written as linked
22486
22579
  // `inspection_findings`. Empty for a clean tool call.
22487
- inspections: external_exports.array(ToolCallInspection).default([])
22580
+ inspections: external_exports.array(ToolCallInspectionInput).default([])
22488
22581
  });
22489
22582
  var InventoryInput = external_exports.object({
22490
22583
  objectType: InventoryObjectType,
@@ -22558,7 +22651,8 @@ var InspectionFindingInput = external_exports.object({
22558
22651
  // same findingKey — mirrors the legacy `findings.first_detected_at`.
22559
22652
  // Optional: when omitted, the writer derives it from the referenced audit
22560
22653
  // event's startedAt on first insert (see SqliteInspectionFindingsRepository).
22561
- firstDetectedAt: external_exports.iso.datetime().optional()
22654
+ firstDetectedAt: external_exports.iso.datetime().optional(),
22655
+ ...findingLocationFields
22562
22656
  });
22563
22657
  var InventoryContext = external_exports.object({
22564
22658
  host: InventoryInput.optional(),
@@ -23337,6 +23431,20 @@ var AttachedCredential = external_exports.object({
23337
23431
  keyPrefix: external_exports.string().min(1).max(16).optional(),
23338
23432
  mintedAt: external_exports.iso.datetime().optional()
23339
23433
  });
23434
+ var AttachmentMode = external_exports.enum(["machine", "scoped"]);
23435
+ var ATTACHED_CREDENTIAL_SCOPED_SPEC_VERSION = 2;
23436
+ var AttachedCredentialV1 = AttachedCredential;
23437
+ var AttachedCredentialV2 = AttachedCredential.extend({
23438
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SCOPED_SPEC_VERSION),
23439
+ mode: external_exports.literal("scoped")
23440
+ });
23441
+ var AttachedCredentialAny = external_exports.discriminatedUnion("specVersion", [
23442
+ AttachedCredentialV1,
23443
+ AttachedCredentialV2
23444
+ ]);
23445
+ function attachmentModeOf(credential) {
23446
+ return credential.specVersion === ATTACHED_CREDENTIAL_SPEC_VERSION ? "machine" : "scoped";
23447
+ }
23340
23448
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
23341
23449
  function unsafeEndpointReason(endpoint) {
23342
23450
  let parsed2;
@@ -23642,6 +23750,130 @@ var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
23642
23750
  var SemVer = external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/);
23643
23751
  var PublisherKind = external_exports.enum(["labs", "user", "org"]);
23644
23752
 
23753
+ // ../../packages/schema/src/zod/builtin-policy-id.ts
23754
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23755
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23756
+
23757
+ // ../../packages/schema/src/zod/event.ts
23758
+ var EventKind = external_exports.enum(["prompt", "response", "code_change", "tool_use"]).meta({ id: "EventKind" });
23759
+ var CAPTURE_EVENT_TYPES_SQL = EventKind.options.map((k) => `'${k}'`).join(",");
23760
+ var EventMetadata = external_exports.object({
23761
+ sessionId: external_exports.string().optional(),
23762
+ repo: external_exports.string().optional(),
23763
+ filePath: external_exports.string().optional(),
23764
+ // The host tool whose input/output was scanned (e.g. 'Bash', 'WebFetch'),
23765
+ // set by the tool-scanning hooks. The tool NAME only — never the tool's
23766
+ // arguments or output, which can carry the very value a finding masked
23767
+ // (metadata is stored unredacted). Gives findings on non-file captures a
23768
+ // display location ("via Bash") when no filePath exists.
23769
+ toolName: external_exports.string().optional(),
23770
+ // Set (true) by the worktree scanner when the file is excluded by the
23771
+ // repo's .gitignore. Gitignored files ARE still scanned — local scratch and
23772
+ // generated code can leak real secrets — but the provenance is recorded so
23773
+ // policy/dashboards can treat those findings as informational rather than
23774
+ // blocking. Omitted (not false) for tracked files and non-scan events.
23775
+ gitignored: external_exports.boolean().optional(),
23776
+ // Set (true) ONLY when the event's `content` is the COMPLETE file at
23777
+ // capture time (a worktree scan reading from disk). Hook-captured edits
23778
+ // (e.g. an Edit tool's new_string) are partial fragments and MUST NOT set
23779
+ // this. The resolver-on-ingest keys its fixed-at-source dropout
23780
+ // diff on this marker: only a whole-file snapshot can prove a previously
23781
+ // open finding is gone; a fragment's absence proves nothing (the secret
23782
+ // may live outside the hunk). Omitted (not false) for fragments and
23783
+ // non-scan events, so pre-marker clients safely default to the
23784
+ // non-authoritative path.
23785
+ wholeFile: external_exports.boolean().optional(),
23786
+ model: external_exports.string().optional(),
23787
+ turnIndex: external_exports.number().int().nonnegative().optional(),
23788
+ // Distributed-tracing correlation. `correlationId` ties a recorded event back
23789
+ // to the request that captured/ingested it (a UUID, generated independently of
23790
+ // the trace id); `traceId` is the W3C trace id (32 lowercase hex chars) of the
23791
+ // originating span when telemetry is enabled. Both optional + backward
23792
+ // compatible — populated by the plugin (see @akasecurity/plugin-sdk).
23793
+ correlationId: external_exports.uuid().optional(),
23794
+ traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).optional(),
23795
+ // Ids of the detection exceptions that downgraded findings in this capture
23796
+ // to 'allow' — the enforcement audit trail's link back to the grant that
23797
+ // authorized the bypass. Absent on captures where no exception applied.
23798
+ exceptionIds: external_exports.array(external_exports.guid()).optional(),
23799
+ // The assistant message this capture belongs to, and the conversation it sits
23800
+ // in — set by the browser extension's network capture so a stored `response`
23801
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
23802
+ // on every other capture path, which has no such id.
23803
+ //
23804
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
23805
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
23806
+ // places an event is PARSED; the local write path types the event and parses
23807
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
23808
+ messageId: external_exports.string().min(1).optional(),
23809
+ conversationId: external_exports.string().optional(),
23810
+ // How long THIS capture's inspection blocked its caller, in whole
23811
+ // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
23812
+ // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
23813
+ // detection + redaction, the work the host session actually waits on.
23814
+ //
23815
+ // Stamped ONLY on live in-flight captures. A capture that carries its own
23816
+ // `occurredAt` is replaying past work (the transcript backfill, the worktree
23817
+ // scan), and its scan duration is not latency any host session experienced,
23818
+ // so those rows leave this ABSENT rather than reporting a misleading number.
23819
+ // Absent is also what every pre-measurement client writes, and what a
23820
+ // clock failure degrades to — a reader must treat absence as "not measured"
23821
+ // and never as a zero, which would read as "inspection is free".
23822
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
23823
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
23824
+ // workspace's `redactFallback`, applied because the field could not be
23825
+ // masked in place (a shell command, a URL, or any argument on a host whose
23826
+ // hook contract offers no rewrite channel).
23827
+ //
23828
+ // It exists because the action alone cannot say why. A finding recorded as
23829
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
23830
+ // assigned Redact on a field that could not take one — and those are
23831
+ // different facts about the same row: the first is a policy the user chose,
23832
+ // the second is a masking the host could not perform. Absent means no
23833
+ // degrade happened, which is every ordinary capture.
23834
+ //
23835
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
23836
+ // is the CAPTURE while `actionTaken` is per FINDING:
23837
+ //
23838
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
23839
+ // `redact` alongside a finding ASSIGNED the same action stores both
23840
+ // identically and one reason for the pair; attributing it to both
23841
+ // describes the assigned one wrongly, and to neither loses the degrade.
23842
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
23843
+ // became, not the reason the capture ended as it did — a capture denied
23844
+ // by some other finding's own Block policy still carries `block` here,
23845
+ // and clearing the workspace's fallback would not have let it through.
23846
+ // Gate on the value against what a fallback can produce; never read the
23847
+ // field's presence as "this was the fallback's doing".
23848
+ //
23849
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23850
+ // Closing either means moving the reason onto the finding row, which
23851
+ // already carries its own action.
23852
+ redactDegradedTo: ActionTaken.optional()
23853
+ }).meta({ id: "EventMetadata" });
23854
+ var Event = external_exports.object({
23855
+ id: external_exports.guid(),
23856
+ sourceTool: SourceTool,
23857
+ kind: EventKind,
23858
+ occurredAt: external_exports.iso.datetime(),
23859
+ contentHash: external_exports.string(),
23860
+ content: external_exports.string(),
23861
+ metadata: EventMetadata.optional()
23862
+ }).meta({ id: "Event" });
23863
+ var IngestEvent = Event.meta({ id: "IngestEvent" });
23864
+ var INGEST_BATCH_MAX = 100;
23865
+ var IngestBatch = external_exports.object({
23866
+ events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
23867
+ // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
23868
+ // additionally rejects any event whose contentHash the store has already
23869
+ // recorded — for re-runnable bulk ingest (worktree scan, transcript
23870
+ // backfill), where a re-run mints fresh event ids for identical content and
23871
+ // would otherwise accumulate duplicates. Live hook traffic must NOT set it:
23872
+ // two genuinely separate prompts can be byte-identical and both belong on
23873
+ // the timeline.
23874
+ dedupe: external_exports.literal("content-hash").optional()
23875
+ }).meta({ id: "IngestBatch" });
23876
+
23645
23877
  // ../../packages/schema/src/zod/rule.ts
23646
23878
  var MatcherType = external_exports.enum(["keyword", "regex"]).meta({ id: "MatcherType" });
23647
23879
  var RuleProbeVerdict = external_exports.enum(["safe", "quarantined"]).meta({ id: "RuleProbeVerdict" });
@@ -23710,7 +23942,10 @@ var Matcher = external_exports.discriminatedUnion("type", [KeywordMatcher, Regex
23710
23942
  var MATCHER_TYPES = MatcherType.options;
23711
23943
  var AppliesTo = external_exports.strictObject({
23712
23944
  // Dot-prefixed, e.g. ".py" — matches the scanner's SOURCE_EXTENSIONS shape.
23713
- extensions: external_exports.array(external_exports.string().regex(/^\.[A-Za-z0-9]+$/)).min(1)
23945
+ extensions: external_exports.array(external_exports.string().regex(/^\.[A-Za-z0-9]+$/)).min(1).optional(),
23946
+ eventKinds: external_exports.array(EventKind).min(1).optional()
23947
+ }).refine((v) => v.extensions !== void 0 || v.eventKinds !== void 0, {
23948
+ message: "appliesTo needs extensions, eventKinds, or both"
23714
23949
  }).meta({ id: "AppliesTo" });
23715
23950
  var PostValidatorName = external_exports.enum(["entropy", "luhn"]).meta({ id: "PostValidatorName" });
23716
23951
  var PostValidatorRef = external_exports.union(
@@ -23733,6 +23968,7 @@ var PostValidatorRef = external_exports.union(
23733
23968
  )}) or { "name": ..., "config": { ... } }. An unrecognized name would be a false-positive guard that never runs.`
23734
23969
  }
23735
23970
  ).meta({ id: "PostValidatorRef" });
23971
+ var RuleEvidence = external_exports.enum(["code", "value"]).meta({ id: "RuleEvidence" });
23736
23972
  var RequiresNearby = external_exports.strictObject({
23737
23973
  // Each array, when present, must be non-empty and contain non-empty strings —
23738
23974
  // an empty/blank criterion would either never fire or (for labels) match
@@ -23755,6 +23991,8 @@ var RuleFixture = external_exports.strictObject({
23755
23991
  // Simulated file context for the scan, so fixtures can assert `appliesTo`
23756
23992
  // gating (e.g. a Python-only pattern must NOT fire in a .ts file).
23757
23993
  filePath: external_exports.string().optional(),
23994
+ // Simulated capture kind, so fixtures can assert `appliesTo.eventKinds`.
23995
+ eventKind: EventKind.optional(),
23758
23996
  expectedSpans: external_exports.array(external_exports.strictObject({ start: external_exports.number(), end: external_exports.number() })).optional()
23759
23997
  }).meta({ id: "RuleFixture" });
23760
23998
  var Rule = external_exports.strictObject({
@@ -23780,7 +24018,9 @@ var Rule = external_exports.strictObject({
23780
24018
  appliesTo: AppliesTo.optional(),
23781
24019
  postValidators: external_exports.array(PostValidatorRef).optional(),
23782
24020
  requiresNearby: RequiresNearby.optional(),
23783
- examples: external_exports.array(external_exports.string()).optional()
24021
+ examples: external_exports.array(external_exports.string()).optional(),
24022
+ // Whether the matched text is itself sensitive. Absent means 'value'.
24023
+ evidence: RuleEvidence.optional()
23784
24024
  }).meta({ id: "Rule" });
23785
24025
  var Author = external_exports.object({
23786
24026
  name: external_exports.string(),
@@ -23797,7 +24037,11 @@ var PackManifest = external_exports.object({
23797
24037
  description: external_exports.string().optional(),
23798
24038
  author: Author.optional(),
23799
24039
  license: external_exports.string().optional(),
23800
- sourceUrl: external_exports.url().optional()
24040
+ sourceUrl: external_exports.url().optional(),
24041
+ // The built-in policy a FIRST install of this pack assigns
24042
+ // (installed_packs.policy_id). Absent leaves the pack unassigned, so its
24043
+ // rules follow the category policies. An existing install never takes it.
24044
+ defaultPolicy: BuiltinPolicyId.optional()
23801
24045
  }).meta({ id: "PackManifest" });
23802
24046
 
23803
24047
  // ../../packages/schema/src/zod/detection.ts
@@ -23825,10 +24069,12 @@ var DetectionListItem = external_exports.object({
23825
24069
  // Per-pack enforcement-policy assignment. Holds a BuiltinPolicyId ARCHETYPE
23826
24070
  // (monitor|warn|redact|block) — NOT a policies-table Policy.id guid; a
23827
24071
  // detection is a PACK, and its policy is the archetype applied to all its
23828
- // rules. Absent == unassigned, which resolves to Monitor everywhere
23829
- // (DEFAULT_PACK_POLICY_ID). Every enforcement surface expands it into
23830
- // per-rule policies (see policyIdToAction). Typed z.string() (not
23831
- // the enum) to keep the OpenAPI response tolerant of a future custom id.
24072
+ // rules. Absent == unassigned, which resolves to Monitor by default
24073
+ // (DEFAULT_PACK_POLICY_ID); a host may resolve it to a policy of its own
24074
+ // (see the dashboard's `unassignedPolicy`). Every enforcement surface
24075
+ // expands it into per-rule policies (see policyIdToAction). Typed
24076
+ // z.string() (not the enum) to keep the OpenAPI response tolerant of a
24077
+ // future custom id.
23832
24078
  policyId: external_exports.string().optional(),
23833
24079
  // Set ONLY when a newer snapshot is available for this pack (OSS: the
23834
24080
  // bundled inventory recorded in available_packs differs from the installed
@@ -23897,10 +24143,12 @@ var DetectionDetail = external_exports.object({
23897
24143
  // Per-pack enforcement-policy assignment. Holds a BuiltinPolicyId ARCHETYPE
23898
24144
  // (monitor|warn|redact|block) — NOT a policies-table Policy.id guid; a
23899
24145
  // detection is a PACK, and its policy is the archetype applied to all its
23900
- // rules. Absent == unassigned, which resolves to Monitor everywhere
23901
- // (DEFAULT_PACK_POLICY_ID). Every enforcement surface expands it into
23902
- // per-rule policies (see policyIdToAction). Typed z.string() (not
23903
- // the enum) to keep the OpenAPI response tolerant of a future custom id.
24146
+ // rules. Absent == unassigned, which resolves to Monitor by default
24147
+ // (DEFAULT_PACK_POLICY_ID); a host may resolve it to a policy of its own
24148
+ // (see the dashboard's `unassignedPolicy`). Every enforcement surface
24149
+ // expands it into per-rule policies (see policyIdToAction). Typed
24150
+ // z.string() (not the enum) to keep the OpenAPI response tolerant of a
24151
+ // future custom id.
23904
24152
  policyId: external_exports.string().optional()
23905
24153
  }).meta({ id: "DetectionDetail" });
23906
24154
  var LibraryItem = external_exports.object({
@@ -24047,126 +24295,6 @@ function buildDetectionsList(summaries, query) {
24047
24295
  return { counts, items: filtered.map(summaryToDetectionListItem) };
24048
24296
  }
24049
24297
 
24050
- // ../../packages/schema/src/zod/event.ts
24051
- var EventKind = external_exports.enum(["prompt", "response", "code_change", "tool_use"]).meta({ id: "EventKind" });
24052
- var CAPTURE_EVENT_TYPES_SQL = EventKind.options.map((k) => `'${k}'`).join(",");
24053
- var EventMetadata = external_exports.object({
24054
- sessionId: external_exports.string().optional(),
24055
- repo: external_exports.string().optional(),
24056
- filePath: external_exports.string().optional(),
24057
- // The host tool whose input/output was scanned (e.g. 'Bash', 'WebFetch'),
24058
- // set by the tool-scanning hooks. The tool NAME only — never the tool's
24059
- // arguments or output, which can carry the very value a finding masked
24060
- // (metadata is stored unredacted). Gives findings on non-file captures a
24061
- // display location ("via Bash") when no filePath exists.
24062
- toolName: external_exports.string().optional(),
24063
- // Set (true) by the worktree scanner when the file is excluded by the
24064
- // repo's .gitignore. Gitignored files ARE still scanned — local scratch and
24065
- // generated code can leak real secrets — but the provenance is recorded so
24066
- // policy/dashboards can treat those findings as informational rather than
24067
- // blocking. Omitted (not false) for tracked files and non-scan events.
24068
- gitignored: external_exports.boolean().optional(),
24069
- // Set (true) ONLY when the event's `content` is the COMPLETE file at
24070
- // capture time (a worktree scan reading from disk). Hook-captured edits
24071
- // (e.g. an Edit tool's new_string) are partial fragments and MUST NOT set
24072
- // this. The resolver-on-ingest keys its fixed-at-source dropout
24073
- // diff on this marker: only a whole-file snapshot can prove a previously
24074
- // open finding is gone; a fragment's absence proves nothing (the secret
24075
- // may live outside the hunk). Omitted (not false) for fragments and
24076
- // non-scan events, so pre-marker clients safely default to the
24077
- // non-authoritative path.
24078
- wholeFile: external_exports.boolean().optional(),
24079
- model: external_exports.string().optional(),
24080
- turnIndex: external_exports.number().int().nonnegative().optional(),
24081
- // Distributed-tracing correlation. `correlationId` ties a recorded event back
24082
- // to the request that captured/ingested it (a UUID, generated independently of
24083
- // the trace id); `traceId` is the W3C trace id (32 lowercase hex chars) of the
24084
- // originating span when telemetry is enabled. Both optional + backward
24085
- // compatible — populated by the plugin (see @akasecurity/plugin-sdk).
24086
- correlationId: external_exports.uuid().optional(),
24087
- traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).optional(),
24088
- // Ids of the detection exceptions that downgraded findings in this capture
24089
- // to 'allow' — the enforcement audit trail's link back to the grant that
24090
- // authorized the bypass. Absent on captures where no exception applied.
24091
- exceptionIds: external_exports.array(external_exports.guid()).optional(),
24092
- // The assistant message this capture belongs to, and the conversation it sits
24093
- // in — set by the browser extension's network capture so a stored `response`
24094
- // row can be joined to the `llm_call` leaf describing the same turn. Absent
24095
- // on every other capture path, which has no such id.
24096
- //
24097
- // Non-empty for the reason WebExchange.messageId is: it is the join key, and
24098
- // a blank one matches no `llm_call` leaf. That refusal reaches only the
24099
- // places an event is PARSED; the local write path types the event and parses
24100
- // nothing, which is why `toCaptureAttributes` omits a blank one separately.
24101
- messageId: external_exports.string().min(1).optional(),
24102
- conversationId: external_exports.string().optional(),
24103
- // How long THIS capture's inspection blocked its caller, in whole
24104
- // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
24105
- // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
24106
- // detection + redaction, the work the host session actually waits on.
24107
- //
24108
- // Stamped ONLY on live in-flight captures. A capture that carries its own
24109
- // `occurredAt` is replaying past work (the transcript backfill, the worktree
24110
- // scan), and its scan duration is not latency any host session experienced,
24111
- // so those rows leave this ABSENT rather than reporting a misleading number.
24112
- // Absent is also what every pre-measurement client writes, and what a
24113
- // clock failure degrades to — a reader must treat absence as "not measured"
24114
- // and never as a zero, which would read as "inspection is free".
24115
- inspectionMs: external_exports.number().int().nonnegative().optional(),
24116
- // What a `redact` this capture COULD NOT CARRY OUT became instead — the
24117
- // workspace's `redactFallback`, applied because the field could not be
24118
- // masked in place (a shell command, a URL, or any argument on a host whose
24119
- // hook contract offers no rewrite channel).
24120
- //
24121
- // It exists because the action alone cannot say why. A finding recorded as
24122
- // `warn` reads identically whether its detection was ASSIGNED Warn or was
24123
- // assigned Redact on a field that could not take one — and those are
24124
- // different facts about the same row: the first is a policy the user chose,
24125
- // the second is a masking the host could not perform. Absent means no
24126
- // degrade happened, which is every ordinary capture.
24127
- //
24128
- // TWO LIMITS a reader of a stored row has to know, because the grain here
24129
- // is the CAPTURE while `actionTaken` is per FINDING:
24130
- //
24131
- // - It does not say WHICH finding degraded. A capture carrying a degraded
24132
- // `redact` alongside a finding ASSIGNED the same action stores both
24133
- // identically and one reason for the pair; attributing it to both
24134
- // describes the assigned one wrongly, and to neither loses the degrade.
24135
- // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
24136
- // became, not the reason the capture ended as it did — a capture denied
24137
- // by some other finding's own Block policy still carries `block` here,
24138
- // and clearing the workspace's fallback would not have let it through.
24139
- // Gate on the value against what a fallback can produce; never read the
24140
- // field's presence as "this was the fallback's doing".
24141
- //
24142
- // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
24143
- // Closing either means moving the reason onto the finding row, which
24144
- // already carries its own action.
24145
- redactDegradedTo: ActionTaken.optional()
24146
- }).meta({ id: "EventMetadata" });
24147
- var Event = external_exports.object({
24148
- id: external_exports.guid(),
24149
- sourceTool: SourceTool,
24150
- kind: EventKind,
24151
- occurredAt: external_exports.iso.datetime(),
24152
- contentHash: external_exports.string(),
24153
- content: external_exports.string(),
24154
- metadata: EventMetadata.optional()
24155
- }).meta({ id: "Event" });
24156
- var IngestEvent = Event.meta({ id: "IngestEvent" });
24157
- var INGEST_BATCH_MAX = 100;
24158
- var IngestBatch = external_exports.object({
24159
- events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
24160
- // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
24161
- // additionally rejects any event whose contentHash the store has already
24162
- // recorded — for re-runnable bulk ingest (worktree scan, transcript
24163
- // backfill), where a re-run mints fresh event ids for identical content and
24164
- // would otherwise accumulate duplicates. Live hook traffic must NOT set it:
24165
- // two genuinely separate prompts can be byte-identical and both belong on
24166
- // the timeline.
24167
- dedupe: external_exports.literal("content-hash").optional()
24168
- }).meta({ id: "IngestBatch" });
24169
-
24170
24298
  // ../../packages/schema/src/zod/exception.ts
24171
24299
  var ExceptionScope = external_exports.enum(["once", "temporary", "permanent"]);
24172
24300
  var ExceptionConditions = external_exports.object({
@@ -24634,6 +24762,8 @@ function toInstanceDetail(row) {
24634
24762
  provider: toApiProvider(row.sourceTool),
24635
24763
  repo: row.repo,
24636
24764
  file: row.file,
24765
+ ...row.line === void 0 ? {} : { line: row.line },
24766
+ ...row.col === void 0 ? {} : { col: row.col },
24637
24767
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
24638
24768
  eventId: row.eventId,
24639
24769
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
@@ -24647,7 +24777,11 @@ function toInstanceDetail(row) {
24647
24777
  category,
24648
24778
  subtype: row.ruleId,
24649
24779
  severity: row.severity,
24650
- match: { maskedValue: row.maskedMatch, contextPrefix: "" },
24780
+ match: {
24781
+ maskedValue: row.maskedMatch,
24782
+ contextPrefix: "",
24783
+ ...row.context === void 0 ? {} : { context: row.context }
24784
+ },
24651
24785
  detection: { id: row.ruleId, name: null },
24652
24786
  policy: { id: `category:${category}`, name: category }
24653
24787
  };
@@ -24759,8 +24893,6 @@ var Policy = external_exports.object({
24759
24893
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
24760
24894
  provenance: PolicyProvenance.optional()
24761
24895
  }).meta({ id: "Policy" });
24762
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
24763
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
24764
24896
  var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
24765
24897
  id: "RedactFallback"
24766
24898
  });
@@ -25234,7 +25366,7 @@ var VaultConsent = external_exports.object({
25234
25366
  });
25235
25367
 
25236
25368
  // ../../packages/schema/src/zod/local.ts
25237
- var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
25369
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 9;
25238
25370
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
25239
25371
  var RunMode = external_exports.enum(["standalone", "attached"]);
25240
25372
  var ControlPlaneConnection = external_exports.object({
@@ -25254,6 +25386,37 @@ var HistorySyncConsent = external_exports.object({
25254
25386
  payloadVersion: external_exports.number().int().positive(),
25255
25387
  endpoint: external_exports.string()
25256
25388
  });
25389
+ var ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH = 512;
25390
+ var AttachmentScopeEntry = external_exports.object({
25391
+ kind: external_exports.enum(["repo", "account"]),
25392
+ identity: printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH).min(1),
25393
+ label: printable(80).optional(),
25394
+ enrolledAt: external_exports.iso.datetime()
25395
+ });
25396
+ var AttachmentScope = external_exports.object({
25397
+ endpoint: external_exports.string().min(1),
25398
+ entries: external_exports.array(AttachmentScopeEntry)
25399
+ });
25400
+ var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
25401
+ function parseAttachmentScope(raw) {
25402
+ try {
25403
+ const envelope = AttachmentScopeEnvelope.safeParse(raw);
25404
+ if (!envelope.success) return void 0;
25405
+ const entries = [];
25406
+ for (const candidate of envelope.data.entries) {
25407
+ const entry = AttachmentScopeEntry.safeParse(candidate);
25408
+ if (entry.success) entries.push(entry.data);
25409
+ }
25410
+ return { endpoint: envelope.data.endpoint, entries };
25411
+ } catch {
25412
+ return void 0;
25413
+ }
25414
+ }
25415
+ function scopeForEndpoint(raw, endpoint) {
25416
+ if (endpoint === void 0) return void 0;
25417
+ const scope = parseAttachmentScope(raw);
25418
+ return scope?.endpoint === endpoint ? scope : void 0;
25419
+ }
25257
25420
  var WebChatCaptureConsent = external_exports.object({
25258
25421
  acknowledgedAt: external_exports.iso.datetime(),
25259
25422
  version: external_exports.number().int().positive()
@@ -25324,6 +25487,23 @@ var WorkspaceSettings = external_exports.object({
25324
25487
  // both widenings. Absent until granted, and a grant for a different endpoint
25325
25488
  // or an older payload no longer counts.
25326
25489
  historySyncConsent: HistorySyncConsent.optional(),
25490
+ // The identities a SCOPED attachment forwards and the deployment they were
25491
+ // enrolled for (see AttachmentScope). Absent until something is enrolled.
25492
+ //
25493
+ // `z.unknown()`, NOT `AttachmentScope`, and the difference is this field's
25494
+ // whole failure mode. A settings.json that fails this schema reads as the
25495
+ // unonboarded defaults (readUserSettings in @akasecurity/persistence), and the
25496
+ // next save writes those defaults back over it. Typed, one entry with an
25497
+ // unknown `kind`, a control character or a bad timestamp would cost the
25498
+ // attachment, every consent and onboardedAt, permanently. Untyped, the value
25499
+ // is kept exactly as found and validated where it is used: parseAttachmentScope
25500
+ // drops a bad entry by itself, and on a scoped attachment resolveScope reads a
25501
+ // bad envelope as no entries, which keeps every event local.
25502
+ //
25503
+ // No default: absent must stay absent, so defaultWorkspaceSettings() and a
25504
+ // fresh settings.json do not change. No `.meta({ id })`, like every field
25505
+ // here. Not a ManagedSettingKey.
25506
+ attachmentScope: external_exports.unknown().optional(),
25327
25507
  // What the browser extension may record from a web chat, and the grant that
25328
25508
  // authorizes it. Absent until the user answers: recording something that was
25329
25509
  // never recorded before is never an assumed grant on upgrade, so the whole
@@ -25347,6 +25527,32 @@ function defaultWorkspaceSettings() {
25347
25527
  function isAttached(settings) {
25348
25528
  return settings.runMode === "attached" && settings.controlPlane !== void 0;
25349
25529
  }
25530
+ function resolveScope(input2, extraEntries) {
25531
+ try {
25532
+ if (input2.mode === "machine") return { mode: "machine", keys: /* @__PURE__ */ new Set() };
25533
+ const keys = /* @__PURE__ */ new Set();
25534
+ const stored = scopeForEndpoint(input2.scope, input2.endpoint);
25535
+ for (const entry of stored?.entries ?? []) {
25536
+ keys.add(entry.identity);
25537
+ }
25538
+ for (const candidate of extraEntries ?? []) {
25539
+ const entry = AttachmentScopeEntry.safeParse(candidate);
25540
+ if (entry.success) keys.add(entry.data.identity);
25541
+ }
25542
+ return { mode: "scoped", keys };
25543
+ } catch {
25544
+ return { mode: "scoped", keys: /* @__PURE__ */ new Set() };
25545
+ }
25546
+ }
25547
+ function scopeVerdict(resolved, key) {
25548
+ try {
25549
+ if (resolved.mode === "machine") return "forward";
25550
+ if (typeof key !== "string" || key === "") return "local";
25551
+ return resolved.keys.has(key) ? "forward" : "local";
25552
+ } catch {
25553
+ return "local";
25554
+ }
25555
+ }
25350
25556
  function toInventoryRow(input2, id, now) {
25351
25557
  return {
25352
25558
  id,
@@ -25418,7 +25624,10 @@ function toInspectionFindingRow(input2) {
25418
25624
  actionTaken: input2.actionTaken,
25419
25625
  confidence: input2.confidence,
25420
25626
  findingKey: input2.findingKey ?? null,
25421
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
25627
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null,
25628
+ line: input2.line ?? null,
25629
+ col: input2.col ?? null,
25630
+ context: input2.context ? JSON.stringify(input2.context) : null
25422
25631
  };
25423
25632
  }
25424
25633
  function toCaptureAttributes(event) {
@@ -26727,6 +26936,15 @@ var COUNTED_SCOPE = `
26727
26936
  OR outbox_owed = 1
26728
26937
  )`;
26729
26938
  var SKIPPED = -1;
26939
+ function inScope(column) {
26940
+ return `${column} IN (SELECT value FROM json_each(:scopeKeys))`;
26941
+ }
26942
+ function scopeKeysParam(scopeKeys) {
26943
+ return JSON.stringify(scopeKeys);
26944
+ }
26945
+ var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26946
+ FROM audit_events AS session_root
26947
+ WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26730
26948
  var ROW_COLUMNS = `id,
26731
26949
  parent_id AS parentId,
26732
26950
  root_session_id AS rootSessionId,
@@ -26755,6 +26973,18 @@ var SqliteHistorySyncRepository = class {
26755
26973
  ORDER BY earliest
26756
26974
  LIMIT :limit`
26757
26975
  );
26976
+ this.scopedSessionsStmt = db.prepare(
26977
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
26978
+ FROM audit_events
26979
+ WHERE synced_at IS NULL
26980
+ AND event_type IN (${TYPE_LIST})
26981
+ AND started_at < :before
26982
+ AND ${inScope("scope_key")}
26983
+ AND ${inScope(ROOT_SCOPE_KEY)}
26984
+ GROUP BY sessionId
26985
+ ORDER BY earliest
26986
+ LIMIT :limit`
26987
+ );
26758
26988
  this.rowsStmt = db.prepare(
26759
26989
  `SELECT ${ROW_COLUMNS}
26760
26990
  FROM audit_events
@@ -26765,6 +26995,18 @@ var SqliteHistorySyncRepository = class {
26765
26995
  ORDER BY (event_type = 'session') DESC, started_at
26766
26996
  LIMIT :limit`
26767
26997
  );
26998
+ this.scopedRowsStmt = db.prepare(
26999
+ `SELECT ${ROW_COLUMNS}
27000
+ FROM audit_events
27001
+ WHERE synced_at IS NULL
27002
+ AND event_type IN (${TYPE_LIST})
27003
+ AND started_at < :before
27004
+ AND COALESCE(root_session_id, id) = :sessionId
27005
+ AND ${inScope("scope_key")}
27006
+ AND ${inScope(ROOT_SCOPE_KEY)}
27007
+ ORDER BY (event_type = 'session') DESC, started_at
27008
+ LIMIT :limit`
27009
+ );
26768
27010
  this.captureRowsStmt = db.prepare(
26769
27011
  `SELECT ${ROW_COLUMNS}
26770
27012
  FROM audit_events
@@ -26776,6 +27018,18 @@ var SqliteHistorySyncRepository = class {
26776
27018
  ORDER BY started_at
26777
27019
  LIMIT :limit`
26778
27020
  );
27021
+ this.scopedCaptureRowsStmt = db.prepare(
27022
+ `SELECT ${ROW_COLUMNS}
27023
+ FROM audit_events
27024
+ WHERE synced_at IS NULL
27025
+ AND sync_claimed_at IS NULL
27026
+ AND outbox_owed = 1
27027
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27028
+ AND started_at < :before
27029
+ AND ${inScope("scope_key")}
27030
+ ORDER BY started_at
27031
+ LIMIT :limit`
27032
+ );
26779
27033
  this.markOwedStmt = db.prepare(
26780
27034
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
26781
27035
  );
@@ -26785,6 +27039,20 @@ var SqliteHistorySyncRepository = class {
26785
27039
  AND event_type IN (${CAPTURE_TYPE_LIST})
26786
27040
  AND started_at < :before`
26787
27041
  );
27042
+ this.scopedCaptureBacklogOwedStmt = db.prepare(
27043
+ `UPDATE audit_events SET outbox_owed = 1
27044
+ WHERE synced_at IS NULL
27045
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27046
+ AND started_at < :before
27047
+ AND ${inScope("scope_key")}`
27048
+ );
27049
+ this.markScopeCapturesOwedStmt = db.prepare(
27050
+ `UPDATE audit_events SET outbox_owed = 1
27051
+ WHERE synced_at IS NULL
27052
+ AND outbox_owed IS NULL
27053
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27054
+ AND ${inScope("scope_key")}`
27055
+ );
26788
27056
  this.stampStmt = db.prepare(
26789
27057
  `UPDATE audit_events
26790
27058
  SET synced_at = :at,
@@ -26943,6 +27211,15 @@ var SqliteHistorySyncRepository = class {
26943
27211
  claimRowStmt;
26944
27212
  releaseRowStmt;
26945
27213
  releaseStaleClaimsStmt;
27214
+ // The SCOPED twins, for a scoped attachment: the same reads and seeds with the
27215
+ // scope clause added, prepared once here beside the machine statements, so a
27216
+ // machine attachment's statements are untouched and neither form is compiled
27217
+ // per call.
27218
+ scopedSessionsStmt;
27219
+ scopedRowsStmt;
27220
+ scopedCaptureRowsStmt;
27221
+ scopedCaptureBacklogOwedStmt;
27222
+ markScopeCapturesOwedStmt;
26946
27223
  /**
26947
27224
  * The masked detections recorded against one tool call.
26948
27225
  *
@@ -26962,15 +27239,33 @@ var SqliteHistorySyncRepository = class {
26962
27239
  * path's to deliver; this drain exists for what was recorded before it, and a
26963
27240
  * row both paths send is at best a duplicate request and at worst — for a
26964
27241
  * session root — an overwrite of the inventory ids the live path resolved.
27242
+ *
27243
+ * `scopeKeys` is a scoped attachment's filter: a session is offered only while
27244
+ * its root's key is one of them AND at least one of its unsent rows' keys is
27245
+ * (see scopedSessionsStmt). Omitted, this runs the machine statement,
27246
+ * unchanged; an empty list offers nothing.
26965
27247
  */
26966
- pendingSessions(limit, before) {
26967
- return allRows(this.sessionsStmt, { limit, before }).map(
26968
- (r) => r.sessionId
26969
- );
27248
+ pendingSessions(limit, before, scopeKeys) {
27249
+ const rows = scopeKeys === void 0 ? allRows(this.sessionsStmt, { limit, before }) : allRows(this.scopedSessionsStmt, {
27250
+ limit,
27251
+ before,
27252
+ scopeKeys: scopeKeysParam(scopeKeys)
27253
+ });
27254
+ return rows.map((r) => r.sessionId);
26970
27255
  }
26971
- /** One session's undelivered structural rows within the backlog, root first. */
26972
- pendingRows(sessionId, limit, before) {
26973
- return allRows(this.rowsStmt, { sessionId, limit, before });
27256
+ /**
27257
+ * One session's undelivered structural rows within the backlog, root first.
27258
+ *
27259
+ * With `scopeKeys`, only the rows whose own key AND whose session root's key
27260
+ * are among them, whichever session id is passed.
27261
+ */
27262
+ pendingRows(sessionId, limit, before, scopeKeys) {
27263
+ return scopeKeys === void 0 ? allRows(this.rowsStmt, { sessionId, limit, before }) : allRows(this.scopedRowsStmt, {
27264
+ sessionId,
27265
+ limit,
27266
+ before,
27267
+ scopeKeys: scopeKeysParam(scopeKeys)
27268
+ });
26974
27269
  }
26975
27270
  /**
26976
27271
  * Captures this machine still owes the deployment, oldest first.
@@ -26979,9 +27274,17 @@ var SqliteHistorySyncRepository = class {
26979
27274
  * by a time window — see captureRowsStmt for why a window could not express
26980
27275
  * this. `before` is the grace window that leaves a just-recorded capture to
26981
27276
  * the live path.
27277
+ *
27278
+ * With `scopeKeys`, only captures stamped with one of them, decided per
27279
+ * capture: /v1/events stubs a missing root, so a capture never waits on its
27280
+ * session's scope. An empty list reads nothing.
26982
27281
  */
26983
- pendingCaptureRows(limit, before) {
26984
- return allRows(this.captureRowsStmt, { limit, before });
27282
+ pendingCaptureRows(limit, before, scopeKeys) {
27283
+ return scopeKeys === void 0 ? allRows(this.captureRowsStmt, { limit, before }) : allRows(this.scopedCaptureRowsStmt, {
27284
+ limit,
27285
+ before,
27286
+ scopeKeys: scopeKeysParam(scopeKeys)
27287
+ });
26985
27288
  }
26986
27289
  /**
26987
27290
  * Record that a capture is OWED to the deployment.
@@ -27013,9 +27316,37 @@ var SqliteHistorySyncRepository = class {
27013
27316
  * Returns how many rows matched, for the caller to log or test against. Not a
27014
27317
  * count of NEWLY marked rows — a row still unsynced from an earlier call
27015
27318
  * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27319
+ *
27320
+ * `scopeKeys` scopes it for a scoped attachment: only captures stamped with one
27321
+ * of the keys are marked, and an empty list marks none. The scoped capture read
27322
+ * is what keeps a personal capture out of a batch; this keeps the marker to
27323
+ * what the grant covers. Omitted, it runs the machine statement, unchanged.
27016
27324
  */
27017
- markCaptureBacklogOwed(before) {
27018
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27325
+ markCaptureBacklogOwed(before, scopeKeys) {
27326
+ const result = scopeKeys === void 0 ? this.markCaptureBacklogOwedStmt.run({ before }) : this.scopedCaptureBacklogOwedStmt.run({ before, scopeKeys: scopeKeysParam(scopeKeys) });
27327
+ return Number(result.changes);
27328
+ }
27329
+ /**
27330
+ * Mark owed every unsent capture stamped with one of `scopeKeys`: the re-seed
27331
+ * an enrollment runs.
27332
+ *
27333
+ * This ASSUMES the contract a scoped caller keeps, and cannot check it: nothing
27334
+ * else marks an out-of-scope capture owed (the live forward must refuse it
27335
+ * before its owed branch, and the consent-time seed must be handed the key
27336
+ * list). Under that contract, an enrolled repository's unsent captures are
27337
+ * reachable only if this runs when the repository is enrolled. Like the
27338
+ * consent seed it is one explicit human action, never something a pass infers,
27339
+ * and its caller must know the history grant is in force: this method cannot
27340
+ * check consent and must not be called without it.
27341
+ *
27342
+ * No time bound. Delivered and skipped rows are never re-opened, and a row
27343
+ * already owed is not counted, so the return value is how many rows this call
27344
+ * newly marked. An empty list marks nothing.
27345
+ */
27346
+ markScopeCapturesOwed(scopeKeys) {
27347
+ return Number(
27348
+ this.markScopeCapturesOwedStmt.run({ scopeKeys: scopeKeysParam(scopeKeys) }).changes
27349
+ );
27019
27350
  }
27020
27351
  /**
27021
27352
  * Record delivery. Called only AFTER the far side has accepted the rows.
@@ -27220,8 +27551,12 @@ var SqliteHistorySyncRepository = class {
27220
27551
  * disown from eating THIS SAME CALL's own re-mark is the order, not the
27221
27552
  * bound — disown runs first, re-mark second, both inside the one
27222
27553
  * transaction above.
27554
+ *
27555
+ * `scopeKeys` scopes the re-mark exactly as `markCaptureBacklogOwed` is scoped.
27556
+ * The disown before it is not scoped, and must not be: it clears the previous
27557
+ * deployment's markers whatever their scope.
27223
27558
  */
27224
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
27559
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore, scopeKeys) {
27225
27560
  this.ensureRowStmt.run();
27226
27561
  withTransaction(
27227
27562
  this.db,
@@ -27232,7 +27567,7 @@ var SqliteHistorySyncRepository = class {
27232
27567
  this.disownCapturesStmt.run({ attachedAt: backlogBefore });
27233
27568
  }
27234
27569
  if (backfillCapturesBefore !== void 0) {
27235
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
27570
+ this.markCaptureBacklogOwed(backfillCapturesBefore, scopeKeys);
27236
27571
  }
27237
27572
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27238
27573
  },
@@ -27398,6 +27733,7 @@ function applyMigrations(db, file2, options = {}) {
27398
27733
  db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
27399
27734
  }
27400
27735
  ensureSyncedAtColumn(db, "audit_events");
27736
+ ensureScopeKeyColumn(db);
27401
27737
  ensureScanLedgerTable(db);
27402
27738
  ensureHistorySyncTable(db);
27403
27739
  ensureBlockedDetectionsTable(db);
@@ -27823,6 +28159,21 @@ function ensureSyncedAtColumn(db, table) {
27823
28159
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
27824
28160
  );
27825
28161
  }
28162
+ 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";
28163
+ function ensureScopeKeyColumn(db) {
28164
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
28165
+ if (hasScopeKeyColumn(db)) return;
28166
+ withTransaction(
28167
+ db,
28168
+ () => {
28169
+ if (!hasScopeKeyColumn(db)) db.exec(SCOPE_KEY_COLUMN_DDL);
28170
+ },
28171
+ "IMMEDIATE"
28172
+ );
28173
+ }
28174
+ function hasScopeKeyColumn(db) {
28175
+ return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28176
+ }
27826
28177
  function ensureScanLedgerTable(db) {
27827
28178
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27828
28179
  path TEXT PRIMARY KEY,
@@ -28700,6 +29051,19 @@ var SqliteAuditEventsRepository = class {
28700
29051
  if (typeof provider === "string") return provider;
28701
29052
  return void 0;
28702
29053
  }
29054
+ // The `scope_key` stored on a session root's attributes: the key the history
29055
+ // drain decides that root by. It is NOT necessarily the key of the root event a
29056
+ // caller just wrote, because roots are first-write-wins (see the session-root
29057
+ // upsert above) and the root event that arrives second leaves the stored row as
29058
+ // it was. Returns undefined when the id is not a session root, when the root is
29059
+ // a stub or carries no key, and when the stored value is not a string, which is
29060
+ // what the drain's scoped reads would not match either.
29061
+ sessionScopeKey(sessionId) {
29062
+ const row = this.findById(sessionId);
29063
+ if (row?.event_type !== "session" || !row.attributes) return void 0;
29064
+ const key = parseJsonObject(row.attributes)?.scope_key;
29065
+ return typeof key === "string" ? key : void 0;
29066
+ }
28703
29067
  // Every `llm_call` leaf's session id + raw attribute bag, for the read-time token
28704
29068
  // rollups. The caller parses each bag and prices it via the
28705
29069
  // cost model — we stay a thin reader here (no business logic, no cost). `root_session_id`
@@ -28720,6 +29084,8 @@ var SqliteAuditEventsRepository = class {
28720
29084
  var DEFAULT_BATCH_SIZE = 500;
28721
29085
  var DEFAULT_MAX_ROWS = 5e4;
28722
29086
  var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
29087
+ var SWEEP = { kind: "sweep" };
29088
+ var HOLD_ALL = { kind: "hold-all" };
28723
29089
  var SqliteBodyRetentionRepository = class {
28724
29090
  constructor(db) {
28725
29091
  this.db = db;
@@ -28736,6 +29102,14 @@ var SqliteBodyRetentionRepository = class {
28736
29102
  this.candidatesSyncSafeStmt = this.db.prepare(
28737
29103
  select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
28738
29104
  );
29105
+ this.candidatesScopedStmt = this.db.prepare(
29106
+ select(
29107
+ `AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL
29108
+ OR (outbox_owed IS NOT 1
29109
+ AND (scope_key IS NULL
29110
+ OR scope_key NOT IN (SELECT value FROM json_each(:scopeKeys)))))`
29111
+ )
29112
+ );
28739
29113
  this.heldBySyncStmt = this.db.prepare(`
28740
29114
  SELECT COUNT(*) AS n
28741
29115
  FROM audit_events
@@ -28743,37 +29117,63 @@ var SqliteBodyRetentionRepository = class {
28743
29117
  AND started_at < :cutoff
28744
29118
  AND event_type IN (${SYNC_LANE_TYPES_SQL})
28745
29119
  AND synced_at IS NULL`);
29120
+ this.heldByScopeStmt = this.db.prepare(`
29121
+ SELECT COUNT(*) AS n
29122
+ FROM audit_events
29123
+ WHERE content IS NOT NULL
29124
+ AND started_at < :cutoff
29125
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
29126
+ AND synced_at IS NULL
29127
+ AND (outbox_owed = 1
29128
+ OR scope_key IN (SELECT value FROM json_each(:scopeKeys)))`);
28746
29129
  this.expireStmt = this.db.prepare(
28747
29130
  `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
28748
29131
  );
29132
+ this.expireContextsStmt = this.db.prepare(
29133
+ `UPDATE inspection_findings SET context = NULL
29134
+ WHERE id IN (
29135
+ SELECT f.id
29136
+ FROM inspection_findings f INDEXED BY idx_inspection_findings_context
29137
+ JOIN audit_events e ON e.id = f.audit_event_id
29138
+ WHERE f.context IS NOT NULL
29139
+ AND f.first_detected_at < :cutoff
29140
+ AND e.content IS NULL
29141
+ AND e.started_at < :cutoff
29142
+ LIMIT :limit)`
29143
+ );
28749
29144
  }
28750
29145
  db;
28751
29146
  candidatesStmt;
28752
29147
  candidatesSyncSafeStmt;
29148
+ candidatesScopedStmt;
28753
29149
  heldBySyncStmt;
29150
+ heldByScopeStmt;
28754
29151
  expireStmt;
28755
- /** How many bytes a pass with these options would free, changing nothing. */
29152
+ expireContextsStmt;
29153
+ /**
29154
+ * How many body bytes a pass with these options would free, changing
29155
+ * nothing. Finding excerpts are not counted (see `bytesFreed`).
29156
+ */
28756
29157
  preview(opts) {
28757
- const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
28758
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
28759
- const rows = stmt.all({ cutoff: opts.cutoff, limit });
29158
+ const lane = laneOf(opts.sweepSyncLane);
29159
+ const rows = this.candidates(lane, opts.cutoff, opts.maxRows ?? DEFAULT_MAX_ROWS);
28760
29160
  return {
28761
29161
  rowsExpired: rows.length,
28762
29162
  bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
28763
- rowsHeldBySync: this.countHeldBySync(opts)
29163
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff)
28764
29164
  };
28765
29165
  }
28766
29166
  /** Clear eligible bodies, in bounded batches. */
28767
29167
  expire(opts) {
28768
29168
  const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
28769
29169
  const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
28770
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
29170
+ const lane = laneOf(opts.sweepSyncLane);
28771
29171
  let rowsExpired = 0;
28772
29172
  let bytesFreed = 0;
28773
29173
  let done = true;
28774
29174
  while (rowsExpired < maxRows) {
28775
29175
  const remaining = Math.min(batchSize, maxRows - rowsExpired);
28776
- const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
29176
+ const batch = this.candidates(lane, opts.cutoff, remaining);
28777
29177
  if (batch.length === 0) break;
28778
29178
  withTransaction(
28779
29179
  this.db,
@@ -28786,17 +29186,60 @@ var SqliteBodyRetentionRepository = class {
28786
29186
  bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
28787
29187
  if (batch.length < remaining) break;
28788
29188
  if (rowsExpired >= maxRows) {
28789
- done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
29189
+ done = this.candidates(lane, opts.cutoff, 1).length === 0;
28790
29190
  }
28791
29191
  }
28792
- return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
29192
+ this.expireContexts(opts.cutoff, batchSize, maxRows);
29193
+ return {
29194
+ rowsExpired,
29195
+ bytesFreed,
29196
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff),
29197
+ done
29198
+ };
29199
+ }
29200
+ // Clear the excerpts that outlived their body, one bounded transaction per
29201
+ // batch for the same reason the body sweep batches, and at most `maxRows` of
29202
+ // them per pass under the same cap: the next pass picks up the rest.
29203
+ expireContexts(cutoff, batchSize, maxRows) {
29204
+ let total = 0;
29205
+ while (total < maxRows) {
29206
+ const limit = Math.min(batchSize, maxRows - total);
29207
+ let cleared = 0;
29208
+ withTransaction(
29209
+ this.db,
29210
+ () => {
29211
+ cleared = Number(this.expireContextsStmt.run({ cutoff, limit }).changes);
29212
+ },
29213
+ "IMMEDIATE"
29214
+ );
29215
+ total += cleared;
29216
+ if (cleared < limit) return;
29217
+ }
29218
+ }
29219
+ /**
29220
+ * One batch of candidates under `lane`, bound with exactly the parameters its
29221
+ * statement names — node:sqlite refuses a named parameter a statement does not
29222
+ * declare, so the key list goes to the scoped statements only.
29223
+ *
29224
+ * Anything that is not `sweep` or `hold-keys` takes the hold-all statement.
29225
+ * The type admits no fourth kind, but this decides what is destroyed, and the
29226
+ * direction an unforeseen value falls has to be holding.
29227
+ */
29228
+ candidates(lane, cutoff, limit) {
29229
+ 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 });
29230
+ return rows;
28793
29231
  }
28794
- countHeldBySync(opts) {
28795
- if (opts.sweepSyncLane) return 0;
28796
- const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
29232
+ countHeldBySync(lane, cutoff) {
29233
+ if (lane.kind === "sweep") return 0;
29234
+ const row = lane.kind === "hold-keys" ? this.heldByScopeStmt.get({ cutoff, scopeKeys: JSON.stringify(lane.keys) }) : this.heldBySyncStmt.get({ cutoff });
28797
29235
  return row.n;
28798
29236
  }
28799
29237
  };
29238
+ function laneOf(gate2) {
29239
+ if (gate2 === true) return SWEEP;
29240
+ if (gate2 === false) return HOLD_ALL;
29241
+ return gate2;
29242
+ }
28800
29243
 
28801
29244
  // ../../packages/persistence/src/repositories/capture-status.ts
28802
29245
  var STATUS_LOOKBACK_ROWS = 128;
@@ -29705,6 +30148,8 @@ function toFlatFindingRow(r) {
29705
30148
  repo: r.repo ?? "",
29706
30149
  file: r.file ?? "",
29707
30150
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
30151
+ ...r.line === null ? {} : { line: r.line },
30152
+ ...r.col === null ? {} : { col: r.col },
29708
30153
  eventId: r.event_id,
29709
30154
  ...r.session_id === null ? {} : { sessionId: r.session_id },
29710
30155
  status: deriveInstanceStatus(r),
@@ -29782,7 +30227,8 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
29782
30227
  ${latestResolutionStatusSql("f")} AS latest_status,
29783
30228
  e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
29784
30229
  e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
29785
- e.outbox_owed AS outbox_owed`;
30230
+ e.outbox_owed AS outbox_owed,
30231
+ f.line AS line, f.col AS col`;
29786
30232
  var DAY_MS3 = 864e5;
29787
30233
  var SqliteFindingsRepository = class {
29788
30234
  constructor(db) {
@@ -30205,6 +30651,27 @@ var SqliteFindingsRepository = class {
30205
30651
  ).get(id);
30206
30652
  return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
30207
30653
  }
30654
+ /**
30655
+ * One finding's excerpt source (see FindingContextSource). A primary-key
30656
+ * seek, like `findingInstance`, and the only findings read that touches the
30657
+ * event's text — which is why the list never projects the excerpt and the
30658
+ * drawer asks for it here, one finding at a time.
30659
+ */
30660
+ findingContextSource(id) {
30661
+ const row = this.db.prepare(
30662
+ `SELECT f.context AS context, e.content AS content,
30663
+ f.span_start AS spanStart, f.span_end AS spanEnd,
30664
+ d.rule_id AS ruleId, d.category AS category,
30665
+ json_extract(e.attributes, '$.whole_file') AS wholeFile,
30666
+ e.tool_name AS toolName, e.event_type AS eventType
30667
+ FROM inspection_findings f
30668
+ JOIN audit_events e ON e.id = f.audit_event_id
30669
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30670
+ WHERE f.id = ?`
30671
+ ).get(id);
30672
+ if (row === void 0) return null;
30673
+ return { ...row, wholeFile: row.wholeFile === 1 };
30674
+ }
30208
30675
  /**
30209
30676
  * The one statement both instance-level scans run: every finding in scope,
30210
30677
  * joined to its event and definition, newest first.
@@ -30341,6 +30808,61 @@ var SqliteFindingsRepository = class {
30341
30808
  ])
30342
30809
  );
30343
30810
  }
30811
+ /**
30812
+ * The Findings page's summary strip: whole-store counts over exactly the rows
30813
+ * the instance reads list (the four capture kinds), each equal to what
30814
+ * listFindingInstances totals for the same filters — see FindingsOverview.
30815
+ *
30816
+ * ONE grouped aggregate whose keys are the raw classifier inputs, not the
30817
+ * answers: the statement groups by the three inputs deriveFindingStatus
30818
+ * reads, and each group is then classified here by that same function. So
30819
+ * SQL never restates the status rule, and the strip cannot disagree with the
30820
+ * list about which status a finding has. The group count is bounded by a
30821
+ * handful of status inputs, not by the store, so only the scan grows with it
30822
+ * — the same linear cost every other unscoped read on the page already pays.
30823
+ *
30824
+ * The definitions join selects nothing. It is there because the list's scan
30825
+ * joins it too, so a finding whose definition row is missing is left out of
30826
+ * both rather than counted here and absent there.
30827
+ *
30828
+ * The latest-resolution join is the derived-table form, which
30829
+ * resolution-sql.ts recommends for an aggregate over many findings.
30830
+ */
30831
+ findingsOverview() {
30832
+ const rows = allRows(
30833
+ this.db.prepare(
30834
+ `SELECT e.event_type AS kind, (f.finding_key IS NOT NULL) AS keyed,
30835
+ latest.status AS latest_status, count(*) AS c
30836
+ FROM inspection_findings f
30837
+ JOIN audit_events e ON e.id = f.audit_event_id
30838
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30839
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30840
+ ON latest.finding_key = f.finding_key
30841
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30842
+ GROUP BY e.event_type, keyed, latest.status`
30843
+ )
30844
+ );
30845
+ const byStatus = {
30846
+ open: 0,
30847
+ handled: 0,
30848
+ resolved: 0,
30849
+ dismissed: 0
30850
+ };
30851
+ let findings = 0;
30852
+ for (const row of rows) {
30853
+ const status = deriveFindingStatus({
30854
+ kind: row.kind,
30855
+ // The classifier only asks whether a key exists, never what it is. The
30856
+ // stand-in is non-empty so a truthiness test of the key reads it as
30857
+ // present, exactly as it would a real one.
30858
+ findingKey: row.keyed ? "keyed" : null,
30859
+ latestResolutionStatus: row.latest_status
30860
+ });
30861
+ findings += row.c;
30862
+ byStatus[status] += row.c;
30863
+ }
30864
+ return Promise.resolve({ findings, ...byStatus });
30865
+ }
30344
30866
  healthSummary() {
30345
30867
  const total = countScalar(
30346
30868
  this.db,
@@ -30468,12 +30990,13 @@ var SqliteInspectionFindingsRepository = class {
30468
30990
  `INSERT INTO inspection_findings
30469
30991
  (id, audit_event_id, inspection_definition_id, classified_data_id,
30470
30992
  span_start, span_end, masked_match, action_taken, confidence,
30471
- finding_key, first_detected_at)
30993
+ finding_key, first_detected_at, line, col, context)
30472
30994
  VALUES
30473
30995
  (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
30474
30996
  :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
30475
30997
  :findingKey,
30476
- COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
30998
+ COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)),
30999
+ :line, :col, :context)
30477
31000
  ON CONFLICT(id) DO UPDATE SET
30478
31001
  inspection_definition_id = excluded.inspection_definition_id
30479
31002
  ON CONFLICT (finding_key) DO UPDATE SET
@@ -30484,7 +31007,10 @@ var SqliteInspectionFindingsRepository = class {
30484
31007
  span_end = excluded.span_end,
30485
31008
  masked_match = excluded.masked_match,
30486
31009
  action_taken = excluded.action_taken,
30487
- confidence = excluded.confidence`
31010
+ confidence = excluded.confidence,
31011
+ line = excluded.line,
31012
+ col = excluded.col,
31013
+ context = excluded.context`
30488
31014
  );
30489
31015
  this.sessionDupStmt = db.prepare(
30490
31016
  `SELECT 1 FROM inspection_findings f
@@ -30534,7 +31060,10 @@ var SqliteInspectionFindingsRepository = class {
30534
31060
  actionTaken: row.actionTaken,
30535
31061
  confidence: row.confidence,
30536
31062
  findingKey: row.findingKey,
30537
- firstDetectedAt: row.firstDetectedAt
31063
+ firstDetectedAt: row.firstDetectedAt,
31064
+ line: row.line,
31065
+ col: row.col,
31066
+ context: row.context
30538
31067
  })
30539
31068
  );
30540
31069
  }
@@ -30900,8 +31429,8 @@ var SqliteInstalledPacksRepository = class {
30900
31429
  this.db = db;
30901
31430
  this.baseDir = baseDir;
30902
31431
  this.insertMissingStmt = db.prepare(
30903
- `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
30904
- VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
31432
+ `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31433
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
30905
31434
  ON CONFLICT (namespace, pack_id) DO NOTHING`
30906
31435
  );
30907
31436
  this.upsertAvailableStmt = db.prepare(
@@ -30961,7 +31490,10 @@ var SqliteInstalledPacksRepository = class {
30961
31490
  version: pack.version,
30962
31491
  name: pack.name,
30963
31492
  rulesJson: JSON.stringify(pack.rules),
30964
- ruleIds: new Set(pack.rules.map((r) => r.id))
31493
+ ruleIds: new Set(pack.rules.map((r) => r.id)),
31494
+ // Only a first install takes it: an existing row is never modified here,
31495
+ // so a policy the user chose (or cleared) is never overwritten.
31496
+ defaultPolicyId: pack.defaultPolicyId ?? null
30965
31497
  }));
30966
31498
  if (this.storedSignature() === inventorySignature(rows)) return;
30967
31499
  const now = Date.now();
@@ -30990,7 +31522,7 @@ var SqliteInstalledPacksRepository = class {
30990
31522
  } else {
30991
31523
  behind = true;
30992
31524
  }
30993
- this.insertMissingStmt.run(params);
31525
+ this.insertMissingStmt.run({ ...params, policyId: row.defaultPolicyId });
30994
31526
  }
30995
31527
  if (!behind) this.pruneAvailable(rows.map((r) => `${r.namespace}/${r.packId}`));
30996
31528
  },
@@ -31108,7 +31640,8 @@ var SqliteInstalledPacksRepository = class {
31108
31640
  rejectedRules: [],
31109
31641
  ruleActions: /* @__PURE__ */ new Map(),
31110
31642
  ruleVersions: /* @__PURE__ */ new Map(),
31111
- reversibleRules: /* @__PURE__ */ new Set()
31643
+ reversibleRules: /* @__PURE__ */ new Set(),
31644
+ assignedRules: /* @__PURE__ */ new Set()
31112
31645
  };
31113
31646
  const reject = (pack, ruleId, reason) => {
31114
31647
  if (out.rejectedRules.length >= REJECTED_RULE_DETAIL_CAP) return;
@@ -31141,6 +31674,8 @@ var SqliteInstalledPacksRepository = class {
31141
31674
  out.ruleVersions.set(parsed2.data.id, row.version);
31142
31675
  if (reversible) out.reversibleRules.add(parsed2.data.id);
31143
31676
  else out.reversibleRules.delete(parsed2.data.id);
31677
+ if (row.policyId !== null) out.assignedRules.add(parsed2.data.id);
31678
+ else out.assignedRules.delete(parsed2.data.id);
31144
31679
  } else {
31145
31680
  out.invalidRules += 1;
31146
31681
  reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
@@ -32227,6 +32762,7 @@ var SqliteInventoryAssetsRepository = class {
32227
32762
 
32228
32763
  // ../../packages/persistence/src/repositories/policies.ts
32229
32764
  import { randomUUID as randomUUID6 } from "crypto";
32765
+ var SEED_BATCH_WINDOW_MS = 6e4;
32230
32766
  var SqlitePoliciesRepository = class {
32231
32767
  constructor(db) {
32232
32768
  this.db = db;
@@ -32248,39 +32784,123 @@ var SqlitePoliciesRepository = class {
32248
32784
  });
32249
32785
  return Promise.resolve(policies);
32250
32786
  }
32251
- // Seed one policy per bundled category from DEFAULT_ACTIONS so the
32252
- // detection-type config exists from first run. Only when the table is empty,
32253
- // so a user's edits are never clobbered.
32787
+ // Seed one policy per bundled category at Monitor so the detection-type config
32788
+ // exists from first run. An unassigned pack's rules follow these rows, so
32789
+ // Monitor here is the posture of every pack that ships no defaultPolicy; a pack
32790
+ // that ships one carries its own assignment instead. Only when the
32791
+ // table is empty, so a user's edits are never clobbered.
32254
32792
  seedDefaults() {
32255
32793
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32256
- if (count > 0) return;
32794
+ if (count > 0) {
32795
+ this.markEarlierChoices();
32796
+ this.monitorUntouchedSeeds();
32797
+ return;
32798
+ }
32257
32799
  const stmt = this.db.prepare(
32258
32800
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
32259
32801
  VALUES (:id, 'global', :target, :action, 1, :now, :now)`
32260
32802
  );
32261
32803
  failOpenTransaction(this.db, () => {
32262
- for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
32804
+ for (const category of Object.keys(DEFAULT_ACTIONS)) {
32263
32805
  stmt.run({
32264
32806
  id: randomUUID6(),
32265
32807
  target: JSON.stringify({ category }),
32266
- action,
32808
+ action: "log",
32267
32809
  now: Date.now()
32268
32810
  });
32269
32811
  }
32270
32812
  });
32271
32813
  }
32814
+ // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32815
+ // equal to created_at, so a choice made for a category that had no row yet
32816
+ // (one added in a release after the store was seeded) looks exactly like a
32817
+ // seed. Left alone, fill-gaps would overwrite it and monitorUntouchedSeeds
32818
+ // could reset it. This pass marks such rows as chosen (updated_at =
32819
+ // created_at + 1) before either can read them. A row is an earlier build's
32820
+ // choice, not its seed, when either:
32821
+ // - its action is neither the old seed value (DEFAULT_ACTIONS) nor Monitor,
32822
+ // which no seed of any build ever wrote; or
32823
+ // - it was created well after the seed batch. Every build seeds all of its
32824
+ // categories in one transaction, and only into an empty table, so a row
32825
+ // created later came from upsertCategoryAction.
32826
+ // It needs no marker of its own: every row this build writes has updated_at >
32827
+ // created_at, and the seeds it leaves equal (fresh 'log' seeds, and seeds
32828
+ // moved to Monitor below, which keep their created_at) match neither test, so
32829
+ // after one pass it finds nothing and stays a read. What it cannot tell apart
32830
+ // is an earlier build's choice that equals the seed value AND was made within
32831
+ // the seed batch window; that row is read as a seed.
32832
+ markEarlierChoices() {
32833
+ const rows = allRows(
32834
+ this.db.prepare(
32835
+ `SELECT id, json_extract(target, '$.category') AS category, action,
32836
+ created_at AS c, updated_at AS u
32837
+ FROM policies
32838
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL`
32839
+ )
32840
+ );
32841
+ if (rows.length === 0) return;
32842
+ const seedBatchStart = Math.min(...rows.map((row) => row.c));
32843
+ const seeded = DEFAULT_ACTIONS;
32844
+ const choices = rows.filter(
32845
+ (row) => row.u === row.c && (row.action !== "log" && row.action !== seeded[row.category] || row.c > seedBatchStart + SEED_BATCH_WINDOW_MS)
32846
+ );
32847
+ if (choices.length === 0) return;
32848
+ const stmt = this.db.prepare(
32849
+ `UPDATE policies SET updated_at = created_at + 1 WHERE id = :id AND updated_at = created_at`
32850
+ );
32851
+ failOpenTransaction(this.db, () => {
32852
+ for (const row of choices) stmt.run({ id: row.id });
32853
+ });
32854
+ }
32855
+ // Stores seeded by an earlier build hold DEFAULT_ACTIONS in their category
32856
+ // rows. Those rows used to be shadowed by the Monitor every unassigned pack
32857
+ // emitted; now that unassigned packs defer to them, an untouched one would
32858
+ // turn Monitor into Warn on upgrade with nobody having asked. So a row still
32859
+ // exactly as seeded — the seeded action, never updated since it was created —
32860
+ // is moved to Monitor. A row the user, the setup wizard or the warn-era cap
32861
+ // ever wrote has a later updated_at and is left alone. updated_at is NOT
32862
+ // advanced, so a moved row still reads as an untouched seed (see
32863
+ // isCategoryChosen); it never matches again because it is no longer off 'log'.
32864
+ // One knock-on: when the installed snapshot is unusable (corrupt rules_json)
32865
+ // the gateway falls back to the bundled packs with no per-rule policies, so
32866
+ // every rule follows these rows. On an upgraded store that fallback now
32867
+ // monitors where the earlier build warned.
32868
+ monitorUntouchedSeeds() {
32869
+ const untouched = allRows(
32870
+ this.db.prepare(
32871
+ `SELECT json_extract(target, '$.category') AS category, action FROM policies
32872
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL
32873
+ AND action <> 'log' AND updated_at = created_at`
32874
+ )
32875
+ ).filter(
32876
+ (row) => DEFAULT_ACTIONS[row.category] === row.action
32877
+ );
32878
+ if (untouched.length === 0) return;
32879
+ const stmt = this.db.prepare(
32880
+ `UPDATE policies SET action = 'log'
32881
+ WHERE scope = 'global' AND json_extract(target, '$.category') = :category
32882
+ AND action = :seeded AND action <> 'log' AND updated_at = created_at`
32883
+ );
32884
+ failOpenTransaction(this.db, () => {
32885
+ for (const row of untouched) {
32886
+ stmt.run({ category: row.category, seeded: row.action });
32887
+ }
32888
+ });
32889
+ }
32272
32890
  // Insert-or-update the single global per-category policy row, keyed on the
32273
32891
  // existing uq_policies_scope_target unique index (scope, target). `action`
32274
32892
  // uses the SAME vocabulary seedDefaults writes (DEFAULT_ACTIONS' ActionTaken
32275
32893
  // values), so the runtime's resolveAction reads rows written by either path
32276
32894
  // identically. On conflict, `action`, `enabled`, and `updated_at` are updated;
32277
- // `id` and `created_at` are left exactly as they were.
32895
+ // `id` and `created_at` are left exactly as they were. Either way updated_at
32896
+ // ends up later than created_at, which is what marks the row as chosen.
32278
32897
  upsertCategoryAction(category, action) {
32279
32898
  const now = Date.now();
32280
32899
  this.db.prepare(
32281
32900
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
32282
- VALUES (:id, 'global', :target, :action, 1, :now, :now)
32283
- ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
32901
+ VALUES (:id, 'global', :target, :action, 1, :now, :now + 1)
32902
+ ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32903
+ updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32284
32904
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32285
32905
  }
32286
32906
  // Caps every global per-category policy currently set to block/redact down
@@ -32294,6 +32914,16 @@ var SqlitePoliciesRepository = class {
32294
32914
  ).run({ now: Date.now() });
32295
32915
  return Number(info.changes);
32296
32916
  }
32917
+ // Whether the category's row was ever written after it was created — by the
32918
+ // user, the setup wizard or a cap. A row still as seeded (updated_at equal to
32919
+ // created_at) is not a choice, so a posture filling gaps may replace it.
32920
+ isCategoryChosen(category) {
32921
+ const row = this.db.prepare(
32922
+ `SELECT created_at AS c, updated_at AS u FROM policies
32923
+ WHERE scope='global' AND json_extract(target,'$.category') = :category`
32924
+ ).get({ category });
32925
+ return row !== void 0 && row.u !== row.c;
32926
+ }
32297
32927
  // Read the current action for a single global per-category policy row, mirroring
32298
32928
  // upsertCategoryAction's category-lookup predicate. Returns undefined when no
32299
32929
  // row exists yet, so callers can distinguish an unset category from a set one.
@@ -34539,6 +35169,11 @@ var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
34539
35169
  function linkHost(input2, hostId) {
34540
35170
  return hostId ? { ...input2, hostId } : input2;
34541
35171
  }
35172
+ function captureAttributesOf(event, scopeKey) {
35173
+ const attributes = toCaptureAttributes(event);
35174
+ if (scopeKey === void 0 || scopeKey === "") return attributes;
35175
+ return { ...attributes, scope_key: scopeKey };
35176
+ }
34542
35177
  function closeQuietly(db) {
34543
35178
  try {
34544
35179
  db.close();
@@ -34724,7 +35359,7 @@ function openLocalDatabase(dir, options = {}) {
34724
35359
  );
34725
35360
  return dismissed;
34726
35361
  }
34727
- function recordCapture(event, detected) {
35362
+ function recordCapture(event, detected, scopeKey) {
34728
35363
  failOpenTransaction(db, () => {
34729
35364
  const sessionId = event.metadata?.sessionId;
34730
35365
  if (sessionId) {
@@ -34739,7 +35374,7 @@ function openLocalDatabase(dir, options = {}) {
34739
35374
  rootSessionId: sessionId,
34740
35375
  content: event.content,
34741
35376
  contentHash: event.contentHash,
34742
- attributes: toCaptureAttributes(event)
35377
+ attributes: captureAttributesOf(event, scopeKey)
34743
35378
  });
34744
35379
  const definitionIds = /* @__PURE__ */ new Map();
34745
35380
  for (const finding of detected) {
@@ -34769,7 +35404,12 @@ function openLocalDatabase(dir, options = {}) {
34769
35404
  maskedMatch: finding.maskedMatch,
34770
35405
  actionTaken: finding.actionTaken,
34771
35406
  confidence: finding.confidence,
34772
- findingKey: finding.findingKey ?? void 0
35407
+ findingKey: finding.findingKey ?? void 0,
35408
+ ...finding.location === void 0 ? {} : {
35409
+ line: finding.location.line,
35410
+ col: finding.location.col,
35411
+ context: finding.location.context
35412
+ }
34773
35413
  });
34774
35414
  }
34775
35415
  });
@@ -34945,22 +35585,54 @@ function trimSlashes(path) {
34945
35585
  while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
34946
35586
  return path.slice(start, end);
34947
35587
  }
34948
- function canonicalGitUrl(url2) {
35588
+ function parseGitRemote(url2) {
34949
35589
  const trimmed = url2.trim();
34950
- if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
35590
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return void 0;
34951
35591
  const scheme = SCHEME_FORM.exec(trimmed);
34952
35592
  const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
34953
35593
  const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
34954
- if (host === void 0) return trimmed;
34955
- const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
34956
- const bare = trimSlashes(path);
34957
- const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
34958
- return cleaned === "" ? host : `${host}/${cleaned}`;
35594
+ if (host === void 0) return void 0;
35595
+ const bare = trimSlashes((scheme === null ? scp?.[2] : scheme[2]) ?? "");
35596
+ return { host, path: bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare };
35597
+ }
35598
+ function canonicalGitUrl(url2) {
35599
+ const remote = parseGitRemote(url2);
35600
+ if (remote === void 0) return url2.trim();
35601
+ return remote.path === "" ? remote.host : `${remote.host}/${remote.path}`;
34959
35602
  }
34960
35603
  function hashProjectKey(projectKey) {
34961
35604
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
34962
35605
  return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
34963
35606
  }
35607
+ var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35608
+ var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
35609
+ var SKIPPED_USERINFO = /^([^@/]+)@/;
35610
+ var ENDS_AUTHORITY = /[?#\\]/;
35611
+ var PLAIN_HOST = /^[A-Za-z0-9._-]+$/;
35612
+ var QUERY_OR_FRAGMENT = /[?#]/;
35613
+ function namesTheHostGitContacts(url2, host) {
35614
+ if (!PLAIN_HOST.test(host)) return false;
35615
+ const trimmed = url2.trim();
35616
+ const scheme = URL_SCHEME.exec(trimmed);
35617
+ if (scheme === null) {
35618
+ const userinfo2 = SKIPPED_USERINFO.exec(trimmed)?.[1];
35619
+ return !userinfo2?.includes(":");
35620
+ }
35621
+ if (!SCHEME_FORM.test(trimmed)) return false;
35622
+ const userinfo = SKIPPED_USERINFO.exec(trimmed.slice(scheme[0].length))?.[1];
35623
+ return userinfo === void 0 || !ENDS_AUTHORITY.test(userinfo);
35624
+ }
35625
+ function canonicalRepoUrl(url2) {
35626
+ const remote = parseGitRemote(url2);
35627
+ if (remote === void 0 || !namesTheHostGitContacts(url2, remote.host)) return void 0;
35628
+ const path = trimSlashes(remote.path);
35629
+ if (path === "" || QUERY_OR_FRAGMENT.test(path)) return void 0;
35630
+ const key = `${remote.host}/${path}`;
35631
+ return SCOPE_KEY.safeParse(key).success ? key : void 0;
35632
+ }
35633
+ function scopeKeyOfProjectKey(projectKey) {
35634
+ return projectKey.startsWith("git:") ? canonicalRepoUrl(projectKey.slice("git:".length)) : void 0;
35635
+ }
34964
35636
  function toIngestHit(hit) {
34965
35637
  return {
34966
35638
  host: hit.host,
@@ -35297,7 +35969,7 @@ async function send(options) {
35297
35969
  }
35298
35970
  }
35299
35971
  };
35300
- return new Promise((resolve3, reject) => {
35972
+ return new Promise((resolve4, reject) => {
35301
35973
  let settled = false;
35302
35974
  const fail = (reason, status) => {
35303
35975
  if (settled) return;
@@ -35323,7 +35995,7 @@ async function send(options) {
35323
35995
  res.on("end", () => {
35324
35996
  if (settled) return;
35325
35997
  settled = true;
35326
- resolve3({
35998
+ resolve4({
35327
35999
  status: res.statusCode ?? 0,
35328
36000
  headers: res.headers,
35329
36001
  body: Buffer.concat(chunks).toString("utf8")
@@ -35687,9 +36359,9 @@ function readForwardDrops(dataDir2) {
35687
36359
  }
35688
36360
 
35689
36361
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35690
- import { randomUUID as randomUUID15 } from "crypto";
36362
+ import { randomUUID as randomUUID16 } from "crypto";
35691
36363
  import { readFile, rename, writeFile } from "fs/promises";
35692
- import { join as join27 } from "path";
36364
+ import { join as join28 } from "path";
35693
36365
 
35694
36366
  // ../../packages/plugin-sdk/src/config.ts
35695
36367
  import { existsSync as existsSync8 } from "fs";
@@ -37642,10 +38314,10 @@ function isCorroborated(candidate, candidates, text, normalization) {
37642
38314
  }
37643
38315
  return false;
37644
38316
  }
37645
- function buildCandidates(matchText, ruleset, extension) {
38317
+ function buildCandidates(matchText, ruleset, extension, eventKind) {
37646
38318
  const candidates = [];
37647
38319
  for (const rule of ruleset) {
37648
- if (!ruleApplies(rule, extension)) continue;
38320
+ if (!ruleApplies(rule, extension, eventKind)) continue;
37649
38321
  const spans = MATCHERS[rule.matcher.type](matchText, rule);
37650
38322
  for (const span of spans) {
37651
38323
  const rawMatch = matchText.slice(span.start, span.end);
@@ -37755,22 +38427,30 @@ function extensionOf(filePath) {
37755
38427
  const dot = base.lastIndexOf(".");
37756
38428
  return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
37757
38429
  }
37758
- function ruleApplies(rule, extension) {
37759
- if (!rule.appliesTo || extension === void 0) return true;
37760
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
38430
+ function ruleApplies(rule, extension, eventKind) {
38431
+ const scope = rule.appliesTo;
38432
+ if (!scope) return true;
38433
+ if (scope.eventKinds && (eventKind === void 0 || !scope.eventKinds.some((k) => k === eventKind))) {
38434
+ return false;
38435
+ }
38436
+ if (!scope.extensions || extension === void 0) return true;
38437
+ return scope.extensions.some((e) => e.toLowerCase() === extension);
37761
38438
  }
37762
38439
  function scan(text, rules, context) {
37763
38440
  const ruleset = rules ?? getLoadedRules();
37764
38441
  const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
37765
38442
  const normalization = normalizeFormatChars(text);
37766
- const originalCandidates = buildCandidates(text, ruleset, extension);
38443
+ const originalCandidates = buildCandidates(text, ruleset, extension, context?.eventKind);
37767
38444
  if (!normalization) return gate(originalCandidates, text, void 0);
37768
38445
  const pooledOriginal = originalCandidates.map(
37769
38446
  (candidate) => withNormalizedSpan(candidate, normalization)
37770
38447
  );
37771
- const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
37772
- (candidate) => mapCandidateToOriginal(candidate, normalization, text)
37773
- );
38448
+ const normalizedCandidates = buildCandidates(
38449
+ normalization.normalized,
38450
+ ruleset,
38451
+ extension,
38452
+ context?.eventKind
38453
+ ).map((candidate) => mapCandidateToOriginal(candidate, normalization, text));
37774
38454
  const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
37775
38455
  return mergeOverlappingSameRule(findings, text);
37776
38456
  }
@@ -37807,6 +38487,47 @@ function redact(text, findings) {
37807
38487
  return result;
37808
38488
  }
37809
38489
 
38490
+ // ../../packages/detections/src/evidence.ts
38491
+ var BUNDLED_CODE_EVIDENCE = /* @__PURE__ */ new Set([
38492
+ "code-flaws/auth-jwt-no-verify",
38493
+ "code-flaws/auth-ssl-verify-false",
38494
+ "code-flaws/cmd-inject-exec",
38495
+ "code-flaws/cmd-inject-node-exec",
38496
+ "code-flaws/cmd-inject-shell",
38497
+ "code-flaws/crypto-insecure-random",
38498
+ "code-flaws/crypto-weak-hash-md5",
38499
+ "code-flaws/crypto-weak-hash-sha1",
38500
+ "code-flaws/deser-java-ois",
38501
+ "code-flaws/deser-pickle",
38502
+ "code-flaws/deser-yaml-unsafe",
38503
+ "code-flaws/dev-debug-enabled",
38504
+ "code-flaws/dev-wildcard-cors",
38505
+ "code-flaws/eval-dynamic-exec",
38506
+ "code-flaws/path-traversal-join",
38507
+ "code-flaws/path-traversal-open",
38508
+ "code-flaws/prototype-pollution-merge",
38509
+ "code-flaws/regex-redos-backtrack",
38510
+ "code-flaws/sql-inject-concat",
38511
+ "code-flaws/sql-inject-concat-dot",
38512
+ "code-flaws/sql-inject-format",
38513
+ "code-flaws/sql-inject-interp",
38514
+ "code-flaws/ssrf-user-url",
38515
+ "code-flaws/xss-dangerously-set",
38516
+ "code-flaws/xss-inner-html",
38517
+ "code-flaws/xss-unescaped-render"
38518
+ ]);
38519
+ var VALUE_CATEGORIES = /* @__PURE__ */ new Set([
38520
+ "secret",
38521
+ "pii",
38522
+ "financial",
38523
+ "phi"
38524
+ ]);
38525
+ function ruleEvidence(rule) {
38526
+ if (rule.category !== void 0 && VALUE_CATEGORIES.has(rule.category)) return "value";
38527
+ if (rule.evidence !== void 0) return rule.evidence;
38528
+ return BUNDLED_CODE_EVIDENCE.has(rule.id) ? "code" : "value";
38529
+ }
38530
+
37810
38531
  // ../../packages/detections/src/mask.ts
37811
38532
  function maskMatch(raw) {
37812
38533
  if (raw.length <= 5) return "***";
@@ -38062,6 +38783,281 @@ function checkRuleTiming(rule, corroborate) {
38062
38783
  return { verdict, worstMs: ms, corroboratedMs: work, probe };
38063
38784
  }
38064
38785
 
38786
+ // ../../packages/plugin-sdk/src/raw-egress.ts
38787
+ var RawEgressError = class extends Error {
38788
+ // The text as far as masking got it, when the throw came from a verifier that
38789
+ // had already produced one. A caller that must not propagate the throw (the
38790
+ // history walk) blunt-redacts THIS rather than the raw input: starting over
38791
+ // from the raw text discards every span the masker did cover, which for a
38792
+ // value clipped by the window edge is the only redaction it was ever going to
38793
+ // get — the blunt pass splits on whole values and cannot remove a partial run.
38794
+ masked;
38795
+ constructor(message, masked) {
38796
+ super(message);
38797
+ this.name = "RawEgressError";
38798
+ if (masked !== void 0) this.masked = masked;
38799
+ }
38800
+ };
38801
+ var MIN_RAW_LEN = 4;
38802
+ var RAW_RUN_LEN = 8;
38803
+ function carriesRawRun(text, rawValues) {
38804
+ let windows = null;
38805
+ for (const raw of new Set(rawValues)) {
38806
+ if (raw.length < MIN_RAW_LEN) continue;
38807
+ if (raw.length < RAW_RUN_LEN) {
38808
+ if (text.includes(raw)) return true;
38809
+ continue;
38810
+ }
38811
+ if (windows === null) {
38812
+ windows = /* @__PURE__ */ new Set();
38813
+ for (let i = 0; i + RAW_RUN_LEN <= text.length; i += 1) {
38814
+ windows.add(text.slice(i, i + RAW_RUN_LEN));
38815
+ }
38816
+ }
38817
+ if (windows.size === 0) continue;
38818
+ let preview = null;
38819
+ for (let i = 0; i + RAW_RUN_LEN <= raw.length; i += 1) {
38820
+ const window = raw.slice(i, i + RAW_RUN_LEN);
38821
+ if (!windows.has(window)) continue;
38822
+ preview ??= safeMaskedMatch(raw);
38823
+ if (!preview.includes(window)) return true;
38824
+ }
38825
+ }
38826
+ return false;
38827
+ }
38828
+ function safeMaskedMatch(rawMatch) {
38829
+ const masked = maskMatch(rawMatch);
38830
+ if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
38831
+ return "***";
38832
+ }
38833
+ return masked;
38834
+ }
38835
+ function assertRawFree(text, rawValues) {
38836
+ if (carriesRawRun(text, rawValues)) {
38837
+ throw new RawEgressError("text contained a raw detected value");
38838
+ }
38839
+ return text;
38840
+ }
38841
+
38842
+ // ../../packages/plugin-sdk/src/finding-context.ts
38843
+ var CONTEXT_RADIUS = 2;
38844
+ var CONTEXT_LINE_MAX = 240;
38845
+ var BACKSTOP_MARGIN = 256;
38846
+ var CONTEXT_MAX_PER_TEXT = 200;
38847
+ var ELLIPSIS = "\u2026";
38848
+ function evidenceLookup(rules) {
38849
+ const byId = new Map(rules.map((rule) => [rule.id, rule]));
38850
+ return (ruleId) => ruleEvidence(byId.get(ruleId) ?? { id: ruleId });
38851
+ }
38852
+ function createFindingLocator(input2) {
38853
+ let prepared;
38854
+ let built = 0;
38855
+ return (hit) => {
38856
+ prepared ??= prepare(input2);
38857
+ const { starts } = prepared;
38858
+ const lineIndex = lineIndexAt(starts, hit.span.start);
38859
+ const lineStart = starts[lineIndex] ?? 0;
38860
+ let context = null;
38861
+ if (input2.backstopRules !== null && built < CONTEXT_MAX_PER_TEXT) {
38862
+ built += 1;
38863
+ try {
38864
+ context = buildContext(input2, prepared, hit, lineIndex);
38865
+ } catch {
38866
+ context = null;
38867
+ }
38868
+ }
38869
+ return { line: lineIndex + 1, col: hit.span.start - lineStart + 1, context };
38870
+ };
38871
+ }
38872
+ function prepare(input2) {
38873
+ const sorted = [...input2.hits].sort((a, b) => a.span.start - b.span.start);
38874
+ const enforced = input2.enforcedHits;
38875
+ const backstopRules = [...input2.backstopRules ?? []];
38876
+ return {
38877
+ starts: lineStartOffsets(input2.text),
38878
+ sorted,
38879
+ longest: sorted.reduce((max, h) => Math.max(max, h.span.end - h.span.start), 0),
38880
+ isValue: (hit) => enforced?.has(hit) === true || input2.evidenceOf(hit.ruleId) !== "code",
38881
+ backstopRules,
38882
+ backstopEvidence: new Map(backstopRules.map((rule) => [rule.id, ruleEvidence(rule)]))
38883
+ };
38884
+ }
38885
+ function buildContext(input2, prepared, hit, lineIndex) {
38886
+ const { text } = input2;
38887
+ const { starts, sorted, longest, isValue } = prepared;
38888
+ const isCode = !isValue(hit);
38889
+ const radius = isCode ? CONTEXT_RADIUS : 0;
38890
+ const hitColumn = hit.span.start - (starts[lineIndex] ?? 0);
38891
+ const segments = [];
38892
+ const firstIndex = Math.max(0, lineIndex - radius);
38893
+ const lastIndex = Math.min(starts.length - 1, lineIndex + radius);
38894
+ for (let index = firstIndex; index <= lastIndex; index += 1) {
38895
+ const lineStart = starts[index] ?? 0;
38896
+ if (index > lineIndex && lineStart >= text.length) break;
38897
+ const next = starts[index + 1];
38898
+ let lineEnd = next === void 0 ? text.length : next - 1;
38899
+ if (lineEnd > lineStart && text.charCodeAt(lineEnd - 1) === 13) lineEnd -= 1;
38900
+ const length = lineEnd - lineStart;
38901
+ const offset = Math.min(
38902
+ Math.max(0, hitColumn - Math.floor(CONTEXT_LINE_MAX / 2)),
38903
+ Math.max(0, length - CONTEXT_LINE_MAX)
38904
+ );
38905
+ const start = lineStart + offset;
38906
+ segments.push({
38907
+ lineIndex: index,
38908
+ start,
38909
+ end: Math.min(lineEnd, start + CONTEXT_LINE_MAX),
38910
+ lineStart,
38911
+ lineEnd
38912
+ });
38913
+ }
38914
+ const regions = [];
38915
+ const rawValues = [];
38916
+ const windowStart = segments[0]?.start ?? hit.span.start;
38917
+ const windowEnd = segments[segments.length - 1]?.end ?? hit.span.end;
38918
+ for (const other of overlapping(sorted, longest, windowStart, windowEnd)) {
38919
+ if (!isValue(other)) continue;
38920
+ regions.push({ start: other.span.start, end: other.span.end, category: other.category });
38921
+ rawValues.push(other.rawMatch);
38922
+ }
38923
+ for (const found of backstop(text, segments, prepared)) {
38924
+ regions.push(found.region);
38925
+ rawValues.push(found.rawMatch);
38926
+ }
38927
+ const merged = mergeRegions(regions);
38928
+ const shown = cutAtValues(segments, lineIndex, valueLinesOf(merged, starts));
38929
+ const lines = [];
38930
+ let match = null;
38931
+ for (const segment of shown) {
38932
+ const rendered = renderSegment(text, segment, merged);
38933
+ lines.push(rendered.text);
38934
+ if (isCode && segment.lineIndex === lineIndex) {
38935
+ const matchEnd = Math.min(hit.span.end, segment.end);
38936
+ const start = rendered.position(hit.span.start, "start");
38937
+ const end = rendered.position(matchEnd, "end");
38938
+ match = end > start ? { line: lineIndex + 1, start, end } : null;
38939
+ }
38940
+ }
38941
+ assertRawFree(lines.join("\n"), rawValues);
38942
+ return {
38943
+ basis: input2.basis,
38944
+ firstLine: (shown[0]?.lineIndex ?? lineIndex) + 1,
38945
+ lines,
38946
+ match
38947
+ };
38948
+ }
38949
+ function valueLinesOf(regions, starts) {
38950
+ const lines = /* @__PURE__ */ new Set();
38951
+ for (const region of regions) {
38952
+ const last = lineIndexAt(starts, Math.max(region.start, region.end - 1));
38953
+ for (let index = lineIndexAt(starts, region.start); index <= last; index += 1) {
38954
+ lines.add(index);
38955
+ }
38956
+ }
38957
+ return lines;
38958
+ }
38959
+ function cutAtValues(segments, lineIndex, valueLines) {
38960
+ if (!segments.some((segment) => valueLines.has(segment.lineIndex))) return [...segments];
38961
+ return segments.filter((segment) => segment.lineIndex === lineIndex);
38962
+ }
38963
+ function overlapping(sorted, longest, start, end) {
38964
+ let low = 0;
38965
+ let high = sorted.length;
38966
+ const floor = start - longest;
38967
+ while (low < high) {
38968
+ const mid = low + high >>> 1;
38969
+ if ((sorted[mid]?.span.start ?? 0) < floor) low = mid + 1;
38970
+ else high = mid;
38971
+ }
38972
+ const out = [];
38973
+ for (let i = low; i < sorted.length; i += 1) {
38974
+ const hit = sorted[i];
38975
+ if (hit === void 0 || hit.span.start >= end) break;
38976
+ if (hit.span.end > start) out.push(hit);
38977
+ }
38978
+ return out;
38979
+ }
38980
+ function backstop(text, segments, prepared) {
38981
+ const { backstopRules: rules, backstopEvidence: evidence } = prepared;
38982
+ if (rules.length === 0) return [];
38983
+ const pieces = [];
38984
+ let joined = "";
38985
+ for (const segment of segments) {
38986
+ const from = Math.max(segment.lineStart, segment.start - BACKSTOP_MARGIN);
38987
+ const to = Math.min(segment.lineEnd, segment.end + BACKSTOP_MARGIN);
38988
+ if (joined.length > 0) joined += "\n";
38989
+ pieces.push({ from, to, at: joined.length });
38990
+ joined += text.slice(from, to);
38991
+ }
38992
+ const out = [];
38993
+ for (const found of scan(joined, rules)) {
38994
+ if ((evidence.get(found.ruleId) ?? "value") === "code") continue;
38995
+ for (const piece of pieces) {
38996
+ const length = piece.to - piece.from;
38997
+ const start = Math.max(found.span.start, piece.at);
38998
+ const end = Math.min(found.span.end, piece.at + length);
38999
+ if (end <= start) continue;
39000
+ out.push({
39001
+ region: {
39002
+ start: piece.from + (start - piece.at),
39003
+ end: piece.from + (end - piece.at),
39004
+ category: found.category
39005
+ },
39006
+ rawMatch: found.rawMatch
39007
+ });
39008
+ }
39009
+ }
39010
+ return out;
39011
+ }
39012
+ function mergeRegions(regions) {
39013
+ const sorted = [...regions].sort((a, b) => a.start - b.start || a.end - b.end);
39014
+ const out = [];
39015
+ for (const region of sorted) {
39016
+ const open3 = out[out.length - 1];
39017
+ if (open3 && region.start < open3.end) open3.end = Math.max(open3.end, region.end);
39018
+ else out.push({ ...region });
39019
+ }
39020
+ return out;
39021
+ }
39022
+ function renderSegment(text, segment, regions) {
39023
+ const pieces = [];
39024
+ let out = segment.start > segment.lineStart ? ELLIPSIS : "";
39025
+ let cursor = segment.start;
39026
+ const emit = (to, replacement) => {
39027
+ const piece = replacement ?? text.slice(cursor, to);
39028
+ pieces.push({
39029
+ from: cursor,
39030
+ to,
39031
+ outFrom: out.length,
39032
+ outTo: out.length + piece.length,
39033
+ redacted: replacement !== null
39034
+ });
39035
+ out += piece;
39036
+ cursor = to;
39037
+ };
39038
+ for (const region of regions) {
39039
+ if (region.end <= segment.start || region.start >= segment.end) continue;
39040
+ const start = Math.max(region.start, segment.start);
39041
+ if (start > cursor) emit(start, null);
39042
+ emit(Math.min(region.end, segment.end), `[REDACTED:${region.category.toUpperCase()}]`);
39043
+ }
39044
+ if (cursor < segment.end) emit(segment.end, null);
39045
+ const body = out.length;
39046
+ if (segment.end < segment.lineEnd) out += ELLIPSIS;
39047
+ const position = (offset, side) => {
39048
+ for (const piece of pieces) {
39049
+ if (offset < piece.from || offset > piece.to) continue;
39050
+ if (piece.redacted) {
39051
+ if (side === "start" && offset === piece.to) continue;
39052
+ return side === "start" ? piece.outFrom : piece.outTo;
39053
+ }
39054
+ return piece.outFrom + (offset - piece.from);
39055
+ }
39056
+ return offset <= segment.start ? pieces[0]?.outFrom ?? 0 : body;
39057
+ };
39058
+ return { text: out, position };
39059
+ }
39060
+
38065
39061
  // ../../rules/code-flaws/auth-jwt-no-verify.json
38066
39062
  var auth_jwt_no_verify_default = {
38067
39063
  specVersion: 1,
@@ -38136,8 +39132,9 @@ var cmd_inject_node_exec_default = {
38136
39132
  severity: "critical",
38137
39133
  matcher: {
38138
39134
  type: "regex",
38139
- pattern: "\\bexec(?:Sync)?\\s*\\(\\s*(?!['\"`])",
38140
- flags: "g"
39135
+ pattern: `(?:\\b(?:(?:node_)?child_process|childProcess|cp)\\s*\\??\\.\\s*|\\brequire\\s*\\(\\s*['"](?:node:)?child_process['"]\\s*\\)\\s*\\??\\.\\s*|(?<![\\w$.]))(exec(?:Sync)?\\s*\\(\\s*)(?!['"\`])`,
39136
+ flags: "g",
39137
+ captureGroup: 1
38141
39138
  },
38142
39139
  requiresNearby: {
38143
39140
  labels: ["input", "request", "param", "argv", "user", "query", "body"],
@@ -38639,6 +39636,120 @@ var xss_unescaped_render_default = {
38639
39636
  }
38640
39637
  };
38641
39638
 
39639
+ // ../../rules/command-risk/credential-file-read.json
39640
+ var credential_file_read_default = {
39641
+ specVersion: 1,
39642
+ id: "command-risk/credential-file-read",
39643
+ name: "Dump of a credential-bearing file",
39644
+ category: "custom",
39645
+ severity: "medium",
39646
+ matcher: {
39647
+ type: "regex",
39648
+ pattern: `\\b(?:cat|bat|less|more|head|tail|sed|awk|nl|xxd|strings|base64)(?<=(?:^|[;&|({\\x60]|\\$\\(|-[A-Za-z]*c[ \\t]+["'])[ \\t]*(?:(?:then|do|else|!)[ \\t]+)?(?:(?:sudo|doas|env|command|exec|nohup|nice|time|xargs)(?:[ \\t]+[^\\s;|&"'\\x60]{1,100}){0,4}?[ \\t]+)?(?:[\\w.~-]*/){0,8}(?:cat|bat|less|more|head|tail|sed|awk|nl|xxd|strings|base64))[ \\t]+(?:[^\\s;|&]{1,200}[ \\t]+){0,8}?["']?(?:[^\\s;|&"']*/)?(?:\\.env(?!\\.(?:example|sample|template|dist))(?:\\.[A-Za-z0-9_-]+)?|[A-Za-z0-9_-]*\\.env|\\.zshenv|\\.zshrc|\\.zprofile|\\.bashrc|\\.bash_profile|\\.netrc|\\.npmrc|\\.pgpass|\\.git-credentials|\\.aws/(?:credentials|config)|(?:[A-Za-z0-9_.-]*[_.-])?auth\\.json|\\.?credentials\\.json|id_(?:rsa|ed25519|ecdsa|dsa))(?=$|[\\s"';|&)])`,
39649
+ flags: "gm"
39650
+ },
39651
+ examples: ["cat ~/.zshenv", "cat /tmp/host-auth.json"],
39652
+ appliesTo: {
39653
+ eventKinds: ["tool_use"]
39654
+ }
39655
+ };
39656
+
39657
+ // ../../rules/command-risk/curl-pipe-shell.json
39658
+ var curl_pipe_shell_default = {
39659
+ specVersion: 1,
39660
+ id: "command-risk/curl-pipe-shell",
39661
+ name: "curl/wget piped to a shell",
39662
+ category: "custom",
39663
+ severity: "high",
39664
+ matcher: {
39665
+ type: "regex",
39666
+ pattern: `\\b(?:curl|wget)(?<=(?:^|[;&|({\\x60]|\\$\\(|-[A-Za-z]*c[ \\t]+["'])[ \\t]*(?:(?:then|do|else|!)[ \\t]+)?(?:(?:sudo|doas|env|command|exec|nohup|nice|time|xargs)(?:[ \\t]+[^\\s;|&"'\\x60]{1,100}){0,4}?[ \\t]+)?(?:[\\w.~-]*/){0,8}(?:curl|wget))\\b(?:[^\\n|;&\\\\]|\\\\[\\s\\S]){0,300}\\|[ \\t]*(?:(?:sudo|doas|env)(?:[ \\t]+[^\\s|;&]{1,200}){0,4}?[ \\t]+)?(?:[^\\s|;&]{0,200}/)?(?:ba|z|da|k)?sh(?![\\w.-])`,
39667
+ flags: "gm"
39668
+ },
39669
+ examples: [
39670
+ "curl -fsSL https://get.example.dev/install.sh | bash",
39671
+ "wget -qO- https://get.example.dev/setup | sudo sh -s -- --yes"
39672
+ ],
39673
+ appliesTo: {
39674
+ eventKinds: ["tool_use"]
39675
+ }
39676
+ };
39677
+
39678
+ // ../../rules/command-risk/git-force-push.json
39679
+ var git_force_push_default = {
39680
+ specVersion: 1,
39681
+ id: "command-risk/git-force-push",
39682
+ name: "git push --force / -f",
39683
+ category: "custom",
39684
+ severity: "high",
39685
+ matcher: {
39686
+ type: "regex",
39687
+ pattern: `\\bgit(?<=(?:^|[;&|({\\x60]|\\$\\(|-[A-Za-z]*c[ \\t]+["'])[ \\t]*(?:(?:then|do|else|!)[ \\t]+)?(?:(?:sudo|doas|env|command|exec|nohup|nice|time|xargs)(?:[ \\t]+[^\\s;|&"'\\x60]{1,100}){0,4}?[ \\t]+)?(?:[\\w.~-]*/){0,8}git)(?:[ \\t]+(?:-[Cc][ \\t]+[^\\s;|&]{1,200}|--[a-z][a-z-]{0,40}(?:=[^\\s;|&]{1,200})?)){0,4}[ \\t]+push(?:[ \\t]+[^\\s;|&]{1,200}){0,8}?[ \\t]+(?:-[A-Za-z]*f[A-Za-z]*|--force(?![\\w-])|\\+[^\\s;|&+]{1,200})(?=[\\s;|&)"'\\x60]|$)`,
39688
+ flags: "gm"
39689
+ },
39690
+ examples: ["git push -q -f origin feature-x", "git push --force origin main"],
39691
+ appliesTo: {
39692
+ eventKinds: ["tool_use"]
39693
+ }
39694
+ };
39695
+
39696
+ // ../../rules/command-risk/git-reset-hard.json
39697
+ var git_reset_hard_default = {
39698
+ specVersion: 1,
39699
+ id: "command-risk/git-reset-hard",
39700
+ name: "git reset --hard at command position",
39701
+ category: "custom",
39702
+ severity: "high",
39703
+ matcher: {
39704
+ type: "regex",
39705
+ pattern: `\\bgit(?<=(?:^|[;&|({\\x60]|\\$\\(|-[A-Za-z]*c[ \\t]+["'])[ \\t]*(?:(?:then|do|else|!)[ \\t]+)?(?:(?:sudo|doas|env|command|exec|nohup|nice|time|xargs)(?:[ \\t]+[^\\s;|&"'\\x60]{1,100}){0,4}?[ \\t]+)?(?:[\\w.~-]*/){0,8}git)(?:[ \\t]+(?:-[Cc][ \\t]+[^\\s;|&]{1,200}|--[a-z][a-z-]{0,40}(?:=[^\\s;|&]{1,200})?)){0,4}[ \\t]+reset(?:[ \\t]+[^\\s;|&]{1,200}){0,8}?[ \\t]+--hard\\b`,
39706
+ flags: "gm"
39707
+ },
39708
+ examples: ["git reset --hard HEAD~1", "cd /tmp/demo-repo && git reset --hard origin/main"],
39709
+ appliesTo: {
39710
+ eventKinds: ["tool_use"]
39711
+ }
39712
+ };
39713
+
39714
+ // ../../rules/command-risk/pkill-broad.json
39715
+ var pkill_broad_default = {
39716
+ specVersion: 1,
39717
+ id: "command-risk/pkill-broad",
39718
+ name: "pkill -f (command-line pattern kill)",
39719
+ category: "custom",
39720
+ severity: "medium",
39721
+ matcher: {
39722
+ type: "regex",
39723
+ pattern: `\\bpkill(?<=(?:^|[;&|({\\x60]|\\$\\(|-[A-Za-z]*c[ \\t]+["'])[ \\t]*(?:(?:then|do|else|!)[ \\t]+)?(?:(?:sudo|doas|env|command|exec|nohup|nice|time|xargs)(?:[ \\t]+[^\\s;|&"'\\x60]{1,100}){0,4}?[ \\t]+)?(?:[\\w.~-]*/){0,8}pkill)(?:[ \\t]+[^\\s;|&]{1,200}){0,8}?[ \\t]+(?:-[A-Za-z0-9]*f[A-Za-z0-9]*|--full)[ \\t]+["'\\w]`,
39724
+ flags: "gm"
39725
+ },
39726
+ examples: ['pkill -f "Brave Browser"', 'pkill -TERM -f "bun src/main.ts"'],
39727
+ appliesTo: {
39728
+ eventKinds: ["tool_use"]
39729
+ }
39730
+ };
39731
+
39732
+ // ../../rules/command-risk/rm-rf-home-or-shared.json
39733
+ var rm_rf_home_or_shared_default = {
39734
+ specVersion: 1,
39735
+ id: "command-risk/rm-rf-home-or-shared",
39736
+ name: "Recursive rm of home, /Users or a system directory",
39737
+ category: "custom",
39738
+ severity: "high",
39739
+ matcher: {
39740
+ type: "regex",
39741
+ pattern: `\\brm(?<=(?:^|[;&|({\\x60]|\\$\\(|-[A-Za-z]*c[ \\t]+["'])[ \\t]*(?:(?:then|do|else|!)[ \\t]+)?(?:(?:sudo|doas|env|command|exec|nohup|nice|time|xargs)(?:[ \\t]+[^\\s;|&"'\\x60]{1,100}){0,4}?[ \\t]+)?(?:[\\w.~-]*/){0,8}rm)(?:[ \\t]+[^\\s;|&]{1,200}){0,8}?[ \\t]+(?:-[A-Za-z]*[rR][A-Za-z]*|--recursive)(?:[ \\t]+[^\\s;|&]{1,200}){0,8}?[ \\t]+["']?(?:~|\\$HOME(?!\\w)|\\$\\{HOME\\}|/(?:Users|home)(?=[/\\s"';|&)]|$)|/(?:etc|var|usr|bin|sbin|lib|opt|System|Library)?/?\\*?(?=[\\s"';|&)]|$)|\\.\\.(?:/\\.\\.)*/?(?=[\\s"';|&)]|$))`,
39742
+ flags: "gm"
39743
+ },
39744
+ examples: [
39745
+ "rm -rf ~/projects/demo-app/$WORKDIR",
39746
+ "rm -rf ~/worktrees/x ~/.claude-demo/projects/-Users-x"
39747
+ ],
39748
+ appliesTo: {
39749
+ eventKinds: ["tool_use"]
39750
+ }
39751
+ };
39752
+
38642
39753
  // ../../rules/core-code-context/db-table-name.json
38643
39754
  var db_table_name_default = {
38644
39755
  specVersion: 1,
@@ -38715,6 +39826,24 @@ var file_path_default = {
38715
39826
  ]
38716
39827
  };
38717
39828
 
39829
+ // ../../rules/core-code-context/gcp-service-account-email.json
39830
+ var gcp_service_account_email_default = {
39831
+ specVersion: 1,
39832
+ id: "core-code-context/gcp-service-account-email",
39833
+ name: "GCP service account email",
39834
+ category: "code_context",
39835
+ severity: "low",
39836
+ matcher: {
39837
+ type: "regex",
39838
+ pattern: "(?<![a-z0-9-])[a-z0-9-]{3,}@[a-z0-9][a-z0-9-]{2,60}\\.iam\\.gserviceaccount\\.com\\b",
39839
+ flags: "g"
39840
+ },
39841
+ examples: [
39842
+ "deploy-bot@sample-project.iam.gserviceaccount.com",
39843
+ "12345678-1234-1234-1234-123456789012@my-project.iam.gserviceaccount.com"
39844
+ ]
39845
+ };
39846
+
38718
39847
  // ../../rules/core-code-context/internal-domain.json
38719
39848
  var internal_domain_default = {
38720
39849
  specVersion: 1,
@@ -38724,7 +39853,7 @@ var internal_domain_default = {
38724
39853
  severity: "low",
38725
39854
  matcher: {
38726
39855
  type: "regex",
38727
- pattern: "(?<![A-Za-z0-9.-])[A-Za-z0-9][A-Za-z0-9.-]{0,251}\\.(?:internal|corp|local|lan|intranet|private|dev|staging|test|qa)(?:\\.(?:com|net|org|io|co|app))?\\b",
39856
+ pattern: "(?<![A-Za-z0-9.-])[A-Za-z0-9][A-Za-z0-9.-]{0,251}\\.(?:internal|corp|local|lan|intranet|private|staging|test|qa)(?:\\.(?:com|net|org|io|co|app))?\\b(?!\\.[A-Za-z0-9-]+(?!\\.?[A-Za-z0-9]))(?!\\.(?:d|tsx?|jsx?|mjs|cjs|json|md|py|sh|ya?ml|toml|txt|log|snap|html|css|rs|go)\\b)",
38728
39857
  flags: "gi"
38729
39858
  },
38730
39859
  examples: ["db.internal.com", "app.corp.local", "api.staging.example.com"]
@@ -38739,7 +39868,7 @@ var internal_ip_default = {
38739
39868
  severity: "low",
38740
39869
  matcher: {
38741
39870
  type: "regex",
38742
- pattern: "(?<![\\d.])(?:10\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|172\\.(?:1[6-9]|2\\d|3[01])\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|192\\.168\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))(?![\\d])",
39871
+ pattern: "(?<!\\d\\.?)(?:10\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|172\\.(?:1[6-9]|2\\d|3[01])\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|192\\.168\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))(?!\\d|\\.\\d+\\.\\d)",
38743
39872
  flags: "g"
38744
39873
  },
38745
39874
  examples: ["10.0.0.1", "192.168.1.1", "172.16.0.1"]
@@ -38813,7 +39942,7 @@ var credit_card_default = {
38813
39942
  severity: "critical",
38814
39943
  matcher: {
38815
39944
  type: "regex",
38816
- pattern: "\\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})\\b",
39945
+ pattern: "(?<![.\\d])\\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})\\b",
38817
39946
  flags: "g"
38818
39947
  },
38819
39948
  postValidators: ["luhn"],
@@ -38936,8 +40065,8 @@ var swift_default = {
38936
40065
  severity: "high",
38937
40066
  matcher: {
38938
40067
  type: "regex",
38939
- pattern: "\\b(?:swift|bic)\\b[\\s#:=-]{0,8}([A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?)\\b",
38940
- flags: "gi",
40068
+ pattern: "\\b(?:[Ss][Ww][Ii][Ff][Tt]|[Bb][Ii][Cc])\\b[\\s#:=-]{0,8}([A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?)\\b",
40069
+ flags: "g",
38941
40070
  captureGroup: 1
38942
40071
  },
38943
40072
  examples: ["SWIFT: BOFAUS3N", "BIC: CHASGB2LXXX"]
@@ -39105,7 +40234,17 @@ var dob_default = {
39105
40234
  },
39106
40235
  requiresNearby: {
39107
40236
  categories: ["pii"],
39108
- labels: ["dob", "date of birth", "birth", "d.o.b"],
40237
+ labels: [
40238
+ "dob",
40239
+ "date of birth",
40240
+ "birth",
40241
+ "d.o.b",
40242
+ "nascimento",
40243
+ "naissance",
40244
+ "nacimiento",
40245
+ "geburtsdatum",
40246
+ "nascita"
40247
+ ],
39109
40248
  windowChars: 160
39110
40249
  },
39111
40250
  examples: ["DOB: 1985-03-22", "Date of birth: 03/22/1985"]
@@ -39174,7 +40313,7 @@ var ip_address_default = {
39174
40313
  severity: "low",
39175
40314
  matcher: {
39176
40315
  type: "regex",
39177
- pattern: "\\b(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\b",
40316
+ pattern: "(?<!\\d\\.)\\b(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\b(?!\\.\\d+\\.\\d)",
39178
40317
  flags: "g"
39179
40318
  },
39180
40319
  examples: ["192.168.1.1", "10.0.0.1"]
@@ -39275,7 +40414,7 @@ var phone_intl_default = {
39275
40414
  severity: "high",
39276
40415
  matcher: {
39277
40416
  type: "regex",
39278
- pattern: "\\+\\d{1,3}(?:[-.\\s]\\d{1,14}){1,5}\\b",
40417
+ pattern: "\\+(?=(?:\\D?\\d){8})\\d{1,3}(?:[-.\\s]\\d{1,14}){1,5}\\b",
39279
40418
  flags: "g"
39280
40419
  },
39281
40420
  examples: ["+44 20 7946 0958", "+86 138 0013 8000"]
@@ -39324,7 +40463,7 @@ var vin_default = {
39324
40463
  severity: "medium",
39325
40464
  matcher: {
39326
40465
  type: "regex",
39327
- pattern: "\\b[A-HJ-NPR-Z0-9]{17}\\b",
40466
+ pattern: "\\b(?=[A-HJ-NPR-Z0-9]{0,16}[A-HJ-NPR-Z])(?=[A-HJ-NPR-Z0-9]{0,16}\\d)[A-HJ-NPR-Z0-9]{17}\\b",
39328
40467
  flags: "g"
39329
40468
  },
39330
40469
  examples: ["1HGCM82633A004352"]
@@ -39483,7 +40622,7 @@ var generic_high_entropy_secret_default = {
39483
40622
  severity: "high",
39484
40623
  matcher: {
39485
40624
  type: "regex",
39486
- pattern: `(?<![A-Za-z0-9_-])[A-Za-z0-9_]{0,34}(?:(?:secret|token|passw(?:or)?d|credentials?|(?<!api[_-]?)key)(?:["']?\\s*:|\\s+=)|(?:passwd|credential|(?<!api[_-]?)(?<!secret_)(?<!private_)(?<!encryption_)(?<!signing_)key)=)\\s*["']?((?!eyJ)[A-Za-z0-9+/_\\-]{20,200})`,
40625
+ pattern: `(?<![A-Za-z0-9_-])[A-Za-z0-9_]{0,34}(?:(?:secret|token|(?<!no)passw(?:or)?d|credentials?|(?<!api[_-]?)key)(?:["']?\\s*:|\\s+=)|(?:(?<!no)passwd|credential|(?<!api[_-]?)(?<!secret_)(?<!private_)(?<!encryption_)(?<!signing_)key)=)\\s*["']?((?!eyJ)[A-Za-z0-9+/_\\-]{20,200})`,
39487
40626
  flags: "gi",
39488
40627
  captureGroup: 1
39489
40628
  },
@@ -39537,7 +40676,7 @@ var password_field_default = {
39537
40676
  severity: "high",
39538
40677
  matcher: {
39539
40678
  type: "regex",
39540
- pattern: `["']?\\b(?:password|passwd|pwd|pass|secret|token|api[_-]?key|apikey)\\b["']?\\s*:\\s*["']([^"'\\n]{4,})["']`,
40679
+ pattern: `["']?\\b(?:password|passwd|pwd|pass|secret|token|api[_-]?key|apikey)\\b["']?\\s*:\\s*["'](?!(?:fail|pass|true|false|null|none|string|required)["'])([^"'\\n]{4,})["']`,
39541
40680
  flags: "gi",
39542
40681
  captureGroup: 1
39543
40682
  },
@@ -39570,7 +40709,7 @@ var ssh_private_key_default = {
39570
40709
  severity: "critical",
39571
40710
  matcher: {
39572
40711
  type: "regex",
39573
- pattern: "-----BEGIN (?:RSA |DSA |EC |OPENSSH |SSH2 )?PRIVATE KEY-----",
40712
+ pattern: "-----BEGIN ((?:RSA |DSA |EC |OPENSSH |SSH2 |ENCRYPTED )?)PRIVATE KEY-----(?:(?:[A-Za-z0-9+/=\\s\\\\:,]|-(?!-)){0,8000}?-----END \\1PRIVATE KEY-----)?",
39574
40713
  flags: "g"
39575
40714
  },
39576
40715
  examples: [
@@ -39651,7 +40790,7 @@ var cloudflare_api_key_default = {
39651
40790
  severity: "critical",
39652
40791
  matcher: {
39653
40792
  type: "regex",
39654
- pattern: `cloudflare.{0,40}?["'\\s:=]([A-Za-z0-9_-]{40})`,
40793
+ pattern: `cloudflare.{0,40}?(?<![?&][A-Za-z0-9_]{1,20})(?<!sha(?:1|256|384|512))["'\\s:=]([A-Za-z0-9_-]{40})`,
39655
40794
  flags: "gi",
39656
40795
  captureGroup: 1
39657
40796
  },
@@ -39707,21 +40846,25 @@ var discord_token_default = {
39707
40846
  examples: ["AbCdEfGhIjKlMnOpQrStUvWx.YzAbCd.ABCdEfGhIjKlMnOpQrStUvWxYzAbCdEf"]
39708
40847
  };
39709
40848
 
39710
- // ../../rules/secrets/gcp-service-account.json
39711
- var gcp_service_account_default = {
40849
+ // ../../rules/secrets/gcp-service-account-key.json
40850
+ var gcp_service_account_key_default = {
39712
40851
  specVersion: 1,
39713
- id: "secrets/gcp-service-account",
39714
- name: "GCP service account key",
40852
+ id: "secrets/gcp-service-account-key",
40853
+ name: "GCP service account key file",
39715
40854
  category: "secret",
39716
40855
  severity: "critical",
39717
40856
  matcher: {
39718
40857
  type: "regex",
39719
- pattern: "(?<![a-z0-9-])[a-z0-9-]{3,}@[a-z0-9][a-z0-9-]{2,60}\\.iam\\.gserviceaccount\\.com\\b",
39720
- flags: "g"
40858
+ pattern: '"private_key_id"\\s*:\\s*"([a-f0-9]{40})"',
40859
+ flags: "g",
40860
+ captureGroup: 1
40861
+ },
40862
+ requiresNearby: {
40863
+ labels: ["service_account", "client_email"],
40864
+ windowChars: 400
39721
40865
  },
39722
40866
  examples: [
39723
- "deploy-bot@sample-project.iam.gserviceaccount.com",
39724
- "12345678-1234-1234-1234-123456789012@my-project.iam.gserviceaccount.com"
40867
+ '{"type": "service_account", "project_id": "sample-project", "private_key_id": "0a1b2c3d0a1b2c3d0a1b2c3d0a1b2c3d0a1b2c3d"}'
39725
40868
  ]
39726
40869
  };
39727
40870
 
@@ -39870,6 +41013,24 @@ var stripe_live_key_default = {
39870
41013
  examples: ["sk_live_aBcDeFgHiJkLmNoPqRsTuVwXyZ"]
39871
41014
  };
39872
41015
 
41016
+ // ../../rules/secrets/tailscale-key.json
41017
+ var tailscale_key_default = {
41018
+ specVersion: 1,
41019
+ id: "secrets/tailscale-key",
41020
+ name: "Tailscale auth/API/client key",
41021
+ category: "secret",
41022
+ severity: "critical",
41023
+ matcher: {
41024
+ type: "regex",
41025
+ pattern: "\\btskey-(?:auth|api|client)-(?![Xx]+-)[A-Za-z0-9]{8,32}-[A-Za-z0-9]{16,64}\\b",
41026
+ flags: "g"
41027
+ },
41028
+ examples: [
41029
+ "sudo tailscale up --auth-key=tskey-auth-kAb3Xk9QzCNTRL-Ab3Xk9QzAb3Xk9QzAb3Xk9QzAb3Xk9Qz",
41030
+ "TS_API_KEY=tskey-api-kEXAMPLE1CNTRL-EXAMPLEEXAMPLEEXAMPLEEXAMPLE12"
41031
+ ]
41032
+ };
41033
+
39873
41034
  // ../../rules/secrets/terraform-cloud-token.json
39874
41035
  var terraform_cloud_token_default = {
39875
41036
  specVersion: 1,
@@ -39912,7 +41073,7 @@ var vault_token_default = {
39912
41073
  severity: "critical",
39913
41074
  matcher: {
39914
41075
  type: "regex",
39915
- pattern: "\\b(?:hvs\\.[A-Za-z0-9\\-_]{20,50}|s\\.[A-Za-z0-9\\-_]{20,50})\\b",
41076
+ pattern: "\\b(?:hvs\\.[A-Za-z0-9\\-_]{20,200}|s\\.(?=[A-Za-z0-9_-]{0,49}\\d)(?=[A-Za-z0-9_-]{0,49}[A-Z])[A-Za-z0-9\\-_]{20,50})\\b",
39916
41077
  flags: "g"
39917
41078
  },
39918
41079
  postValidators: ["entropy"],
@@ -39957,10 +41118,24 @@ var BUNDLED_PACKS = [
39957
41118
  regex_redos_backtrack_default
39958
41119
  ]
39959
41120
  },
41121
+ {
41122
+ packId: "command-risk",
41123
+ name: "Risky agent commands",
41124
+ version: "0.1.0",
41125
+ defaultPolicy: "warn",
41126
+ rawRules: [
41127
+ pkill_broad_default,
41128
+ rm_rf_home_or_shared_default,
41129
+ git_force_push_default,
41130
+ git_reset_hard_default,
41131
+ curl_pipe_shell_default,
41132
+ credential_file_read_default
41133
+ ]
41134
+ },
39960
41135
  {
39961
41136
  packId: "core-code-context",
39962
41137
  name: "Code Context",
39963
- version: "0.1.0",
41138
+ version: "0.2.1",
39964
41139
  rawRules: [
39965
41140
  internal_ip_default,
39966
41141
  localhost_ref_default,
@@ -39969,13 +41144,14 @@ var BUNDLED_PACKS = [
39969
41144
  stack_trace_default,
39970
41145
  internal_url_default,
39971
41146
  feature_flag_default,
39972
- db_table_name_default
41147
+ db_table_name_default,
41148
+ gcp_service_account_email_default
39973
41149
  ]
39974
41150
  },
39975
41151
  {
39976
41152
  packId: "core-financial",
39977
41153
  name: "Financial Information",
39978
- version: "0.1.0",
41154
+ version: "0.1.1",
39979
41155
  rawRules: [
39980
41156
  credit_card_default,
39981
41157
  iban_default,
@@ -40005,7 +41181,7 @@ var BUNDLED_PACKS = [
40005
41181
  {
40006
41182
  packId: "core-pii",
40007
41183
  name: "Core PII",
40008
- version: "0.2.0",
41184
+ version: "0.2.2",
40009
41185
  rawRules: [
40010
41186
  email_default,
40011
41187
  ssn_default,
@@ -40026,11 +41202,11 @@ var BUNDLED_PACKS = [
40026
41202
  {
40027
41203
  packId: "secrets",
40028
41204
  name: "Secrets & Credentials",
40029
- version: "0.1.0",
41205
+ version: "0.2.0",
41206
+ defaultPolicy: "warn",
40030
41207
  rawRules: [
40031
41208
  aws_access_key_default,
40032
41209
  aws_secret_key_default,
40033
- gcp_service_account_default,
40034
41210
  azure_connection_string_default,
40035
41211
  openai_api_key_default,
40036
41212
  anthropic_api_key_default,
@@ -40048,13 +41224,15 @@ var BUNDLED_PACKS = [
40048
41224
  pulumi_access_token_default,
40049
41225
  terraform_cloud_token_default,
40050
41226
  vault_token_default,
40051
- github_pat_default
41227
+ github_pat_default,
41228
+ gcp_service_account_key_default,
41229
+ tailscale_key_default
40052
41230
  ]
40053
41231
  },
40054
41232
  {
40055
41233
  packId: "secrets-infra",
40056
41234
  name: "Infrastructure Secrets",
40057
- version: "0.1.0",
41235
+ version: "0.1.1",
40058
41236
  rawRules: [
40059
41237
  ssh_private_key_default,
40060
41238
  db_connection_string_default,
@@ -40089,32 +41267,74 @@ function bundledDetections() {
40089
41267
  packId: pack.packId,
40090
41268
  version: pack.version,
40091
41269
  name: pack.name,
40092
- rules: pack.rawRules.map((raw) => Rule.parse(raw))
41270
+ rules: pack.rawRules.map((raw) => Rule.parse(raw)),
41271
+ defaultPolicyId: pack.defaultPolicy
40093
41272
  }));
40094
41273
  return cachedDetections;
40095
41274
  }
40096
41275
 
41276
+ // ../../packages/plugin-sdk/src/mask.ts
41277
+ var packsReady = false;
41278
+ var packsFailed = false;
41279
+ function ensureBundledPacks() {
41280
+ if (packsReady) return true;
41281
+ if (packsFailed) return false;
41282
+ try {
41283
+ registerBundledPacks();
41284
+ packsReady = true;
41285
+ return true;
41286
+ } catch {
41287
+ packsFailed = true;
41288
+ return false;
41289
+ }
41290
+ }
41291
+ function bundledMaskingRules() {
41292
+ return ensureBundledPacks() ? getLoadedRules() : null;
41293
+ }
41294
+
40097
41295
  // ../../packages/plugin-sdk/src/repo.ts
40098
41296
  import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
40099
41297
  import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
40100
41298
  function resolveRepoIdentity(cwd) {
40101
41299
  try {
40102
- const root = findGitRoot(cwd);
40103
- if (!root) return void 0;
40104
- const ctx = resolveGitContext(root);
40105
- const headRoot = ctx?.headRoot ?? root;
40106
- const url2 = ctx ? remoteUrl(ctx) : void 0;
41300
+ const location = locateRepo(cwd);
41301
+ if (!location) return void 0;
40107
41302
  return {
40108
41303
  // The path fallback is normalized to posix separators (a no-op outside
40109
41304
  // win32) so the persistence layer's `/`-separated checkout-path patterns
40110
41305
  // (the ghost sweep + the read-side worktree filter) match it as written.
40111
- url: url2 ?? headRoot.split(sep2).join("/"),
40112
- name: (url2 ? slugFromUrl(url2) : void 0) ?? basename2(headRoot)
41306
+ url: location.remote ?? location.headRoot.split(sep2).join("/"),
41307
+ name: slugOf(location)
40113
41308
  };
40114
41309
  } catch {
40115
41310
  return void 0;
40116
41311
  }
40117
41312
  }
41313
+ var ATTRIBUTION_MEMO_LIMIT = 64;
41314
+ var attributionMemo = /* @__PURE__ */ new Map();
41315
+ var NO_ATTRIBUTION = Object.freeze({});
41316
+ function resolveRepoAttribution(cwd) {
41317
+ try {
41318
+ const remembered = attributionMemo.get(cwd);
41319
+ if (remembered !== void 0) return remembered;
41320
+ const attribution = attributeRepo(cwd);
41321
+ if (attributionMemo.size >= ATTRIBUTION_MEMO_LIMIT) attributionMemo.clear();
41322
+ attributionMemo.set(cwd, attribution);
41323
+ return attribution;
41324
+ } catch {
41325
+ return NO_ATTRIBUTION;
41326
+ }
41327
+ }
41328
+ function attributeRepo(cwd) {
41329
+ const location = locateRepo(cwd);
41330
+ if (!location) return NO_ATTRIBUTION;
41331
+ const remote = isAbsolute(cwd) ? location.remote : void 0;
41332
+ const scopeKey = remote === void 0 ? void 0 : canonicalRepoUrl(remote);
41333
+ return Object.freeze({
41334
+ repo: slugOf(location),
41335
+ ...scopeKey === void 0 ? {} : { scopeKey }
41336
+ });
41337
+ }
40118
41338
  function resolveWorktreeRoot(cwd) {
40119
41339
  try {
40120
41340
  return findGitRoot(cwd);
@@ -40165,6 +41385,15 @@ function remoteUrl(ctx) {
40165
41385
  const remotes = parseRemoteUrls(config2);
40166
41386
  return remotes.origin ?? Object.values(remotes)[0];
40167
41387
  }
41388
+ function locateRepo(cwd) {
41389
+ const root = findGitRoot(cwd);
41390
+ if (!root) return void 0;
41391
+ const ctx = resolveGitContext(root);
41392
+ return { headRoot: ctx?.headRoot ?? root, remote: ctx ? remoteUrl(ctx) : void 0 };
41393
+ }
41394
+ function slugOf(location) {
41395
+ return (location.remote ? slugFromUrl(location.remote) : void 0) ?? basename2(location.headRoot);
41396
+ }
40168
41397
  function parseRemoteUrls(config2) {
40169
41398
  const remotes = {};
40170
41399
  let current;
@@ -40231,18 +41460,27 @@ var ATTRIBUTION_MIN_SHARE = 0.5;
40231
41460
  var resolvedWorkerUrl;
40232
41461
  function resolveWorkerUrl() {
40233
41462
  if (resolvedWorkerUrl !== void 0) return resolvedWorkerUrl ?? void 0;
40234
- for (const name of ["scan-worker.js", "scan-worker.ts"]) {
40235
- const candidate = new URL(name, import.meta.url);
40236
- try {
41463
+ resolvedWorkerUrl = null;
41464
+ try {
41465
+ const built = new URL(
41466
+ /* webpackIgnore: true */
41467
+ "./scan-worker.js",
41468
+ import.meta.url
41469
+ );
41470
+ for (const candidate of [built, sourceTwin(built)]) {
40237
41471
  if (existsSync10(fileURLToPath(candidate))) {
40238
41472
  resolvedWorkerUrl = candidate;
40239
- return candidate;
41473
+ break;
40240
41474
  }
40241
- } catch {
40242
41475
  }
41476
+ } catch {
40243
41477
  }
40244
- resolvedWorkerUrl = null;
40245
- return void 0;
41478
+ return resolvedWorkerUrl ?? void 0;
41479
+ }
41480
+ function sourceTwin(url2) {
41481
+ const twin = new URL(url2);
41482
+ twin.pathname = twin.pathname.replace(/\.js$/, ".ts");
41483
+ return twin;
40246
41484
  }
40247
41485
  function messageOf(error62) {
40248
41486
  return error62 instanceof Error ? error62.message : String(error62);
@@ -40419,8 +41657,8 @@ function createIsolatedScanner(data, opts = {}) {
40419
41657
  }
40420
41658
  function enqueue(spec) {
40421
41659
  const next = chain.then(
40422
- () => new Promise((resolve3) => {
40423
- spec(resolve3);
41660
+ () => new Promise((resolve4) => {
41661
+ spec(resolve4);
40424
41662
  })
40425
41663
  );
40426
41664
  chain = next.then(
@@ -40431,7 +41669,7 @@ function createIsolatedScanner(data, opts = {}) {
40431
41669
  }
40432
41670
  return {
40433
41671
  scan(text, context, scanOpts) {
40434
- return enqueue((resolve3) => {
41672
+ return enqueue((resolve4) => {
40435
41673
  runOne(
40436
41674
  {
40437
41675
  budgetMs,
@@ -40440,27 +41678,28 @@ function createIsolatedScanner(data, opts = {}) {
40440
41678
  id,
40441
41679
  text,
40442
41680
  filePath: context?.filePath,
41681
+ eventKind: context?.eventKind,
40443
41682
  attribute: scanOpts?.attribute === true
40444
41683
  }),
40445
41684
  reply: (message) => {
40446
41685
  if (message.kind !== "result") return false;
40447
- resolve3({ status: "ok", findings: message.findings });
41686
+ resolve4({ status: "ok", findings: message.findings });
40448
41687
  return true;
40449
41688
  }
40450
41689
  },
40451
- resolve3
41690
+ resolve4
40452
41691
  );
40453
41692
  });
40454
41693
  },
40455
41694
  probe(rule) {
40456
- return enqueue((resolve3) => {
41695
+ return enqueue((resolve4) => {
40457
41696
  runOne(
40458
41697
  {
40459
41698
  budgetMs: probeBudgetMs,
40460
41699
  build: (id) => ({ kind: "probe", id, rule }),
40461
41700
  reply: (message) => {
40462
41701
  if (message.kind !== "probed") return false;
40463
- resolve3({
41702
+ resolve4({
40464
41703
  status: "ok",
40465
41704
  verdict: message.verdict,
40466
41705
  worstMs: message.worstMs,
@@ -40469,7 +41708,7 @@ function createIsolatedScanner(data, opts = {}) {
40469
41708
  return true;
40470
41709
  }
40471
41710
  },
40472
- resolve3
41711
+ resolve4
40473
41712
  );
40474
41713
  });
40475
41714
  },
@@ -40821,6 +42060,7 @@ function resolveNonGitProject(startDir, recognizeMarker) {
40821
42060
  }
40822
42061
 
40823
42062
  // ../../packages/plugin-sdk/src/policy-resolver.ts
42063
+ import { randomUUID as randomUUID14 } from "crypto";
40824
42064
  function createPolicyResolver(bundle) {
40825
42065
  const byRule = /* @__PURE__ */ new Map();
40826
42066
  const byCategory = /* @__PURE__ */ new Map();
@@ -40854,6 +42094,14 @@ function createPolicyResolver(bundle) {
40854
42094
  }
40855
42095
  };
40856
42096
  }
42097
+ function assignedRulePolicies(installed) {
42098
+ const out = [];
42099
+ for (const [ruleId, action] of installed.ruleActions) {
42100
+ if (installed.assignedRules && !installed.assignedRules.has(ruleId)) continue;
42101
+ out.push({ id: randomUUID14(), scope: "global", target: { ruleId }, action, enabled: true });
42102
+ }
42103
+ return out;
42104
+ }
40857
42105
 
40858
42106
  // ../../packages/plugin-sdk/src/project-files.ts
40859
42107
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
@@ -40886,7 +42134,7 @@ var codexProviderEnvShape = {
40886
42134
  var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
40887
42135
 
40888
42136
  // ../../packages/plugin-sdk/src/runtime.ts
40889
- import { randomUUID as randomUUID14 } from "crypto";
42137
+ import { randomUUID as randomUUID15 } from "crypto";
40890
42138
  var ENFORCEMENT_CEILING_ENABLED = false;
40891
42139
  function applyEnforcementCeiling(action, policyMode, enabled) {
40892
42140
  if (!enabled || policyMode !== "warn") return action;
@@ -40935,6 +42183,7 @@ function createPluginRuntime(gateway, settings, opts) {
40935
42183
  let redactFallback = settings.redactFallback;
40936
42184
  const dataDir2 = opts?.dataDir;
40937
42185
  let rules = [];
42186
+ let evidenceOf = evidenceLookup(rules);
40938
42187
  let scanner;
40939
42188
  let bundleExceptions = [];
40940
42189
  let initialized = false;
@@ -40974,6 +42223,7 @@ function createPluginRuntime(gateway, settings, opts) {
40974
42223
  else verified.push(rule);
40975
42224
  }
40976
42225
  rules = [...verified, ...unverified];
42226
+ evidenceOf = evidenceLookup(rules);
40977
42227
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
40978
42228
  bundleExceptions = bundle.exceptions ?? [];
40979
42229
  redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
@@ -41118,7 +42368,7 @@ function createPluginRuntime(gateway, settings, opts) {
41118
42368
  const pair = `${finding.ruleId}:${fp}`;
41119
42369
  if (seen.has(pair)) continue;
41120
42370
  seen.add(pair);
41121
- const reference = randomUUID14().replaceAll("-", "").slice(0, 6);
42371
+ const reference = randomUUID15().replaceAll("-", "").slice(0, 6);
41122
42372
  const maskedValue = maskMatch(finding.rawMatch);
41123
42373
  try {
41124
42374
  await gateway.recordBlockedDetection({
@@ -41174,7 +42424,7 @@ function createPluginRuntime(gateway, settings, opts) {
41174
42424
  const filePath = input2.metadata?.filePath;
41175
42425
  const { decision, excepted, exceptionIds } = await evaluate(
41176
42426
  input2.text,
41177
- filePath ? { filePath } : void 0,
42427
+ { filePath, eventKind: input2.kind },
41178
42428
  {
41179
42429
  sourceTool: input2.sourceTool,
41180
42430
  metadata: input2.metadata,
@@ -41208,6 +42458,14 @@ function createPluginRuntime(gateway, settings, opts) {
41208
42458
  const isAtRest = input2.kind === "code_change" && filePath !== void 0;
41209
42459
  const findingKeyFingerprintKey = isAtRest ? keyForLedger() : null;
41210
42460
  const findingKeyFpCache = /* @__PURE__ */ new Map();
42461
+ const locate = createFindingLocator({
42462
+ text: input2.text,
42463
+ basis: input2.metadata?.wholeFile === true ? "file" : input2.lineBasis ?? "excerpt",
42464
+ hits: decision.findings,
42465
+ evidenceOf,
42466
+ backstopRules: bundledMaskingRules(),
42467
+ enforcedHits: new Set(maskedFindings)
42468
+ });
41211
42469
  const findings = decision.findings.map((match) => {
41212
42470
  const maskedMatch = maskMatch(match.rawMatch);
41213
42471
  const findingKey = isAtRest && filePath ? computeFindingKey({
@@ -41220,7 +42478,7 @@ function createPluginRuntime(gateway, settings, opts) {
41220
42478
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
41221
42479
  }) : void 0;
41222
42480
  return {
41223
- id: randomUUID14(),
42481
+ id: randomUUID15(),
41224
42482
  eventId: event.id,
41225
42483
  ruleId: match.ruleId,
41226
42484
  category: match.category,
@@ -41229,10 +42487,16 @@ function createPluginRuntime(gateway, settings, opts) {
41229
42487
  maskedMatch,
41230
42488
  actionTaken: actionForFinding(match, excepted, opts2.rewritable),
41231
42489
  confidence: match.confidence,
41232
- ...findingKey ? { findingKey } : {}
42490
+ ...findingKey ? { findingKey } : {},
42491
+ location: locate(match)
41233
42492
  };
41234
42493
  });
41235
- await gateway.recordCapture({ event, findings, dedupe: opts2.dedupe });
42494
+ await gateway.recordCapture({
42495
+ event,
42496
+ findings,
42497
+ dedupe: opts2.dedupe,
42498
+ ...input2.scopeKey !== void 0 ? { scopeKey: input2.scopeKey } : {}
42499
+ });
41236
42500
  if (isAtRest) {
41237
42501
  decision.findingKeys = findings.map((f) => f.findingKey).filter((k) => k !== void 0 && k !== null);
41238
42502
  }
@@ -41246,7 +42510,7 @@ function createPluginRuntime(gateway, settings, opts) {
41246
42510
  const sorted = [...rules].sort((a, b) => a.id.localeCompare(b.id));
41247
42511
  return contentHashOf(JSON.stringify(sorted));
41248
42512
  } catch {
41249
- return `unresolved-${randomUUID14()}`;
42513
+ return `unresolved-${randomUUID15()}`;
41250
42514
  }
41251
42515
  }
41252
42516
  function scanIsolationDegraded() {
@@ -41262,12 +42526,16 @@ function createPluginRuntime(gateway, settings, opts) {
41262
42526
  return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
41263
42527
  }
41264
42528
 
42529
+ // ../../packages/plugin-sdk/src/scope-key.ts
42530
+ import { existsSync as existsSync12 } from "fs";
42531
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
42532
+
41265
42533
  // ../../packages/plugin-sdk/src/suppressions.ts
41266
42534
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
41267
42535
 
41268
42536
  // ../../packages/plugin-sdk/src/throttle.ts
41269
42537
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
41270
- import { join as join26 } from "path";
42538
+ import { join as join27 } from "path";
41271
42539
 
41272
42540
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
41273
42541
  function isInvalidRequest(err) {
@@ -41288,7 +42556,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
41288
42556
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
41289
42557
  function createForwardPolicy(deps) {
41290
42558
  const now = deps.now ?? (() => Date.now());
41291
- const file2 = join27(deps.dir, STATE_FILENAME);
42559
+ const file2 = join28(deps.dir, STATE_FILENAME);
41292
42560
  let state = null;
41293
42561
  let loading = null;
41294
42562
  async function readState() {
@@ -41313,7 +42581,7 @@ function createForwardPolicy(deps) {
41313
42581
  state = next;
41314
42582
  try {
41315
42583
  await ensureDataDir(deps.dir);
41316
- const tmp = `${file2}.${randomUUID15()}.tmp`;
42584
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
41317
42585
  await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
41318
42586
  await rename(tmp, file2);
41319
42587
  } catch {
@@ -41380,6 +42648,33 @@ function createForwardPolicy(deps) {
41380
42648
  };
41381
42649
  }
41382
42650
 
42651
+ // ../../packages/plugin-runtime/src/session-root-key.ts
42652
+ function sessionToolIsKeyed(tool) {
42653
+ return !WebSourceTool.safeParse(tool).success;
42654
+ }
42655
+
42656
+ // ../../packages/plugin-runtime/src/attached/scope-strip.ts
42657
+ function withoutScopeKey(event) {
42658
+ const attributes = event.attributes;
42659
+ if (attributes == null || !Object.hasOwn(attributes, "scope_key")) return event;
42660
+ const rest = { ...attributes };
42661
+ delete rest.scope_key;
42662
+ if (Object.keys(rest).length > 0) return { ...event, attributes: rest };
42663
+ const bare = { ...event };
42664
+ delete bare.attributes;
42665
+ return bare;
42666
+ }
42667
+
42668
+ // ../../packages/plugin-runtime/src/attached/scoped-repo.ts
42669
+ function withScopedRepo(event, scopeKey) {
42670
+ const repo = scopeKey.split("/").filter((segment) => segment !== "").pop();
42671
+ if (repo !== void 0) return { ...event, metadata: { ...event.metadata, repo } };
42672
+ if (event.metadata?.repo === void 0) return event;
42673
+ const metadata = { ...event.metadata };
42674
+ delete metadata.repo;
42675
+ return { ...event, metadata };
42676
+ }
42677
+
41383
42678
  // ../../packages/plugin-runtime/src/attached/gateway.ts
41384
42679
  var bundledRulesFlatCache;
41385
42680
  function bundledRulesFlat() {
@@ -41399,14 +42694,176 @@ var AttachedDataGateway = class {
41399
42694
  * what it can from the descriptors it already has.
41400
42695
  */
41401
42696
  remoteInventory = null;
42697
+ /**
42698
+ * The verdict this instance reached for each session ROOT it recorded, keyed
42699
+ * by root id, from the key the local store holds for that root (see
42700
+ * `rootVerdict`). It is what a child row is held to (see `auditVerdict`).
42701
+ *
42702
+ * Per instance on purpose. An instance is resolved per hook process, per
42703
+ * native-host request, and per reconcile or backfill pass, and the
42704
+ * reconcilers record each session's root before its leaves. Never written in
42705
+ * machine mode, where nothing reads it.
42706
+ */
42707
+ rootVerdicts = /* @__PURE__ */ new Map();
42708
+ // ---------------------------------------------------------------------
42709
+ // The scope verdict: whether a row written locally may also be forwarded.
42710
+ // ---------------------------------------------------------------------
42711
+ /**
42712
+ * The one question every forward asks, answered TOTALLY: `'forward'` or
42713
+ * `'local'`, never a throw.
42714
+ *
42715
+ * The key is read INSIDE the guard, through a thunk, because reading it is
42716
+ * part of what can fail: a damaged bag, or a canonicalizer meeting an input
42717
+ * it never expected. A throw out of here would not be neutral. It would
42718
+ * reject `recordCapture` into the runtime's swallow, make the scanner read a
42719
+ * failed write and withhold its ledger commit, or drop a whole reconcile
42720
+ * pass. So a throw is answered `'local'`: the direction that degrades to
42721
+ * standalone behaviour, never to over-forwarding.
42722
+ *
42723
+ * Machine mode answers before any key is read, so a machine attachment pays
42724
+ * nothing for scoping and forwards exactly what it always has.
42725
+ */
42726
+ verdictFor(keyOf) {
42727
+ try {
42728
+ if (this.deps.attachment.mode === "machine") return "forward";
42729
+ return scopeVerdict(this.deps.attachment, keyOf());
42730
+ } catch {
42731
+ return "local";
42732
+ }
42733
+ }
42734
+ /**
42735
+ * The verdict for an audit row, with the session-root rule on top.
42736
+ *
42737
+ * A session ROOT has two halves. What the rows that hang off it are held to is
42738
+ * the key its row holds in the local store, recorded per root (see
42739
+ * `rootVerdict`), not the key on the root event just handed in: roots are
42740
+ * first-write-wins in the store, so when two producers record a root for one
42741
+ * session (the session-start hook, then a reconcile pass) the second leaves
42742
+ * the stored row as it was, and the history drain decides that row, not this
42743
+ * event. Whether this root EVENT is itself sent takes both keys: the stored
42744
+ * one AND its own. The event's attributes (cwd, project, repo) describe where
42745
+ * it was recorded from, so a root event keyed to a personal directory is never
42746
+ * sent under an enrolled stored root, though the enrolled leaves still forward
42747
+ * under it: the instance that wrote the stored root is expected to have
42748
+ * forwarded it. If it did not (the root was written while standalone or under
42749
+ * another attachment, or its forward failed), the plane refuses those leaves
42750
+ * and the history drain ships the root first. Any other row with a root
42751
+ * reference (`rootSessionId`, else `parentId`) forwards only when its own key
42752
+ * is in scope AND this instance recorded an in-scope verdict for that root.
42753
+ * The audit-event route has real foreign keys on both columns and stubs no
42754
+ * missing root, so a leaf sent after its root was kept local is refused
42755
+ * there, and a refused forward counts toward the breaker that guards every
42756
+ * other one. A root this instance never recorded is therefore `'local'`: the
42757
+ * only answer that cannot orphan a row. A row with no root reference at all
42758
+ * has nothing to orphan, and is decided by its own key.
42759
+ *
42760
+ * What this costs is stated rather than discovered. A session whose stored
42761
+ * root is not keyed to an enrolled repository keeps its token and tool
42762
+ * records local, even the ones that ran inside one. A row recorded by an
42763
+ * instance that did not record its root cannot see the root's verdict, so it
42764
+ * stays local on a scoped attachment. Captures are not held to this: their
42765
+ * route plants a missing root itself, so they decide per event.
42766
+ */
42767
+ auditVerdict(event) {
42768
+ try {
42769
+ if (this.deps.attachment.mode === "machine") return "forward";
42770
+ if (event.eventType !== "session") {
42771
+ return this.leafVerdict(event.attributes, rootReferenceOf(event));
42772
+ }
42773
+ if (this.rootVerdict(event.id) === "local") return "local";
42774
+ return this.verdictFor(() => scopeKeyOf(event.attributes));
42775
+ } catch {
42776
+ return "local";
42777
+ }
42778
+ }
42779
+ /**
42780
+ * A session root's verdict, from the key the local store holds for it.
42781
+ *
42782
+ * Read back ONCE per root per instance, after the local write, and recorded.
42783
+ * The write comes first so the row exists and a stub a leaf planted ahead of
42784
+ * it has been healed; the read is the store's answer, which is the first
42785
+ * authoritative root the session ever had. No key, a row that is not a root,
42786
+ * and a store that cannot answer all mean `'local'`: the read happens inside
42787
+ * `verdictFor`'s guard, so a throw is an answer and never a rejection.
42788
+ *
42789
+ * Scoped mode only: `auditVerdict` answers a machine attachment before it
42790
+ * gets here, so a machine attachment pays no store read.
42791
+ */
42792
+ rootVerdict(rootId) {
42793
+ const recorded = this.rootVerdicts.get(rootId);
42794
+ if (recorded !== void 0) return recorded;
42795
+ const verdict = this.verdictFor(() => this.deps.local.readSessionScopeKey(rootId));
42796
+ this.rootVerdicts.set(rootId, verdict);
42797
+ return verdict;
42798
+ }
42799
+ /** A child row's verdict: its own key in scope AND its root's recorded verdict. */
42800
+ leafVerdict(attributes, rootId) {
42801
+ try {
42802
+ if (this.deps.attachment.mode === "machine") return "forward";
42803
+ if (this.verdictFor(() => scopeKeyOf(attributes)) === "local") return "local";
42804
+ if (rootId === void 0) return "forward";
42805
+ return this.rootVerdicts.get(rootId) === "forward" ? "forward" : "local";
42806
+ } catch {
42807
+ return "local";
42808
+ }
42809
+ }
42810
+ /**
42811
+ * The leaves of a batch that may be forwarded, filtered BEFORE `forwardBatch`
42812
+ * and never inside it. That loop tallies everything it does not deliver as a
42813
+ * forward drop, and a row this attachment may not send is not a lost one. Each
42814
+ * leaf is held to its root by the same reference `auditVerdict` uses
42815
+ * (`rootReferenceOf`).
42816
+ * Machine mode hands back the batch itself, so the batch path is exactly what
42817
+ * it was. A throw forwards nothing.
42818
+ */
42819
+ forwardableLeaves(inputs) {
42820
+ try {
42821
+ if (this.deps.attachment.mode === "machine") return inputs;
42822
+ return inputs.filter(
42823
+ (input2) => this.leafVerdict(input2.attributes, rootReferenceOf(input2)) === "forward"
42824
+ );
42825
+ } catch {
42826
+ return [];
42827
+ }
42828
+ }
42829
+ /**
42830
+ * The event `recordCapture` sends for a capture the verdict let through, or
42831
+ * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
42832
+ *
42833
+ * Machine mode sends `record.event` itself, the same object, so a machine
42834
+ * attachment's body is exactly what it was. A scoped attachment sends a COPY
42835
+ * whose `metadata.repo` names the repository of the capture's own key
42836
+ * (`withScopedRepo`). A hook's slug names the session's directory, while a
42837
+ * capture that names a file is keyed by that file's repository, so on a
42838
+ * scoped attachment the slug could otherwise label an enrolled repository's
42839
+ * capture with a personal repository's name. The key here is the one the
42840
+ * verdict just admitted, so the name sent is always an enrolled
42841
+ * repository's.
42842
+ *
42843
+ * A throw sends nothing and leaves the row unmarked, the direction every
42844
+ * fault on this path takes: toward standalone behaviour, never toward
42845
+ * forwarding something unchecked.
42846
+ */
42847
+ captureForWire(record2) {
42848
+ try {
42849
+ if (this.deps.attachment.mode === "machine") return record2.event;
42850
+ const key = record2.scopeKey;
42851
+ return key === void 0 ? void 0 : withScopedRepo(record2.event, key);
42852
+ } catch {
42853
+ return void 0;
42854
+ }
42855
+ }
41402
42856
  // ---------------------------------------------------------------------
41403
42857
  // Writes: local first, then forward.
41404
42858
  // ---------------------------------------------------------------------
41405
42859
  async recordCapture(record2) {
41406
42860
  await this.deps.local.recordCapture(record2);
42861
+ if (this.verdictFor(() => record2.scopeKey) === "local") return;
42862
+ const wireEvent = this.captureForWire(record2);
42863
+ if (wireEvent === void 0) return;
41407
42864
  const forwarded = await this.deps.forward.run(
41408
42865
  () => this.deps.client.ingestEvents({
41409
- events: [record2.event],
42866
+ events: [wireEvent],
41410
42867
  ...record2.dedupe ? { dedupe: record2.dedupe } : {}
41411
42868
  }),
41412
42869
  { decisionPath: true }
@@ -41419,8 +42876,12 @@ var AttachedDataGateway = class {
41419
42876
  }
41420
42877
  async ensureInventory(ctx) {
41421
42878
  const resolved = await this.deps.local.ensureInventory(ctx);
41422
- const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
41423
- this.remoteInventory = remote.ok ? remote.value : null;
42879
+ if (this.verdictFor(() => inventoryKey(ctx)) === "forward") {
42880
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
42881
+ this.remoteInventory = remote.ok ? remote.value : null;
42882
+ } else {
42883
+ this.remoteInventory = null;
42884
+ }
41424
42885
  const snapshot = await (async () => {
41425
42886
  try {
41426
42887
  return await this.deps.posture?.prepare() ?? null;
@@ -41451,6 +42912,7 @@ var AttachedDataGateway = class {
41451
42912
  // a retried tool_call, exactly this path — can never stomp a populated row.
41452
42913
  async recordAuditEvent(event) {
41453
42914
  await this.deps.local.recordAuditEvent(event);
42915
+ if (this.auditVerdict(event) === "local") return;
41454
42916
  const forwarded = await this.deps.forward.run(
41455
42917
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
41456
42918
  );
@@ -41464,6 +42926,7 @@ var AttachedDataGateway = class {
41464
42926
  async recordLlmCall(input2) {
41465
42927
  await this.deps.local.recordLlmCall(input2);
41466
42928
  const event = llmAuditEvent(input2);
42929
+ if (this.auditVerdict(event) === "local") return;
41467
42930
  const forwarded = await this.deps.forward.run(
41468
42931
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
41469
42932
  );
@@ -41634,7 +43097,7 @@ var AttachedDataGateway = class {
41634
43097
  // here would replace that with N separate local writes.
41635
43098
  async recordLlmCalls(inputs) {
41636
43099
  await this.deps.local.recordLlmCalls(inputs);
41637
- await this.forwardBatch(inputs, (input2) => llmAuditEvent(input2));
43100
+ await this.forwardBatch(this.forwardableLeaves(inputs), (input2) => llmAuditEvent(input2));
41638
43101
  }
41639
43102
  // `input.inspections` (secrets detected client-side in the tool's masked
41640
43103
  // target) ride along on the request's `inspections` field — the control plane
@@ -41644,7 +43107,7 @@ var AttachedDataGateway = class {
41644
43107
  // way — this only stops the FINDING row itself from being dropped.
41645
43108
  async recordToolCalls(inputs) {
41646
43109
  await this.deps.local.recordToolCalls(inputs);
41647
- await this.forwardBatch(inputs, (input2) => toolAuditEvent(input2));
43110
+ await this.forwardBatch(this.forwardableLeaves(inputs), (input2) => toolAuditEvent(input2));
41648
43111
  }
41649
43112
  // Forwarded as a `config_scan` audit event: there is no dedicated
41650
43113
  // config-scan ingest endpoint, and the audit-event door is the one the
@@ -41669,6 +43132,7 @@ var AttachedDataGateway = class {
41669
43132
  // local store.
41670
43133
  async recordConfigScan(record2) {
41671
43134
  await this.deps.local.recordConfigScan(record2);
43135
+ if (this.verdictFor(() => void 0) === "local") return;
41672
43136
  const forwarded = await this.deps.forward.run(
41673
43137
  () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
41674
43138
  );
@@ -41690,6 +43154,7 @@ var AttachedDataGateway = class {
41690
43154
  */
41691
43155
  async recordProjectEgress(input2) {
41692
43156
  const summary = await this.deps.local.recordProjectEgress(input2);
43157
+ if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
41693
43158
  await this.deps.forward.run(
41694
43159
  () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
41695
43160
  );
@@ -41911,14 +43376,15 @@ var AttachedDataGateway = class {
41911
43376
  }
41912
43377
  };
41913
43378
  function reKeyForForward(event, remote) {
43379
+ const outbound = withoutScopeKey(event);
41914
43380
  if (remote === null) {
41915
- const stripped = { ...event };
43381
+ const stripped = { ...outbound };
41916
43382
  delete stripped.hostId;
41917
43383
  delete stripped.harnessId;
41918
43384
  delete stripped.sourceProjectId;
41919
43385
  return stripped;
41920
43386
  }
41921
- const rekeyed = { ...event };
43387
+ const rekeyed = { ...outbound };
41922
43388
  delete rekeyed.hostId;
41923
43389
  delete rekeyed.harnessId;
41924
43390
  delete rekeyed.sourceProjectId;
@@ -41927,6 +43393,19 @@ function reKeyForForward(event, remote) {
41927
43393
  if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
41928
43394
  return rekeyed;
41929
43395
  }
43396
+ function rootReferenceOf(row) {
43397
+ return row.rootSessionId ?? row.parentId;
43398
+ }
43399
+ function scopeKeyOf(attributes) {
43400
+ if (attributes == null || !Object.hasOwn(attributes, "scope_key")) return void 0;
43401
+ const key = attributes.scope_key;
43402
+ return typeof key === "string" ? key : void 0;
43403
+ }
43404
+ function inventoryKey(ctx) {
43405
+ const tool = ctx.harness?.identityKey;
43406
+ if (tool === void 0 || !sessionToolIsKeyed(tool)) return void 0;
43407
+ return canonicalRepoUrl(ctx.project?.url ?? "");
43408
+ }
41930
43409
  var BATCH_FORWARD_BUDGET_MS = 3e3;
41931
43410
  function llmAuditEvent(input2) {
41932
43411
  return {
@@ -41946,7 +43425,20 @@ function toolAuditEvent(input2) {
41946
43425
  parentId: input2.parentId,
41947
43426
  rootSessionId: input2.rootSessionId,
41948
43427
  attributes: input2.attributes,
41949
- inspections: input2.inspections
43428
+ inspections: input2.inspections.map(toWireInspection)
43429
+ };
43430
+ }
43431
+ function toWireInspection(insp) {
43432
+ return {
43433
+ ruleId: insp.ruleId,
43434
+ ruleName: insp.ruleName,
43435
+ ruleVersion: insp.ruleVersion,
43436
+ category: insp.category,
43437
+ severity: insp.severity,
43438
+ span: insp.span,
43439
+ maskedMatch: insp.maskedMatch,
43440
+ actionTaken: insp.actionTaken,
43441
+ confidence: insp.confidence
41950
43442
  };
41951
43443
  }
41952
43444
 
@@ -41970,17 +43462,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
41970
43462
 
41971
43463
  // ../../packages/plugin-runtime/src/attached/install-record.ts
41972
43464
  import { readFile as readFile2, stat } from "fs/promises";
41973
- import { basename as basename6, dirname as dirname6, join as join28, resolve as resolve2 } from "path";
43465
+ import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
41974
43466
  async function readInstalledVersion(installRoot) {
41975
43467
  try {
41976
43468
  const versionDir = resolve2(installRoot);
41977
- const pluginDir = dirname6(versionDir);
41978
- const marketplaceDir = dirname6(pluginDir);
41979
- const cacheDir = dirname6(marketplaceDir);
43469
+ const pluginDir = dirname7(versionDir);
43470
+ const marketplaceDir = dirname7(pluginDir);
43471
+ const cacheDir = dirname7(marketplaceDir);
41980
43472
  if (basename6(cacheDir) !== "cache") return null;
41981
43473
  const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
41982
43474
  const record2 = JSON.parse(
41983
- await readFile2(join28(dirname6(cacheDir), "installed_plugins.json"), "utf8")
43475
+ await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
41984
43476
  );
41985
43477
  const plugins = record2?.plugins;
41986
43478
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -42040,9 +43532,9 @@ async function readInstalledVersionBounded(installRoot) {
42040
43532
  }
42041
43533
 
42042
43534
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42043
- import { randomUUID as randomUUID16 } from "crypto";
43535
+ import { randomUUID as randomUUID17 } from "crypto";
42044
43536
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42045
- import { join as join29 } from "path";
43537
+ import { join as join30 } from "path";
42046
43538
 
42047
43539
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
42048
43540
  import { rename as rename2 } from "fs/promises";
@@ -42050,11 +43542,11 @@ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
42050
43542
  var IMMEDIATE_RETRIES = 8;
42051
43543
  var TIMED_RETRIES = 4;
42052
43544
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
42053
- var delay = (ms) => new Promise((resolve3) => {
42054
- setTimeout(resolve3, ms);
43545
+ var delay = (ms) => new Promise((resolve4) => {
43546
+ setTimeout(resolve4, ms);
42055
43547
  });
42056
- var yieldToLoop = () => new Promise((resolve3) => {
42057
- setImmediate(resolve3);
43548
+ var yieldToLoop = () => new Promise((resolve4) => {
43549
+ setImmediate(resolve4);
42058
43550
  });
42059
43551
  async function publishByRename(tmp, file2, move = rename2) {
42060
43552
  for (let attempt = 1; ; attempt += 1) {
@@ -42071,7 +43563,7 @@ async function publishByRename(tmp, file2, move = rename2) {
42071
43563
 
42072
43564
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42073
43565
  function createPolicyStore(dir = dataDir()) {
42074
- const file2 = join29(dir, "policy-cache.json");
43566
+ const file2 = join30(dir, "policy-cache.json");
42075
43567
  async function read() {
42076
43568
  try {
42077
43569
  const raw = await readFile3(file2, "utf8");
@@ -42103,7 +43595,7 @@ function createPolicyStore(dir = dataDir()) {
42103
43595
  }
42104
43596
  }
42105
43597
  async function publishRecord(record2) {
42106
- const tmp = `${file2}.${randomUUID16()}.tmp`;
43598
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
42107
43599
  try {
42108
43600
  await writeFile2(tmp, JSON.stringify(record2), {
42109
43601
  encoding: "utf8",
@@ -42191,7 +43683,7 @@ async function runPolicySync(deps) {
42191
43683
 
42192
43684
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
42193
43685
  import { readFileSync as readFileSync19 } from "fs";
42194
- import { join as join30 } from "path";
43686
+ import { join as join31 } from "path";
42195
43687
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
42196
43688
  var OUTCOME_KEYS = {
42197
43689
  ok: true,
@@ -42205,7 +43697,7 @@ var OUTCOME_KEYS = {
42205
43697
  };
42206
43698
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
42207
43699
  function postureReportStatePath(dataDir2) {
42208
- return join30(dataDir2, POSTURE_REPORT_STATE_FILENAME);
43700
+ return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42209
43701
  }
42210
43702
  function writePostureReportState(dataDir2, state) {
42211
43703
  try {
@@ -42219,7 +43711,7 @@ function writePostureReportState(dataDir2, state) {
42219
43711
  // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
42220
43712
  var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
42221
43713
  function createPostureReporter(deps) {
42222
- async function prepare() {
43714
+ async function prepare2() {
42223
43715
  try {
42224
43716
  const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
42225
43717
  if (state === null) return null;
@@ -42268,7 +43760,7 @@ function createPostureReporter(deps) {
42268
43760
  } catch {
42269
43761
  }
42270
43762
  }
42271
- return { prepare, send: send2 };
43763
+ return { prepare: prepare2, send: send2 };
42272
43764
  }
42273
43765
 
42274
43766
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
@@ -42383,16 +43875,16 @@ function readStorePosture(dbPath2) {
42383
43875
  }
42384
43876
 
42385
43877
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42386
- import { randomUUID as randomUUID17 } from "crypto";
43878
+ import { randomUUID as randomUUID18 } from "crypto";
42387
43879
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42388
- import { join as join31 } from "path";
43880
+ import { join as join32 } from "path";
42389
43881
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42390
43882
  function createPostureStore(dir = settingsDir(), legacyDir) {
42391
- const file2 = join31(dir, "posture-state.json");
42392
- const legacyFile = legacyDir === void 0 ? null : join31(legacyDir, "posture-state.json");
43883
+ const file2 = join32(dir, "posture-state.json");
43884
+ const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
42393
43885
  async function persist(state) {
42394
43886
  await ensureDataDir(dir);
42395
- const tmp = `${file2}.${randomUUID17()}.tmp`;
43887
+ const tmp = `${file2}.${randomUUID18()}.tmp`;
42396
43888
  try {
42397
43889
  await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
42398
43890
  await publishByRename(tmp, file2);
@@ -42434,7 +43926,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42434
43926
  }
42435
43927
  return legacy;
42436
43928
  }
42437
- const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
43929
+ const fresh = { deviceId: randomUUID18(), lastAttemptedAtMs: 0 };
42438
43930
  try {
42439
43931
  await ensureDataDir(dir);
42440
43932
  if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
@@ -42458,10 +43950,10 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42458
43950
 
42459
43951
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42460
43952
  import { readFileSync as readFileSync20 } from "fs";
42461
- import { join as join32 } from "path";
43953
+ import { join as join33 } from "path";
42462
43954
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
42463
43955
  function syncStatePath(dataDir2) {
42464
- return join32(dataDir2, SYNC_STATE_FILENAME);
43956
+ return join33(dataDir2, SYNC_STATE_FILENAME);
42465
43957
  }
42466
43958
  function writeSyncState(dataDir2, result) {
42467
43959
  try {
@@ -42525,9 +44017,6 @@ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
42525
44017
  // ../../packages/plugin-runtime/src/attached/factory.ts
42526
44018
  import { hostname as hostname6 } from "os";
42527
44019
 
42528
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
42529
- import { randomUUID as randomUUID18 } from "crypto";
42530
-
42531
44020
  // ../../packages/plugin-runtime/src/recorder.ts
42532
44021
  var PLUGIN_RECORDER_BINARY = "plugin";
42533
44022
 
@@ -42544,7 +44033,7 @@ var StandaloneDataGateway = class {
42544
44033
  this.db.installedPacks.recordInventory(detections, meta4);
42545
44034
  }
42546
44035
  recordCapture(record2) {
42547
- this.db.recordCapture(record2.event, record2.findings);
44036
+ this.db.recordCapture(record2.event, record2.findings, record2.scopeKey);
42548
44037
  return Promise.resolve();
42549
44038
  }
42550
44039
  ensureInventory(ctx) {
@@ -42570,12 +44059,12 @@ var StandaloneDataGateway = class {
42570
44059
  // reconciler drops the whole pass and recovers it idempotently on the next read.
42571
44060
  recordLlmCalls(inputs) {
42572
44061
  if (inputs.length === 0) return Promise.resolve();
42573
- return new Promise((resolve3, reject) => {
44062
+ return new Promise((resolve4, reject) => {
42574
44063
  try {
42575
44064
  this.db.auditEvents.runInTransaction(() => {
42576
44065
  for (const input2 of inputs) this.db.auditEvents.insertLlmCall(input2);
42577
44066
  });
42578
- resolve3();
44067
+ resolve4();
42579
44068
  } catch (err) {
42580
44069
  reject(err instanceof Error ? err : new Error(String(err)));
42581
44070
  }
@@ -42587,12 +44076,12 @@ var StandaloneDataGateway = class {
42587
44076
  // drops the whole pass and recovers it idempotently next time.
42588
44077
  recordToolCalls(inputs) {
42589
44078
  if (inputs.length === 0) return Promise.resolve();
42590
- return new Promise((resolve3, reject) => {
44079
+ return new Promise((resolve4, reject) => {
42591
44080
  try {
42592
44081
  this.db.auditEvents.runInTransaction(() => {
42593
44082
  for (const input2 of inputs) this.writeToolCall(input2);
42594
44083
  });
42595
- resolve3();
44084
+ resolve4();
42596
44085
  } catch (err) {
42597
44086
  reject(err instanceof Error ? err : new Error(String(err)));
42598
44087
  }
@@ -42631,7 +44120,10 @@ var StandaloneDataGateway = class {
42631
44120
  span: insp.span,
42632
44121
  maskedMatch: insp.maskedMatch,
42633
44122
  actionTaken: insp.actionTaken,
42634
- confidence: insp.confidence
44123
+ confidence: insp.confidence,
44124
+ ...insp.line === void 0 ? {} : { line: insp.line },
44125
+ ...insp.col === void 0 ? {} : { col: insp.col },
44126
+ ...insp.context === void 0 ? {} : { context: insp.context }
42635
44127
  });
42636
44128
  }
42637
44129
  }
@@ -42646,6 +44138,14 @@ var StandaloneDataGateway = class {
42646
44138
  readSessionProvider(sessionId) {
42647
44139
  return Promise.resolve(this.db.auditEvents.sessionProvider(sessionId));
42648
44140
  }
44141
+ // The key the store holds for a session root, which is not always the key of
44142
+ // the root event just recorded: roots are first-write-wins, so a second root
44143
+ // event for a session leaves the stored one as it was. The attached gateway
44144
+ // decides what to forward from this, because it is the row the history drain
44145
+ // will decide by.
44146
+ readSessionScopeKey(sessionId) {
44147
+ return this.db.auditEvents.sessionScopeKey(sessionId);
44148
+ }
42649
44149
  readCaptureStatuses() {
42650
44150
  return Promise.resolve(this.db.captureStatus.latest(Date.now()));
42651
44151
  }
@@ -42713,6 +44213,7 @@ var StandaloneDataGateway = class {
42713
44213
  ruleActions: /* @__PURE__ */ new Map(),
42714
44214
  ruleVersions: /* @__PURE__ */ new Map(),
42715
44215
  reversibleRules: /* @__PURE__ */ new Set(),
44216
+ assignedRules: /* @__PURE__ */ new Set(),
42716
44217
  complete: true
42717
44218
  };
42718
44219
  }
@@ -42726,6 +44227,7 @@ var StandaloneDataGateway = class {
42726
44227
  ruleActions: snapshot.ruleActions,
42727
44228
  ruleVersions: snapshot.ruleVersions,
42728
44229
  reversibleRules: snapshot.reversibleRules,
44230
+ assignedRules: snapshot.assignedRules,
42729
44231
  complete: true
42730
44232
  };
42731
44233
  } catch {
@@ -42736,13 +44238,7 @@ var StandaloneDataGateway = class {
42736
44238
  const policies = await this.db.policies.readPolicies();
42737
44239
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
42738
44240
  const installed = this.installedScanRules();
42739
- const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
42740
- id: randomUUID18(),
42741
- scope: "global",
42742
- target: { ruleId },
42743
- action,
42744
- enabled: true
42745
- })) : [];
44241
+ const rulePolicies = installed ? assignedRulePolicies(installed) : [];
42746
44242
  let exceptions;
42747
44243
  try {
42748
44244
  const key = this.dataDir ? readFingerprintKey(this.dataDir) : null;
@@ -42923,6 +44419,11 @@ function resolveGatewayForConfig(config2, meta4) {
42923
44419
  if (connection === void 0) return local;
42924
44420
  const credential = readControlPlaneCredential(config2.settingsDir, connection);
42925
44421
  if (credential === null) return local;
44422
+ const attachment = resolveScope({
44423
+ mode: attachmentModeOf(credential),
44424
+ scope: config2.settings.attachmentScope,
44425
+ endpoint: connection.endpoint
44426
+ });
42926
44427
  const client = createRemoteClient({
42927
44428
  endpoint: connection.endpoint,
42928
44429
  apiKey: credential.apiKey
@@ -42936,6 +44437,7 @@ function resolveGatewayForConfig(config2, meta4) {
42936
44437
  dataDir: config2.dataDir,
42937
44438
  readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
42938
44439
  forward,
44440
+ attachment,
42939
44441
  posture: createPostureReporter({
42940
44442
  // THROUGH THE BREAKER, and wrapped HERE rather than around
42941
44443
  // `PostureReporter.send`. The reporter swallows every error by
@@ -42988,7 +44490,7 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
42988
44490
 
42989
44491
  // ../../packages/scanner/src/discover.ts
42990
44492
  import { readdirSync as readdirSync5 } from "fs";
42991
- import { join as join33 } from "path";
44493
+ import { join as join34 } from "path";
42992
44494
 
42993
44495
  // ../../packages/scanner/src/constants.ts
42994
44496
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -43012,15 +44514,15 @@ var DISCOVER_SKIP = /* @__PURE__ */ new Set([
43012
44514
  import { basename as basename7, relative } from "path";
43013
44515
 
43014
44516
  // ../../packages/scanner/src/scan.ts
43015
- import { existsSync as existsSync12, readFileSync as readFileSync22 } from "fs";
43016
- import { extname as extname2, isAbsolute as isAbsolute2, relative as relative3 } from "path";
44517
+ import { existsSync as existsSync14, readFileSync as readFileSync22 } from "fs";
44518
+ import { extname as extname2, isAbsolute as isAbsolute3, relative as relative3 } from "path";
43017
44519
 
43018
44520
  // ../../packages/scanner/src/manifests.ts
43019
44521
  import { statSync as statSync11 } from "fs";
43020
44522
 
43021
44523
  // ../../packages/scanner/src/walk.ts
43022
44524
  import { readdirSync as readdirSync6, readFileSync as readFileSync21, statSync as statSync10 } from "fs";
43023
- import { extname, join as join34, relative as relative2, sep as sep4 } from "path";
44525
+ import { extname, join as join35, relative as relative2, sep as sep4 } from "path";
43024
44526
  var import_ignore2 = __toESM(require_ignore(), 1);
43025
44527
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
43026
44528
  ".ts",
@@ -43071,7 +44573,7 @@ function* walkTree(rootDir, opts = {}) {
43071
44573
  );
43072
44574
  for (const entry of dirents) {
43073
44575
  const name = entry.name;
43074
- const fullPath = join34(dir, name);
44576
+ const fullPath = join35(dir, name);
43075
44577
  if (entry.isDirectory()) {
43076
44578
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
43077
44579
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {
@@ -43163,6 +44665,38 @@ function computeResolutions(prior, current) {
43163
44665
  return [...new Set(prior)].filter((k) => !cur.has(k));
43164
44666
  }
43165
44667
 
44668
+ // ../../packages/scanner/src/scope-key.ts
44669
+ import { existsSync as existsSync13 } from "fs";
44670
+ import { join as join36, posix as posix2, resolve as resolve3 } from "path";
44671
+ function scopeKeysUnder(rootDir) {
44672
+ const base = resolve3(rootDir);
44673
+ const keyByDir = /* @__PURE__ */ new Map();
44674
+ return (relativePath) => {
44675
+ const climbed = [];
44676
+ let dir = posix2.dirname(relativePath);
44677
+ let key;
44678
+ for (; ; ) {
44679
+ if (keyByDir.has(dir)) {
44680
+ key = keyByDir.get(dir);
44681
+ break;
44682
+ }
44683
+ climbed.push(dir);
44684
+ const parent = posix2.dirname(dir);
44685
+ if (parent === dir) {
44686
+ key = resolveRepoAttribution(base).scopeKey;
44687
+ break;
44688
+ }
44689
+ if (existsSync13(join36(base, dir, ".git"))) {
44690
+ key = resolveRepoAttribution(join36(base, dir)).scopeKey;
44691
+ break;
44692
+ }
44693
+ dir = parent;
44694
+ }
44695
+ for (const at of climbed) keyByDir.set(at, key);
44696
+ return key;
44697
+ };
44698
+ }
44699
+
43166
44700
  // ../../packages/scanner/src/scan.ts
43167
44701
  async function loadLedger(gateway, runtime, dataSharesInPlace) {
43168
44702
  const egressMaterial = `${dataSharesInPlace ? "egress:on" : "egress:off"}
@@ -43244,12 +44778,12 @@ async function reopenRedetectedFindings(gateway, path, currentKeys, evidence, re
43244
44778
  }
43245
44779
  function isUnderRoot(path, rootDir) {
43246
44780
  const rel = relative3(rootDir, path);
43247
- return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
44781
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute3(rel);
43248
44782
  }
43249
44783
  async function sweepDeletedFiles(gateway, rootDir, paths) {
43250
44784
  const deleted = [];
43251
44785
  for (const path of paths) {
43252
- if (!isUnderRoot(path, rootDir) || existsSync12(path)) continue;
44786
+ if (!isUnderRoot(path, rootDir) || existsSync14(path)) continue;
43253
44787
  deleted.push(path);
43254
44788
  await resolveRemovedFindings(gateway, path, [], { deleted: true });
43255
44789
  }
@@ -43264,6 +44798,7 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
43264
44798
  let findings = 0;
43265
44799
  let gitignoredFindings = 0;
43266
44800
  const egress = config2.settings.dataSharesInPlace ? startEgress(rootDir) : null;
44801
+ const scopeKeyOf2 = scopeKeysUnder(rootDir);
43267
44802
  const shouldRead = (meta4) => {
43268
44803
  const prev = ledger.previous.get(meta4.path);
43269
44804
  if (prev?.mtime === meta4.mtime) {
@@ -43298,6 +44833,7 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
43298
44833
  }
43299
44834
  seen.add(hash2);
43300
44835
  scanned++;
44836
+ const scopeKey = scopeKeyOf2(file2.relativePath);
43301
44837
  const result = await runtime.capture(
43302
44838
  {
43303
44839
  kind: "code_change",
@@ -43315,7 +44851,10 @@ async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts) {
43315
44851
  filePath: file2.path,
43316
44852
  wholeFile: true,
43317
44853
  ...file2.gitignored ? { gitignored: true } : {}
43318
- }
44854
+ },
44855
+ // Beside the event, never in its metadata: EventMetadata is a published
44856
+ // wire shape, and only the local writer stores the key.
44857
+ ...scopeKey !== void 0 ? { scopeKey } : {}
43319
44858
  },
43320
44859
  // 'content-hash': a re-run mints fresh event ids for identical content;
43321
44860
  // the store uses the hash to drop what it already recorded.