@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.
@@ -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) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
@@ -329,7 +330,7 @@ var require_ignore = __commonJS({
329
330
  // Zero, one or several directories
330
331
  // should not use '*', or it will be replaced by the next replacer
331
332
  // Check if it is not the last `'/**'`
332
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : "\\/.+",
333
+ (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
333
334
  "*"
334
335
  ],
335
336
  // normal intermediate wildcards
@@ -407,7 +408,7 @@ var require_ignore = __commonJS({
407
408
  // 'js' will match 'a.js' and 'a.js/'
408
409
  (source) => {
409
410
  const last = source[source.length - 1];
410
- if (!last || last === TRAILING_WILDCARD) {
411
+ if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
411
412
  return source;
412
413
  }
413
414
  return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
@@ -418,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) {
@@ -1013,6 +1045,10 @@ var SQLITE_MIGRATIONS = [
1013
1045
  {
1014
1046
  tag: "0036_secret_vault_identity_fingerprint",
1015
1047
  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"
1048
+ },
1049
+ {
1050
+ tag: "0037_finding_location",
1051
+ 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;"
1016
1052
  }
1017
1053
  ];
1018
1054
 
@@ -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
  });
@@ -25229,7 +25361,7 @@ var VaultConsent = external_exports.object({
25229
25361
  });
25230
25362
 
25231
25363
  // ../../packages/schema/src/zod/local.ts
25232
- var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
25364
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 9;
25233
25365
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
25234
25366
  var RunMode = external_exports.enum(["standalone", "attached"]);
25235
25367
  var ControlPlaneConnection = external_exports.object({
@@ -25249,6 +25381,37 @@ var HistorySyncConsent = external_exports.object({
25249
25381
  payloadVersion: external_exports.number().int().positive(),
25250
25382
  endpoint: external_exports.string()
25251
25383
  });
25384
+ var ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH = 512;
25385
+ var AttachmentScopeEntry = external_exports.object({
25386
+ kind: external_exports.enum(["repo", "account"]),
25387
+ identity: printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH).min(1),
25388
+ label: printable(80).optional(),
25389
+ enrolledAt: external_exports.iso.datetime()
25390
+ });
25391
+ var AttachmentScope = external_exports.object({
25392
+ endpoint: external_exports.string().min(1),
25393
+ entries: external_exports.array(AttachmentScopeEntry)
25394
+ });
25395
+ var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
25396
+ function parseAttachmentScope(raw) {
25397
+ try {
25398
+ const envelope = AttachmentScopeEnvelope.safeParse(raw);
25399
+ if (!envelope.success) return void 0;
25400
+ const entries = [];
25401
+ for (const candidate of envelope.data.entries) {
25402
+ const entry = AttachmentScopeEntry.safeParse(candidate);
25403
+ if (entry.success) entries.push(entry.data);
25404
+ }
25405
+ return { endpoint: envelope.data.endpoint, entries };
25406
+ } catch {
25407
+ return void 0;
25408
+ }
25409
+ }
25410
+ function scopeForEndpoint(raw, endpoint) {
25411
+ if (endpoint === void 0) return void 0;
25412
+ const scope = parseAttachmentScope(raw);
25413
+ return scope?.endpoint === endpoint ? scope : void 0;
25414
+ }
25252
25415
  var WebChatCaptureConsent = external_exports.object({
25253
25416
  acknowledgedAt: external_exports.iso.datetime(),
25254
25417
  version: external_exports.number().int().positive()
@@ -25319,6 +25482,23 @@ var WorkspaceSettings = external_exports.object({
25319
25482
  // both widenings. Absent until granted, and a grant for a different endpoint
25320
25483
  // or an older payload no longer counts.
25321
25484
  historySyncConsent: HistorySyncConsent.optional(),
25485
+ // The identities a SCOPED attachment forwards and the deployment they were
25486
+ // enrolled for (see AttachmentScope). Absent until something is enrolled.
25487
+ //
25488
+ // `z.unknown()`, NOT `AttachmentScope`, and the difference is this field's
25489
+ // whole failure mode. A settings.json that fails this schema reads as the
25490
+ // unonboarded defaults (readUserSettings in @akasecurity/persistence), and the
25491
+ // next save writes those defaults back over it. Typed, one entry with an
25492
+ // unknown `kind`, a control character or a bad timestamp would cost the
25493
+ // attachment, every consent and onboardedAt, permanently. Untyped, the value
25494
+ // is kept exactly as found and validated where it is used: parseAttachmentScope
25495
+ // drops a bad entry by itself, and on a scoped attachment resolveScope reads a
25496
+ // bad envelope as no entries, which keeps every event local.
25497
+ //
25498
+ // No default: absent must stay absent, so defaultWorkspaceSettings() and a
25499
+ // fresh settings.json do not change. No `.meta({ id })`, like every field
25500
+ // here. Not a ManagedSettingKey.
25501
+ attachmentScope: external_exports.unknown().optional(),
25322
25502
  // What the browser extension may record from a web chat, and the grant that
25323
25503
  // authorizes it. Absent until the user answers: recording something that was
25324
25504
  // never recorded before is never an assumed grant on upgrade, so the whole
@@ -25342,6 +25522,32 @@ function defaultWorkspaceSettings() {
25342
25522
  function isAttached(settings) {
25343
25523
  return settings.runMode === "attached" && settings.controlPlane !== void 0;
25344
25524
  }
25525
+ function resolveScope(input2, extraEntries) {
25526
+ try {
25527
+ if (input2.mode === "machine") return { mode: "machine", keys: /* @__PURE__ */ new Set() };
25528
+ const keys = /* @__PURE__ */ new Set();
25529
+ const stored = scopeForEndpoint(input2.scope, input2.endpoint);
25530
+ for (const entry of stored?.entries ?? []) {
25531
+ keys.add(entry.identity);
25532
+ }
25533
+ for (const candidate of extraEntries ?? []) {
25534
+ const entry = AttachmentScopeEntry.safeParse(candidate);
25535
+ if (entry.success) keys.add(entry.data.identity);
25536
+ }
25537
+ return { mode: "scoped", keys };
25538
+ } catch {
25539
+ return { mode: "scoped", keys: /* @__PURE__ */ new Set() };
25540
+ }
25541
+ }
25542
+ function scopeVerdict(resolved, key) {
25543
+ try {
25544
+ if (resolved.mode === "machine") return "forward";
25545
+ if (typeof key !== "string" || key === "") return "local";
25546
+ return resolved.keys.has(key) ? "forward" : "local";
25547
+ } catch {
25548
+ return "local";
25549
+ }
25550
+ }
25345
25551
  function toInventoryRow(input2, id, now) {
25346
25552
  return {
25347
25553
  id,
@@ -25413,7 +25619,10 @@ function toInspectionFindingRow(input2) {
25413
25619
  actionTaken: input2.actionTaken,
25414
25620
  confidence: input2.confidence,
25415
25621
  findingKey: input2.findingKey ?? null,
25416
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
25622
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null,
25623
+ line: input2.line ?? null,
25624
+ col: input2.col ?? null,
25625
+ context: input2.context ? JSON.stringify(input2.context) : null
25417
25626
  };
25418
25627
  }
25419
25628
  function toCaptureAttributes(event) {
@@ -26692,6 +26901,15 @@ var COUNTED_SCOPE = `
26692
26901
  OR outbox_owed = 1
26693
26902
  )`;
26694
26903
  var SKIPPED = -1;
26904
+ function inScope(column) {
26905
+ return `${column} IN (SELECT value FROM json_each(:scopeKeys))`;
26906
+ }
26907
+ function scopeKeysParam(scopeKeys) {
26908
+ return JSON.stringify(scopeKeys);
26909
+ }
26910
+ var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26911
+ FROM audit_events AS session_root
26912
+ WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26695
26913
  var ROW_COLUMNS = `id,
26696
26914
  parent_id AS parentId,
26697
26915
  root_session_id AS rootSessionId,
@@ -26720,6 +26938,18 @@ var SqliteHistorySyncRepository = class {
26720
26938
  ORDER BY earliest
26721
26939
  LIMIT :limit`
26722
26940
  );
26941
+ this.scopedSessionsStmt = db.prepare(
26942
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
26943
+ FROM audit_events
26944
+ WHERE synced_at IS NULL
26945
+ AND event_type IN (${TYPE_LIST})
26946
+ AND started_at < :before
26947
+ AND ${inScope("scope_key")}
26948
+ AND ${inScope(ROOT_SCOPE_KEY)}
26949
+ GROUP BY sessionId
26950
+ ORDER BY earliest
26951
+ LIMIT :limit`
26952
+ );
26723
26953
  this.rowsStmt = db.prepare(
26724
26954
  `SELECT ${ROW_COLUMNS}
26725
26955
  FROM audit_events
@@ -26730,6 +26960,18 @@ var SqliteHistorySyncRepository = class {
26730
26960
  ORDER BY (event_type = 'session') DESC, started_at
26731
26961
  LIMIT :limit`
26732
26962
  );
26963
+ this.scopedRowsStmt = db.prepare(
26964
+ `SELECT ${ROW_COLUMNS}
26965
+ FROM audit_events
26966
+ WHERE synced_at IS NULL
26967
+ AND event_type IN (${TYPE_LIST})
26968
+ AND started_at < :before
26969
+ AND COALESCE(root_session_id, id) = :sessionId
26970
+ AND ${inScope("scope_key")}
26971
+ AND ${inScope(ROOT_SCOPE_KEY)}
26972
+ ORDER BY (event_type = 'session') DESC, started_at
26973
+ LIMIT :limit`
26974
+ );
26733
26975
  this.captureRowsStmt = db.prepare(
26734
26976
  `SELECT ${ROW_COLUMNS}
26735
26977
  FROM audit_events
@@ -26741,6 +26983,18 @@ var SqliteHistorySyncRepository = class {
26741
26983
  ORDER BY started_at
26742
26984
  LIMIT :limit`
26743
26985
  );
26986
+ this.scopedCaptureRowsStmt = db.prepare(
26987
+ `SELECT ${ROW_COLUMNS}
26988
+ FROM audit_events
26989
+ WHERE synced_at IS NULL
26990
+ AND sync_claimed_at IS NULL
26991
+ AND outbox_owed = 1
26992
+ AND event_type IN (${CAPTURE_TYPE_LIST})
26993
+ AND started_at < :before
26994
+ AND ${inScope("scope_key")}
26995
+ ORDER BY started_at
26996
+ LIMIT :limit`
26997
+ );
26744
26998
  this.markOwedStmt = db.prepare(
26745
26999
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
26746
27000
  );
@@ -26750,6 +27004,20 @@ var SqliteHistorySyncRepository = class {
26750
27004
  AND event_type IN (${CAPTURE_TYPE_LIST})
26751
27005
  AND started_at < :before`
26752
27006
  );
27007
+ this.scopedCaptureBacklogOwedStmt = db.prepare(
27008
+ `UPDATE audit_events SET outbox_owed = 1
27009
+ WHERE synced_at IS NULL
27010
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27011
+ AND started_at < :before
27012
+ AND ${inScope("scope_key")}`
27013
+ );
27014
+ this.markScopeCapturesOwedStmt = db.prepare(
27015
+ `UPDATE audit_events SET outbox_owed = 1
27016
+ WHERE synced_at IS NULL
27017
+ AND outbox_owed IS NULL
27018
+ AND event_type IN (${CAPTURE_TYPE_LIST})
27019
+ AND ${inScope("scope_key")}`
27020
+ );
26753
27021
  this.stampStmt = db.prepare(
26754
27022
  `UPDATE audit_events
26755
27023
  SET synced_at = :at,
@@ -26908,6 +27176,15 @@ var SqliteHistorySyncRepository = class {
26908
27176
  claimRowStmt;
26909
27177
  releaseRowStmt;
26910
27178
  releaseStaleClaimsStmt;
27179
+ // The SCOPED twins, for a scoped attachment: the same reads and seeds with the
27180
+ // scope clause added, prepared once here beside the machine statements, so a
27181
+ // machine attachment's statements are untouched and neither form is compiled
27182
+ // per call.
27183
+ scopedSessionsStmt;
27184
+ scopedRowsStmt;
27185
+ scopedCaptureRowsStmt;
27186
+ scopedCaptureBacklogOwedStmt;
27187
+ markScopeCapturesOwedStmt;
26911
27188
  /**
26912
27189
  * The masked detections recorded against one tool call.
26913
27190
  *
@@ -26927,15 +27204,33 @@ var SqliteHistorySyncRepository = class {
26927
27204
  * path's to deliver; this drain exists for what was recorded before it, and a
26928
27205
  * row both paths send is at best a duplicate request and at worst — for a
26929
27206
  * session root — an overwrite of the inventory ids the live path resolved.
27207
+ *
27208
+ * `scopeKeys` is a scoped attachment's filter: a session is offered only while
27209
+ * its root's key is one of them AND at least one of its unsent rows' keys is
27210
+ * (see scopedSessionsStmt). Omitted, this runs the machine statement,
27211
+ * unchanged; an empty list offers nothing.
26930
27212
  */
26931
- pendingSessions(limit, before) {
26932
- return allRows(this.sessionsStmt, { limit, before }).map(
26933
- (r) => r.sessionId
26934
- );
27213
+ pendingSessions(limit, before, scopeKeys) {
27214
+ const rows = scopeKeys === void 0 ? allRows(this.sessionsStmt, { limit, before }) : allRows(this.scopedSessionsStmt, {
27215
+ limit,
27216
+ before,
27217
+ scopeKeys: scopeKeysParam(scopeKeys)
27218
+ });
27219
+ return rows.map((r) => r.sessionId);
26935
27220
  }
26936
- /** One session's undelivered structural rows within the backlog, root first. */
26937
- pendingRows(sessionId, limit, before) {
26938
- return allRows(this.rowsStmt, { sessionId, limit, before });
27221
+ /**
27222
+ * One session's undelivered structural rows within the backlog, root first.
27223
+ *
27224
+ * With `scopeKeys`, only the rows whose own key AND whose session root's key
27225
+ * are among them, whichever session id is passed.
27226
+ */
27227
+ pendingRows(sessionId, limit, before, scopeKeys) {
27228
+ return scopeKeys === void 0 ? allRows(this.rowsStmt, { sessionId, limit, before }) : allRows(this.scopedRowsStmt, {
27229
+ sessionId,
27230
+ limit,
27231
+ before,
27232
+ scopeKeys: scopeKeysParam(scopeKeys)
27233
+ });
26939
27234
  }
26940
27235
  /**
26941
27236
  * Captures this machine still owes the deployment, oldest first.
@@ -26944,9 +27239,17 @@ var SqliteHistorySyncRepository = class {
26944
27239
  * by a time window — see captureRowsStmt for why a window could not express
26945
27240
  * this. `before` is the grace window that leaves a just-recorded capture to
26946
27241
  * the live path.
27242
+ *
27243
+ * With `scopeKeys`, only captures stamped with one of them, decided per
27244
+ * capture: /v1/events stubs a missing root, so a capture never waits on its
27245
+ * session's scope. An empty list reads nothing.
26947
27246
  */
26948
- pendingCaptureRows(limit, before) {
26949
- return allRows(this.captureRowsStmt, { limit, before });
27247
+ pendingCaptureRows(limit, before, scopeKeys) {
27248
+ return scopeKeys === void 0 ? allRows(this.captureRowsStmt, { limit, before }) : allRows(this.scopedCaptureRowsStmt, {
27249
+ limit,
27250
+ before,
27251
+ scopeKeys: scopeKeysParam(scopeKeys)
27252
+ });
26950
27253
  }
26951
27254
  /**
26952
27255
  * Record that a capture is OWED to the deployment.
@@ -26978,9 +27281,37 @@ var SqliteHistorySyncRepository = class {
26978
27281
  * Returns how many rows matched, for the caller to log or test against. Not a
26979
27282
  * count of NEWLY marked rows — a row still unsynced from an earlier call
26980
27283
  * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27284
+ *
27285
+ * `scopeKeys` scopes it for a scoped attachment: only captures stamped with one
27286
+ * of the keys are marked, and an empty list marks none. The scoped capture read
27287
+ * is what keeps a personal capture out of a batch; this keeps the marker to
27288
+ * what the grant covers. Omitted, it runs the machine statement, unchanged.
26981
27289
  */
26982
- markCaptureBacklogOwed(before) {
26983
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27290
+ markCaptureBacklogOwed(before, scopeKeys) {
27291
+ const result = scopeKeys === void 0 ? this.markCaptureBacklogOwedStmt.run({ before }) : this.scopedCaptureBacklogOwedStmt.run({ before, scopeKeys: scopeKeysParam(scopeKeys) });
27292
+ return Number(result.changes);
27293
+ }
27294
+ /**
27295
+ * Mark owed every unsent capture stamped with one of `scopeKeys`: the re-seed
27296
+ * an enrollment runs.
27297
+ *
27298
+ * This ASSUMES the contract a scoped caller keeps, and cannot check it: nothing
27299
+ * else marks an out-of-scope capture owed (the live forward must refuse it
27300
+ * before its owed branch, and the consent-time seed must be handed the key
27301
+ * list). Under that contract, an enrolled repository's unsent captures are
27302
+ * reachable only if this runs when the repository is enrolled. Like the
27303
+ * consent seed it is one explicit human action, never something a pass infers,
27304
+ * and its caller must know the history grant is in force: this method cannot
27305
+ * check consent and must not be called without it.
27306
+ *
27307
+ * No time bound. Delivered and skipped rows are never re-opened, and a row
27308
+ * already owed is not counted, so the return value is how many rows this call
27309
+ * newly marked. An empty list marks nothing.
27310
+ */
27311
+ markScopeCapturesOwed(scopeKeys) {
27312
+ return Number(
27313
+ this.markScopeCapturesOwedStmt.run({ scopeKeys: scopeKeysParam(scopeKeys) }).changes
27314
+ );
26984
27315
  }
26985
27316
  /**
26986
27317
  * Record delivery. Called only AFTER the far side has accepted the rows.
@@ -27185,8 +27516,12 @@ var SqliteHistorySyncRepository = class {
27185
27516
  * disown from eating THIS SAME CALL's own re-mark is the order, not the
27186
27517
  * bound — disown runs first, re-mark second, both inside the one
27187
27518
  * transaction above.
27519
+ *
27520
+ * `scopeKeys` scopes the re-mark exactly as `markCaptureBacklogOwed` is scoped.
27521
+ * The disown before it is not scoped, and must not be: it clears the previous
27522
+ * deployment's markers whatever their scope.
27188
27523
  */
27189
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
27524
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore, scopeKeys) {
27190
27525
  this.ensureRowStmt.run();
27191
27526
  withTransaction(
27192
27527
  this.db,
@@ -27197,7 +27532,7 @@ var SqliteHistorySyncRepository = class {
27197
27532
  this.disownCapturesStmt.run({ attachedAt: backlogBefore });
27198
27533
  }
27199
27534
  if (backfillCapturesBefore !== void 0) {
27200
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
27535
+ this.markCaptureBacklogOwed(backfillCapturesBefore, scopeKeys);
27201
27536
  }
27202
27537
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27203
27538
  },
@@ -27363,6 +27698,7 @@ function applyMigrations(db, file2, options = {}) {
27363
27698
  db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
27364
27699
  }
27365
27700
  ensureSyncedAtColumn(db, "audit_events");
27701
+ ensureScopeKeyColumn(db);
27366
27702
  ensureScanLedgerTable(db);
27367
27703
  ensureHistorySyncTable(db);
27368
27704
  ensureBlockedDetectionsTable(db);
@@ -27788,6 +28124,21 @@ function ensureSyncedAtColumn(db, table) {
27788
28124
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
27789
28125
  );
27790
28126
  }
28127
+ 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";
28128
+ function ensureScopeKeyColumn(db) {
28129
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
28130
+ if (hasScopeKeyColumn(db)) return;
28131
+ withTransaction(
28132
+ db,
28133
+ () => {
28134
+ if (!hasScopeKeyColumn(db)) db.exec(SCOPE_KEY_COLUMN_DDL);
28135
+ },
28136
+ "IMMEDIATE"
28137
+ );
28138
+ }
28139
+ function hasScopeKeyColumn(db) {
28140
+ return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28141
+ }
27791
28142
  function ensureScanLedgerTable(db) {
27792
28143
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27793
28144
  path TEXT PRIMARY KEY,
@@ -28665,6 +29016,19 @@ var SqliteAuditEventsRepository = class {
28665
29016
  if (typeof provider === "string") return provider;
28666
29017
  return void 0;
28667
29018
  }
29019
+ // The `scope_key` stored on a session root's attributes: the key the history
29020
+ // drain decides that root by. It is NOT necessarily the key of the root event a
29021
+ // caller just wrote, because roots are first-write-wins (see the session-root
29022
+ // upsert above) and the root event that arrives second leaves the stored row as
29023
+ // it was. Returns undefined when the id is not a session root, when the root is
29024
+ // a stub or carries no key, and when the stored value is not a string, which is
29025
+ // what the drain's scoped reads would not match either.
29026
+ sessionScopeKey(sessionId) {
29027
+ const row = this.findById(sessionId);
29028
+ if (row?.event_type !== "session" || !row.attributes) return void 0;
29029
+ const key = parseJsonObject(row.attributes)?.scope_key;
29030
+ return typeof key === "string" ? key : void 0;
29031
+ }
28668
29032
  // Every `llm_call` leaf's session id + raw attribute bag, for the read-time token
28669
29033
  // rollups. The caller parses each bag and prices it via the
28670
29034
  // cost model — we stay a thin reader here (no business logic, no cost). `root_session_id`
@@ -28685,6 +29049,8 @@ var SqliteAuditEventsRepository = class {
28685
29049
  var DEFAULT_BATCH_SIZE = 500;
28686
29050
  var DEFAULT_MAX_ROWS = 5e4;
28687
29051
  var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
29052
+ var SWEEP = { kind: "sweep" };
29053
+ var HOLD_ALL = { kind: "hold-all" };
28688
29054
  var SqliteBodyRetentionRepository = class {
28689
29055
  constructor(db) {
28690
29056
  this.db = db;
@@ -28701,6 +29067,14 @@ var SqliteBodyRetentionRepository = class {
28701
29067
  this.candidatesSyncSafeStmt = this.db.prepare(
28702
29068
  select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
28703
29069
  );
29070
+ this.candidatesScopedStmt = this.db.prepare(
29071
+ select(
29072
+ `AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL
29073
+ OR (outbox_owed IS NOT 1
29074
+ AND (scope_key IS NULL
29075
+ OR scope_key NOT IN (SELECT value FROM json_each(:scopeKeys)))))`
29076
+ )
29077
+ );
28704
29078
  this.heldBySyncStmt = this.db.prepare(`
28705
29079
  SELECT COUNT(*) AS n
28706
29080
  FROM audit_events
@@ -28708,37 +29082,63 @@ var SqliteBodyRetentionRepository = class {
28708
29082
  AND started_at < :cutoff
28709
29083
  AND event_type IN (${SYNC_LANE_TYPES_SQL})
28710
29084
  AND synced_at IS NULL`);
29085
+ this.heldByScopeStmt = this.db.prepare(`
29086
+ SELECT COUNT(*) AS n
29087
+ FROM audit_events
29088
+ WHERE content IS NOT NULL
29089
+ AND started_at < :cutoff
29090
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
29091
+ AND synced_at IS NULL
29092
+ AND (outbox_owed = 1
29093
+ OR scope_key IN (SELECT value FROM json_each(:scopeKeys)))`);
28711
29094
  this.expireStmt = this.db.prepare(
28712
29095
  `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
28713
29096
  );
29097
+ this.expireContextsStmt = this.db.prepare(
29098
+ `UPDATE inspection_findings SET context = NULL
29099
+ WHERE id IN (
29100
+ SELECT f.id
29101
+ FROM inspection_findings f INDEXED BY idx_inspection_findings_context
29102
+ JOIN audit_events e ON e.id = f.audit_event_id
29103
+ WHERE f.context IS NOT NULL
29104
+ AND f.first_detected_at < :cutoff
29105
+ AND e.content IS NULL
29106
+ AND e.started_at < :cutoff
29107
+ LIMIT :limit)`
29108
+ );
28714
29109
  }
28715
29110
  db;
28716
29111
  candidatesStmt;
28717
29112
  candidatesSyncSafeStmt;
29113
+ candidatesScopedStmt;
28718
29114
  heldBySyncStmt;
29115
+ heldByScopeStmt;
28719
29116
  expireStmt;
28720
- /** How many bytes a pass with these options would free, changing nothing. */
29117
+ expireContextsStmt;
29118
+ /**
29119
+ * How many body bytes a pass with these options would free, changing
29120
+ * nothing. Finding excerpts are not counted (see `bytesFreed`).
29121
+ */
28721
29122
  preview(opts) {
28722
- const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
28723
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
28724
- const rows = stmt.all({ cutoff: opts.cutoff, limit });
29123
+ const lane = laneOf(opts.sweepSyncLane);
29124
+ const rows = this.candidates(lane, opts.cutoff, opts.maxRows ?? DEFAULT_MAX_ROWS);
28725
29125
  return {
28726
29126
  rowsExpired: rows.length,
28727
29127
  bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
28728
- rowsHeldBySync: this.countHeldBySync(opts)
29128
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff)
28729
29129
  };
28730
29130
  }
28731
29131
  /** Clear eligible bodies, in bounded batches. */
28732
29132
  expire(opts) {
28733
29133
  const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
28734
29134
  const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
28735
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
29135
+ const lane = laneOf(opts.sweepSyncLane);
28736
29136
  let rowsExpired = 0;
28737
29137
  let bytesFreed = 0;
28738
29138
  let done = true;
28739
29139
  while (rowsExpired < maxRows) {
28740
29140
  const remaining = Math.min(batchSize, maxRows - rowsExpired);
28741
- const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
29141
+ const batch = this.candidates(lane, opts.cutoff, remaining);
28742
29142
  if (batch.length === 0) break;
28743
29143
  withTransaction(
28744
29144
  this.db,
@@ -28751,17 +29151,60 @@ var SqliteBodyRetentionRepository = class {
28751
29151
  bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
28752
29152
  if (batch.length < remaining) break;
28753
29153
  if (rowsExpired >= maxRows) {
28754
- done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
29154
+ done = this.candidates(lane, opts.cutoff, 1).length === 0;
28755
29155
  }
28756
29156
  }
28757
- return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
29157
+ this.expireContexts(opts.cutoff, batchSize, maxRows);
29158
+ return {
29159
+ rowsExpired,
29160
+ bytesFreed,
29161
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff),
29162
+ done
29163
+ };
28758
29164
  }
28759
- countHeldBySync(opts) {
28760
- if (opts.sweepSyncLane) return 0;
28761
- const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
29165
+ // Clear the excerpts that outlived their body, one bounded transaction per
29166
+ // batch for the same reason the body sweep batches, and at most `maxRows` of
29167
+ // them per pass under the same cap: the next pass picks up the rest.
29168
+ expireContexts(cutoff, batchSize, maxRows) {
29169
+ let total = 0;
29170
+ while (total < maxRows) {
29171
+ const limit = Math.min(batchSize, maxRows - total);
29172
+ let cleared = 0;
29173
+ withTransaction(
29174
+ this.db,
29175
+ () => {
29176
+ cleared = Number(this.expireContextsStmt.run({ cutoff, limit }).changes);
29177
+ },
29178
+ "IMMEDIATE"
29179
+ );
29180
+ total += cleared;
29181
+ if (cleared < limit) return;
29182
+ }
29183
+ }
29184
+ /**
29185
+ * One batch of candidates under `lane`, bound with exactly the parameters its
29186
+ * statement names — node:sqlite refuses a named parameter a statement does not
29187
+ * declare, so the key list goes to the scoped statements only.
29188
+ *
29189
+ * Anything that is not `sweep` or `hold-keys` takes the hold-all statement.
29190
+ * The type admits no fourth kind, but this decides what is destroyed, and the
29191
+ * direction an unforeseen value falls has to be holding.
29192
+ */
29193
+ candidates(lane, cutoff, limit) {
29194
+ 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 });
29195
+ return rows;
29196
+ }
29197
+ countHeldBySync(lane, cutoff) {
29198
+ if (lane.kind === "sweep") return 0;
29199
+ const row = lane.kind === "hold-keys" ? this.heldByScopeStmt.get({ cutoff, scopeKeys: JSON.stringify(lane.keys) }) : this.heldBySyncStmt.get({ cutoff });
28762
29200
  return row.n;
28763
29201
  }
28764
29202
  };
29203
+ function laneOf(gate2) {
29204
+ if (gate2 === true) return SWEEP;
29205
+ if (gate2 === false) return HOLD_ALL;
29206
+ return gate2;
29207
+ }
28765
29208
 
28766
29209
  // ../../packages/persistence/src/repositories/capture-status.ts
28767
29210
  var STATUS_LOOKBACK_ROWS = 128;
@@ -29670,6 +30113,8 @@ function toFlatFindingRow(r) {
29670
30113
  repo: r.repo ?? "",
29671
30114
  file: r.file ?? "",
29672
30115
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
30116
+ ...r.line === null ? {} : { line: r.line },
30117
+ ...r.col === null ? {} : { col: r.col },
29673
30118
  eventId: r.event_id,
29674
30119
  ...r.session_id === null ? {} : { sessionId: r.session_id },
29675
30120
  status: deriveInstanceStatus(r),
@@ -29747,7 +30192,8 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
29747
30192
  ${latestResolutionStatusSql("f")} AS latest_status,
29748
30193
  e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
29749
30194
  e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
29750
- e.outbox_owed AS outbox_owed`;
30195
+ e.outbox_owed AS outbox_owed,
30196
+ f.line AS line, f.col AS col`;
29751
30197
  var DAY_MS3 = 864e5;
29752
30198
  var SqliteFindingsRepository = class {
29753
30199
  constructor(db) {
@@ -30170,6 +30616,27 @@ var SqliteFindingsRepository = class {
30170
30616
  ).get(id);
30171
30617
  return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
30172
30618
  }
30619
+ /**
30620
+ * One finding's excerpt source (see FindingContextSource). A primary-key
30621
+ * seek, like `findingInstance`, and the only findings read that touches the
30622
+ * event's text — which is why the list never projects the excerpt and the
30623
+ * drawer asks for it here, one finding at a time.
30624
+ */
30625
+ findingContextSource(id) {
30626
+ const row = this.db.prepare(
30627
+ `SELECT f.context AS context, e.content AS content,
30628
+ f.span_start AS spanStart, f.span_end AS spanEnd,
30629
+ d.rule_id AS ruleId, d.category AS category,
30630
+ json_extract(e.attributes, '$.whole_file') AS wholeFile,
30631
+ e.tool_name AS toolName, e.event_type AS eventType
30632
+ FROM inspection_findings f
30633
+ JOIN audit_events e ON e.id = f.audit_event_id
30634
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30635
+ WHERE f.id = ?`
30636
+ ).get(id);
30637
+ if (row === void 0) return null;
30638
+ return { ...row, wholeFile: row.wholeFile === 1 };
30639
+ }
30173
30640
  /**
30174
30641
  * The one statement both instance-level scans run: every finding in scope,
30175
30642
  * joined to its event and definition, newest first.
@@ -30306,6 +30773,61 @@ var SqliteFindingsRepository = class {
30306
30773
  ])
30307
30774
  );
30308
30775
  }
30776
+ /**
30777
+ * The Findings page's summary strip: whole-store counts over exactly the rows
30778
+ * the instance reads list (the four capture kinds), each equal to what
30779
+ * listFindingInstances totals for the same filters — see FindingsOverview.
30780
+ *
30781
+ * ONE grouped aggregate whose keys are the raw classifier inputs, not the
30782
+ * answers: the statement groups by the three inputs deriveFindingStatus
30783
+ * reads, and each group is then classified here by that same function. So
30784
+ * SQL never restates the status rule, and the strip cannot disagree with the
30785
+ * list about which status a finding has. The group count is bounded by a
30786
+ * handful of status inputs, not by the store, so only the scan grows with it
30787
+ * — the same linear cost every other unscoped read on the page already pays.
30788
+ *
30789
+ * The definitions join selects nothing. It is there because the list's scan
30790
+ * joins it too, so a finding whose definition row is missing is left out of
30791
+ * both rather than counted here and absent there.
30792
+ *
30793
+ * The latest-resolution join is the derived-table form, which
30794
+ * resolution-sql.ts recommends for an aggregate over many findings.
30795
+ */
30796
+ findingsOverview() {
30797
+ const rows = allRows(
30798
+ this.db.prepare(
30799
+ `SELECT e.event_type AS kind, (f.finding_key IS NOT NULL) AS keyed,
30800
+ latest.status AS latest_status, count(*) AS c
30801
+ FROM inspection_findings f
30802
+ JOIN audit_events e ON e.id = f.audit_event_id
30803
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30804
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30805
+ ON latest.finding_key = f.finding_key
30806
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30807
+ GROUP BY e.event_type, keyed, latest.status`
30808
+ )
30809
+ );
30810
+ const byStatus = {
30811
+ open: 0,
30812
+ handled: 0,
30813
+ resolved: 0,
30814
+ dismissed: 0
30815
+ };
30816
+ let findings = 0;
30817
+ for (const row of rows) {
30818
+ const status = deriveFindingStatus({
30819
+ kind: row.kind,
30820
+ // The classifier only asks whether a key exists, never what it is. The
30821
+ // stand-in is non-empty so a truthiness test of the key reads it as
30822
+ // present, exactly as it would a real one.
30823
+ findingKey: row.keyed ? "keyed" : null,
30824
+ latestResolutionStatus: row.latest_status
30825
+ });
30826
+ findings += row.c;
30827
+ byStatus[status] += row.c;
30828
+ }
30829
+ return Promise.resolve({ findings, ...byStatus });
30830
+ }
30309
30831
  healthSummary() {
30310
30832
  const total = countScalar(
30311
30833
  this.db,
@@ -30433,12 +30955,13 @@ var SqliteInspectionFindingsRepository = class {
30433
30955
  `INSERT INTO inspection_findings
30434
30956
  (id, audit_event_id, inspection_definition_id, classified_data_id,
30435
30957
  span_start, span_end, masked_match, action_taken, confidence,
30436
- finding_key, first_detected_at)
30958
+ finding_key, first_detected_at, line, col, context)
30437
30959
  VALUES
30438
30960
  (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
30439
30961
  :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
30440
30962
  :findingKey,
30441
- COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
30963
+ COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)),
30964
+ :line, :col, :context)
30442
30965
  ON CONFLICT(id) DO UPDATE SET
30443
30966
  inspection_definition_id = excluded.inspection_definition_id
30444
30967
  ON CONFLICT (finding_key) DO UPDATE SET
@@ -30449,7 +30972,10 @@ var SqliteInspectionFindingsRepository = class {
30449
30972
  span_end = excluded.span_end,
30450
30973
  masked_match = excluded.masked_match,
30451
30974
  action_taken = excluded.action_taken,
30452
- confidence = excluded.confidence`
30975
+ confidence = excluded.confidence,
30976
+ line = excluded.line,
30977
+ col = excluded.col,
30978
+ context = excluded.context`
30453
30979
  );
30454
30980
  this.sessionDupStmt = db.prepare(
30455
30981
  `SELECT 1 FROM inspection_findings f
@@ -30499,7 +31025,10 @@ var SqliteInspectionFindingsRepository = class {
30499
31025
  actionTaken: row.actionTaken,
30500
31026
  confidence: row.confidence,
30501
31027
  findingKey: row.findingKey,
30502
- firstDetectedAt: row.firstDetectedAt
31028
+ firstDetectedAt: row.firstDetectedAt,
31029
+ line: row.line,
31030
+ col: row.col,
31031
+ context: row.context
30503
31032
  })
30504
31033
  );
30505
31034
  }
@@ -30865,8 +31394,8 @@ var SqliteInstalledPacksRepository = class {
30865
31394
  this.db = db;
30866
31395
  this.baseDir = baseDir;
30867
31396
  this.insertMissingStmt = db.prepare(
30868
- `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
30869
- VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
31397
+ `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31398
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
30870
31399
  ON CONFLICT (namespace, pack_id) DO NOTHING`
30871
31400
  );
30872
31401
  this.upsertAvailableStmt = db.prepare(
@@ -30926,7 +31455,10 @@ var SqliteInstalledPacksRepository = class {
30926
31455
  version: pack.version,
30927
31456
  name: pack.name,
30928
31457
  rulesJson: JSON.stringify(pack.rules),
30929
- ruleIds: new Set(pack.rules.map((r) => r.id))
31458
+ ruleIds: new Set(pack.rules.map((r) => r.id)),
31459
+ // Only a first install takes it: an existing row is never modified here,
31460
+ // so a policy the user chose (or cleared) is never overwritten.
31461
+ defaultPolicyId: pack.defaultPolicyId ?? null
30930
31462
  }));
30931
31463
  if (this.storedSignature() === inventorySignature(rows)) return;
30932
31464
  const now = Date.now();
@@ -30955,7 +31487,7 @@ var SqliteInstalledPacksRepository = class {
30955
31487
  } else {
30956
31488
  behind = true;
30957
31489
  }
30958
- this.insertMissingStmt.run(params);
31490
+ this.insertMissingStmt.run({ ...params, policyId: row.defaultPolicyId });
30959
31491
  }
30960
31492
  if (!behind) this.pruneAvailable(rows.map((r) => `${r.namespace}/${r.packId}`));
30961
31493
  },
@@ -31073,7 +31605,8 @@ var SqliteInstalledPacksRepository = class {
31073
31605
  rejectedRules: [],
31074
31606
  ruleActions: /* @__PURE__ */ new Map(),
31075
31607
  ruleVersions: /* @__PURE__ */ new Map(),
31076
- reversibleRules: /* @__PURE__ */ new Set()
31608
+ reversibleRules: /* @__PURE__ */ new Set(),
31609
+ assignedRules: /* @__PURE__ */ new Set()
31077
31610
  };
31078
31611
  const reject = (pack, ruleId, reason) => {
31079
31612
  if (out.rejectedRules.length >= REJECTED_RULE_DETAIL_CAP) return;
@@ -31106,6 +31639,8 @@ var SqliteInstalledPacksRepository = class {
31106
31639
  out.ruleVersions.set(parsed2.data.id, row.version);
31107
31640
  if (reversible) out.reversibleRules.add(parsed2.data.id);
31108
31641
  else out.reversibleRules.delete(parsed2.data.id);
31642
+ if (row.policyId !== null) out.assignedRules.add(parsed2.data.id);
31643
+ else out.assignedRules.delete(parsed2.data.id);
31109
31644
  } else {
31110
31645
  out.invalidRules += 1;
31111
31646
  reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
@@ -32192,6 +32727,7 @@ var SqliteInventoryAssetsRepository = class {
32192
32727
 
32193
32728
  // ../../packages/persistence/src/repositories/policies.ts
32194
32729
  import { randomUUID as randomUUID6 } from "crypto";
32730
+ var SEED_BATCH_WINDOW_MS = 6e4;
32195
32731
  var SqlitePoliciesRepository = class {
32196
32732
  constructor(db) {
32197
32733
  this.db = db;
@@ -32213,39 +32749,123 @@ var SqlitePoliciesRepository = class {
32213
32749
  });
32214
32750
  return Promise.resolve(policies);
32215
32751
  }
32216
- // Seed one policy per bundled category from DEFAULT_ACTIONS so the
32217
- // detection-type config exists from first run. Only when the table is empty,
32218
- // so a user's edits are never clobbered.
32752
+ // Seed one policy per bundled category at Monitor so the detection-type config
32753
+ // exists from first run. An unassigned pack's rules follow these rows, so
32754
+ // Monitor here is the posture of every pack that ships no defaultPolicy; a pack
32755
+ // that ships one carries its own assignment instead. Only when the
32756
+ // table is empty, so a user's edits are never clobbered.
32219
32757
  seedDefaults() {
32220
32758
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32221
- if (count > 0) return;
32759
+ if (count > 0) {
32760
+ this.markEarlierChoices();
32761
+ this.monitorUntouchedSeeds();
32762
+ return;
32763
+ }
32222
32764
  const stmt = this.db.prepare(
32223
32765
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
32224
32766
  VALUES (:id, 'global', :target, :action, 1, :now, :now)`
32225
32767
  );
32226
32768
  failOpenTransaction(this.db, () => {
32227
- for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
32769
+ for (const category of Object.keys(DEFAULT_ACTIONS)) {
32228
32770
  stmt.run({
32229
32771
  id: randomUUID6(),
32230
32772
  target: JSON.stringify({ category }),
32231
- action,
32773
+ action: "log",
32232
32774
  now: Date.now()
32233
32775
  });
32234
32776
  }
32235
32777
  });
32236
32778
  }
32779
+ // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32780
+ // equal to created_at, so a choice made for a category that had no row yet
32781
+ // (one added in a release after the store was seeded) looks exactly like a
32782
+ // seed. Left alone, fill-gaps would overwrite it and monitorUntouchedSeeds
32783
+ // could reset it. This pass marks such rows as chosen (updated_at =
32784
+ // created_at + 1) before either can read them. A row is an earlier build's
32785
+ // choice, not its seed, when either:
32786
+ // - its action is neither the old seed value (DEFAULT_ACTIONS) nor Monitor,
32787
+ // which no seed of any build ever wrote; or
32788
+ // - it was created well after the seed batch. Every build seeds all of its
32789
+ // categories in one transaction, and only into an empty table, so a row
32790
+ // created later came from upsertCategoryAction.
32791
+ // It needs no marker of its own: every row this build writes has updated_at >
32792
+ // created_at, and the seeds it leaves equal (fresh 'log' seeds, and seeds
32793
+ // moved to Monitor below, which keep their created_at) match neither test, so
32794
+ // after one pass it finds nothing and stays a read. What it cannot tell apart
32795
+ // is an earlier build's choice that equals the seed value AND was made within
32796
+ // the seed batch window; that row is read as a seed.
32797
+ markEarlierChoices() {
32798
+ const rows = allRows(
32799
+ this.db.prepare(
32800
+ `SELECT id, json_extract(target, '$.category') AS category, action,
32801
+ created_at AS c, updated_at AS u
32802
+ FROM policies
32803
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL`
32804
+ )
32805
+ );
32806
+ if (rows.length === 0) return;
32807
+ const seedBatchStart = Math.min(...rows.map((row) => row.c));
32808
+ const seeded = DEFAULT_ACTIONS;
32809
+ const choices = rows.filter(
32810
+ (row) => row.u === row.c && (row.action !== "log" && row.action !== seeded[row.category] || row.c > seedBatchStart + SEED_BATCH_WINDOW_MS)
32811
+ );
32812
+ if (choices.length === 0) return;
32813
+ const stmt = this.db.prepare(
32814
+ `UPDATE policies SET updated_at = created_at + 1 WHERE id = :id AND updated_at = created_at`
32815
+ );
32816
+ failOpenTransaction(this.db, () => {
32817
+ for (const row of choices) stmt.run({ id: row.id });
32818
+ });
32819
+ }
32820
+ // Stores seeded by an earlier build hold DEFAULT_ACTIONS in their category
32821
+ // rows. Those rows used to be shadowed by the Monitor every unassigned pack
32822
+ // emitted; now that unassigned packs defer to them, an untouched one would
32823
+ // turn Monitor into Warn on upgrade with nobody having asked. So a row still
32824
+ // exactly as seeded — the seeded action, never updated since it was created —
32825
+ // is moved to Monitor. A row the user, the setup wizard or the warn-era cap
32826
+ // ever wrote has a later updated_at and is left alone. updated_at is NOT
32827
+ // advanced, so a moved row still reads as an untouched seed (see
32828
+ // isCategoryChosen); it never matches again because it is no longer off 'log'.
32829
+ // One knock-on: when the installed snapshot is unusable (corrupt rules_json)
32830
+ // the gateway falls back to the bundled packs with no per-rule policies, so
32831
+ // every rule follows these rows. On an upgraded store that fallback now
32832
+ // monitors where the earlier build warned.
32833
+ monitorUntouchedSeeds() {
32834
+ const untouched = allRows(
32835
+ this.db.prepare(
32836
+ `SELECT json_extract(target, '$.category') AS category, action FROM policies
32837
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL
32838
+ AND action <> 'log' AND updated_at = created_at`
32839
+ )
32840
+ ).filter(
32841
+ (row) => DEFAULT_ACTIONS[row.category] === row.action
32842
+ );
32843
+ if (untouched.length === 0) return;
32844
+ const stmt = this.db.prepare(
32845
+ `UPDATE policies SET action = 'log'
32846
+ WHERE scope = 'global' AND json_extract(target, '$.category') = :category
32847
+ AND action = :seeded AND action <> 'log' AND updated_at = created_at`
32848
+ );
32849
+ failOpenTransaction(this.db, () => {
32850
+ for (const row of untouched) {
32851
+ stmt.run({ category: row.category, seeded: row.action });
32852
+ }
32853
+ });
32854
+ }
32237
32855
  // Insert-or-update the single global per-category policy row, keyed on the
32238
32856
  // existing uq_policies_scope_target unique index (scope, target). `action`
32239
32857
  // uses the SAME vocabulary seedDefaults writes (DEFAULT_ACTIONS' ActionTaken
32240
32858
  // values), so the runtime's resolveAction reads rows written by either path
32241
32859
  // identically. On conflict, `action`, `enabled`, and `updated_at` are updated;
32242
- // `id` and `created_at` are left exactly as they were.
32860
+ // `id` and `created_at` are left exactly as they were. Either way updated_at
32861
+ // ends up later than created_at, which is what marks the row as chosen.
32243
32862
  upsertCategoryAction(category, action) {
32244
32863
  const now = Date.now();
32245
32864
  this.db.prepare(
32246
32865
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
32247
- VALUES (:id, 'global', :target, :action, 1, :now, :now)
32248
- ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
32866
+ VALUES (:id, 'global', :target, :action, 1, :now, :now + 1)
32867
+ ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32868
+ updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32249
32869
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32250
32870
  }
32251
32871
  // Caps every global per-category policy currently set to block/redact down
@@ -32259,6 +32879,16 @@ var SqlitePoliciesRepository = class {
32259
32879
  ).run({ now: Date.now() });
32260
32880
  return Number(info.changes);
32261
32881
  }
32882
+ // Whether the category's row was ever written after it was created — by the
32883
+ // user, the setup wizard or a cap. A row still as seeded (updated_at equal to
32884
+ // created_at) is not a choice, so a posture filling gaps may replace it.
32885
+ isCategoryChosen(category) {
32886
+ const row = this.db.prepare(
32887
+ `SELECT created_at AS c, updated_at AS u FROM policies
32888
+ WHERE scope='global' AND json_extract(target,'$.category') = :category`
32889
+ ).get({ category });
32890
+ return row !== void 0 && row.u !== row.c;
32891
+ }
32262
32892
  // Read the current action for a single global per-category policy row, mirroring
32263
32893
  // upsertCategoryAction's category-lookup predicate. Returns undefined when no
32264
32894
  // row exists yet, so callers can distinguish an unset category from a set one.
@@ -34504,6 +35134,11 @@ var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
34504
35134
  function linkHost(input2, hostId) {
34505
35135
  return hostId ? { ...input2, hostId } : input2;
34506
35136
  }
35137
+ function captureAttributesOf(event, scopeKey) {
35138
+ const attributes = toCaptureAttributes(event);
35139
+ if (scopeKey === void 0 || scopeKey === "") return attributes;
35140
+ return { ...attributes, scope_key: scopeKey };
35141
+ }
34507
35142
  function closeQuietly(db) {
34508
35143
  try {
34509
35144
  db.close();
@@ -34689,7 +35324,7 @@ function openLocalDatabase(dir, options = {}) {
34689
35324
  );
34690
35325
  return dismissed;
34691
35326
  }
34692
- function recordCapture(event, detected) {
35327
+ function recordCapture(event, detected, scopeKey) {
34693
35328
  failOpenTransaction(db, () => {
34694
35329
  const sessionId = event.metadata?.sessionId;
34695
35330
  if (sessionId) {
@@ -34704,7 +35339,7 @@ function openLocalDatabase(dir, options = {}) {
34704
35339
  rootSessionId: sessionId,
34705
35340
  content: event.content,
34706
35341
  contentHash: event.contentHash,
34707
- attributes: toCaptureAttributes(event)
35342
+ attributes: captureAttributesOf(event, scopeKey)
34708
35343
  });
34709
35344
  const definitionIds = /* @__PURE__ */ new Map();
34710
35345
  for (const finding of detected) {
@@ -34734,7 +35369,12 @@ function openLocalDatabase(dir, options = {}) {
34734
35369
  maskedMatch: finding.maskedMatch,
34735
35370
  actionTaken: finding.actionTaken,
34736
35371
  confidence: finding.confidence,
34737
- findingKey: finding.findingKey ?? void 0
35372
+ findingKey: finding.findingKey ?? void 0,
35373
+ ...finding.location === void 0 ? {} : {
35374
+ line: finding.location.line,
35375
+ col: finding.location.col,
35376
+ context: finding.location.context
35377
+ }
34738
35378
  });
34739
35379
  }
34740
35380
  });
@@ -34910,22 +35550,54 @@ function trimSlashes(path) {
34910
35550
  while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
34911
35551
  return path.slice(start, end);
34912
35552
  }
34913
- function canonicalGitUrl(url2) {
35553
+ function parseGitRemote(url2) {
34914
35554
  const trimmed = url2.trim();
34915
- if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
35555
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return void 0;
34916
35556
  const scheme = SCHEME_FORM.exec(trimmed);
34917
35557
  const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
34918
35558
  const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
34919
- if (host === void 0) return trimmed;
34920
- const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
34921
- const bare = trimSlashes(path);
34922
- const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
34923
- return cleaned === "" ? host : `${host}/${cleaned}`;
35559
+ if (host === void 0) return void 0;
35560
+ const bare = trimSlashes((scheme === null ? scp?.[2] : scheme[2]) ?? "");
35561
+ return { host, path: bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare };
35562
+ }
35563
+ function canonicalGitUrl(url2) {
35564
+ const remote = parseGitRemote(url2);
35565
+ if (remote === void 0) return url2.trim();
35566
+ return remote.path === "" ? remote.host : `${remote.host}/${remote.path}`;
34924
35567
  }
34925
35568
  function hashProjectKey(projectKey) {
34926
35569
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
34927
35570
  return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
34928
35571
  }
35572
+ var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35573
+ var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
35574
+ var SKIPPED_USERINFO = /^([^@/]+)@/;
35575
+ var ENDS_AUTHORITY = /[?#\\]/;
35576
+ var PLAIN_HOST = /^[A-Za-z0-9._-]+$/;
35577
+ var QUERY_OR_FRAGMENT = /[?#]/;
35578
+ function namesTheHostGitContacts(url2, host) {
35579
+ if (!PLAIN_HOST.test(host)) return false;
35580
+ const trimmed = url2.trim();
35581
+ const scheme = URL_SCHEME.exec(trimmed);
35582
+ if (scheme === null) {
35583
+ const userinfo2 = SKIPPED_USERINFO.exec(trimmed)?.[1];
35584
+ return !userinfo2?.includes(":");
35585
+ }
35586
+ if (!SCHEME_FORM.test(trimmed)) return false;
35587
+ const userinfo = SKIPPED_USERINFO.exec(trimmed.slice(scheme[0].length))?.[1];
35588
+ return userinfo === void 0 || !ENDS_AUTHORITY.test(userinfo);
35589
+ }
35590
+ function canonicalRepoUrl(url2) {
35591
+ const remote = parseGitRemote(url2);
35592
+ if (remote === void 0 || !namesTheHostGitContacts(url2, remote.host)) return void 0;
35593
+ const path = trimSlashes(remote.path);
35594
+ if (path === "" || QUERY_OR_FRAGMENT.test(path)) return void 0;
35595
+ const key = `${remote.host}/${path}`;
35596
+ return SCOPE_KEY.safeParse(key).success ? key : void 0;
35597
+ }
35598
+ function scopeKeyOfProjectKey(projectKey) {
35599
+ return projectKey.startsWith("git:") ? canonicalRepoUrl(projectKey.slice("git:".length)) : void 0;
35600
+ }
34929
35601
  function toIngestHit(hit) {
34930
35602
  return {
34931
35603
  host: hit.host,
@@ -35744,6 +36416,23 @@ var WEBHOOK_URL = new RegExp(
35744
36416
  ).join("|")}))[^\\s'"\`<>()[\\]{},;]+`,
35745
36417
  "gi"
35746
36418
  );
36419
+ function lineStartOffsets(text) {
36420
+ const starts = [0];
36421
+ for (let i = 0; i < text.length; i += 1) {
36422
+ if (text[i] === "\n") starts.push(i + 1);
36423
+ }
36424
+ return starts;
36425
+ }
36426
+ function lineIndexAt(starts, offset) {
36427
+ let low = 0;
36428
+ let high = starts.length - 1;
36429
+ while (low < high) {
36430
+ const mid = Math.ceil((low + high) / 2);
36431
+ if ((starts[mid] ?? 0) <= offset) low = mid;
36432
+ else high = mid - 1;
36433
+ }
36434
+ return low;
36435
+ }
35747
36436
 
35748
36437
  // ../../packages/detections/src/escape-regexp.ts
35749
36438
  function escapeRegExp2(value) {
@@ -36031,10 +36720,10 @@ function isCorroborated(candidate, candidates, text, normalization) {
36031
36720
  }
36032
36721
  return false;
36033
36722
  }
36034
- function buildCandidates(matchText, ruleset, extension) {
36723
+ function buildCandidates(matchText, ruleset, extension, eventKind) {
36035
36724
  const candidates = [];
36036
36725
  for (const rule of ruleset) {
36037
- if (!ruleApplies(rule, extension)) continue;
36726
+ if (!ruleApplies(rule, extension, eventKind)) continue;
36038
36727
  const spans = MATCHERS[rule.matcher.type](matchText, rule);
36039
36728
  for (const span of spans) {
36040
36729
  const rawMatch = matchText.slice(span.start, span.end);
@@ -36144,22 +36833,30 @@ function extensionOf(filePath) {
36144
36833
  const dot = base.lastIndexOf(".");
36145
36834
  return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
36146
36835
  }
36147
- function ruleApplies(rule, extension) {
36148
- if (!rule.appliesTo || extension === void 0) return true;
36149
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
36836
+ function ruleApplies(rule, extension, eventKind) {
36837
+ const scope = rule.appliesTo;
36838
+ if (!scope) return true;
36839
+ if (scope.eventKinds && (eventKind === void 0 || !scope.eventKinds.some((k) => k === eventKind))) {
36840
+ return false;
36841
+ }
36842
+ if (!scope.extensions || extension === void 0) return true;
36843
+ return scope.extensions.some((e) => e.toLowerCase() === extension);
36150
36844
  }
36151
36845
  function scan(text, rules, context) {
36152
36846
  const ruleset = rules ?? getLoadedRules();
36153
36847
  const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
36154
36848
  const normalization = normalizeFormatChars(text);
36155
- const originalCandidates = buildCandidates(text, ruleset, extension);
36849
+ const originalCandidates = buildCandidates(text, ruleset, extension, context?.eventKind);
36156
36850
  if (!normalization) return gate(originalCandidates, text, void 0);
36157
36851
  const pooledOriginal = originalCandidates.map(
36158
36852
  (candidate) => withNormalizedSpan(candidate, normalization)
36159
36853
  );
36160
- const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
36161
- (candidate) => mapCandidateToOriginal(candidate, normalization, text)
36162
- );
36854
+ const normalizedCandidates = buildCandidates(
36855
+ normalization.normalized,
36856
+ ruleset,
36857
+ extension,
36858
+ context?.eventKind
36859
+ ).map((candidate) => mapCandidateToOriginal(candidate, normalization, text));
36163
36860
  const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
36164
36861
  return mergeOverlappingSameRule(findings, text);
36165
36862
  }
@@ -36196,6 +36893,47 @@ function redact(text, findings) {
36196
36893
  return result;
36197
36894
  }
36198
36895
 
36896
+ // ../../packages/detections/src/evidence.ts
36897
+ var BUNDLED_CODE_EVIDENCE = /* @__PURE__ */ new Set([
36898
+ "code-flaws/auth-jwt-no-verify",
36899
+ "code-flaws/auth-ssl-verify-false",
36900
+ "code-flaws/cmd-inject-exec",
36901
+ "code-flaws/cmd-inject-node-exec",
36902
+ "code-flaws/cmd-inject-shell",
36903
+ "code-flaws/crypto-insecure-random",
36904
+ "code-flaws/crypto-weak-hash-md5",
36905
+ "code-flaws/crypto-weak-hash-sha1",
36906
+ "code-flaws/deser-java-ois",
36907
+ "code-flaws/deser-pickle",
36908
+ "code-flaws/deser-yaml-unsafe",
36909
+ "code-flaws/dev-debug-enabled",
36910
+ "code-flaws/dev-wildcard-cors",
36911
+ "code-flaws/eval-dynamic-exec",
36912
+ "code-flaws/path-traversal-join",
36913
+ "code-flaws/path-traversal-open",
36914
+ "code-flaws/prototype-pollution-merge",
36915
+ "code-flaws/regex-redos-backtrack",
36916
+ "code-flaws/sql-inject-concat",
36917
+ "code-flaws/sql-inject-concat-dot",
36918
+ "code-flaws/sql-inject-format",
36919
+ "code-flaws/sql-inject-interp",
36920
+ "code-flaws/ssrf-user-url",
36921
+ "code-flaws/xss-dangerously-set",
36922
+ "code-flaws/xss-inner-html",
36923
+ "code-flaws/xss-unescaped-render"
36924
+ ]);
36925
+ var VALUE_CATEGORIES = /* @__PURE__ */ new Set([
36926
+ "secret",
36927
+ "pii",
36928
+ "financial",
36929
+ "phi"
36930
+ ]);
36931
+ function ruleEvidence(rule) {
36932
+ if (rule.category !== void 0 && VALUE_CATEGORIES.has(rule.category)) return "value";
36933
+ if (rule.evidence !== void 0) return rule.evidence;
36934
+ return BUNDLED_CODE_EVIDENCE.has(rule.id) ? "code" : "value";
36935
+ }
36936
+
36199
36937
  // ../../packages/detections/src/mask.ts
36200
36938
  function maskMatch(raw) {
36201
36939
  if (raw.length <= 5) return "***";
@@ -36364,6 +37102,281 @@ var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].m
36364
37102
  var CPU_CORROBORATION_SHARE = 0.2;
36365
37103
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36366
37104
 
37105
+ // ../../packages/plugin-sdk/src/raw-egress.ts
37106
+ var RawEgressError = class extends Error {
37107
+ // The text as far as masking got it, when the throw came from a verifier that
37108
+ // had already produced one. A caller that must not propagate the throw (the
37109
+ // history walk) blunt-redacts THIS rather than the raw input: starting over
37110
+ // from the raw text discards every span the masker did cover, which for a
37111
+ // value clipped by the window edge is the only redaction it was ever going to
37112
+ // get — the blunt pass splits on whole values and cannot remove a partial run.
37113
+ masked;
37114
+ constructor(message, masked) {
37115
+ super(message);
37116
+ this.name = "RawEgressError";
37117
+ if (masked !== void 0) this.masked = masked;
37118
+ }
37119
+ };
37120
+ var MIN_RAW_LEN = 4;
37121
+ var RAW_RUN_LEN = 8;
37122
+ function carriesRawRun(text, rawValues) {
37123
+ let windows = null;
37124
+ for (const raw of new Set(rawValues)) {
37125
+ if (raw.length < MIN_RAW_LEN) continue;
37126
+ if (raw.length < RAW_RUN_LEN) {
37127
+ if (text.includes(raw)) return true;
37128
+ continue;
37129
+ }
37130
+ if (windows === null) {
37131
+ windows = /* @__PURE__ */ new Set();
37132
+ for (let i = 0; i + RAW_RUN_LEN <= text.length; i += 1) {
37133
+ windows.add(text.slice(i, i + RAW_RUN_LEN));
37134
+ }
37135
+ }
37136
+ if (windows.size === 0) continue;
37137
+ let preview = null;
37138
+ for (let i = 0; i + RAW_RUN_LEN <= raw.length; i += 1) {
37139
+ const window = raw.slice(i, i + RAW_RUN_LEN);
37140
+ if (!windows.has(window)) continue;
37141
+ preview ??= safeMaskedMatch(raw);
37142
+ if (!preview.includes(window)) return true;
37143
+ }
37144
+ }
37145
+ return false;
37146
+ }
37147
+ function safeMaskedMatch(rawMatch) {
37148
+ const masked = maskMatch(rawMatch);
37149
+ if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37150
+ return "***";
37151
+ }
37152
+ return masked;
37153
+ }
37154
+ function assertRawFree(text, rawValues) {
37155
+ if (carriesRawRun(text, rawValues)) {
37156
+ throw new RawEgressError("text contained a raw detected value");
37157
+ }
37158
+ return text;
37159
+ }
37160
+
37161
+ // ../../packages/plugin-sdk/src/finding-context.ts
37162
+ var CONTEXT_RADIUS = 2;
37163
+ var CONTEXT_LINE_MAX = 240;
37164
+ var BACKSTOP_MARGIN = 256;
37165
+ var CONTEXT_MAX_PER_TEXT = 200;
37166
+ var ELLIPSIS = "\u2026";
37167
+ function evidenceLookup(rules) {
37168
+ const byId = new Map(rules.map((rule) => [rule.id, rule]));
37169
+ return (ruleId) => ruleEvidence(byId.get(ruleId) ?? { id: ruleId });
37170
+ }
37171
+ function createFindingLocator(input2) {
37172
+ let prepared;
37173
+ let built = 0;
37174
+ return (hit) => {
37175
+ prepared ??= prepare(input2);
37176
+ const { starts } = prepared;
37177
+ const lineIndex = lineIndexAt(starts, hit.span.start);
37178
+ const lineStart = starts[lineIndex] ?? 0;
37179
+ let context = null;
37180
+ if (input2.backstopRules !== null && built < CONTEXT_MAX_PER_TEXT) {
37181
+ built += 1;
37182
+ try {
37183
+ context = buildContext(input2, prepared, hit, lineIndex);
37184
+ } catch {
37185
+ context = null;
37186
+ }
37187
+ }
37188
+ return { line: lineIndex + 1, col: hit.span.start - lineStart + 1, context };
37189
+ };
37190
+ }
37191
+ function prepare(input2) {
37192
+ const sorted = [...input2.hits].sort((a, b) => a.span.start - b.span.start);
37193
+ const enforced = input2.enforcedHits;
37194
+ const backstopRules = [...input2.backstopRules ?? []];
37195
+ return {
37196
+ starts: lineStartOffsets(input2.text),
37197
+ sorted,
37198
+ longest: sorted.reduce((max, h) => Math.max(max, h.span.end - h.span.start), 0),
37199
+ isValue: (hit) => enforced?.has(hit) === true || input2.evidenceOf(hit.ruleId) !== "code",
37200
+ backstopRules,
37201
+ backstopEvidence: new Map(backstopRules.map((rule) => [rule.id, ruleEvidence(rule)]))
37202
+ };
37203
+ }
37204
+ function buildContext(input2, prepared, hit, lineIndex) {
37205
+ const { text } = input2;
37206
+ const { starts, sorted, longest, isValue } = prepared;
37207
+ const isCode = !isValue(hit);
37208
+ const radius = isCode ? CONTEXT_RADIUS : 0;
37209
+ const hitColumn = hit.span.start - (starts[lineIndex] ?? 0);
37210
+ const segments = [];
37211
+ const firstIndex = Math.max(0, lineIndex - radius);
37212
+ const lastIndex = Math.min(starts.length - 1, lineIndex + radius);
37213
+ for (let index = firstIndex; index <= lastIndex; index += 1) {
37214
+ const lineStart = starts[index] ?? 0;
37215
+ if (index > lineIndex && lineStart >= text.length) break;
37216
+ const next = starts[index + 1];
37217
+ let lineEnd = next === void 0 ? text.length : next - 1;
37218
+ if (lineEnd > lineStart && text.charCodeAt(lineEnd - 1) === 13) lineEnd -= 1;
37219
+ const length = lineEnd - lineStart;
37220
+ const offset = Math.min(
37221
+ Math.max(0, hitColumn - Math.floor(CONTEXT_LINE_MAX / 2)),
37222
+ Math.max(0, length - CONTEXT_LINE_MAX)
37223
+ );
37224
+ const start = lineStart + offset;
37225
+ segments.push({
37226
+ lineIndex: index,
37227
+ start,
37228
+ end: Math.min(lineEnd, start + CONTEXT_LINE_MAX),
37229
+ lineStart,
37230
+ lineEnd
37231
+ });
37232
+ }
37233
+ const regions = [];
37234
+ const rawValues = [];
37235
+ const windowStart = segments[0]?.start ?? hit.span.start;
37236
+ const windowEnd = segments[segments.length - 1]?.end ?? hit.span.end;
37237
+ for (const other of overlapping(sorted, longest, windowStart, windowEnd)) {
37238
+ if (!isValue(other)) continue;
37239
+ regions.push({ start: other.span.start, end: other.span.end, category: other.category });
37240
+ rawValues.push(other.rawMatch);
37241
+ }
37242
+ for (const found of backstop(text, segments, prepared)) {
37243
+ regions.push(found.region);
37244
+ rawValues.push(found.rawMatch);
37245
+ }
37246
+ const merged = mergeRegions(regions);
37247
+ const shown = cutAtValues(segments, lineIndex, valueLinesOf(merged, starts));
37248
+ const lines = [];
37249
+ let match = null;
37250
+ for (const segment of shown) {
37251
+ const rendered = renderSegment(text, segment, merged);
37252
+ lines.push(rendered.text);
37253
+ if (isCode && segment.lineIndex === lineIndex) {
37254
+ const matchEnd = Math.min(hit.span.end, segment.end);
37255
+ const start = rendered.position(hit.span.start, "start");
37256
+ const end = rendered.position(matchEnd, "end");
37257
+ match = end > start ? { line: lineIndex + 1, start, end } : null;
37258
+ }
37259
+ }
37260
+ assertRawFree(lines.join("\n"), rawValues);
37261
+ return {
37262
+ basis: input2.basis,
37263
+ firstLine: (shown[0]?.lineIndex ?? lineIndex) + 1,
37264
+ lines,
37265
+ match
37266
+ };
37267
+ }
37268
+ function valueLinesOf(regions, starts) {
37269
+ const lines = /* @__PURE__ */ new Set();
37270
+ for (const region of regions) {
37271
+ const last = lineIndexAt(starts, Math.max(region.start, region.end - 1));
37272
+ for (let index = lineIndexAt(starts, region.start); index <= last; index += 1) {
37273
+ lines.add(index);
37274
+ }
37275
+ }
37276
+ return lines;
37277
+ }
37278
+ function cutAtValues(segments, lineIndex, valueLines) {
37279
+ if (!segments.some((segment) => valueLines.has(segment.lineIndex))) return [...segments];
37280
+ return segments.filter((segment) => segment.lineIndex === lineIndex);
37281
+ }
37282
+ function overlapping(sorted, longest, start, end) {
37283
+ let low = 0;
37284
+ let high = sorted.length;
37285
+ const floor = start - longest;
37286
+ while (low < high) {
37287
+ const mid = low + high >>> 1;
37288
+ if ((sorted[mid]?.span.start ?? 0) < floor) low = mid + 1;
37289
+ else high = mid;
37290
+ }
37291
+ const out = [];
37292
+ for (let i = low; i < sorted.length; i += 1) {
37293
+ const hit = sorted[i];
37294
+ if (hit === void 0 || hit.span.start >= end) break;
37295
+ if (hit.span.end > start) out.push(hit);
37296
+ }
37297
+ return out;
37298
+ }
37299
+ function backstop(text, segments, prepared) {
37300
+ const { backstopRules: rules, backstopEvidence: evidence } = prepared;
37301
+ if (rules.length === 0) return [];
37302
+ const pieces = [];
37303
+ let joined = "";
37304
+ for (const segment of segments) {
37305
+ const from = Math.max(segment.lineStart, segment.start - BACKSTOP_MARGIN);
37306
+ const to = Math.min(segment.lineEnd, segment.end + BACKSTOP_MARGIN);
37307
+ if (joined.length > 0) joined += "\n";
37308
+ pieces.push({ from, to, at: joined.length });
37309
+ joined += text.slice(from, to);
37310
+ }
37311
+ const out = [];
37312
+ for (const found of scan(joined, rules)) {
37313
+ if ((evidence.get(found.ruleId) ?? "value") === "code") continue;
37314
+ for (const piece of pieces) {
37315
+ const length = piece.to - piece.from;
37316
+ const start = Math.max(found.span.start, piece.at);
37317
+ const end = Math.min(found.span.end, piece.at + length);
37318
+ if (end <= start) continue;
37319
+ out.push({
37320
+ region: {
37321
+ start: piece.from + (start - piece.at),
37322
+ end: piece.from + (end - piece.at),
37323
+ category: found.category
37324
+ },
37325
+ rawMatch: found.rawMatch
37326
+ });
37327
+ }
37328
+ }
37329
+ return out;
37330
+ }
37331
+ function mergeRegions(regions) {
37332
+ const sorted = [...regions].sort((a, b) => a.start - b.start || a.end - b.end);
37333
+ const out = [];
37334
+ for (const region of sorted) {
37335
+ const open3 = out[out.length - 1];
37336
+ if (open3 && region.start < open3.end) open3.end = Math.max(open3.end, region.end);
37337
+ else out.push({ ...region });
37338
+ }
37339
+ return out;
37340
+ }
37341
+ function renderSegment(text, segment, regions) {
37342
+ const pieces = [];
37343
+ let out = segment.start > segment.lineStart ? ELLIPSIS : "";
37344
+ let cursor = segment.start;
37345
+ const emit = (to, replacement) => {
37346
+ const piece = replacement ?? text.slice(cursor, to);
37347
+ pieces.push({
37348
+ from: cursor,
37349
+ to,
37350
+ outFrom: out.length,
37351
+ outTo: out.length + piece.length,
37352
+ redacted: replacement !== null
37353
+ });
37354
+ out += piece;
37355
+ cursor = to;
37356
+ };
37357
+ for (const region of regions) {
37358
+ if (region.end <= segment.start || region.start >= segment.end) continue;
37359
+ const start = Math.max(region.start, segment.start);
37360
+ if (start > cursor) emit(start, null);
37361
+ emit(Math.min(region.end, segment.end), `[REDACTED:${region.category.toUpperCase()}]`);
37362
+ }
37363
+ if (cursor < segment.end) emit(segment.end, null);
37364
+ const body = out.length;
37365
+ if (segment.end < segment.lineEnd) out += ELLIPSIS;
37366
+ const position = (offset, side) => {
37367
+ for (const piece of pieces) {
37368
+ if (offset < piece.from || offset > piece.to) continue;
37369
+ if (piece.redacted) {
37370
+ if (side === "start" && offset === piece.to) continue;
37371
+ return side === "start" ? piece.outFrom : piece.outTo;
37372
+ }
37373
+ return piece.outFrom + (offset - piece.from);
37374
+ }
37375
+ return offset <= segment.start ? pieces[0]?.outFrom ?? 0 : body;
37376
+ };
37377
+ return { text: out, position };
37378
+ }
37379
+
36367
37380
  // ../../rules/code-flaws/auth-jwt-no-verify.json
36368
37381
  var auth_jwt_no_verify_default = {
36369
37382
  specVersion: 1,
@@ -36438,8 +37451,9 @@ var cmd_inject_node_exec_default = {
36438
37451
  severity: "critical",
36439
37452
  matcher: {
36440
37453
  type: "regex",
36441
- pattern: "\\bexec(?:Sync)?\\s*\\(\\s*(?!['\"`])",
36442
- flags: "g"
37454
+ pattern: `(?:\\b(?:(?:node_)?child_process|childProcess|cp)\\s*\\??\\.\\s*|\\brequire\\s*\\(\\s*['"](?:node:)?child_process['"]\\s*\\)\\s*\\??\\.\\s*|(?<![\\w$.]))(exec(?:Sync)?\\s*\\(\\s*)(?!['"\`])`,
37455
+ flags: "g",
37456
+ captureGroup: 1
36443
37457
  },
36444
37458
  requiresNearby: {
36445
37459
  labels: ["input", "request", "param", "argv", "user", "query", "body"],
@@ -36941,6 +37955,120 @@ var xss_unescaped_render_default = {
36941
37955
  }
36942
37956
  };
36943
37957
 
37958
+ // ../../rules/command-risk/credential-file-read.json
37959
+ var credential_file_read_default = {
37960
+ specVersion: 1,
37961
+ id: "command-risk/credential-file-read",
37962
+ name: "Dump of a credential-bearing file",
37963
+ category: "custom",
37964
+ severity: "medium",
37965
+ matcher: {
37966
+ type: "regex",
37967
+ 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"';|&)])`,
37968
+ flags: "gm"
37969
+ },
37970
+ examples: ["cat ~/.zshenv", "cat /tmp/host-auth.json"],
37971
+ appliesTo: {
37972
+ eventKinds: ["tool_use"]
37973
+ }
37974
+ };
37975
+
37976
+ // ../../rules/command-risk/curl-pipe-shell.json
37977
+ var curl_pipe_shell_default = {
37978
+ specVersion: 1,
37979
+ id: "command-risk/curl-pipe-shell",
37980
+ name: "curl/wget piped to a shell",
37981
+ category: "custom",
37982
+ severity: "high",
37983
+ matcher: {
37984
+ type: "regex",
37985
+ 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.-])`,
37986
+ flags: "gm"
37987
+ },
37988
+ examples: [
37989
+ "curl -fsSL https://get.example.dev/install.sh | bash",
37990
+ "wget -qO- https://get.example.dev/setup | sudo sh -s -- --yes"
37991
+ ],
37992
+ appliesTo: {
37993
+ eventKinds: ["tool_use"]
37994
+ }
37995
+ };
37996
+
37997
+ // ../../rules/command-risk/git-force-push.json
37998
+ var git_force_push_default = {
37999
+ specVersion: 1,
38000
+ id: "command-risk/git-force-push",
38001
+ name: "git push --force / -f",
38002
+ category: "custom",
38003
+ severity: "high",
38004
+ matcher: {
38005
+ type: "regex",
38006
+ 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]|$)`,
38007
+ flags: "gm"
38008
+ },
38009
+ examples: ["git push -q -f origin feature-x", "git push --force origin main"],
38010
+ appliesTo: {
38011
+ eventKinds: ["tool_use"]
38012
+ }
38013
+ };
38014
+
38015
+ // ../../rules/command-risk/git-reset-hard.json
38016
+ var git_reset_hard_default = {
38017
+ specVersion: 1,
38018
+ id: "command-risk/git-reset-hard",
38019
+ name: "git reset --hard at command position",
38020
+ category: "custom",
38021
+ severity: "high",
38022
+ matcher: {
38023
+ type: "regex",
38024
+ 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`,
38025
+ flags: "gm"
38026
+ },
38027
+ examples: ["git reset --hard HEAD~1", "cd /tmp/demo-repo && git reset --hard origin/main"],
38028
+ appliesTo: {
38029
+ eventKinds: ["tool_use"]
38030
+ }
38031
+ };
38032
+
38033
+ // ../../rules/command-risk/pkill-broad.json
38034
+ var pkill_broad_default = {
38035
+ specVersion: 1,
38036
+ id: "command-risk/pkill-broad",
38037
+ name: "pkill -f (command-line pattern kill)",
38038
+ category: "custom",
38039
+ severity: "medium",
38040
+ matcher: {
38041
+ type: "regex",
38042
+ 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]`,
38043
+ flags: "gm"
38044
+ },
38045
+ examples: ['pkill -f "Brave Browser"', 'pkill -TERM -f "bun src/main.ts"'],
38046
+ appliesTo: {
38047
+ eventKinds: ["tool_use"]
38048
+ }
38049
+ };
38050
+
38051
+ // ../../rules/command-risk/rm-rf-home-or-shared.json
38052
+ var rm_rf_home_or_shared_default = {
38053
+ specVersion: 1,
38054
+ id: "command-risk/rm-rf-home-or-shared",
38055
+ name: "Recursive rm of home, /Users or a system directory",
38056
+ category: "custom",
38057
+ severity: "high",
38058
+ matcher: {
38059
+ type: "regex",
38060
+ 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"';|&)]|$))`,
38061
+ flags: "gm"
38062
+ },
38063
+ examples: [
38064
+ "rm -rf ~/projects/demo-app/$WORKDIR",
38065
+ "rm -rf ~/worktrees/x ~/.claude-demo/projects/-Users-x"
38066
+ ],
38067
+ appliesTo: {
38068
+ eventKinds: ["tool_use"]
38069
+ }
38070
+ };
38071
+
36944
38072
  // ../../rules/core-code-context/db-table-name.json
36945
38073
  var db_table_name_default = {
36946
38074
  specVersion: 1,
@@ -37017,6 +38145,24 @@ var file_path_default = {
37017
38145
  ]
37018
38146
  };
37019
38147
 
38148
+ // ../../rules/core-code-context/gcp-service-account-email.json
38149
+ var gcp_service_account_email_default = {
38150
+ specVersion: 1,
38151
+ id: "core-code-context/gcp-service-account-email",
38152
+ name: "GCP service account email",
38153
+ category: "code_context",
38154
+ severity: "low",
38155
+ matcher: {
38156
+ type: "regex",
38157
+ pattern: "(?<![a-z0-9-])[a-z0-9-]{3,}@[a-z0-9][a-z0-9-]{2,60}\\.iam\\.gserviceaccount\\.com\\b",
38158
+ flags: "g"
38159
+ },
38160
+ examples: [
38161
+ "deploy-bot@sample-project.iam.gserviceaccount.com",
38162
+ "12345678-1234-1234-1234-123456789012@my-project.iam.gserviceaccount.com"
38163
+ ]
38164
+ };
38165
+
37020
38166
  // ../../rules/core-code-context/internal-domain.json
37021
38167
  var internal_domain_default = {
37022
38168
  specVersion: 1,
@@ -37026,7 +38172,7 @@ var internal_domain_default = {
37026
38172
  severity: "low",
37027
38173
  matcher: {
37028
38174
  type: "regex",
37029
- 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",
38175
+ 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)",
37030
38176
  flags: "gi"
37031
38177
  },
37032
38178
  examples: ["db.internal.com", "app.corp.local", "api.staging.example.com"]
@@ -37041,7 +38187,7 @@ var internal_ip_default = {
37041
38187
  severity: "low",
37042
38188
  matcher: {
37043
38189
  type: "regex",
37044
- 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])",
38190
+ 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)",
37045
38191
  flags: "g"
37046
38192
  },
37047
38193
  examples: ["10.0.0.1", "192.168.1.1", "172.16.0.1"]
@@ -37115,7 +38261,7 @@ var credit_card_default = {
37115
38261
  severity: "critical",
37116
38262
  matcher: {
37117
38263
  type: "regex",
37118
- 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",
38264
+ 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",
37119
38265
  flags: "g"
37120
38266
  },
37121
38267
  postValidators: ["luhn"],
@@ -37238,8 +38384,8 @@ var swift_default = {
37238
38384
  severity: "high",
37239
38385
  matcher: {
37240
38386
  type: "regex",
37241
- pattern: "\\b(?:swift|bic)\\b[\\s#:=-]{0,8}([A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?)\\b",
37242
- flags: "gi",
38387
+ 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",
38388
+ flags: "g",
37243
38389
  captureGroup: 1
37244
38390
  },
37245
38391
  examples: ["SWIFT: BOFAUS3N", "BIC: CHASGB2LXXX"]
@@ -37407,7 +38553,17 @@ var dob_default = {
37407
38553
  },
37408
38554
  requiresNearby: {
37409
38555
  categories: ["pii"],
37410
- labels: ["dob", "date of birth", "birth", "d.o.b"],
38556
+ labels: [
38557
+ "dob",
38558
+ "date of birth",
38559
+ "birth",
38560
+ "d.o.b",
38561
+ "nascimento",
38562
+ "naissance",
38563
+ "nacimiento",
38564
+ "geburtsdatum",
38565
+ "nascita"
38566
+ ],
37411
38567
  windowChars: 160
37412
38568
  },
37413
38569
  examples: ["DOB: 1985-03-22", "Date of birth: 03/22/1985"]
@@ -37476,7 +38632,7 @@ var ip_address_default = {
37476
38632
  severity: "low",
37477
38633
  matcher: {
37478
38634
  type: "regex",
37479
- pattern: "\\b(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\b",
38635
+ 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)",
37480
38636
  flags: "g"
37481
38637
  },
37482
38638
  examples: ["192.168.1.1", "10.0.0.1"]
@@ -37577,7 +38733,7 @@ var phone_intl_default = {
37577
38733
  severity: "high",
37578
38734
  matcher: {
37579
38735
  type: "regex",
37580
- pattern: "\\+\\d{1,3}(?:[-.\\s]\\d{1,14}){1,5}\\b",
38736
+ pattern: "\\+(?=(?:\\D?\\d){8})\\d{1,3}(?:[-.\\s]\\d{1,14}){1,5}\\b",
37581
38737
  flags: "g"
37582
38738
  },
37583
38739
  examples: ["+44 20 7946 0958", "+86 138 0013 8000"]
@@ -37626,7 +38782,7 @@ var vin_default = {
37626
38782
  severity: "medium",
37627
38783
  matcher: {
37628
38784
  type: "regex",
37629
- pattern: "\\b[A-HJ-NPR-Z0-9]{17}\\b",
38785
+ 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",
37630
38786
  flags: "g"
37631
38787
  },
37632
38788
  examples: ["1HGCM82633A004352"]
@@ -37785,7 +38941,7 @@ var generic_high_entropy_secret_default = {
37785
38941
  severity: "high",
37786
38942
  matcher: {
37787
38943
  type: "regex",
37788
- 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})`,
38944
+ 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})`,
37789
38945
  flags: "gi",
37790
38946
  captureGroup: 1
37791
38947
  },
@@ -37839,7 +38995,7 @@ var password_field_default = {
37839
38995
  severity: "high",
37840
38996
  matcher: {
37841
38997
  type: "regex",
37842
- pattern: `["']?\\b(?:password|passwd|pwd|pass|secret|token|api[_-]?key|apikey)\\b["']?\\s*:\\s*["']([^"'\\n]{4,})["']`,
38998
+ pattern: `["']?\\b(?:password|passwd|pwd|pass|secret|token|api[_-]?key|apikey)\\b["']?\\s*:\\s*["'](?!(?:fail|pass|true|false|null|none|string|required)["'])([^"'\\n]{4,})["']`,
37843
38999
  flags: "gi",
37844
39000
  captureGroup: 1
37845
39001
  },
@@ -37872,7 +39028,7 @@ var ssh_private_key_default = {
37872
39028
  severity: "critical",
37873
39029
  matcher: {
37874
39030
  type: "regex",
37875
- pattern: "-----BEGIN (?:RSA |DSA |EC |OPENSSH |SSH2 )?PRIVATE KEY-----",
39031
+ pattern: "-----BEGIN ((?:RSA |DSA |EC |OPENSSH |SSH2 |ENCRYPTED )?)PRIVATE KEY-----(?:(?:[A-Za-z0-9+/=\\s\\\\:,]|-(?!-)){0,8000}?-----END \\1PRIVATE KEY-----)?",
37876
39032
  flags: "g"
37877
39033
  },
37878
39034
  examples: [
@@ -37953,7 +39109,7 @@ var cloudflare_api_key_default = {
37953
39109
  severity: "critical",
37954
39110
  matcher: {
37955
39111
  type: "regex",
37956
- pattern: `cloudflare.{0,40}?["'\\s:=]([A-Za-z0-9_-]{40})`,
39112
+ pattern: `cloudflare.{0,40}?(?<![?&][A-Za-z0-9_]{1,20})(?<!sha(?:1|256|384|512))["'\\s:=]([A-Za-z0-9_-]{40})`,
37957
39113
  flags: "gi",
37958
39114
  captureGroup: 1
37959
39115
  },
@@ -38009,21 +39165,25 @@ var discord_token_default = {
38009
39165
  examples: ["AbCdEfGhIjKlMnOpQrStUvWx.YzAbCd.ABCdEfGhIjKlMnOpQrStUvWxYzAbCdEf"]
38010
39166
  };
38011
39167
 
38012
- // ../../rules/secrets/gcp-service-account.json
38013
- var gcp_service_account_default = {
39168
+ // ../../rules/secrets/gcp-service-account-key.json
39169
+ var gcp_service_account_key_default = {
38014
39170
  specVersion: 1,
38015
- id: "secrets/gcp-service-account",
38016
- name: "GCP service account key",
39171
+ id: "secrets/gcp-service-account-key",
39172
+ name: "GCP service account key file",
38017
39173
  category: "secret",
38018
39174
  severity: "critical",
38019
39175
  matcher: {
38020
39176
  type: "regex",
38021
- pattern: "(?<![a-z0-9-])[a-z0-9-]{3,}@[a-z0-9][a-z0-9-]{2,60}\\.iam\\.gserviceaccount\\.com\\b",
38022
- flags: "g"
39177
+ pattern: '"private_key_id"\\s*:\\s*"([a-f0-9]{40})"',
39178
+ flags: "g",
39179
+ captureGroup: 1
39180
+ },
39181
+ requiresNearby: {
39182
+ labels: ["service_account", "client_email"],
39183
+ windowChars: 400
38023
39184
  },
38024
39185
  examples: [
38025
- "deploy-bot@sample-project.iam.gserviceaccount.com",
38026
- "12345678-1234-1234-1234-123456789012@my-project.iam.gserviceaccount.com"
39186
+ '{"type": "service_account", "project_id": "sample-project", "private_key_id": "0a1b2c3d0a1b2c3d0a1b2c3d0a1b2c3d0a1b2c3d"}'
38027
39187
  ]
38028
39188
  };
38029
39189
 
@@ -38172,6 +39332,24 @@ var stripe_live_key_default = {
38172
39332
  examples: ["sk_live_aBcDeFgHiJkLmNoPqRsTuVwXyZ"]
38173
39333
  };
38174
39334
 
39335
+ // ../../rules/secrets/tailscale-key.json
39336
+ var tailscale_key_default = {
39337
+ specVersion: 1,
39338
+ id: "secrets/tailscale-key",
39339
+ name: "Tailscale auth/API/client key",
39340
+ category: "secret",
39341
+ severity: "critical",
39342
+ matcher: {
39343
+ type: "regex",
39344
+ pattern: "\\btskey-(?:auth|api|client)-(?![Xx]+-)[A-Za-z0-9]{8,32}-[A-Za-z0-9]{16,64}\\b",
39345
+ flags: "g"
39346
+ },
39347
+ examples: [
39348
+ "sudo tailscale up --auth-key=tskey-auth-kAb3Xk9QzCNTRL-Ab3Xk9QzAb3Xk9QzAb3Xk9QzAb3Xk9Qz",
39349
+ "TS_API_KEY=tskey-api-kEXAMPLE1CNTRL-EXAMPLEEXAMPLEEXAMPLEEXAMPLE12"
39350
+ ]
39351
+ };
39352
+
38175
39353
  // ../../rules/secrets/terraform-cloud-token.json
38176
39354
  var terraform_cloud_token_default = {
38177
39355
  specVersion: 1,
@@ -38214,7 +39392,7 @@ var vault_token_default = {
38214
39392
  severity: "critical",
38215
39393
  matcher: {
38216
39394
  type: "regex",
38217
- pattern: "\\b(?:hvs\\.[A-Za-z0-9\\-_]{20,50}|s\\.[A-Za-z0-9\\-_]{20,50})\\b",
39395
+ 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",
38218
39396
  flags: "g"
38219
39397
  },
38220
39398
  postValidators: ["entropy"],
@@ -38259,10 +39437,24 @@ var BUNDLED_PACKS = [
38259
39437
  regex_redos_backtrack_default
38260
39438
  ]
38261
39439
  },
39440
+ {
39441
+ packId: "command-risk",
39442
+ name: "Risky agent commands",
39443
+ version: "0.1.0",
39444
+ defaultPolicy: "warn",
39445
+ rawRules: [
39446
+ pkill_broad_default,
39447
+ rm_rf_home_or_shared_default,
39448
+ git_force_push_default,
39449
+ git_reset_hard_default,
39450
+ curl_pipe_shell_default,
39451
+ credential_file_read_default
39452
+ ]
39453
+ },
38262
39454
  {
38263
39455
  packId: "core-code-context",
38264
39456
  name: "Code Context",
38265
- version: "0.1.0",
39457
+ version: "0.2.1",
38266
39458
  rawRules: [
38267
39459
  internal_ip_default,
38268
39460
  localhost_ref_default,
@@ -38271,13 +39463,14 @@ var BUNDLED_PACKS = [
38271
39463
  stack_trace_default,
38272
39464
  internal_url_default,
38273
39465
  feature_flag_default,
38274
- db_table_name_default
39466
+ db_table_name_default,
39467
+ gcp_service_account_email_default
38275
39468
  ]
38276
39469
  },
38277
39470
  {
38278
39471
  packId: "core-financial",
38279
39472
  name: "Financial Information",
38280
- version: "0.1.0",
39473
+ version: "0.1.1",
38281
39474
  rawRules: [
38282
39475
  credit_card_default,
38283
39476
  iban_default,
@@ -38307,7 +39500,7 @@ var BUNDLED_PACKS = [
38307
39500
  {
38308
39501
  packId: "core-pii",
38309
39502
  name: "Core PII",
38310
- version: "0.2.0",
39503
+ version: "0.2.2",
38311
39504
  rawRules: [
38312
39505
  email_default,
38313
39506
  ssn_default,
@@ -38328,11 +39521,11 @@ var BUNDLED_PACKS = [
38328
39521
  {
38329
39522
  packId: "secrets",
38330
39523
  name: "Secrets & Credentials",
38331
- version: "0.1.0",
39524
+ version: "0.2.0",
39525
+ defaultPolicy: "warn",
38332
39526
  rawRules: [
38333
39527
  aws_access_key_default,
38334
39528
  aws_secret_key_default,
38335
- gcp_service_account_default,
38336
39529
  azure_connection_string_default,
38337
39530
  openai_api_key_default,
38338
39531
  anthropic_api_key_default,
@@ -38350,13 +39543,15 @@ var BUNDLED_PACKS = [
38350
39543
  pulumi_access_token_default,
38351
39544
  terraform_cloud_token_default,
38352
39545
  vault_token_default,
38353
- github_pat_default
39546
+ github_pat_default,
39547
+ gcp_service_account_key_default,
39548
+ tailscale_key_default
38354
39549
  ]
38355
39550
  },
38356
39551
  {
38357
39552
  packId: "secrets-infra",
38358
39553
  name: "Infrastructure Secrets",
38359
- version: "0.1.0",
39554
+ version: "0.1.1",
38360
39555
  rawRules: [
38361
39556
  ssh_private_key_default,
38362
39557
  db_connection_string_default,
@@ -38391,7 +39586,8 @@ function bundledDetections() {
38391
39586
  packId: pack.packId,
38392
39587
  version: pack.version,
38393
39588
  name: pack.name,
38394
- rules: pack.rawRules.map((raw) => Rule.parse(raw))
39589
+ rules: pack.rawRules.map((raw) => Rule.parse(raw)),
39590
+ defaultPolicyId: pack.defaultPolicy
38395
39591
  }));
38396
39592
  return cachedDetections;
38397
39593
  }
@@ -38411,7 +39607,7 @@ function ensureBundledPacks() {
38411
39607
  return false;
38412
39608
  }
38413
39609
  }
38414
- function scanText(text, ruleVersions) {
39610
+ function scanText(text, ruleVersions, options = {}) {
38415
39611
  if (!ensureBundledPacks()) return { masked: "[REDACTED]", findings: [] };
38416
39612
  try {
38417
39613
  const rules = getLoadedRules();
@@ -38419,6 +39615,13 @@ function scanText(text, ruleVersions) {
38419
39615
  const matches = dropShieldedFindings(scan(shielded.text, rules), shielded.spans);
38420
39616
  if (matches.length === 0) return { masked: text, findings: [] };
38421
39617
  const byId = new Map(rules.map((r) => [r.id, r]));
39618
+ const locate = options.locate === true ? createFindingLocator({
39619
+ text,
39620
+ basis: "excerpt",
39621
+ hits: matches,
39622
+ evidenceOf: evidenceLookup(rules),
39623
+ backstopRules: rules
39624
+ }) : void 0;
38422
39625
  const findings = matches.map((m) => {
38423
39626
  const rule = byId.get(m.ruleId);
38424
39627
  return {
@@ -38429,7 +39632,8 @@ function scanText(text, ruleVersions) {
38429
39632
  severity: m.severity,
38430
39633
  span: m.span,
38431
39634
  maskedMatch: maskMatch(m.rawMatch),
38432
- confidence: m.confidence
39635
+ confidence: m.confidence,
39636
+ ...locate === void 0 ? {} : { location: locate(m) }
38433
39637
  };
38434
39638
  });
38435
39639
  return { masked: redact(text, matches), findings };
@@ -38443,22 +39647,44 @@ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as
38443
39647
  import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
38444
39648
  function resolveRepoIdentity(cwd) {
38445
39649
  try {
38446
- const root = findGitRoot(cwd);
38447
- if (!root) return void 0;
38448
- const ctx = resolveGitContext(root);
38449
- const headRoot = ctx?.headRoot ?? root;
38450
- const url2 = ctx ? remoteUrl(ctx) : void 0;
39650
+ const location = locateRepo(cwd);
39651
+ if (!location) return void 0;
38451
39652
  return {
38452
39653
  // The path fallback is normalized to posix separators (a no-op outside
38453
39654
  // win32) so the persistence layer's `/`-separated checkout-path patterns
38454
39655
  // (the ghost sweep + the read-side worktree filter) match it as written.
38455
- url: url2 ?? headRoot.split(sep2).join("/"),
38456
- name: (url2 ? slugFromUrl(url2) : void 0) ?? basename2(headRoot)
39656
+ url: location.remote ?? location.headRoot.split(sep2).join("/"),
39657
+ name: slugOf(location)
38457
39658
  };
38458
39659
  } catch {
38459
39660
  return void 0;
38460
39661
  }
38461
39662
  }
39663
+ var ATTRIBUTION_MEMO_LIMIT = 64;
39664
+ var attributionMemo = /* @__PURE__ */ new Map();
39665
+ var NO_ATTRIBUTION = Object.freeze({});
39666
+ function resolveRepoAttribution(cwd) {
39667
+ try {
39668
+ const remembered = attributionMemo.get(cwd);
39669
+ if (remembered !== void 0) return remembered;
39670
+ const attribution = attributeRepo(cwd);
39671
+ if (attributionMemo.size >= ATTRIBUTION_MEMO_LIMIT) attributionMemo.clear();
39672
+ attributionMemo.set(cwd, attribution);
39673
+ return attribution;
39674
+ } catch {
39675
+ return NO_ATTRIBUTION;
39676
+ }
39677
+ }
39678
+ function attributeRepo(cwd) {
39679
+ const location = locateRepo(cwd);
39680
+ if (!location) return NO_ATTRIBUTION;
39681
+ const remote = isAbsolute(cwd) ? location.remote : void 0;
39682
+ const scopeKey = remote === void 0 ? void 0 : canonicalRepoUrl(remote);
39683
+ return Object.freeze({
39684
+ repo: slugOf(location),
39685
+ ...scopeKey === void 0 ? {} : { scopeKey }
39686
+ });
39687
+ }
38462
39688
  function findGitRoot(start) {
38463
39689
  let dir = start;
38464
39690
  for (; ; ) {
@@ -38502,6 +39728,15 @@ function remoteUrl(ctx) {
38502
39728
  const remotes = parseRemoteUrls(config2);
38503
39729
  return remotes.origin ?? Object.values(remotes)[0];
38504
39730
  }
39731
+ function locateRepo(cwd) {
39732
+ const root = findGitRoot(cwd);
39733
+ if (!root) return void 0;
39734
+ const ctx = resolveGitContext(root);
39735
+ return { headRoot: ctx?.headRoot ?? root, remote: ctx ? remoteUrl(ctx) : void 0 };
39736
+ }
39737
+ function slugOf(location) {
39738
+ return (location.remote ? slugFromUrl(location.remote) : void 0) ?? basename2(location.headRoot);
39739
+ }
38505
39740
  function parseRemoteUrls(config2) {
38506
39741
  const remotes = {};
38507
39742
  let current;
@@ -38627,6 +39862,17 @@ import { join as join23 } from "path";
38627
39862
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
38628
39863
  import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
38629
39864
 
39865
+ // ../../packages/plugin-sdk/src/policy-resolver.ts
39866
+ import { randomUUID as randomUUID14 } from "crypto";
39867
+ function assignedRulePolicies(installed) {
39868
+ const out = [];
39869
+ for (const [ruleId, action] of installed.ruleActions) {
39870
+ if (installed.assignedRules && !installed.assignedRules.has(ruleId)) continue;
39871
+ out.push({ id: randomUUID14(), scope: "global", target: { ruleId }, action, enabled: true });
39872
+ }
39873
+ return out;
39874
+ }
39875
+
38630
39876
  // ../../packages/plugin-sdk/src/project-files.ts
38631
39877
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
38632
39878
  import { basename as basename5, join as join24 } from "path";
@@ -38668,14 +39914,48 @@ function codexProviderFromModelId(modelId) {
38668
39914
  }
38669
39915
 
38670
39916
  // ../../packages/plugin-sdk/src/runtime.ts
38671
- import { randomUUID as randomUUID14 } from "crypto";
39917
+ import { randomUUID as randomUUID15 } from "crypto";
39918
+
39919
+ // ../../packages/plugin-sdk/src/scope-key.ts
39920
+ import { existsSync as existsSync12 } from "fs";
39921
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join25, normalize } from "path";
39922
+ function scopeKeyMemo() {
39923
+ const memo2 = /* @__PURE__ */ new Map();
39924
+ return (cwd) => {
39925
+ if (cwd === void 0) return void 0;
39926
+ if (memo2.has(cwd)) return memo2.get(cwd);
39927
+ const key = resolveRepoAttribution(cwd).scopeKey;
39928
+ memo2.set(cwd, key);
39929
+ return key;
39930
+ };
39931
+ }
39932
+ function sessionRootScopeKey(cwd) {
39933
+ return cwd === void 0 ? void 0 : resolveRepoAttribution(cwd).scopeKey;
39934
+ }
39935
+ function toolCallScopeKey(tc, scopeKeyOf2) {
39936
+ if (tc.keyless === true) return void 0;
39937
+ if (tc.filePaths === void 0 && tc.searchRoot === void 0) return scopeKeyOf2(tc.cwd);
39938
+ const resolved = (path) => isAbsolute2(path) ? normalize(path) : join25(tc.cwd ?? "", path);
39939
+ const walkStart = (path) => isAbsolute2(path) && existsSync12(join25(path, ".git")) ? path : dirname6(path);
39940
+ const locations = [
39941
+ ...(tc.filePaths ?? []).map((path) => walkStart(resolved(path))),
39942
+ ...tc.searchRoot === void 0 ? [] : [resolved(tc.searchRoot)]
39943
+ ];
39944
+ let agreed;
39945
+ for (const location of locations) {
39946
+ const key = scopeKeyOf2(location);
39947
+ if (key === void 0 || agreed !== void 0 && key !== agreed) return void 0;
39948
+ agreed = key;
39949
+ }
39950
+ return agreed;
39951
+ }
38672
39952
 
38673
39953
  // ../../packages/plugin-sdk/src/suppressions.ts
38674
39954
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38675
39955
 
38676
39956
  // ../../packages/plugin-sdk/src/throttle.ts
38677
39957
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38678
- import { join as join25 } from "path";
39958
+ import { join as join26 } from "path";
38679
39959
 
38680
39960
  // ../../packages/remote/src/http.ts
38681
39961
  import { request as httpRequest } from "http";
@@ -39054,10 +40334,10 @@ function withTimeout(promise2, ms) {
39054
40334
 
39055
40335
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
39056
40336
  import { readFileSync as readFileSync17 } from "fs";
39057
- import { join as join26 } from "path";
40337
+ import { join as join27 } from "path";
39058
40338
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
39059
40339
  function forwardDropsPath(dataDir2) {
39060
- return join26(dataDir2, FORWARD_DROPS_FILENAME);
40340
+ return join27(dataDir2, FORWARD_DROPS_FILENAME);
39061
40341
  }
39062
40342
  function recordForwardDrops(dataDir2, count, nowMs) {
39063
40343
  if (count <= 0) return;
@@ -39092,9 +40372,9 @@ function readForwardDrops(dataDir2) {
39092
40372
  }
39093
40373
 
39094
40374
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
39095
- import { randomUUID as randomUUID15 } from "crypto";
40375
+ import { randomUUID as randomUUID16 } from "crypto";
39096
40376
  import { readFile, rename, writeFile } from "fs/promises";
39097
- import { join as join27 } from "path";
40377
+ import { join as join28 } from "path";
39098
40378
  function isInvalidRequest(err) {
39099
40379
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
39100
40380
  }
@@ -39113,7 +40393,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
39113
40393
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
39114
40394
  function createForwardPolicy(deps) {
39115
40395
  const now = deps.now ?? (() => Date.now());
39116
- const file2 = join27(deps.dir, STATE_FILENAME);
40396
+ const file2 = join28(deps.dir, STATE_FILENAME);
39117
40397
  let state = null;
39118
40398
  let loading = null;
39119
40399
  async function readState() {
@@ -39138,7 +40418,7 @@ function createForwardPolicy(deps) {
39138
40418
  state = next;
39139
40419
  try {
39140
40420
  await ensureDataDir(deps.dir);
39141
- const tmp = `${file2}.${randomUUID15()}.tmp`;
40421
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
39142
40422
  await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
39143
40423
  await rename(tmp, file2);
39144
40424
  } catch {
@@ -39205,6 +40485,33 @@ function createForwardPolicy(deps) {
39205
40485
  };
39206
40486
  }
39207
40487
 
40488
+ // ../../packages/plugin-runtime/src/session-root-key.ts
40489
+ function sessionToolIsKeyed(tool) {
40490
+ return !WebSourceTool.safeParse(tool).success;
40491
+ }
40492
+
40493
+ // ../../packages/plugin-runtime/src/attached/scope-strip.ts
40494
+ function withoutScopeKey(event) {
40495
+ const attributes = event.attributes;
40496
+ if (attributes == null || !Object.hasOwn(attributes, "scope_key")) return event;
40497
+ const rest = { ...attributes };
40498
+ delete rest.scope_key;
40499
+ if (Object.keys(rest).length > 0) return { ...event, attributes: rest };
40500
+ const bare = { ...event };
40501
+ delete bare.attributes;
40502
+ return bare;
40503
+ }
40504
+
40505
+ // ../../packages/plugin-runtime/src/attached/scoped-repo.ts
40506
+ function withScopedRepo(event, scopeKey) {
40507
+ const repo = scopeKey.split("/").filter((segment) => segment !== "").pop();
40508
+ if (repo !== void 0) return { ...event, metadata: { ...event.metadata, repo } };
40509
+ if (event.metadata?.repo === void 0) return event;
40510
+ const metadata = { ...event.metadata };
40511
+ delete metadata.repo;
40512
+ return { ...event, metadata };
40513
+ }
40514
+
39208
40515
  // ../../packages/plugin-runtime/src/attached/gateway.ts
39209
40516
  var bundledRulesFlatCache;
39210
40517
  function bundledRulesFlat() {
@@ -39224,14 +40531,176 @@ var AttachedDataGateway = class {
39224
40531
  * what it can from the descriptors it already has.
39225
40532
  */
39226
40533
  remoteInventory = null;
40534
+ /**
40535
+ * The verdict this instance reached for each session ROOT it recorded, keyed
40536
+ * by root id, from the key the local store holds for that root (see
40537
+ * `rootVerdict`). It is what a child row is held to (see `auditVerdict`).
40538
+ *
40539
+ * Per instance on purpose. An instance is resolved per hook process, per
40540
+ * native-host request, and per reconcile or backfill pass, and the
40541
+ * reconcilers record each session's root before its leaves. Never written in
40542
+ * machine mode, where nothing reads it.
40543
+ */
40544
+ rootVerdicts = /* @__PURE__ */ new Map();
40545
+ // ---------------------------------------------------------------------
40546
+ // The scope verdict: whether a row written locally may also be forwarded.
40547
+ // ---------------------------------------------------------------------
40548
+ /**
40549
+ * The one question every forward asks, answered TOTALLY: `'forward'` or
40550
+ * `'local'`, never a throw.
40551
+ *
40552
+ * The key is read INSIDE the guard, through a thunk, because reading it is
40553
+ * part of what can fail: a damaged bag, or a canonicalizer meeting an input
40554
+ * it never expected. A throw out of here would not be neutral. It would
40555
+ * reject `recordCapture` into the runtime's swallow, make the scanner read a
40556
+ * failed write and withhold its ledger commit, or drop a whole reconcile
40557
+ * pass. So a throw is answered `'local'`: the direction that degrades to
40558
+ * standalone behaviour, never to over-forwarding.
40559
+ *
40560
+ * Machine mode answers before any key is read, so a machine attachment pays
40561
+ * nothing for scoping and forwards exactly what it always has.
40562
+ */
40563
+ verdictFor(keyOf) {
40564
+ try {
40565
+ if (this.deps.attachment.mode === "machine") return "forward";
40566
+ return scopeVerdict(this.deps.attachment, keyOf());
40567
+ } catch {
40568
+ return "local";
40569
+ }
40570
+ }
40571
+ /**
40572
+ * The verdict for an audit row, with the session-root rule on top.
40573
+ *
40574
+ * A session ROOT has two halves. What the rows that hang off it are held to is
40575
+ * the key its row holds in the local store, recorded per root (see
40576
+ * `rootVerdict`), not the key on the root event just handed in: roots are
40577
+ * first-write-wins in the store, so when two producers record a root for one
40578
+ * session (the session-start hook, then a reconcile pass) the second leaves
40579
+ * the stored row as it was, and the history drain decides that row, not this
40580
+ * event. Whether this root EVENT is itself sent takes both keys: the stored
40581
+ * one AND its own. The event's attributes (cwd, project, repo) describe where
40582
+ * it was recorded from, so a root event keyed to a personal directory is never
40583
+ * sent under an enrolled stored root, though the enrolled leaves still forward
40584
+ * under it: the instance that wrote the stored root is expected to have
40585
+ * forwarded it. If it did not (the root was written while standalone or under
40586
+ * another attachment, or its forward failed), the plane refuses those leaves
40587
+ * and the history drain ships the root first. Any other row with a root
40588
+ * reference (`rootSessionId`, else `parentId`) forwards only when its own key
40589
+ * is in scope AND this instance recorded an in-scope verdict for that root.
40590
+ * The audit-event route has real foreign keys on both columns and stubs no
40591
+ * missing root, so a leaf sent after its root was kept local is refused
40592
+ * there, and a refused forward counts toward the breaker that guards every
40593
+ * other one. A root this instance never recorded is therefore `'local'`: the
40594
+ * only answer that cannot orphan a row. A row with no root reference at all
40595
+ * has nothing to orphan, and is decided by its own key.
40596
+ *
40597
+ * What this costs is stated rather than discovered. A session whose stored
40598
+ * root is not keyed to an enrolled repository keeps its token and tool
40599
+ * records local, even the ones that ran inside one. A row recorded by an
40600
+ * instance that did not record its root cannot see the root's verdict, so it
40601
+ * stays local on a scoped attachment. Captures are not held to this: their
40602
+ * route plants a missing root itself, so they decide per event.
40603
+ */
40604
+ auditVerdict(event) {
40605
+ try {
40606
+ if (this.deps.attachment.mode === "machine") return "forward";
40607
+ if (event.eventType !== "session") {
40608
+ return this.leafVerdict(event.attributes, rootReferenceOf(event));
40609
+ }
40610
+ if (this.rootVerdict(event.id) === "local") return "local";
40611
+ return this.verdictFor(() => scopeKeyOf(event.attributes));
40612
+ } catch {
40613
+ return "local";
40614
+ }
40615
+ }
40616
+ /**
40617
+ * A session root's verdict, from the key the local store holds for it.
40618
+ *
40619
+ * Read back ONCE per root per instance, after the local write, and recorded.
40620
+ * The write comes first so the row exists and a stub a leaf planted ahead of
40621
+ * it has been healed; the read is the store's answer, which is the first
40622
+ * authoritative root the session ever had. No key, a row that is not a root,
40623
+ * and a store that cannot answer all mean `'local'`: the read happens inside
40624
+ * `verdictFor`'s guard, so a throw is an answer and never a rejection.
40625
+ *
40626
+ * Scoped mode only: `auditVerdict` answers a machine attachment before it
40627
+ * gets here, so a machine attachment pays no store read.
40628
+ */
40629
+ rootVerdict(rootId) {
40630
+ const recorded = this.rootVerdicts.get(rootId);
40631
+ if (recorded !== void 0) return recorded;
40632
+ const verdict = this.verdictFor(() => this.deps.local.readSessionScopeKey(rootId));
40633
+ this.rootVerdicts.set(rootId, verdict);
40634
+ return verdict;
40635
+ }
40636
+ /** A child row's verdict: its own key in scope AND its root's recorded verdict. */
40637
+ leafVerdict(attributes, rootId) {
40638
+ try {
40639
+ if (this.deps.attachment.mode === "machine") return "forward";
40640
+ if (this.verdictFor(() => scopeKeyOf(attributes)) === "local") return "local";
40641
+ if (rootId === void 0) return "forward";
40642
+ return this.rootVerdicts.get(rootId) === "forward" ? "forward" : "local";
40643
+ } catch {
40644
+ return "local";
40645
+ }
40646
+ }
40647
+ /**
40648
+ * The leaves of a batch that may be forwarded, filtered BEFORE `forwardBatch`
40649
+ * and never inside it. That loop tallies everything it does not deliver as a
40650
+ * forward drop, and a row this attachment may not send is not a lost one. Each
40651
+ * leaf is held to its root by the same reference `auditVerdict` uses
40652
+ * (`rootReferenceOf`).
40653
+ * Machine mode hands back the batch itself, so the batch path is exactly what
40654
+ * it was. A throw forwards nothing.
40655
+ */
40656
+ forwardableLeaves(inputs) {
40657
+ try {
40658
+ if (this.deps.attachment.mode === "machine") return inputs;
40659
+ return inputs.filter(
40660
+ (input2) => this.leafVerdict(input2.attributes, rootReferenceOf(input2)) === "forward"
40661
+ );
40662
+ } catch {
40663
+ return [];
40664
+ }
40665
+ }
40666
+ /**
40667
+ * The event `recordCapture` sends for a capture the verdict let through, or
40668
+ * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
40669
+ *
40670
+ * Machine mode sends `record.event` itself, the same object, so a machine
40671
+ * attachment's body is exactly what it was. A scoped attachment sends a COPY
40672
+ * whose `metadata.repo` names the repository of the capture's own key
40673
+ * (`withScopedRepo`). A hook's slug names the session's directory, while a
40674
+ * capture that names a file is keyed by that file's repository, so on a
40675
+ * scoped attachment the slug could otherwise label an enrolled repository's
40676
+ * capture with a personal repository's name. The key here is the one the
40677
+ * verdict just admitted, so the name sent is always an enrolled
40678
+ * repository's.
40679
+ *
40680
+ * A throw sends nothing and leaves the row unmarked, the direction every
40681
+ * fault on this path takes: toward standalone behaviour, never toward
40682
+ * forwarding something unchecked.
40683
+ */
40684
+ captureForWire(record2) {
40685
+ try {
40686
+ if (this.deps.attachment.mode === "machine") return record2.event;
40687
+ const key = record2.scopeKey;
40688
+ return key === void 0 ? void 0 : withScopedRepo(record2.event, key);
40689
+ } catch {
40690
+ return void 0;
40691
+ }
40692
+ }
39227
40693
  // ---------------------------------------------------------------------
39228
40694
  // Writes: local first, then forward.
39229
40695
  // ---------------------------------------------------------------------
39230
40696
  async recordCapture(record2) {
39231
40697
  await this.deps.local.recordCapture(record2);
40698
+ if (this.verdictFor(() => record2.scopeKey) === "local") return;
40699
+ const wireEvent = this.captureForWire(record2);
40700
+ if (wireEvent === void 0) return;
39232
40701
  const forwarded = await this.deps.forward.run(
39233
40702
  () => this.deps.client.ingestEvents({
39234
- events: [record2.event],
40703
+ events: [wireEvent],
39235
40704
  ...record2.dedupe ? { dedupe: record2.dedupe } : {}
39236
40705
  }),
39237
40706
  { decisionPath: true }
@@ -39244,8 +40713,12 @@ var AttachedDataGateway = class {
39244
40713
  }
39245
40714
  async ensureInventory(ctx) {
39246
40715
  const resolved = await this.deps.local.ensureInventory(ctx);
39247
- const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
39248
- this.remoteInventory = remote.ok ? remote.value : null;
40716
+ if (this.verdictFor(() => inventoryKey(ctx)) === "forward") {
40717
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
40718
+ this.remoteInventory = remote.ok ? remote.value : null;
40719
+ } else {
40720
+ this.remoteInventory = null;
40721
+ }
39249
40722
  const snapshot = await (async () => {
39250
40723
  try {
39251
40724
  return await this.deps.posture?.prepare() ?? null;
@@ -39276,6 +40749,7 @@ var AttachedDataGateway = class {
39276
40749
  // a retried tool_call, exactly this path — can never stomp a populated row.
39277
40750
  async recordAuditEvent(event) {
39278
40751
  await this.deps.local.recordAuditEvent(event);
40752
+ if (this.auditVerdict(event) === "local") return;
39279
40753
  const forwarded = await this.deps.forward.run(
39280
40754
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
39281
40755
  );
@@ -39289,6 +40763,7 @@ var AttachedDataGateway = class {
39289
40763
  async recordLlmCall(input2) {
39290
40764
  await this.deps.local.recordLlmCall(input2);
39291
40765
  const event = llmAuditEvent(input2);
40766
+ if (this.auditVerdict(event) === "local") return;
39292
40767
  const forwarded = await this.deps.forward.run(
39293
40768
  () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
39294
40769
  );
@@ -39459,7 +40934,7 @@ var AttachedDataGateway = class {
39459
40934
  // here would replace that with N separate local writes.
39460
40935
  async recordLlmCalls(inputs) {
39461
40936
  await this.deps.local.recordLlmCalls(inputs);
39462
- await this.forwardBatch(inputs, (input2) => llmAuditEvent(input2));
40937
+ await this.forwardBatch(this.forwardableLeaves(inputs), (input2) => llmAuditEvent(input2));
39463
40938
  }
39464
40939
  // `input.inspections` (secrets detected client-side in the tool's masked
39465
40940
  // target) ride along on the request's `inspections` field — the control plane
@@ -39469,7 +40944,7 @@ var AttachedDataGateway = class {
39469
40944
  // way — this only stops the FINDING row itself from being dropped.
39470
40945
  async recordToolCalls(inputs) {
39471
40946
  await this.deps.local.recordToolCalls(inputs);
39472
- await this.forwardBatch(inputs, (input2) => toolAuditEvent(input2));
40947
+ await this.forwardBatch(this.forwardableLeaves(inputs), (input2) => toolAuditEvent(input2));
39473
40948
  }
39474
40949
  // Forwarded as a `config_scan` audit event: there is no dedicated
39475
40950
  // config-scan ingest endpoint, and the audit-event door is the one the
@@ -39494,6 +40969,7 @@ var AttachedDataGateway = class {
39494
40969
  // local store.
39495
40970
  async recordConfigScan(record2) {
39496
40971
  await this.deps.local.recordConfigScan(record2);
40972
+ if (this.verdictFor(() => void 0) === "local") return;
39497
40973
  const forwarded = await this.deps.forward.run(
39498
40974
  () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
39499
40975
  );
@@ -39515,6 +40991,7 @@ var AttachedDataGateway = class {
39515
40991
  */
39516
40992
  async recordProjectEgress(input2) {
39517
40993
  const summary = await this.deps.local.recordProjectEgress(input2);
40994
+ if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
39518
40995
  await this.deps.forward.run(
39519
40996
  () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
39520
40997
  );
@@ -39736,14 +41213,15 @@ var AttachedDataGateway = class {
39736
41213
  }
39737
41214
  };
39738
41215
  function reKeyForForward(event, remote) {
41216
+ const outbound = withoutScopeKey(event);
39739
41217
  if (remote === null) {
39740
- const stripped = { ...event };
41218
+ const stripped = { ...outbound };
39741
41219
  delete stripped.hostId;
39742
41220
  delete stripped.harnessId;
39743
41221
  delete stripped.sourceProjectId;
39744
41222
  return stripped;
39745
41223
  }
39746
- const rekeyed = { ...event };
41224
+ const rekeyed = { ...outbound };
39747
41225
  delete rekeyed.hostId;
39748
41226
  delete rekeyed.harnessId;
39749
41227
  delete rekeyed.sourceProjectId;
@@ -39752,6 +41230,19 @@ function reKeyForForward(event, remote) {
39752
41230
  if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
39753
41231
  return rekeyed;
39754
41232
  }
41233
+ function rootReferenceOf(row) {
41234
+ return row.rootSessionId ?? row.parentId;
41235
+ }
41236
+ function scopeKeyOf(attributes) {
41237
+ if (attributes == null || !Object.hasOwn(attributes, "scope_key")) return void 0;
41238
+ const key = attributes.scope_key;
41239
+ return typeof key === "string" ? key : void 0;
41240
+ }
41241
+ function inventoryKey(ctx) {
41242
+ const tool = ctx.harness?.identityKey;
41243
+ if (tool === void 0 || !sessionToolIsKeyed(tool)) return void 0;
41244
+ return canonicalRepoUrl(ctx.project?.url ?? "");
41245
+ }
39755
41246
  var BATCH_FORWARD_BUDGET_MS = 3e3;
39756
41247
  function llmAuditEvent(input2) {
39757
41248
  return {
@@ -39771,7 +41262,20 @@ function toolAuditEvent(input2) {
39771
41262
  parentId: input2.parentId,
39772
41263
  rootSessionId: input2.rootSessionId,
39773
41264
  attributes: input2.attributes,
39774
- inspections: input2.inspections
41265
+ inspections: input2.inspections.map(toWireInspection)
41266
+ };
41267
+ }
41268
+ function toWireInspection(insp) {
41269
+ return {
41270
+ ruleId: insp.ruleId,
41271
+ ruleName: insp.ruleName,
41272
+ ruleVersion: insp.ruleVersion,
41273
+ category: insp.category,
41274
+ severity: insp.severity,
41275
+ span: insp.span,
41276
+ maskedMatch: insp.maskedMatch,
41277
+ actionTaken: insp.actionTaken,
41278
+ confidence: insp.confidence
39775
41279
  };
39776
41280
  }
39777
41281
 
@@ -39795,17 +41299,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
39795
41299
 
39796
41300
  // ../../packages/plugin-runtime/src/attached/install-record.ts
39797
41301
  import { readFile as readFile2, stat } from "fs/promises";
39798
- import { basename as basename6, dirname as dirname6, join as join28, resolve as resolve2 } from "path";
41302
+ import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
39799
41303
  async function readInstalledVersion(installRoot) {
39800
41304
  try {
39801
41305
  const versionDir = resolve2(installRoot);
39802
- const pluginDir = dirname6(versionDir);
39803
- const marketplaceDir = dirname6(pluginDir);
39804
- const cacheDir = dirname6(marketplaceDir);
41306
+ const pluginDir = dirname7(versionDir);
41307
+ const marketplaceDir = dirname7(pluginDir);
41308
+ const cacheDir = dirname7(marketplaceDir);
39805
41309
  if (basename6(cacheDir) !== "cache") return null;
39806
41310
  const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
39807
41311
  const record2 = JSON.parse(
39808
- await readFile2(join28(dirname6(cacheDir), "installed_plugins.json"), "utf8")
41312
+ await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
39809
41313
  );
39810
41314
  const plugins = record2?.plugins;
39811
41315
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -39880,9 +41384,9 @@ async function readInstalledVersionBounded(installRoot) {
39880
41384
  }
39881
41385
 
39882
41386
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39883
- import { randomUUID as randomUUID16 } from "crypto";
41387
+ import { randomUUID as randomUUID17 } from "crypto";
39884
41388
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
39885
- import { join as join29 } from "path";
41389
+ import { join as join30 } from "path";
39886
41390
 
39887
41391
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39888
41392
  import { rename as rename2 } from "fs/promises";
@@ -39911,7 +41415,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39911
41415
 
39912
41416
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39913
41417
  function createPolicyStore(dir = dataDir()) {
39914
- const file2 = join29(dir, "policy-cache.json");
41418
+ const file2 = join30(dir, "policy-cache.json");
39915
41419
  async function read() {
39916
41420
  try {
39917
41421
  const raw = await readFile3(file2, "utf8");
@@ -39943,7 +41447,7 @@ function createPolicyStore(dir = dataDir()) {
39943
41447
  }
39944
41448
  }
39945
41449
  async function publishRecord(record2) {
39946
- const tmp = `${file2}.${randomUUID16()}.tmp`;
41450
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
39947
41451
  try {
39948
41452
  await writeFile2(tmp, JSON.stringify(record2), {
39949
41453
  encoding: "utf8",
@@ -39982,7 +41486,7 @@ function createPolicyStore(dir = dataDir()) {
39982
41486
 
39983
41487
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
39984
41488
  import { readFileSync as readFileSync19 } from "fs";
39985
- import { join as join30 } from "path";
41489
+ import { join as join31 } from "path";
39986
41490
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
39987
41491
  var OUTCOME_KEYS = {
39988
41492
  ok: true,
@@ -39996,7 +41500,7 @@ var OUTCOME_KEYS = {
39996
41500
  };
39997
41501
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
39998
41502
  function postureReportStatePath(dataDir2) {
39999
- return join30(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41503
+ return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
40000
41504
  }
40001
41505
  function writePostureReportState(dataDir2, state) {
40002
41506
  try {
@@ -40010,7 +41514,7 @@ function writePostureReportState(dataDir2, state) {
40010
41514
  // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
40011
41515
  var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
40012
41516
  function createPostureReporter(deps) {
40013
- async function prepare() {
41517
+ async function prepare2() {
40014
41518
  try {
40015
41519
  const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
40016
41520
  if (state === null) return null;
@@ -40059,7 +41563,7 @@ function createPostureReporter(deps) {
40059
41563
  } catch {
40060
41564
  }
40061
41565
  }
40062
- return { prepare, send: send2 };
41566
+ return { prepare: prepare2, send: send2 };
40063
41567
  }
40064
41568
 
40065
41569
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
@@ -40174,16 +41678,16 @@ function readStorePosture(dbPath2) {
40174
41678
  }
40175
41679
 
40176
41680
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
40177
- import { randomUUID as randomUUID17 } from "crypto";
41681
+ import { randomUUID as randomUUID18 } from "crypto";
40178
41682
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
40179
- import { join as join31 } from "path";
41683
+ import { join as join32 } from "path";
40180
41684
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40181
41685
  function createPostureStore(dir = settingsDir(), legacyDir) {
40182
- const file2 = join31(dir, "posture-state.json");
40183
- const legacyFile = legacyDir === void 0 ? null : join31(legacyDir, "posture-state.json");
41686
+ const file2 = join32(dir, "posture-state.json");
41687
+ const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
40184
41688
  async function persist(state) {
40185
41689
  await ensureDataDir(dir);
40186
- const tmp = `${file2}.${randomUUID17()}.tmp`;
41690
+ const tmp = `${file2}.${randomUUID18()}.tmp`;
40187
41691
  try {
40188
41692
  await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
40189
41693
  await publishByRename(tmp, file2);
@@ -40225,7 +41729,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40225
41729
  }
40226
41730
  return legacy;
40227
41731
  }
40228
- const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
41732
+ const fresh = { deviceId: randomUUID18(), lastAttemptedAtMs: 0 };
40229
41733
  try {
40230
41734
  await ensureDataDir(dir);
40231
41735
  if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
@@ -40249,7 +41753,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40249
41753
 
40250
41754
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
40251
41755
  import { readFileSync as readFileSync20 } from "fs";
40252
- import { join as join32 } from "path";
41756
+ import { join as join33 } from "path";
40253
41757
 
40254
41758
  // ../../packages/plugin-runtime/src/attached/status.ts
40255
41759
  var REFUSAL_LINES = {
@@ -40281,9 +41785,6 @@ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40281
41785
  // ../../packages/plugin-runtime/src/attached/factory.ts
40282
41786
  import { hostname as hostname6 } from "os";
40283
41787
 
40284
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
40285
- import { randomUUID as randomUUID18 } from "crypto";
40286
-
40287
41788
  // ../../packages/plugin-runtime/src/recorder.ts
40288
41789
  var PLUGIN_RECORDER_BINARY = "plugin";
40289
41790
 
@@ -40300,7 +41801,7 @@ var StandaloneDataGateway = class {
40300
41801
  this.db.installedPacks.recordInventory(detections, meta4);
40301
41802
  }
40302
41803
  recordCapture(record2) {
40303
- this.db.recordCapture(record2.event, record2.findings);
41804
+ this.db.recordCapture(record2.event, record2.findings, record2.scopeKey);
40304
41805
  return Promise.resolve();
40305
41806
  }
40306
41807
  ensureInventory(ctx) {
@@ -40387,7 +41888,10 @@ var StandaloneDataGateway = class {
40387
41888
  span: insp.span,
40388
41889
  maskedMatch: insp.maskedMatch,
40389
41890
  actionTaken: insp.actionTaken,
40390
- confidence: insp.confidence
41891
+ confidence: insp.confidence,
41892
+ ...insp.line === void 0 ? {} : { line: insp.line },
41893
+ ...insp.col === void 0 ? {} : { col: insp.col },
41894
+ ...insp.context === void 0 ? {} : { context: insp.context }
40391
41895
  });
40392
41896
  }
40393
41897
  }
@@ -40402,6 +41906,14 @@ var StandaloneDataGateway = class {
40402
41906
  readSessionProvider(sessionId) {
40403
41907
  return Promise.resolve(this.db.auditEvents.sessionProvider(sessionId));
40404
41908
  }
41909
+ // The key the store holds for a session root, which is not always the key of
41910
+ // the root event just recorded: roots are first-write-wins, so a second root
41911
+ // event for a session leaves the stored one as it was. The attached gateway
41912
+ // decides what to forward from this, because it is the row the history drain
41913
+ // will decide by.
41914
+ readSessionScopeKey(sessionId) {
41915
+ return this.db.auditEvents.sessionScopeKey(sessionId);
41916
+ }
40405
41917
  readCaptureStatuses() {
40406
41918
  return Promise.resolve(this.db.captureStatus.latest(Date.now()));
40407
41919
  }
@@ -40469,6 +41981,7 @@ var StandaloneDataGateway = class {
40469
41981
  ruleActions: /* @__PURE__ */ new Map(),
40470
41982
  ruleVersions: /* @__PURE__ */ new Map(),
40471
41983
  reversibleRules: /* @__PURE__ */ new Set(),
41984
+ assignedRules: /* @__PURE__ */ new Set(),
40472
41985
  complete: true
40473
41986
  };
40474
41987
  }
@@ -40482,6 +41995,7 @@ var StandaloneDataGateway = class {
40482
41995
  ruleActions: snapshot.ruleActions,
40483
41996
  ruleVersions: snapshot.ruleVersions,
40484
41997
  reversibleRules: snapshot.reversibleRules,
41998
+ assignedRules: snapshot.assignedRules,
40485
41999
  complete: true
40486
42000
  };
40487
42001
  } catch {
@@ -40492,13 +42006,7 @@ var StandaloneDataGateway = class {
40492
42006
  const policies = await this.db.policies.readPolicies();
40493
42007
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
40494
42008
  const installed = this.installedScanRules();
40495
- const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
40496
- id: randomUUID18(),
40497
- scope: "global",
40498
- target: { ruleId },
40499
- action,
40500
- enabled: true
40501
- })) : [];
42009
+ const rulePolicies = installed ? assignedRulePolicies(installed) : [];
40502
42010
  let exceptions;
40503
42011
  try {
40504
42012
  const key = this.dataDir ? readFingerprintKey(this.dataDir) : null;
@@ -40679,6 +42187,11 @@ function resolveGatewayForConfig(config2, meta4) {
40679
42187
  if (connection === void 0) return local;
40680
42188
  const credential = readControlPlaneCredential(config2.settingsDir, connection);
40681
42189
  if (credential === null) return local;
42190
+ const attachment = resolveScope({
42191
+ mode: attachmentModeOf(credential),
42192
+ scope: config2.settings.attachmentScope,
42193
+ endpoint: connection.endpoint
42194
+ });
40682
42195
  const client = createRemoteClient({
40683
42196
  endpoint: connection.endpoint,
40684
42197
  apiKey: credential.apiKey
@@ -40692,6 +42205,7 @@ function resolveGatewayForConfig(config2, meta4) {
40692
42205
  dataDir: config2.dataDir,
40693
42206
  readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
40694
42207
  forward,
42208
+ attachment,
40695
42209
  posture: createPostureReporter({
40696
42210
  // THROUGH THE BREAKER, and wrapped HERE rather than around
40697
42211
  // `PostureReporter.send`. The reporter swallows every error by
@@ -40760,9 +42274,9 @@ import {
40760
42274
  readSync as readSync2,
40761
42275
  writeFileSync as writeFileSync8
40762
42276
  } from "fs";
40763
- import { join as join33 } from "path";
42277
+ import { join as join34 } from "path";
40764
42278
  function offsetsDir(dataDir2) {
40765
- return join33(dataDir2, "usage-offsets");
42279
+ return join34(dataDir2, "usage-offsets");
40766
42280
  }
40767
42281
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
40768
42282
  function safeSessionId(sessionId) {
@@ -40772,7 +42286,7 @@ function safeSessionId(sessionId) {
40772
42286
  return createHash7("sha256").update(sessionId).digest("hex");
40773
42287
  }
40774
42288
  function offsetPath(dataDir2, sessionId) {
40775
- return join33(offsetsDir(dataDir2), safeSessionId(sessionId));
42289
+ return join34(offsetsDir(dataDir2), safeSessionId(sessionId));
40776
42290
  }
40777
42291
  function readOffset(dataDir2, sessionId) {
40778
42292
  try {
@@ -40836,7 +42350,7 @@ function readTail(transcriptPath, startOffset) {
40836
42350
  // src/history/transcripts.ts
40837
42351
  import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync22, readSync as readSync3, statSync as statSync10 } from "fs";
40838
42352
  import { homedir as homedir3 } from "os";
40839
- import { join as join34 } from "path";
42353
+ import { join as join35 } from "path";
40840
42354
  function isRecord(value) {
40841
42355
  return typeof value === "object" && value !== null;
40842
42356
  }
@@ -40934,6 +42448,7 @@ function contentSize(value) {
40934
42448
  function parseTranscriptToolCalls(jsonl, sinceMs = 0, knownSessionId) {
40935
42449
  const sessionIdBySessionMeta = { current: knownSessionId };
40936
42450
  let runKey;
42451
+ let cwd;
40937
42452
  const begins = /* @__PURE__ */ new Map();
40938
42453
  const out = [];
40939
42454
  for (const line of jsonl.split("\n")) {
@@ -40950,11 +42465,14 @@ function parseTranscriptToolCalls(jsonl, sinceMs = 0, knownSessionId) {
40950
42465
  if (!isRecord(payload)) continue;
40951
42466
  if (rec.type === "session_meta") {
40952
42467
  sessionIdBySessionMeta.current = optString(payload.session_id) ?? optString(payload.id);
42468
+ cwd = optString(payload.cwd);
40953
42469
  continue;
40954
42470
  }
40955
42471
  if (rec.type === "turn_context") {
40956
42472
  const turnTs = optString(rec.timestamp);
40957
42473
  runKey = optString(payload.turn_id) ?? (turnTs !== void 0 ? `turn-${turnTs}` : void 0);
42474
+ const turnCwd = optString(payload.cwd);
42475
+ if (turnCwd) cwd = turnCwd;
40958
42476
  continue;
40959
42477
  }
40960
42478
  if (rec.type !== "event_msg") continue;
@@ -40969,6 +42487,10 @@ function parseTranscriptToolCalls(jsonl, sinceMs = 0, knownSessionId) {
40969
42487
  begins.set(callId, {
40970
42488
  toolName: "shell",
40971
42489
  runKey: optString(payload.turn_id) ?? runKey,
42490
+ // The command's own working directory (a shell call can run in another
42491
+ // directory than its turn's), else the directory its turn ran in.
42492
+ cwd: optString(payload.cwd) ?? cwd,
42493
+ filePaths: void 0,
40972
42494
  occurredAt,
40973
42495
  target: command
40974
42496
  });
@@ -40984,6 +42506,9 @@ function parseTranscriptToolCalls(jsonl, sinceMs = 0, knownSessionId) {
40984
42506
  toolUseId: callId,
40985
42507
  toolName: "shell",
40986
42508
  runKey: begin?.runKey ?? optString(payload.turn_id) ?? runKey,
42509
+ // The end event's own cwd, else the begin's (its own, or its turn's).
42510
+ cwd: optString(payload.cwd) ?? begin?.cwd ?? cwd,
42511
+ filePaths: void 0,
40987
42512
  occurredAt: begin?.occurredAt ?? occurredAt,
40988
42513
  inputSize: begin?.target !== void 0 ? begin.target.length : void 0,
40989
42514
  isError: typeof exitCode === "number" ? exitCode !== 0 : void 0,
@@ -40999,6 +42524,8 @@ function parseTranscriptToolCalls(jsonl, sinceMs = 0, knownSessionId) {
40999
42524
  begins.set(callId, {
41000
42525
  toolName: "apply_patch",
41001
42526
  runKey: optString(payload.turn_id) ?? runKey,
42527
+ cwd,
42528
+ filePaths: changes,
41002
42529
  occurredAt,
41003
42530
  target: changes.length > 0 ? changes.join(", ") : void 0
41004
42531
  });
@@ -41008,11 +42535,14 @@ function parseTranscriptToolCalls(jsonl, sinceMs = 0, knownSessionId) {
41008
42535
  const callId = optString(payload.call_id);
41009
42536
  if (callId === void 0 || sessionIdBySessionMeta.current === void 0) continue;
41010
42537
  const begin = begins.get(callId);
42538
+ const endChanges = isRecord(payload.changes) ? Object.keys(payload.changes) : [];
41011
42539
  out.push({
41012
42540
  sessionId: sessionIdBySessionMeta.current,
41013
42541
  toolUseId: callId,
41014
42542
  toolName: "apply_patch",
41015
42543
  runKey: begin?.runKey ?? optString(payload.turn_id) ?? runKey,
42544
+ cwd: begin?.cwd ?? cwd,
42545
+ filePaths: [.../* @__PURE__ */ new Set([...begin?.filePaths ?? [], ...endChanges])],
41016
42546
  occurredAt: begin?.occurredAt ?? occurredAt,
41017
42547
  inputSize: begin?.target !== void 0 ? begin.target.length : void 0,
41018
42548
  isError: typeof payload.success === "boolean" ? !payload.success : void 0,
@@ -41054,6 +42584,7 @@ async function reconcileSession(gateway, sessionId, records, opts = {}) {
41054
42584
  buildSessionRoot(sessionId, ctx, resolved, anchor2, heuristicProvider)
41055
42585
  );
41056
42586
  const provider = await gateway.readSessionProvider(sessionId) ?? heuristicProvider;
42587
+ const scopeKeyOf2 = opts.scopeKeyOf ?? scopeKeyMemo();
41057
42588
  const inputs = records.map((rec) => ({
41058
42589
  sessionId,
41059
42590
  // No stable message id in Codex's usage event — key on the record's own
@@ -41068,7 +42599,8 @@ async function reconcileSession(gateway, sessionId, records, opts = {}) {
41068
42599
  // checkpoint, so its run_key attribution survives the chunk boundary.
41069
42600
  attributes: buildAttributes(
41070
42601
  rec.runKey === void 0 && opts.seedPromptId !== void 0 ? { ...rec, runKey: opts.seedPromptId } : rec,
41071
- provider
42602
+ provider,
42603
+ scopeKeyOf2(rec.cwd)
41072
42604
  )
41073
42605
  }));
41074
42606
  try {
@@ -41080,11 +42612,12 @@ async function reconcileSession(gateway, sessionId, records, opts = {}) {
41080
42612
  }
41081
42613
  async function reconcileSessionToolCalls(gateway, sessionId, toolCalls, opts = {}) {
41082
42614
  if (toolCalls.length === 0) return 0;
42615
+ const scopeKeyOf2 = opts.scopeKeyOf ?? scopeKeyMemo();
41083
42616
  const inputs = toolCalls.map((tc) => {
41084
42617
  const attributes = { tool_name: tc.toolName, tool_use_id: tc.toolUseId };
41085
42618
  let inspections = [];
41086
42619
  if (tc.target !== void 0) {
41087
- const { masked, findings } = scanText(tc.target);
42620
+ const { masked, findings } = scanText(tc.target, void 0, { locate: true });
41088
42621
  if (masked !== "") attributes.target = truncateTarget(masked);
41089
42622
  inspections = findings.map((f) => ({
41090
42623
  ruleId: f.ruleId,
@@ -41095,7 +42628,10 @@ async function reconcileSessionToolCalls(gateway, sessionId, toolCalls, opts = {
41095
42628
  span: f.span,
41096
42629
  maskedMatch: f.maskedMatch,
41097
42630
  actionTaken: "log",
41098
- confidence: f.confidence
42631
+ confidence: f.confidence,
42632
+ line: f.location.line,
42633
+ col: f.location.col,
42634
+ context: f.location.context
41099
42635
  }));
41100
42636
  }
41101
42637
  if (tc.isError !== void 0) attributes.is_error = tc.isError;
@@ -41103,6 +42639,8 @@ async function reconcileSessionToolCalls(gateway, sessionId, toolCalls, opts = {
41103
42639
  if (tc.outputSize !== void 0) attributes.output_size = tc.outputSize;
41104
42640
  const runKey = tc.runKey ?? opts.seedPromptId;
41105
42641
  if (runKey !== void 0) attributes.run_key = runKey;
42642
+ const scopeKey = toolCallScopeKey(tc, scopeKeyOf2);
42643
+ if (scopeKey !== void 0) attributes.scope_key = scopeKey;
41106
42644
  return {
41107
42645
  sessionId,
41108
42646
  toolUseId: tc.toolUseId,
@@ -41135,12 +42673,15 @@ async function reconcileSessionTail(config2, sessionId, transcriptPath) {
41135
42673
  const records = parseTranscriptUsage(chunk, 0, sessionId);
41136
42674
  const toolCallRecords = parseTranscriptToolCalls(chunk, 0, sessionId);
41137
42675
  const gateway = reconcileGateway(config2);
42676
+ const scopeKeyOf2 = scopeKeyMemo();
41138
42677
  try {
41139
42678
  const result = await reconcileSession(gateway, sessionId, records, {
41140
- seedPromptId: checkpoint.lastPromptId
42679
+ seedPromptId: checkpoint.lastPromptId,
42680
+ scopeKeyOf: scopeKeyOf2
41141
42681
  });
41142
42682
  const toolCalls = await reconcileSessionToolCalls(gateway, sessionId, toolCallRecords, {
41143
- seedPromptId: checkpoint.lastPromptId
42683
+ seedPromptId: checkpoint.lastPromptId,
42684
+ scopeKeyOf: scopeKeyOf2
41144
42685
  });
41145
42686
  const toolCallsDropped = toolCallRecords.length > 0 && toolCalls === 0;
41146
42687
  if (result.skipped === 0 && !toolCallsDropped) {
@@ -41167,6 +42708,8 @@ function buildSessionRoot(sessionId, ctx, resolved, anchor2, provider) {
41167
42708
  const hostName = ctx.host?.attributes.host_name;
41168
42709
  if (typeof hostName === "string") attributes.host = hostName;
41169
42710
  if (ctx.project) attributes.project = ctx.project.name;
42711
+ const scopeKey = sessionRootScopeKey(anchor2.cwd);
42712
+ if (scopeKey !== void 0) attributes.scope_key = scopeKey;
41170
42713
  const event = {
41171
42714
  id: sessionId,
41172
42715
  eventType: "session",
@@ -41178,7 +42721,7 @@ function buildSessionRoot(sessionId, ctx, resolved, anchor2, provider) {
41178
42721
  if (Object.keys(attributes).length > 0) event.attributes = attributes;
41179
42722
  return event;
41180
42723
  }
41181
- function buildAttributes(rec, provider) {
42724
+ function buildAttributes(rec, provider, scopeKey) {
41182
42725
  const usage = rec.usage;
41183
42726
  const attrs = {
41184
42727
  model: rec.model ?? "unknown",
@@ -41193,6 +42736,7 @@ function buildAttributes(rec, provider) {
41193
42736
  if (typeof usage.reasoning_output_tokens === "number") {
41194
42737
  attrs.reasoning_output_tokens = usage.reasoning_output_tokens;
41195
42738
  }
42739
+ if (scopeKey !== void 0) attrs.scope_key = scopeKey;
41196
42740
  return attrs;
41197
42741
  }
41198
42742
  function setNum(attrs, key, value) {