@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) {
@@ -1006,6 +1038,10 @@ var SQLITE_MIGRATIONS = [
1006
1038
  {
1007
1039
  tag: "0036_secret_vault_identity_fingerprint",
1008
1040
  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"
1041
+ },
1042
+ {
1043
+ tag: "0037_finding_location",
1044
+ 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;"
1009
1045
  }
1010
1046
  ];
1011
1047
 
@@ -21899,11 +21935,33 @@ var ResolutionMethod = external_exports.enum([
21899
21935
  "false-positive",
21900
21936
  "redetected"
21901
21937
  ]).meta({ id: "ResolutionMethod" });
21938
+ var FindingContextBasis = external_exports.enum(["file", "excerpt"]).meta({ id: "FindingContextBasis" });
21939
+ var FindingContext = external_exports.object({
21940
+ basis: FindingContextBasis,
21941
+ // 1-based line number of `lines[0]`.
21942
+ firstLine: external_exports.number().int().positive(),
21943
+ lines: external_exports.array(external_exports.string()).min(1).max(5),
21944
+ match: external_exports.object({
21945
+ // 1-based line number, within [firstLine, firstLine + lines.length).
21946
+ line: external_exports.number().int().positive(),
21947
+ // Offsets into that entry of `lines`, end exclusive.
21948
+ start: external_exports.number().int().nonnegative(),
21949
+ end: external_exports.number().int().nonnegative()
21950
+ }).nullable()
21951
+ }).meta({ id: "FindingContext" });
21952
+ var FindingLocation = external_exports.object({
21953
+ line: external_exports.number().int().positive(),
21954
+ col: external_exports.number().int().positive(),
21955
+ context: FindingContext.nullable()
21956
+ });
21902
21957
  var FindingMatch = external_exports.object({
21903
21958
  // Masked preview of the matched value. Never raw content.
21904
21959
  maskedValue: external_exports.string(),
21905
- // Redacted source-line prefix. Currently empty (pending privacy review).
21906
- contextPrefix: external_exports.string()
21960
+ // Deprecated: always empty. Superseded by `context`.
21961
+ contextPrefix: external_exports.string(),
21962
+ // The masked lines around the match. Absent when the finding predates
21963
+ // context capture or none could be built safely.
21964
+ context: FindingContext.optional()
21907
21965
  }).meta({ id: "FindingMatch" });
21908
21966
  var FindingDetectionRef = external_exports.object({
21909
21967
  id: external_exports.string(),
@@ -21923,6 +21981,11 @@ var FindingInstance = external_exports.object({
21923
21981
  provider: FindingProvider,
21924
21982
  repo: external_exports.string(),
21925
21983
  file: external_exports.string(),
21984
+ // 1-based line and column of the match start in the scanned text (the
21985
+ // column in UTF-16 code units). Absent for findings that predate location
21986
+ // capture or have no source text.
21987
+ line: external_exports.number().int().positive().optional(),
21988
+ col: external_exports.number().int().positive().optional(),
21926
21989
  // Who the capturing event is attributed to. Optional: a single-user store
21927
21990
  // has no one to attribute a finding to and never sets it.
21928
21991
  user: FindingUser.optional(),
@@ -21984,6 +22047,13 @@ var FindingStats = external_exports.object({
21984
22047
  low: external_exports.number().int().nonnegative()
21985
22048
  })
21986
22049
  }).meta({ id: "FindingStats" });
22050
+ var FindingsOverview = external_exports.object({
22051
+ findings: external_exports.number().int().nonnegative(),
22052
+ open: external_exports.number().int().nonnegative(),
22053
+ handled: external_exports.number().int().nonnegative(),
22054
+ resolved: external_exports.number().int().nonnegative(),
22055
+ dismissed: external_exports.number().int().nonnegative()
22056
+ }).meta({ id: "FindingsOverview" });
21987
22057
  var FindingFacetItem = external_exports.object({
21988
22058
  value: external_exports.string(),
21989
22059
  count: external_exports.number().int().nonnegative()
@@ -22103,6 +22173,7 @@ var FindingInstanceDetail = FindingInstance.extend({
22103
22173
  }).meta({ id: "FindingInstanceDetail" });
22104
22174
  var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
22105
22175
  var MAX_FLAT_FINDINGS_LIMIT = 200;
22176
+ var FindingContextQuery = external_exports.object({ id: external_exports.string().min(1).max(256) });
22106
22177
  var ListFindingInstancesQuery = external_exports.object({
22107
22178
  severity: external_exports.array(Severity).optional(),
22108
22179
  // Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
@@ -22435,7 +22506,23 @@ var CaptureAttributes = external_exports.object({
22435
22506
  // capture denied by another finding's own Block policy carries `block`
22436
22507
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22437
22508
  // repeated rather than referenced because a store reader opens this file.
22438
- redact_degraded_to: ActionTaken.optional()
22509
+ redact_degraded_to: ActionTaken.optional(),
22510
+ // The scope key this capture was stamped with: the canonical repository
22511
+ // (`host/owner/repo`) of the path the capture names (a relative path is read
22512
+ // against its working directory), else of its own working directory, or a
22513
+ // chat account's identity. The store's local `scope_key` column reads it, so
22514
+ // a scoped attachment has a per-row key to work from. Absent when no key
22515
+ // could be derived.
22516
+ //
22517
+ // LOCAL ONLY. That is the contract for every path that sends a row. Producers
22518
+ // stamp it in every attachment mode, and the two structural choke points strip
22519
+ // it: the attached gateway's `reKeyForForward` on the live path, and the
22520
+ // history drain's `rebuildAuditEvent`, which drops it through `withoutScopeKey`.
22521
+ // A capture row's bag reaches the wire through `rebuildCapture`, which builds
22522
+ // the metadata from named keys and never names this one; `toCaptureAttributes`,
22523
+ // which builds the bag from a wire event, never emits it. What a scoped
22524
+ // attachment does with the key is not part of this shape's contract.
22525
+ scope_key: external_exports.string().optional()
22439
22526
  }).catchall(external_exports.unknown());
22440
22527
  var CaptureStatusAttributes = external_exports.object({
22441
22528
  source_tool: external_exports.string().optional(),
@@ -22465,6 +22552,12 @@ var ToolCallInspection = external_exports.object({
22465
22552
  actionTaken: ActionTaken,
22466
22553
  confidence: external_exports.number().min(0).max(1)
22467
22554
  });
22555
+ var findingLocationFields = {
22556
+ line: external_exports.number().int().positive().optional(),
22557
+ col: external_exports.number().int().positive().optional(),
22558
+ context: FindingContext.nullable().optional()
22559
+ };
22560
+ var ToolCallInspectionInput = ToolCallInspection.extend(findingLocationFields);
22468
22561
  var ToolCallInput = external_exports.object({
22469
22562
  sessionId: external_exports.string().min(1),
22470
22563
  toolUseId: external_exports.string().min(1),
@@ -22474,7 +22567,7 @@ var ToolCallInput = external_exports.object({
22474
22567
  attributes: ToolCallAttributes,
22475
22568
  // Secrets detected in the tool's (masked) target — written as linked
22476
22569
  // `inspection_findings`. Empty for a clean tool call.
22477
- inspections: external_exports.array(ToolCallInspection).default([])
22570
+ inspections: external_exports.array(ToolCallInspectionInput).default([])
22478
22571
  });
22479
22572
  var InventoryInput = external_exports.object({
22480
22573
  objectType: InventoryObjectType,
@@ -22548,7 +22641,8 @@ var InspectionFindingInput = external_exports.object({
22548
22641
  // same findingKey — mirrors the legacy `findings.first_detected_at`.
22549
22642
  // Optional: when omitted, the writer derives it from the referenced audit
22550
22643
  // event's startedAt on first insert (see SqliteInspectionFindingsRepository).
22551
- firstDetectedAt: external_exports.iso.datetime().optional()
22644
+ firstDetectedAt: external_exports.iso.datetime().optional(),
22645
+ ...findingLocationFields
22552
22646
  });
22553
22647
  var InventoryContext = external_exports.object({
22554
22648
  host: InventoryInput.optional(),
@@ -23326,6 +23420,17 @@ var AttachedCredential = external_exports.object({
23326
23420
  keyPrefix: external_exports.string().min(1).max(16).optional(),
23327
23421
  mintedAt: external_exports.iso.datetime().optional()
23328
23422
  });
23423
+ var AttachmentMode = external_exports.enum(["machine", "scoped"]);
23424
+ var ATTACHED_CREDENTIAL_SCOPED_SPEC_VERSION = 2;
23425
+ var AttachedCredentialV1 = AttachedCredential;
23426
+ var AttachedCredentialV2 = AttachedCredential.extend({
23427
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SCOPED_SPEC_VERSION),
23428
+ mode: external_exports.literal("scoped")
23429
+ });
23430
+ var AttachedCredentialAny = external_exports.discriminatedUnion("specVersion", [
23431
+ AttachedCredentialV1,
23432
+ AttachedCredentialV2
23433
+ ]);
23329
23434
  var MAX_DATE_MS = 253402300799999;
23330
23435
  var MAX_INT4 = 2147483647;
23331
23436
  var StorePosturePack = external_exports.object({
@@ -23607,6 +23712,130 @@ var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
23607
23712
  var SemVer = external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?$/);
23608
23713
  var PublisherKind = external_exports.enum(["labs", "user", "org"]);
23609
23714
 
23715
+ // ../../packages/schema/src/zod/builtin-policy-id.ts
23716
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23717
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23718
+
23719
+ // ../../packages/schema/src/zod/event.ts
23720
+ var EventKind = external_exports.enum(["prompt", "response", "code_change", "tool_use"]).meta({ id: "EventKind" });
23721
+ var CAPTURE_EVENT_TYPES_SQL = EventKind.options.map((k) => `'${k}'`).join(",");
23722
+ var EventMetadata = external_exports.object({
23723
+ sessionId: external_exports.string().optional(),
23724
+ repo: external_exports.string().optional(),
23725
+ filePath: external_exports.string().optional(),
23726
+ // The host tool whose input/output was scanned (e.g. 'Bash', 'WebFetch'),
23727
+ // set by the tool-scanning hooks. The tool NAME only — never the tool's
23728
+ // arguments or output, which can carry the very value a finding masked
23729
+ // (metadata is stored unredacted). Gives findings on non-file captures a
23730
+ // display location ("via Bash") when no filePath exists.
23731
+ toolName: external_exports.string().optional(),
23732
+ // Set (true) by the worktree scanner when the file is excluded by the
23733
+ // repo's .gitignore. Gitignored files ARE still scanned — local scratch and
23734
+ // generated code can leak real secrets — but the provenance is recorded so
23735
+ // policy/dashboards can treat those findings as informational rather than
23736
+ // blocking. Omitted (not false) for tracked files and non-scan events.
23737
+ gitignored: external_exports.boolean().optional(),
23738
+ // Set (true) ONLY when the event's `content` is the COMPLETE file at
23739
+ // capture time (a worktree scan reading from disk). Hook-captured edits
23740
+ // (e.g. an Edit tool's new_string) are partial fragments and MUST NOT set
23741
+ // this. The resolver-on-ingest keys its fixed-at-source dropout
23742
+ // diff on this marker: only a whole-file snapshot can prove a previously
23743
+ // open finding is gone; a fragment's absence proves nothing (the secret
23744
+ // may live outside the hunk). Omitted (not false) for fragments and
23745
+ // non-scan events, so pre-marker clients safely default to the
23746
+ // non-authoritative path.
23747
+ wholeFile: external_exports.boolean().optional(),
23748
+ model: external_exports.string().optional(),
23749
+ turnIndex: external_exports.number().int().nonnegative().optional(),
23750
+ // Distributed-tracing correlation. `correlationId` ties a recorded event back
23751
+ // to the request that captured/ingested it (a UUID, generated independently of
23752
+ // the trace id); `traceId` is the W3C trace id (32 lowercase hex chars) of the
23753
+ // originating span when telemetry is enabled. Both optional + backward
23754
+ // compatible — populated by the plugin (see @akasecurity/plugin-sdk).
23755
+ correlationId: external_exports.uuid().optional(),
23756
+ traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).optional(),
23757
+ // Ids of the detection exceptions that downgraded findings in this capture
23758
+ // to 'allow' — the enforcement audit trail's link back to the grant that
23759
+ // authorized the bypass. Absent on captures where no exception applied.
23760
+ exceptionIds: external_exports.array(external_exports.guid()).optional(),
23761
+ // The assistant message this capture belongs to, and the conversation it sits
23762
+ // in — set by the browser extension's network capture so a stored `response`
23763
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
23764
+ // on every other capture path, which has no such id.
23765
+ //
23766
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
23767
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
23768
+ // places an event is PARSED; the local write path types the event and parses
23769
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
23770
+ messageId: external_exports.string().min(1).optional(),
23771
+ conversationId: external_exports.string().optional(),
23772
+ // How long THIS capture's inspection blocked its caller, in whole
23773
+ // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
23774
+ // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
23775
+ // detection + redaction, the work the host session actually waits on.
23776
+ //
23777
+ // Stamped ONLY on live in-flight captures. A capture that carries its own
23778
+ // `occurredAt` is replaying past work (the transcript backfill, the worktree
23779
+ // scan), and its scan duration is not latency any host session experienced,
23780
+ // so those rows leave this ABSENT rather than reporting a misleading number.
23781
+ // Absent is also what every pre-measurement client writes, and what a
23782
+ // clock failure degrades to — a reader must treat absence as "not measured"
23783
+ // and never as a zero, which would read as "inspection is free".
23784
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
23785
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
23786
+ // workspace's `redactFallback`, applied because the field could not be
23787
+ // masked in place (a shell command, a URL, or any argument on a host whose
23788
+ // hook contract offers no rewrite channel).
23789
+ //
23790
+ // It exists because the action alone cannot say why. A finding recorded as
23791
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
23792
+ // assigned Redact on a field that could not take one — and those are
23793
+ // different facts about the same row: the first is a policy the user chose,
23794
+ // the second is a masking the host could not perform. Absent means no
23795
+ // degrade happened, which is every ordinary capture.
23796
+ //
23797
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
23798
+ // is the CAPTURE while `actionTaken` is per FINDING:
23799
+ //
23800
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
23801
+ // `redact` alongside a finding ASSIGNED the same action stores both
23802
+ // identically and one reason for the pair; attributing it to both
23803
+ // describes the assigned one wrongly, and to neither loses the degrade.
23804
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
23805
+ // became, not the reason the capture ended as it did — a capture denied
23806
+ // by some other finding's own Block policy still carries `block` here,
23807
+ // and clearing the workspace's fallback would not have let it through.
23808
+ // Gate on the value against what a fallback can produce; never read the
23809
+ // field's presence as "this was the fallback's doing".
23810
+ //
23811
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23812
+ // Closing either means moving the reason onto the finding row, which
23813
+ // already carries its own action.
23814
+ redactDegradedTo: ActionTaken.optional()
23815
+ }).meta({ id: "EventMetadata" });
23816
+ var Event = external_exports.object({
23817
+ id: external_exports.guid(),
23818
+ sourceTool: SourceTool,
23819
+ kind: EventKind,
23820
+ occurredAt: external_exports.iso.datetime(),
23821
+ contentHash: external_exports.string(),
23822
+ content: external_exports.string(),
23823
+ metadata: EventMetadata.optional()
23824
+ }).meta({ id: "Event" });
23825
+ var IngestEvent = Event.meta({ id: "IngestEvent" });
23826
+ var INGEST_BATCH_MAX = 100;
23827
+ var IngestBatch = external_exports.object({
23828
+ events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
23829
+ // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
23830
+ // additionally rejects any event whose contentHash the store has already
23831
+ // recorded — for re-runnable bulk ingest (worktree scan, transcript
23832
+ // backfill), where a re-run mints fresh event ids for identical content and
23833
+ // would otherwise accumulate duplicates. Live hook traffic must NOT set it:
23834
+ // two genuinely separate prompts can be byte-identical and both belong on
23835
+ // the timeline.
23836
+ dedupe: external_exports.literal("content-hash").optional()
23837
+ }).meta({ id: "IngestBatch" });
23838
+
23610
23839
  // ../../packages/schema/src/zod/rule.ts
23611
23840
  var MatcherType = external_exports.enum(["keyword", "regex"]).meta({ id: "MatcherType" });
23612
23841
  var RuleProbeVerdict = external_exports.enum(["safe", "quarantined"]).meta({ id: "RuleProbeVerdict" });
@@ -23675,7 +23904,10 @@ var Matcher = external_exports.discriminatedUnion("type", [KeywordMatcher, Regex
23675
23904
  var MATCHER_TYPES = MatcherType.options;
23676
23905
  var AppliesTo = external_exports.strictObject({
23677
23906
  // Dot-prefixed, e.g. ".py" — matches the scanner's SOURCE_EXTENSIONS shape.
23678
- extensions: external_exports.array(external_exports.string().regex(/^\.[A-Za-z0-9]+$/)).min(1)
23907
+ extensions: external_exports.array(external_exports.string().regex(/^\.[A-Za-z0-9]+$/)).min(1).optional(),
23908
+ eventKinds: external_exports.array(EventKind).min(1).optional()
23909
+ }).refine((v) => v.extensions !== void 0 || v.eventKinds !== void 0, {
23910
+ message: "appliesTo needs extensions, eventKinds, or both"
23679
23911
  }).meta({ id: "AppliesTo" });
23680
23912
  var PostValidatorName = external_exports.enum(["entropy", "luhn"]).meta({ id: "PostValidatorName" });
23681
23913
  var PostValidatorRef = external_exports.union(
@@ -23698,6 +23930,7 @@ var PostValidatorRef = external_exports.union(
23698
23930
  )}) or { "name": ..., "config": { ... } }. An unrecognized name would be a false-positive guard that never runs.`
23699
23931
  }
23700
23932
  ).meta({ id: "PostValidatorRef" });
23933
+ var RuleEvidence = external_exports.enum(["code", "value"]).meta({ id: "RuleEvidence" });
23701
23934
  var RequiresNearby = external_exports.strictObject({
23702
23935
  // Each array, when present, must be non-empty and contain non-empty strings —
23703
23936
  // an empty/blank criterion would either never fire or (for labels) match
@@ -23720,6 +23953,8 @@ var RuleFixture = external_exports.strictObject({
23720
23953
  // Simulated file context for the scan, so fixtures can assert `appliesTo`
23721
23954
  // gating (e.g. a Python-only pattern must NOT fire in a .ts file).
23722
23955
  filePath: external_exports.string().optional(),
23956
+ // Simulated capture kind, so fixtures can assert `appliesTo.eventKinds`.
23957
+ eventKind: EventKind.optional(),
23723
23958
  expectedSpans: external_exports.array(external_exports.strictObject({ start: external_exports.number(), end: external_exports.number() })).optional()
23724
23959
  }).meta({ id: "RuleFixture" });
23725
23960
  var Rule = external_exports.strictObject({
@@ -23745,7 +23980,9 @@ var Rule = external_exports.strictObject({
23745
23980
  appliesTo: AppliesTo.optional(),
23746
23981
  postValidators: external_exports.array(PostValidatorRef).optional(),
23747
23982
  requiresNearby: RequiresNearby.optional(),
23748
- examples: external_exports.array(external_exports.string()).optional()
23983
+ examples: external_exports.array(external_exports.string()).optional(),
23984
+ // Whether the matched text is itself sensitive. Absent means 'value'.
23985
+ evidence: RuleEvidence.optional()
23749
23986
  }).meta({ id: "Rule" });
23750
23987
  var Author = external_exports.object({
23751
23988
  name: external_exports.string(),
@@ -23762,7 +23999,11 @@ var PackManifest = external_exports.object({
23762
23999
  description: external_exports.string().optional(),
23763
24000
  author: Author.optional(),
23764
24001
  license: external_exports.string().optional(),
23765
- sourceUrl: external_exports.url().optional()
24002
+ sourceUrl: external_exports.url().optional(),
24003
+ // The built-in policy a FIRST install of this pack assigns
24004
+ // (installed_packs.policy_id). Absent leaves the pack unassigned, so its
24005
+ // rules follow the category policies. An existing install never takes it.
24006
+ defaultPolicy: BuiltinPolicyId.optional()
23766
24007
  }).meta({ id: "PackManifest" });
23767
24008
 
23768
24009
  // ../../packages/schema/src/zod/detection.ts
@@ -23790,10 +24031,12 @@ var DetectionListItem = external_exports.object({
23790
24031
  // Per-pack enforcement-policy assignment. Holds a BuiltinPolicyId ARCHETYPE
23791
24032
  // (monitor|warn|redact|block) — NOT a policies-table Policy.id guid; a
23792
24033
  // detection is a PACK, and its policy is the archetype applied to all its
23793
- // rules. Absent == unassigned, which resolves to Monitor everywhere
23794
- // (DEFAULT_PACK_POLICY_ID). Every enforcement surface expands it into
23795
- // per-rule policies (see policyIdToAction). Typed z.string() (not
23796
- // the enum) to keep the OpenAPI response tolerant of a future custom id.
24034
+ // rules. Absent == unassigned, which resolves to Monitor by default
24035
+ // (DEFAULT_PACK_POLICY_ID); a host may resolve it to a policy of its own
24036
+ // (see the dashboard's `unassignedPolicy`). Every enforcement surface
24037
+ // expands it into per-rule policies (see policyIdToAction). Typed
24038
+ // z.string() (not the enum) to keep the OpenAPI response tolerant of a
24039
+ // future custom id.
23797
24040
  policyId: external_exports.string().optional(),
23798
24041
  // Set ONLY when a newer snapshot is available for this pack (OSS: the
23799
24042
  // bundled inventory recorded in available_packs differs from the installed
@@ -23862,10 +24105,12 @@ var DetectionDetail = external_exports.object({
23862
24105
  // Per-pack enforcement-policy assignment. Holds a BuiltinPolicyId ARCHETYPE
23863
24106
  // (monitor|warn|redact|block) — NOT a policies-table Policy.id guid; a
23864
24107
  // detection is a PACK, and its policy is the archetype applied to all its
23865
- // rules. Absent == unassigned, which resolves to Monitor everywhere
23866
- // (DEFAULT_PACK_POLICY_ID). Every enforcement surface expands it into
23867
- // per-rule policies (see policyIdToAction). Typed z.string() (not
23868
- // the enum) to keep the OpenAPI response tolerant of a future custom id.
24108
+ // rules. Absent == unassigned, which resolves to Monitor by default
24109
+ // (DEFAULT_PACK_POLICY_ID); a host may resolve it to a policy of its own
24110
+ // (see the dashboard's `unassignedPolicy`). Every enforcement surface
24111
+ // expands it into per-rule policies (see policyIdToAction). Typed
24112
+ // z.string() (not the enum) to keep the OpenAPI response tolerant of a
24113
+ // future custom id.
23869
24114
  policyId: external_exports.string().optional()
23870
24115
  }).meta({ id: "DetectionDetail" });
23871
24116
  var LibraryItem = external_exports.object({
@@ -24012,126 +24257,6 @@ function buildDetectionsList(summaries, query) {
24012
24257
  return { counts, items: filtered.map(summaryToDetectionListItem) };
24013
24258
  }
24014
24259
 
24015
- // ../../packages/schema/src/zod/event.ts
24016
- var EventKind = external_exports.enum(["prompt", "response", "code_change", "tool_use"]).meta({ id: "EventKind" });
24017
- var CAPTURE_EVENT_TYPES_SQL = EventKind.options.map((k) => `'${k}'`).join(",");
24018
- var EventMetadata = external_exports.object({
24019
- sessionId: external_exports.string().optional(),
24020
- repo: external_exports.string().optional(),
24021
- filePath: external_exports.string().optional(),
24022
- // The host tool whose input/output was scanned (e.g. 'Bash', 'WebFetch'),
24023
- // set by the tool-scanning hooks. The tool NAME only — never the tool's
24024
- // arguments or output, which can carry the very value a finding masked
24025
- // (metadata is stored unredacted). Gives findings on non-file captures a
24026
- // display location ("via Bash") when no filePath exists.
24027
- toolName: external_exports.string().optional(),
24028
- // Set (true) by the worktree scanner when the file is excluded by the
24029
- // repo's .gitignore. Gitignored files ARE still scanned — local scratch and
24030
- // generated code can leak real secrets — but the provenance is recorded so
24031
- // policy/dashboards can treat those findings as informational rather than
24032
- // blocking. Omitted (not false) for tracked files and non-scan events.
24033
- gitignored: external_exports.boolean().optional(),
24034
- // Set (true) ONLY when the event's `content` is the COMPLETE file at
24035
- // capture time (a worktree scan reading from disk). Hook-captured edits
24036
- // (e.g. an Edit tool's new_string) are partial fragments and MUST NOT set
24037
- // this. The resolver-on-ingest keys its fixed-at-source dropout
24038
- // diff on this marker: only a whole-file snapshot can prove a previously
24039
- // open finding is gone; a fragment's absence proves nothing (the secret
24040
- // may live outside the hunk). Omitted (not false) for fragments and
24041
- // non-scan events, so pre-marker clients safely default to the
24042
- // non-authoritative path.
24043
- wholeFile: external_exports.boolean().optional(),
24044
- model: external_exports.string().optional(),
24045
- turnIndex: external_exports.number().int().nonnegative().optional(),
24046
- // Distributed-tracing correlation. `correlationId` ties a recorded event back
24047
- // to the request that captured/ingested it (a UUID, generated independently of
24048
- // the trace id); `traceId` is the W3C trace id (32 lowercase hex chars) of the
24049
- // originating span when telemetry is enabled. Both optional + backward
24050
- // compatible — populated by the plugin (see @akasecurity/plugin-sdk).
24051
- correlationId: external_exports.uuid().optional(),
24052
- traceId: external_exports.string().regex(/^[0-9a-f]{32}$/).optional(),
24053
- // Ids of the detection exceptions that downgraded findings in this capture
24054
- // to 'allow' — the enforcement audit trail's link back to the grant that
24055
- // authorized the bypass. Absent on captures where no exception applied.
24056
- exceptionIds: external_exports.array(external_exports.guid()).optional(),
24057
- // The assistant message this capture belongs to, and the conversation it sits
24058
- // in — set by the browser extension's network capture so a stored `response`
24059
- // row can be joined to the `llm_call` leaf describing the same turn. Absent
24060
- // on every other capture path, which has no such id.
24061
- //
24062
- // Non-empty for the reason WebExchange.messageId is: it is the join key, and
24063
- // a blank one matches no `llm_call` leaf. That refusal reaches only the
24064
- // places an event is PARSED; the local write path types the event and parses
24065
- // nothing, which is why `toCaptureAttributes` omits a blank one separately.
24066
- messageId: external_exports.string().min(1).optional(),
24067
- conversationId: external_exports.string().optional(),
24068
- // How long THIS capture's inspection blocked its caller, in whole
24069
- // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
24070
- // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
24071
- // detection + redaction, the work the host session actually waits on.
24072
- //
24073
- // Stamped ONLY on live in-flight captures. A capture that carries its own
24074
- // `occurredAt` is replaying past work (the transcript backfill, the worktree
24075
- // scan), and its scan duration is not latency any host session experienced,
24076
- // so those rows leave this ABSENT rather than reporting a misleading number.
24077
- // Absent is also what every pre-measurement client writes, and what a
24078
- // clock failure degrades to — a reader must treat absence as "not measured"
24079
- // and never as a zero, which would read as "inspection is free".
24080
- inspectionMs: external_exports.number().int().nonnegative().optional(),
24081
- // What a `redact` this capture COULD NOT CARRY OUT became instead — the
24082
- // workspace's `redactFallback`, applied because the field could not be
24083
- // masked in place (a shell command, a URL, or any argument on a host whose
24084
- // hook contract offers no rewrite channel).
24085
- //
24086
- // It exists because the action alone cannot say why. A finding recorded as
24087
- // `warn` reads identically whether its detection was ASSIGNED Warn or was
24088
- // assigned Redact on a field that could not take one — and those are
24089
- // different facts about the same row: the first is a policy the user chose,
24090
- // the second is a masking the host could not perform. Absent means no
24091
- // degrade happened, which is every ordinary capture.
24092
- //
24093
- // TWO LIMITS a reader of a stored row has to know, because the grain here
24094
- // is the CAPTURE while `actionTaken` is per FINDING:
24095
- //
24096
- // - It does not say WHICH finding degraded. A capture carrying a degraded
24097
- // `redact` alongside a finding ASSIGNED the same action stores both
24098
- // identically and one reason for the pair; attributing it to both
24099
- // describes the assigned one wrongly, and to neither loses the degrade.
24100
- // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
24101
- // became, not the reason the capture ended as it did — a capture denied
24102
- // by some other finding's own Block policy still carries `block` here,
24103
- // and clearing the workspace's fallback would not have let it through.
24104
- // Gate on the value against what a fallback can produce; never read the
24105
- // field's presence as "this was the fallback's doing".
24106
- //
24107
- // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
24108
- // Closing either means moving the reason onto the finding row, which
24109
- // already carries its own action.
24110
- redactDegradedTo: ActionTaken.optional()
24111
- }).meta({ id: "EventMetadata" });
24112
- var Event = external_exports.object({
24113
- id: external_exports.guid(),
24114
- sourceTool: SourceTool,
24115
- kind: EventKind,
24116
- occurredAt: external_exports.iso.datetime(),
24117
- contentHash: external_exports.string(),
24118
- content: external_exports.string(),
24119
- metadata: EventMetadata.optional()
24120
- }).meta({ id: "Event" });
24121
- var IngestEvent = Event.meta({ id: "IngestEvent" });
24122
- var INGEST_BATCH_MAX = 100;
24123
- var IngestBatch = external_exports.object({
24124
- events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
24125
- // Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
24126
- // additionally rejects any event whose contentHash the store has already
24127
- // recorded — for re-runnable bulk ingest (worktree scan, transcript
24128
- // backfill), where a re-run mints fresh event ids for identical content and
24129
- // would otherwise accumulate duplicates. Live hook traffic must NOT set it:
24130
- // two genuinely separate prompts can be byte-identical and both belong on
24131
- // the timeline.
24132
- dedupe: external_exports.literal("content-hash").optional()
24133
- }).meta({ id: "IngestBatch" });
24134
-
24135
24260
  // ../../packages/schema/src/zod/exception.ts
24136
24261
  var ExceptionScope = external_exports.enum(["once", "temporary", "permanent"]);
24137
24262
  var ExceptionConditions = external_exports.object({
@@ -24599,6 +24724,8 @@ function toInstanceDetail(row) {
24599
24724
  provider: toApiProvider(row.sourceTool),
24600
24725
  repo: row.repo,
24601
24726
  file: row.file,
24727
+ ...row.line === void 0 ? {} : { line: row.line },
24728
+ ...row.col === void 0 ? {} : { col: row.col },
24602
24729
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
24603
24730
  eventId: row.eventId,
24604
24731
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
@@ -24612,7 +24739,11 @@ function toInstanceDetail(row) {
24612
24739
  category,
24613
24740
  subtype: row.ruleId,
24614
24741
  severity: row.severity,
24615
- match: { maskedValue: row.maskedMatch, contextPrefix: "" },
24742
+ match: {
24743
+ maskedValue: row.maskedMatch,
24744
+ contextPrefix: "",
24745
+ ...row.context === void 0 ? {} : { context: row.context }
24746
+ },
24616
24747
  detection: { id: row.ruleId, name: null },
24617
24748
  policy: { id: `category:${category}`, name: category }
24618
24749
  };
@@ -24724,8 +24855,6 @@ var Policy = external_exports.object({
24724
24855
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
24725
24856
  provenance: PolicyProvenance.optional()
24726
24857
  }).meta({ id: "Policy" });
24727
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
24728
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
24729
24858
  var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
24730
24859
  id: "RedactFallback"
24731
24860
  });
@@ -25112,7 +25241,7 @@ var VaultConsent = external_exports.object({
25112
25241
  });
25113
25242
 
25114
25243
  // ../../packages/schema/src/zod/local.ts
25115
- var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
25244
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 9;
25116
25245
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
25117
25246
  var RunMode = external_exports.enum(["standalone", "attached"]);
25118
25247
  var ControlPlaneConnection = external_exports.object({
@@ -25132,6 +25261,18 @@ var HistorySyncConsent = external_exports.object({
25132
25261
  payloadVersion: external_exports.number().int().positive(),
25133
25262
  endpoint: external_exports.string()
25134
25263
  });
25264
+ var ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH = 512;
25265
+ var AttachmentScopeEntry = external_exports.object({
25266
+ kind: external_exports.enum(["repo", "account"]),
25267
+ identity: printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH).min(1),
25268
+ label: printable(80).optional(),
25269
+ enrolledAt: external_exports.iso.datetime()
25270
+ });
25271
+ var AttachmentScope = external_exports.object({
25272
+ endpoint: external_exports.string().min(1),
25273
+ entries: external_exports.array(AttachmentScopeEntry)
25274
+ });
25275
+ var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
25135
25276
  var WebChatCaptureConsent = external_exports.object({
25136
25277
  acknowledgedAt: external_exports.iso.datetime(),
25137
25278
  version: external_exports.number().int().positive()
@@ -25202,6 +25343,23 @@ var WorkspaceSettings = external_exports.object({
25202
25343
  // both widenings. Absent until granted, and a grant for a different endpoint
25203
25344
  // or an older payload no longer counts.
25204
25345
  historySyncConsent: HistorySyncConsent.optional(),
25346
+ // The identities a SCOPED attachment forwards and the deployment they were
25347
+ // enrolled for (see AttachmentScope). Absent until something is enrolled.
25348
+ //
25349
+ // `z.unknown()`, NOT `AttachmentScope`, and the difference is this field's
25350
+ // whole failure mode. A settings.json that fails this schema reads as the
25351
+ // unonboarded defaults (readUserSettings in @akasecurity/persistence), and the
25352
+ // next save writes those defaults back over it. Typed, one entry with an
25353
+ // unknown `kind`, a control character or a bad timestamp would cost the
25354
+ // attachment, every consent and onboardedAt, permanently. Untyped, the value
25355
+ // is kept exactly as found and validated where it is used: parseAttachmentScope
25356
+ // drops a bad entry by itself, and on a scoped attachment resolveScope reads a
25357
+ // bad envelope as no entries, which keeps every event local.
25358
+ //
25359
+ // No default: absent must stay absent, so defaultWorkspaceSettings() and a
25360
+ // fresh settings.json do not change. No `.meta({ id })`, like every field
25361
+ // here. Not a ManagedSettingKey.
25362
+ attachmentScope: external_exports.unknown().optional(),
25205
25363
  // What the browser extension may record from a web chat, and the grant that
25206
25364
  // authorizes it. Absent until the user answers: recording something that was
25207
25365
  // never recorded before is never an assumed grant on upgrade, so the whole
@@ -25299,7 +25457,10 @@ function toInspectionFindingRow(input2) {
25299
25457
  actionTaken: input2.actionTaken,
25300
25458
  confidence: input2.confidence,
25301
25459
  findingKey: input2.findingKey ?? null,
25302
- firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
25460
+ firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null,
25461
+ line: input2.line ?? null,
25462
+ col: input2.col ?? null,
25463
+ context: input2.context ? JSON.stringify(input2.context) : null
25303
25464
  };
25304
25465
  }
25305
25466
  function toCaptureAttributes(event) {
@@ -26451,6 +26612,15 @@ var COUNTED_SCOPE = `
26451
26612
  OR outbox_owed = 1
26452
26613
  )`;
26453
26614
  var SKIPPED = -1;
26615
+ function inScope(column) {
26616
+ return `${column} IN (SELECT value FROM json_each(:scopeKeys))`;
26617
+ }
26618
+ function scopeKeysParam(scopeKeys) {
26619
+ return JSON.stringify(scopeKeys);
26620
+ }
26621
+ var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26622
+ FROM audit_events AS session_root
26623
+ WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26454
26624
  var ROW_COLUMNS = `id,
26455
26625
  parent_id AS parentId,
26456
26626
  root_session_id AS rootSessionId,
@@ -26479,6 +26649,18 @@ var SqliteHistorySyncRepository = class {
26479
26649
  ORDER BY earliest
26480
26650
  LIMIT :limit`
26481
26651
  );
26652
+ this.scopedSessionsStmt = db.prepare(
26653
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
26654
+ FROM audit_events
26655
+ WHERE synced_at IS NULL
26656
+ AND event_type IN (${TYPE_LIST})
26657
+ AND started_at < :before
26658
+ AND ${inScope("scope_key")}
26659
+ AND ${inScope(ROOT_SCOPE_KEY)}
26660
+ GROUP BY sessionId
26661
+ ORDER BY earliest
26662
+ LIMIT :limit`
26663
+ );
26482
26664
  this.rowsStmt = db.prepare(
26483
26665
  `SELECT ${ROW_COLUMNS}
26484
26666
  FROM audit_events
@@ -26489,6 +26671,18 @@ var SqliteHistorySyncRepository = class {
26489
26671
  ORDER BY (event_type = 'session') DESC, started_at
26490
26672
  LIMIT :limit`
26491
26673
  );
26674
+ this.scopedRowsStmt = db.prepare(
26675
+ `SELECT ${ROW_COLUMNS}
26676
+ FROM audit_events
26677
+ WHERE synced_at IS NULL
26678
+ AND event_type IN (${TYPE_LIST})
26679
+ AND started_at < :before
26680
+ AND COALESCE(root_session_id, id) = :sessionId
26681
+ AND ${inScope("scope_key")}
26682
+ AND ${inScope(ROOT_SCOPE_KEY)}
26683
+ ORDER BY (event_type = 'session') DESC, started_at
26684
+ LIMIT :limit`
26685
+ );
26492
26686
  this.captureRowsStmt = db.prepare(
26493
26687
  `SELECT ${ROW_COLUMNS}
26494
26688
  FROM audit_events
@@ -26500,6 +26694,18 @@ var SqliteHistorySyncRepository = class {
26500
26694
  ORDER BY started_at
26501
26695
  LIMIT :limit`
26502
26696
  );
26697
+ this.scopedCaptureRowsStmt = db.prepare(
26698
+ `SELECT ${ROW_COLUMNS}
26699
+ FROM audit_events
26700
+ WHERE synced_at IS NULL
26701
+ AND sync_claimed_at IS NULL
26702
+ AND outbox_owed = 1
26703
+ AND event_type IN (${CAPTURE_TYPE_LIST})
26704
+ AND started_at < :before
26705
+ AND ${inScope("scope_key")}
26706
+ ORDER BY started_at
26707
+ LIMIT :limit`
26708
+ );
26503
26709
  this.markOwedStmt = db.prepare(
26504
26710
  `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
26505
26711
  );
@@ -26509,6 +26715,20 @@ var SqliteHistorySyncRepository = class {
26509
26715
  AND event_type IN (${CAPTURE_TYPE_LIST})
26510
26716
  AND started_at < :before`
26511
26717
  );
26718
+ this.scopedCaptureBacklogOwedStmt = db.prepare(
26719
+ `UPDATE audit_events SET outbox_owed = 1
26720
+ WHERE synced_at IS NULL
26721
+ AND event_type IN (${CAPTURE_TYPE_LIST})
26722
+ AND started_at < :before
26723
+ AND ${inScope("scope_key")}`
26724
+ );
26725
+ this.markScopeCapturesOwedStmt = db.prepare(
26726
+ `UPDATE audit_events SET outbox_owed = 1
26727
+ WHERE synced_at IS NULL
26728
+ AND outbox_owed IS NULL
26729
+ AND event_type IN (${CAPTURE_TYPE_LIST})
26730
+ AND ${inScope("scope_key")}`
26731
+ );
26512
26732
  this.stampStmt = db.prepare(
26513
26733
  `UPDATE audit_events
26514
26734
  SET synced_at = :at,
@@ -26667,6 +26887,15 @@ var SqliteHistorySyncRepository = class {
26667
26887
  claimRowStmt;
26668
26888
  releaseRowStmt;
26669
26889
  releaseStaleClaimsStmt;
26890
+ // The SCOPED twins, for a scoped attachment: the same reads and seeds with the
26891
+ // scope clause added, prepared once here beside the machine statements, so a
26892
+ // machine attachment's statements are untouched and neither form is compiled
26893
+ // per call.
26894
+ scopedSessionsStmt;
26895
+ scopedRowsStmt;
26896
+ scopedCaptureRowsStmt;
26897
+ scopedCaptureBacklogOwedStmt;
26898
+ markScopeCapturesOwedStmt;
26670
26899
  /**
26671
26900
  * The masked detections recorded against one tool call.
26672
26901
  *
@@ -26686,15 +26915,33 @@ var SqliteHistorySyncRepository = class {
26686
26915
  * path's to deliver; this drain exists for what was recorded before it, and a
26687
26916
  * row both paths send is at best a duplicate request and at worst — for a
26688
26917
  * session root — an overwrite of the inventory ids the live path resolved.
26918
+ *
26919
+ * `scopeKeys` is a scoped attachment's filter: a session is offered only while
26920
+ * its root's key is one of them AND at least one of its unsent rows' keys is
26921
+ * (see scopedSessionsStmt). Omitted, this runs the machine statement,
26922
+ * unchanged; an empty list offers nothing.
26689
26923
  */
26690
- pendingSessions(limit, before) {
26691
- return allRows(this.sessionsStmt, { limit, before }).map(
26692
- (r) => r.sessionId
26693
- );
26924
+ pendingSessions(limit, before, scopeKeys) {
26925
+ const rows = scopeKeys === void 0 ? allRows(this.sessionsStmt, { limit, before }) : allRows(this.scopedSessionsStmt, {
26926
+ limit,
26927
+ before,
26928
+ scopeKeys: scopeKeysParam(scopeKeys)
26929
+ });
26930
+ return rows.map((r) => r.sessionId);
26694
26931
  }
26695
- /** One session's undelivered structural rows within the backlog, root first. */
26696
- pendingRows(sessionId, limit, before) {
26697
- return allRows(this.rowsStmt, { sessionId, limit, before });
26932
+ /**
26933
+ * One session's undelivered structural rows within the backlog, root first.
26934
+ *
26935
+ * With `scopeKeys`, only the rows whose own key AND whose session root's key
26936
+ * are among them, whichever session id is passed.
26937
+ */
26938
+ pendingRows(sessionId, limit, before, scopeKeys) {
26939
+ return scopeKeys === void 0 ? allRows(this.rowsStmt, { sessionId, limit, before }) : allRows(this.scopedRowsStmt, {
26940
+ sessionId,
26941
+ limit,
26942
+ before,
26943
+ scopeKeys: scopeKeysParam(scopeKeys)
26944
+ });
26698
26945
  }
26699
26946
  /**
26700
26947
  * Captures this machine still owes the deployment, oldest first.
@@ -26703,9 +26950,17 @@ var SqliteHistorySyncRepository = class {
26703
26950
  * by a time window — see captureRowsStmt for why a window could not express
26704
26951
  * this. `before` is the grace window that leaves a just-recorded capture to
26705
26952
  * the live path.
26953
+ *
26954
+ * With `scopeKeys`, only captures stamped with one of them, decided per
26955
+ * capture: /v1/events stubs a missing root, so a capture never waits on its
26956
+ * session's scope. An empty list reads nothing.
26706
26957
  */
26707
- pendingCaptureRows(limit, before) {
26708
- return allRows(this.captureRowsStmt, { limit, before });
26958
+ pendingCaptureRows(limit, before, scopeKeys) {
26959
+ return scopeKeys === void 0 ? allRows(this.captureRowsStmt, { limit, before }) : allRows(this.scopedCaptureRowsStmt, {
26960
+ limit,
26961
+ before,
26962
+ scopeKeys: scopeKeysParam(scopeKeys)
26963
+ });
26709
26964
  }
26710
26965
  /**
26711
26966
  * Record that a capture is OWED to the deployment.
@@ -26737,9 +26992,37 @@ var SqliteHistorySyncRepository = class {
26737
26992
  * Returns how many rows matched, for the caller to log or test against. Not a
26738
26993
  * count of NEWLY marked rows — a row still unsynced from an earlier call
26739
26994
  * matches again and is counted again, the same as `UPDATE`'s own `changes`.
26995
+ *
26996
+ * `scopeKeys` scopes it for a scoped attachment: only captures stamped with one
26997
+ * of the keys are marked, and an empty list marks none. The scoped capture read
26998
+ * is what keeps a personal capture out of a batch; this keeps the marker to
26999
+ * what the grant covers. Omitted, it runs the machine statement, unchanged.
27000
+ */
27001
+ markCaptureBacklogOwed(before, scopeKeys) {
27002
+ const result = scopeKeys === void 0 ? this.markCaptureBacklogOwedStmt.run({ before }) : this.scopedCaptureBacklogOwedStmt.run({ before, scopeKeys: scopeKeysParam(scopeKeys) });
27003
+ return Number(result.changes);
27004
+ }
27005
+ /**
27006
+ * Mark owed every unsent capture stamped with one of `scopeKeys`: the re-seed
27007
+ * an enrollment runs.
27008
+ *
27009
+ * This ASSUMES the contract a scoped caller keeps, and cannot check it: nothing
27010
+ * else marks an out-of-scope capture owed (the live forward must refuse it
27011
+ * before its owed branch, and the consent-time seed must be handed the key
27012
+ * list). Under that contract, an enrolled repository's unsent captures are
27013
+ * reachable only if this runs when the repository is enrolled. Like the
27014
+ * consent seed it is one explicit human action, never something a pass infers,
27015
+ * and its caller must know the history grant is in force: this method cannot
27016
+ * check consent and must not be called without it.
27017
+ *
27018
+ * No time bound. Delivered and skipped rows are never re-opened, and a row
27019
+ * already owed is not counted, so the return value is how many rows this call
27020
+ * newly marked. An empty list marks nothing.
26740
27021
  */
26741
- markCaptureBacklogOwed(before) {
26742
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27022
+ markScopeCapturesOwed(scopeKeys) {
27023
+ return Number(
27024
+ this.markScopeCapturesOwedStmt.run({ scopeKeys: scopeKeysParam(scopeKeys) }).changes
27025
+ );
26743
27026
  }
26744
27027
  /**
26745
27028
  * Record delivery. Called only AFTER the far side has accepted the rows.
@@ -26944,8 +27227,12 @@ var SqliteHistorySyncRepository = class {
26944
27227
  * disown from eating THIS SAME CALL's own re-mark is the order, not the
26945
27228
  * bound — disown runs first, re-mark second, both inside the one
26946
27229
  * transaction above.
27230
+ *
27231
+ * `scopeKeys` scopes the re-mark exactly as `markCaptureBacklogOwed` is scoped.
27232
+ * The disown before it is not scoped, and must not be: it clears the previous
27233
+ * deployment's markers whatever their scope.
26947
27234
  */
26948
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
27235
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore, scopeKeys) {
26949
27236
  this.ensureRowStmt.run();
26950
27237
  withTransaction(
26951
27238
  this.db,
@@ -26956,7 +27243,7 @@ var SqliteHistorySyncRepository = class {
26956
27243
  this.disownCapturesStmt.run({ attachedAt: backlogBefore });
26957
27244
  }
26958
27245
  if (backfillCapturesBefore !== void 0) {
26959
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
27246
+ this.markCaptureBacklogOwed(backfillCapturesBefore, scopeKeys);
26960
27247
  }
26961
27248
  this.setFingerprintStmt.run({ fingerprint, backlogBefore });
26962
27249
  },
@@ -27122,6 +27409,7 @@ function applyMigrations(db, file2, options = {}) {
27122
27409
  db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
27123
27410
  }
27124
27411
  ensureSyncedAtColumn(db, "audit_events");
27412
+ ensureScopeKeyColumn(db);
27125
27413
  ensureScanLedgerTable(db);
27126
27414
  ensureHistorySyncTable(db);
27127
27415
  ensureBlockedDetectionsTable(db);
@@ -27547,6 +27835,21 @@ function ensureSyncedAtColumn(db, table) {
27547
27835
  ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
27548
27836
  );
27549
27837
  }
27838
+ 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";
27839
+ function ensureScopeKeyColumn(db) {
27840
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27841
+ if (hasScopeKeyColumn(db)) return;
27842
+ withTransaction(
27843
+ db,
27844
+ () => {
27845
+ if (!hasScopeKeyColumn(db)) db.exec(SCOPE_KEY_COLUMN_DDL);
27846
+ },
27847
+ "IMMEDIATE"
27848
+ );
27849
+ }
27850
+ function hasScopeKeyColumn(db) {
27851
+ return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
27852
+ }
27550
27853
  function ensureScanLedgerTable(db) {
27551
27854
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27552
27855
  path TEXT PRIMARY KEY,
@@ -28424,6 +28727,19 @@ var SqliteAuditEventsRepository = class {
28424
28727
  if (typeof provider === "string") return provider;
28425
28728
  return void 0;
28426
28729
  }
28730
+ // The `scope_key` stored on a session root's attributes: the key the history
28731
+ // drain decides that root by. It is NOT necessarily the key of the root event a
28732
+ // caller just wrote, because roots are first-write-wins (see the session-root
28733
+ // upsert above) and the root event that arrives second leaves the stored row as
28734
+ // it was. Returns undefined when the id is not a session root, when the root is
28735
+ // a stub or carries no key, and when the stored value is not a string, which is
28736
+ // what the drain's scoped reads would not match either.
28737
+ sessionScopeKey(sessionId) {
28738
+ const row = this.findById(sessionId);
28739
+ if (row?.event_type !== "session" || !row.attributes) return void 0;
28740
+ const key = parseJsonObject(row.attributes)?.scope_key;
28741
+ return typeof key === "string" ? key : void 0;
28742
+ }
28427
28743
  // Every `llm_call` leaf's session id + raw attribute bag, for the read-time token
28428
28744
  // rollups. The caller parses each bag and prices it via the
28429
28745
  // cost model — we stay a thin reader here (no business logic, no cost). `root_session_id`
@@ -28444,6 +28760,8 @@ var SqliteAuditEventsRepository = class {
28444
28760
  var DEFAULT_BATCH_SIZE = 500;
28445
28761
  var DEFAULT_MAX_ROWS = 5e4;
28446
28762
  var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
28763
+ var SWEEP = { kind: "sweep" };
28764
+ var HOLD_ALL = { kind: "hold-all" };
28447
28765
  var SqliteBodyRetentionRepository = class {
28448
28766
  constructor(db) {
28449
28767
  this.db = db;
@@ -28460,6 +28778,14 @@ var SqliteBodyRetentionRepository = class {
28460
28778
  this.candidatesSyncSafeStmt = this.db.prepare(
28461
28779
  select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
28462
28780
  );
28781
+ this.candidatesScopedStmt = this.db.prepare(
28782
+ select(
28783
+ `AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL
28784
+ OR (outbox_owed IS NOT 1
28785
+ AND (scope_key IS NULL
28786
+ OR scope_key NOT IN (SELECT value FROM json_each(:scopeKeys)))))`
28787
+ )
28788
+ );
28463
28789
  this.heldBySyncStmt = this.db.prepare(`
28464
28790
  SELECT COUNT(*) AS n
28465
28791
  FROM audit_events
@@ -28467,37 +28793,63 @@ var SqliteBodyRetentionRepository = class {
28467
28793
  AND started_at < :cutoff
28468
28794
  AND event_type IN (${SYNC_LANE_TYPES_SQL})
28469
28795
  AND synced_at IS NULL`);
28796
+ this.heldByScopeStmt = this.db.prepare(`
28797
+ SELECT COUNT(*) AS n
28798
+ FROM audit_events
28799
+ WHERE content IS NOT NULL
28800
+ AND started_at < :cutoff
28801
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
28802
+ AND synced_at IS NULL
28803
+ AND (outbox_owed = 1
28804
+ OR scope_key IN (SELECT value FROM json_each(:scopeKeys)))`);
28470
28805
  this.expireStmt = this.db.prepare(
28471
28806
  `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
28472
28807
  );
28808
+ this.expireContextsStmt = this.db.prepare(
28809
+ `UPDATE inspection_findings SET context = NULL
28810
+ WHERE id IN (
28811
+ SELECT f.id
28812
+ FROM inspection_findings f INDEXED BY idx_inspection_findings_context
28813
+ JOIN audit_events e ON e.id = f.audit_event_id
28814
+ WHERE f.context IS NOT NULL
28815
+ AND f.first_detected_at < :cutoff
28816
+ AND e.content IS NULL
28817
+ AND e.started_at < :cutoff
28818
+ LIMIT :limit)`
28819
+ );
28473
28820
  }
28474
28821
  db;
28475
28822
  candidatesStmt;
28476
28823
  candidatesSyncSafeStmt;
28824
+ candidatesScopedStmt;
28477
28825
  heldBySyncStmt;
28826
+ heldByScopeStmt;
28478
28827
  expireStmt;
28479
- /** How many bytes a pass with these options would free, changing nothing. */
28828
+ expireContextsStmt;
28829
+ /**
28830
+ * How many body bytes a pass with these options would free, changing
28831
+ * nothing. Finding excerpts are not counted (see `bytesFreed`).
28832
+ */
28480
28833
  preview(opts) {
28481
- const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
28482
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
28483
- const rows = stmt.all({ cutoff: opts.cutoff, limit });
28834
+ const lane = laneOf(opts.sweepSyncLane);
28835
+ const rows = this.candidates(lane, opts.cutoff, opts.maxRows ?? DEFAULT_MAX_ROWS);
28484
28836
  return {
28485
28837
  rowsExpired: rows.length,
28486
28838
  bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
28487
- rowsHeldBySync: this.countHeldBySync(opts)
28839
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff)
28488
28840
  };
28489
28841
  }
28490
28842
  /** Clear eligible bodies, in bounded batches. */
28491
28843
  expire(opts) {
28492
28844
  const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
28493
28845
  const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
28494
- const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
28846
+ const lane = laneOf(opts.sweepSyncLane);
28495
28847
  let rowsExpired = 0;
28496
28848
  let bytesFreed = 0;
28497
28849
  let done = true;
28498
28850
  while (rowsExpired < maxRows) {
28499
28851
  const remaining = Math.min(batchSize, maxRows - rowsExpired);
28500
- const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
28852
+ const batch = this.candidates(lane, opts.cutoff, remaining);
28501
28853
  if (batch.length === 0) break;
28502
28854
  withTransaction(
28503
28855
  this.db,
@@ -28510,17 +28862,60 @@ var SqliteBodyRetentionRepository = class {
28510
28862
  bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
28511
28863
  if (batch.length < remaining) break;
28512
28864
  if (rowsExpired >= maxRows) {
28513
- done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
28865
+ done = this.candidates(lane, opts.cutoff, 1).length === 0;
28514
28866
  }
28515
28867
  }
28516
- return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
28868
+ this.expireContexts(opts.cutoff, batchSize, maxRows);
28869
+ return {
28870
+ rowsExpired,
28871
+ bytesFreed,
28872
+ rowsHeldBySync: this.countHeldBySync(lane, opts.cutoff),
28873
+ done
28874
+ };
28517
28875
  }
28518
- countHeldBySync(opts) {
28519
- if (opts.sweepSyncLane) return 0;
28520
- const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
28876
+ // Clear the excerpts that outlived their body, one bounded transaction per
28877
+ // batch for the same reason the body sweep batches, and at most `maxRows` of
28878
+ // them per pass under the same cap: the next pass picks up the rest.
28879
+ expireContexts(cutoff, batchSize, maxRows) {
28880
+ let total = 0;
28881
+ while (total < maxRows) {
28882
+ const limit = Math.min(batchSize, maxRows - total);
28883
+ let cleared = 0;
28884
+ withTransaction(
28885
+ this.db,
28886
+ () => {
28887
+ cleared = Number(this.expireContextsStmt.run({ cutoff, limit }).changes);
28888
+ },
28889
+ "IMMEDIATE"
28890
+ );
28891
+ total += cleared;
28892
+ if (cleared < limit) return;
28893
+ }
28894
+ }
28895
+ /**
28896
+ * One batch of candidates under `lane`, bound with exactly the parameters its
28897
+ * statement names — node:sqlite refuses a named parameter a statement does not
28898
+ * declare, so the key list goes to the scoped statements only.
28899
+ *
28900
+ * Anything that is not `sweep` or `hold-keys` takes the hold-all statement.
28901
+ * The type admits no fourth kind, but this decides what is destroyed, and the
28902
+ * direction an unforeseen value falls has to be holding.
28903
+ */
28904
+ candidates(lane, cutoff, limit) {
28905
+ 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 });
28906
+ return rows;
28907
+ }
28908
+ countHeldBySync(lane, cutoff) {
28909
+ if (lane.kind === "sweep") return 0;
28910
+ const row = lane.kind === "hold-keys" ? this.heldByScopeStmt.get({ cutoff, scopeKeys: JSON.stringify(lane.keys) }) : this.heldBySyncStmt.get({ cutoff });
28521
28911
  return row.n;
28522
28912
  }
28523
28913
  };
28914
+ function laneOf(gate) {
28915
+ if (gate === true) return SWEEP;
28916
+ if (gate === false) return HOLD_ALL;
28917
+ return gate;
28918
+ }
28524
28919
 
28525
28920
  // ../../packages/persistence/src/repositories/capture-status.ts
28526
28921
  var STATUS_LOOKBACK_ROWS = 128;
@@ -29429,6 +29824,8 @@ function toFlatFindingRow(r) {
29429
29824
  repo: r.repo ?? "",
29430
29825
  file: r.file ?? "",
29431
29826
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
29827
+ ...r.line === null ? {} : { line: r.line },
29828
+ ...r.col === null ? {} : { col: r.col },
29432
29829
  eventId: r.event_id,
29433
29830
  ...r.session_id === null ? {} : { sessionId: r.session_id },
29434
29831
  status: deriveInstanceStatus(r),
@@ -29506,7 +29903,8 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
29506
29903
  ${latestResolutionStatusSql("f")} AS latest_status,
29507
29904
  e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
29508
29905
  e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
29509
- e.outbox_owed AS outbox_owed`;
29906
+ e.outbox_owed AS outbox_owed,
29907
+ f.line AS line, f.col AS col`;
29510
29908
  var DAY_MS3 = 864e5;
29511
29909
  var SqliteFindingsRepository = class {
29512
29910
  constructor(db) {
@@ -29929,6 +30327,27 @@ var SqliteFindingsRepository = class {
29929
30327
  ).get(id);
29930
30328
  return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
29931
30329
  }
30330
+ /**
30331
+ * One finding's excerpt source (see FindingContextSource). A primary-key
30332
+ * seek, like `findingInstance`, and the only findings read that touches the
30333
+ * event's text — which is why the list never projects the excerpt and the
30334
+ * drawer asks for it here, one finding at a time.
30335
+ */
30336
+ findingContextSource(id) {
30337
+ const row = this.db.prepare(
30338
+ `SELECT f.context AS context, e.content AS content,
30339
+ f.span_start AS spanStart, f.span_end AS spanEnd,
30340
+ d.rule_id AS ruleId, d.category AS category,
30341
+ json_extract(e.attributes, '$.whole_file') AS wholeFile,
30342
+ e.tool_name AS toolName, e.event_type AS eventType
30343
+ FROM inspection_findings f
30344
+ JOIN audit_events e ON e.id = f.audit_event_id
30345
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30346
+ WHERE f.id = ?`
30347
+ ).get(id);
30348
+ if (row === void 0) return null;
30349
+ return { ...row, wholeFile: row.wholeFile === 1 };
30350
+ }
29932
30351
  /**
29933
30352
  * The one statement both instance-level scans run: every finding in scope,
29934
30353
  * joined to its event and definition, newest first.
@@ -30065,6 +30484,61 @@ var SqliteFindingsRepository = class {
30065
30484
  ])
30066
30485
  );
30067
30486
  }
30487
+ /**
30488
+ * The Findings page's summary strip: whole-store counts over exactly the rows
30489
+ * the instance reads list (the four capture kinds), each equal to what
30490
+ * listFindingInstances totals for the same filters — see FindingsOverview.
30491
+ *
30492
+ * ONE grouped aggregate whose keys are the raw classifier inputs, not the
30493
+ * answers: the statement groups by the three inputs deriveFindingStatus
30494
+ * reads, and each group is then classified here by that same function. So
30495
+ * SQL never restates the status rule, and the strip cannot disagree with the
30496
+ * list about which status a finding has. The group count is bounded by a
30497
+ * handful of status inputs, not by the store, so only the scan grows with it
30498
+ * — the same linear cost every other unscoped read on the page already pays.
30499
+ *
30500
+ * The definitions join selects nothing. It is there because the list's scan
30501
+ * joins it too, so a finding whose definition row is missing is left out of
30502
+ * both rather than counted here and absent there.
30503
+ *
30504
+ * The latest-resolution join is the derived-table form, which
30505
+ * resolution-sql.ts recommends for an aggregate over many findings.
30506
+ */
30507
+ findingsOverview() {
30508
+ const rows = allRows(
30509
+ this.db.prepare(
30510
+ `SELECT e.event_type AS kind, (f.finding_key IS NOT NULL) AS keyed,
30511
+ latest.status AS latest_status, count(*) AS c
30512
+ FROM inspection_findings f
30513
+ JOIN audit_events e ON e.id = f.audit_event_id
30514
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30515
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30516
+ ON latest.finding_key = f.finding_key
30517
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
30518
+ GROUP BY e.event_type, keyed, latest.status`
30519
+ )
30520
+ );
30521
+ const byStatus = {
30522
+ open: 0,
30523
+ handled: 0,
30524
+ resolved: 0,
30525
+ dismissed: 0
30526
+ };
30527
+ let findings = 0;
30528
+ for (const row of rows) {
30529
+ const status = deriveFindingStatus({
30530
+ kind: row.kind,
30531
+ // The classifier only asks whether a key exists, never what it is. The
30532
+ // stand-in is non-empty so a truthiness test of the key reads it as
30533
+ // present, exactly as it would a real one.
30534
+ findingKey: row.keyed ? "keyed" : null,
30535
+ latestResolutionStatus: row.latest_status
30536
+ });
30537
+ findings += row.c;
30538
+ byStatus[status] += row.c;
30539
+ }
30540
+ return Promise.resolve({ findings, ...byStatus });
30541
+ }
30068
30542
  healthSummary() {
30069
30543
  const total = countScalar(
30070
30544
  this.db,
@@ -30192,12 +30666,13 @@ var SqliteInspectionFindingsRepository = class {
30192
30666
  `INSERT INTO inspection_findings
30193
30667
  (id, audit_event_id, inspection_definition_id, classified_data_id,
30194
30668
  span_start, span_end, masked_match, action_taken, confidence,
30195
- finding_key, first_detected_at)
30669
+ finding_key, first_detected_at, line, col, context)
30196
30670
  VALUES
30197
30671
  (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
30198
30672
  :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
30199
30673
  :findingKey,
30200
- COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
30674
+ COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)),
30675
+ :line, :col, :context)
30201
30676
  ON CONFLICT(id) DO UPDATE SET
30202
30677
  inspection_definition_id = excluded.inspection_definition_id
30203
30678
  ON CONFLICT (finding_key) DO UPDATE SET
@@ -30208,7 +30683,10 @@ var SqliteInspectionFindingsRepository = class {
30208
30683
  span_end = excluded.span_end,
30209
30684
  masked_match = excluded.masked_match,
30210
30685
  action_taken = excluded.action_taken,
30211
- confidence = excluded.confidence`
30686
+ confidence = excluded.confidence,
30687
+ line = excluded.line,
30688
+ col = excluded.col,
30689
+ context = excluded.context`
30212
30690
  );
30213
30691
  this.sessionDupStmt = db.prepare(
30214
30692
  `SELECT 1 FROM inspection_findings f
@@ -30258,7 +30736,10 @@ var SqliteInspectionFindingsRepository = class {
30258
30736
  actionTaken: row.actionTaken,
30259
30737
  confidence: row.confidence,
30260
30738
  findingKey: row.findingKey,
30261
- firstDetectedAt: row.firstDetectedAt
30739
+ firstDetectedAt: row.firstDetectedAt,
30740
+ line: row.line,
30741
+ col: row.col,
30742
+ context: row.context
30262
30743
  })
30263
30744
  );
30264
30745
  }
@@ -30599,8 +31080,8 @@ var SqliteInstalledPacksRepository = class {
30599
31080
  this.db = db;
30600
31081
  this.baseDir = baseDir;
30601
31082
  this.insertMissingStmt = db.prepare(
30602
- `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
30603
- VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
31083
+ `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31084
+ VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
30604
31085
  ON CONFLICT (namespace, pack_id) DO NOTHING`
30605
31086
  );
30606
31087
  this.upsertAvailableStmt = db.prepare(
@@ -30660,7 +31141,10 @@ var SqliteInstalledPacksRepository = class {
30660
31141
  version: pack.version,
30661
31142
  name: pack.name,
30662
31143
  rulesJson: JSON.stringify(pack.rules),
30663
- ruleIds: new Set(pack.rules.map((r) => r.id))
31144
+ ruleIds: new Set(pack.rules.map((r) => r.id)),
31145
+ // Only a first install takes it: an existing row is never modified here,
31146
+ // so a policy the user chose (or cleared) is never overwritten.
31147
+ defaultPolicyId: pack.defaultPolicyId ?? null
30664
31148
  }));
30665
31149
  if (this.storedSignature() === inventorySignature(rows)) return;
30666
31150
  const now = Date.now();
@@ -30689,7 +31173,7 @@ var SqliteInstalledPacksRepository = class {
30689
31173
  } else {
30690
31174
  behind = true;
30691
31175
  }
30692
- this.insertMissingStmt.run(params);
31176
+ this.insertMissingStmt.run({ ...params, policyId: row.defaultPolicyId });
30693
31177
  }
30694
31178
  if (!behind) this.pruneAvailable(rows.map((r) => `${r.namespace}/${r.packId}`));
30695
31179
  },
@@ -30807,7 +31291,8 @@ var SqliteInstalledPacksRepository = class {
30807
31291
  rejectedRules: [],
30808
31292
  ruleActions: /* @__PURE__ */ new Map(),
30809
31293
  ruleVersions: /* @__PURE__ */ new Map(),
30810
- reversibleRules: /* @__PURE__ */ new Set()
31294
+ reversibleRules: /* @__PURE__ */ new Set(),
31295
+ assignedRules: /* @__PURE__ */ new Set()
30811
31296
  };
30812
31297
  const reject = (pack, ruleId, reason) => {
30813
31298
  if (out.rejectedRules.length >= REJECTED_RULE_DETAIL_CAP) return;
@@ -30840,6 +31325,8 @@ var SqliteInstalledPacksRepository = class {
30840
31325
  out.ruleVersions.set(parsed.data.id, row.version);
30841
31326
  if (reversible) out.reversibleRules.add(parsed.data.id);
30842
31327
  else out.reversibleRules.delete(parsed.data.id);
31328
+ if (row.policyId !== null) out.assignedRules.add(parsed.data.id);
31329
+ else out.assignedRules.delete(parsed.data.id);
30843
31330
  } else {
30844
31331
  out.invalidRules += 1;
30845
31332
  reject(pack, printableRuleId(entry), firstIssueReason(parsed.error));
@@ -31926,6 +32413,7 @@ var SqliteInventoryAssetsRepository = class {
31926
32413
 
31927
32414
  // ../../packages/persistence/src/repositories/policies.ts
31928
32415
  import { randomUUID as randomUUID6 } from "crypto";
32416
+ var SEED_BATCH_WINDOW_MS = 6e4;
31929
32417
  var SqlitePoliciesRepository = class {
31930
32418
  constructor(db) {
31931
32419
  this.db = db;
@@ -31947,39 +32435,123 @@ var SqlitePoliciesRepository = class {
31947
32435
  });
31948
32436
  return Promise.resolve(policies);
31949
32437
  }
31950
- // Seed one policy per bundled category from DEFAULT_ACTIONS so the
31951
- // detection-type config exists from first run. Only when the table is empty,
31952
- // so a user's edits are never clobbered.
32438
+ // Seed one policy per bundled category at Monitor so the detection-type config
32439
+ // exists from first run. An unassigned pack's rules follow these rows, so
32440
+ // Monitor here is the posture of every pack that ships no defaultPolicy; a pack
32441
+ // that ships one carries its own assignment instead. Only when the
32442
+ // table is empty, so a user's edits are never clobbered.
31953
32443
  seedDefaults() {
31954
32444
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
31955
- if (count > 0) return;
32445
+ if (count > 0) {
32446
+ this.markEarlierChoices();
32447
+ this.monitorUntouchedSeeds();
32448
+ return;
32449
+ }
31956
32450
  const stmt = this.db.prepare(
31957
32451
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
31958
32452
  VALUES (:id, 'global', :target, :action, 1, :now, :now)`
31959
32453
  );
31960
32454
  failOpenTransaction(this.db, () => {
31961
- for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
32455
+ for (const category of Object.keys(DEFAULT_ACTIONS)) {
31962
32456
  stmt.run({
31963
32457
  id: randomUUID6(),
31964
32458
  target: JSON.stringify({ category }),
31965
- action,
32459
+ action: "log",
31966
32460
  now: Date.now()
31967
32461
  });
31968
32462
  }
31969
32463
  });
31970
32464
  }
32465
+ // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32466
+ // equal to created_at, so a choice made for a category that had no row yet
32467
+ // (one added in a release after the store was seeded) looks exactly like a
32468
+ // seed. Left alone, fill-gaps would overwrite it and monitorUntouchedSeeds
32469
+ // could reset it. This pass marks such rows as chosen (updated_at =
32470
+ // created_at + 1) before either can read them. A row is an earlier build's
32471
+ // choice, not its seed, when either:
32472
+ // - its action is neither the old seed value (DEFAULT_ACTIONS) nor Monitor,
32473
+ // which no seed of any build ever wrote; or
32474
+ // - it was created well after the seed batch. Every build seeds all of its
32475
+ // categories in one transaction, and only into an empty table, so a row
32476
+ // created later came from upsertCategoryAction.
32477
+ // It needs no marker of its own: every row this build writes has updated_at >
32478
+ // created_at, and the seeds it leaves equal (fresh 'log' seeds, and seeds
32479
+ // moved to Monitor below, which keep their created_at) match neither test, so
32480
+ // after one pass it finds nothing and stays a read. What it cannot tell apart
32481
+ // is an earlier build's choice that equals the seed value AND was made within
32482
+ // the seed batch window; that row is read as a seed.
32483
+ markEarlierChoices() {
32484
+ const rows = allRows(
32485
+ this.db.prepare(
32486
+ `SELECT id, json_extract(target, '$.category') AS category, action,
32487
+ created_at AS c, updated_at AS u
32488
+ FROM policies
32489
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL`
32490
+ )
32491
+ );
32492
+ if (rows.length === 0) return;
32493
+ const seedBatchStart = Math.min(...rows.map((row) => row.c));
32494
+ const seeded = DEFAULT_ACTIONS;
32495
+ const choices = rows.filter(
32496
+ (row) => row.u === row.c && (row.action !== "log" && row.action !== seeded[row.category] || row.c > seedBatchStart + SEED_BATCH_WINDOW_MS)
32497
+ );
32498
+ if (choices.length === 0) return;
32499
+ const stmt = this.db.prepare(
32500
+ `UPDATE policies SET updated_at = created_at + 1 WHERE id = :id AND updated_at = created_at`
32501
+ );
32502
+ failOpenTransaction(this.db, () => {
32503
+ for (const row of choices) stmt.run({ id: row.id });
32504
+ });
32505
+ }
32506
+ // Stores seeded by an earlier build hold DEFAULT_ACTIONS in their category
32507
+ // rows. Those rows used to be shadowed by the Monitor every unassigned pack
32508
+ // emitted; now that unassigned packs defer to them, an untouched one would
32509
+ // turn Monitor into Warn on upgrade with nobody having asked. So a row still
32510
+ // exactly as seeded — the seeded action, never updated since it was created —
32511
+ // is moved to Monitor. A row the user, the setup wizard or the warn-era cap
32512
+ // ever wrote has a later updated_at and is left alone. updated_at is NOT
32513
+ // advanced, so a moved row still reads as an untouched seed (see
32514
+ // isCategoryChosen); it never matches again because it is no longer off 'log'.
32515
+ // One knock-on: when the installed snapshot is unusable (corrupt rules_json)
32516
+ // the gateway falls back to the bundled packs with no per-rule policies, so
32517
+ // every rule follows these rows. On an upgraded store that fallback now
32518
+ // monitors where the earlier build warned.
32519
+ monitorUntouchedSeeds() {
32520
+ const untouched = allRows(
32521
+ this.db.prepare(
32522
+ `SELECT json_extract(target, '$.category') AS category, action FROM policies
32523
+ WHERE scope = 'global' AND json_extract(target, '$.category') IS NOT NULL
32524
+ AND action <> 'log' AND updated_at = created_at`
32525
+ )
32526
+ ).filter(
32527
+ (row) => DEFAULT_ACTIONS[row.category] === row.action
32528
+ );
32529
+ if (untouched.length === 0) return;
32530
+ const stmt = this.db.prepare(
32531
+ `UPDATE policies SET action = 'log'
32532
+ WHERE scope = 'global' AND json_extract(target, '$.category') = :category
32533
+ AND action = :seeded AND action <> 'log' AND updated_at = created_at`
32534
+ );
32535
+ failOpenTransaction(this.db, () => {
32536
+ for (const row of untouched) {
32537
+ stmt.run({ category: row.category, seeded: row.action });
32538
+ }
32539
+ });
32540
+ }
31971
32541
  // Insert-or-update the single global per-category policy row, keyed on the
31972
32542
  // existing uq_policies_scope_target unique index (scope, target). `action`
31973
32543
  // uses the SAME vocabulary seedDefaults writes (DEFAULT_ACTIONS' ActionTaken
31974
32544
  // values), so the runtime's resolveAction reads rows written by either path
31975
32545
  // identically. On conflict, `action`, `enabled`, and `updated_at` are updated;
31976
- // `id` and `created_at` are left exactly as they were.
32546
+ // `id` and `created_at` are left exactly as they were. Either way updated_at
32547
+ // ends up later than created_at, which is what marks the row as chosen.
31977
32548
  upsertCategoryAction(category, action) {
31978
32549
  const now = Date.now();
31979
32550
  this.db.prepare(
31980
32551
  `INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
31981
- VALUES (:id, 'global', :target, :action, 1, :now, :now)
31982
- ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
32552
+ VALUES (:id, 'global', :target, :action, 1, :now, :now + 1)
32553
+ ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32554
+ updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
31983
32555
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
31984
32556
  }
31985
32557
  // Caps every global per-category policy currently set to block/redact down
@@ -31993,6 +32565,16 @@ var SqlitePoliciesRepository = class {
31993
32565
  ).run({ now: Date.now() });
31994
32566
  return Number(info.changes);
31995
32567
  }
32568
+ // Whether the category's row was ever written after it was created — by the
32569
+ // user, the setup wizard or a cap. A row still as seeded (updated_at equal to
32570
+ // created_at) is not a choice, so a posture filling gaps may replace it.
32571
+ isCategoryChosen(category) {
32572
+ const row = this.db.prepare(
32573
+ `SELECT created_at AS c, updated_at AS u FROM policies
32574
+ WHERE scope='global' AND json_extract(target,'$.category') = :category`
32575
+ ).get({ category });
32576
+ return row !== void 0 && row.u !== row.c;
32577
+ }
31996
32578
  // Read the current action for a single global per-category policy row, mirroring
31997
32579
  // upsertCategoryAction's category-lookup predicate. Returns undefined when no
31998
32580
  // row exists yet, so callers can distinguish an unset category from a set one.
@@ -34238,6 +34820,11 @@ var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
34238
34820
  function linkHost(input2, hostId) {
34239
34821
  return hostId ? { ...input2, hostId } : input2;
34240
34822
  }
34823
+ function captureAttributesOf(event, scopeKey) {
34824
+ const attributes = toCaptureAttributes(event);
34825
+ if (scopeKey === void 0 || scopeKey === "") return attributes;
34826
+ return { ...attributes, scope_key: scopeKey };
34827
+ }
34241
34828
  function closeQuietly(db) {
34242
34829
  try {
34243
34830
  db.close();
@@ -34423,7 +35010,7 @@ function openLocalDatabase(dir, options = {}) {
34423
35010
  );
34424
35011
  return dismissed;
34425
35012
  }
34426
- function recordCapture(event, detected) {
35013
+ function recordCapture(event, detected, scopeKey) {
34427
35014
  failOpenTransaction(db, () => {
34428
35015
  const sessionId = event.metadata?.sessionId;
34429
35016
  if (sessionId) {
@@ -34438,7 +35025,7 @@ function openLocalDatabase(dir, options = {}) {
34438
35025
  rootSessionId: sessionId,
34439
35026
  content: event.content,
34440
35027
  contentHash: event.contentHash,
34441
- attributes: toCaptureAttributes(event)
35028
+ attributes: captureAttributesOf(event, scopeKey)
34442
35029
  });
34443
35030
  const definitionIds = /* @__PURE__ */ new Map();
34444
35031
  for (const finding of detected) {
@@ -34468,7 +35055,12 @@ function openLocalDatabase(dir, options = {}) {
34468
35055
  maskedMatch: finding.maskedMatch,
34469
35056
  actionTaken: finding.actionTaken,
34470
35057
  confidence: finding.confidence,
34471
- findingKey: finding.findingKey ?? void 0
35058
+ findingKey: finding.findingKey ?? void 0,
35059
+ ...finding.location === void 0 ? {} : {
35060
+ line: finding.location.line,
35061
+ col: finding.location.col,
35062
+ context: finding.location.context
35063
+ }
34472
35064
  });
34473
35065
  }
34474
35066
  });
@@ -34631,6 +35223,7 @@ function openLocalDatabase(dir, options = {}) {
34631
35223
  // ../../packages/persistence/src/egress-wire.ts
34632
35224
  import { createHash as createHash3 } from "crypto";
34633
35225
  var SLASH = "/".charCodeAt(0);
35226
+ var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
34634
35227
 
34635
35228
  // ../../packages/persistence/src/finding-key.ts
34636
35229
  import { createHash as createHash4 } from "crypto";
@@ -34700,9 +35293,9 @@ import { readFileSync as readFileSync10 } from "fs";
34700
35293
  import { join as join16 } from "path";
34701
35294
 
34702
35295
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
34703
- import { randomUUID as randomUUID15 } from "crypto";
35296
+ import { randomUUID as randomUUID16 } from "crypto";
34704
35297
  import { readFile, rename, writeFile } from "fs/promises";
34705
- import { join as join27 } from "path";
35298
+ import { join as join28 } from "path";
34706
35299
 
34707
35300
  // ../../packages/plugin-sdk/src/config.ts
34708
35301
  import { existsSync as existsSync8 } from "fs";
@@ -35567,6 +36160,7 @@ var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
35567
36160
  // ../../packages/plugin-sdk/src/repo.ts
35568
36161
  import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
35569
36162
  import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36163
+ var NO_ATTRIBUTION = Object.freeze({});
35570
36164
 
35571
36165
  // ../../packages/plugin-sdk/src/events.ts
35572
36166
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -35641,6 +36235,9 @@ import { join as join24 } from "path";
35641
36235
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
35642
36236
  import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
35643
36237
 
36238
+ // ../../packages/plugin-sdk/src/policy-resolver.ts
36239
+ import { randomUUID as randomUUID14 } from "crypto";
36240
+
35644
36241
  // ../../packages/plugin-sdk/src/project-files.ts
35645
36242
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
35646
36243
  import { basename as basename5, join as join25 } from "path";
@@ -35672,14 +36269,18 @@ var codexProviderEnvShape = {
35672
36269
  var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
35673
36270
 
35674
36271
  // ../../packages/plugin-sdk/src/runtime.ts
35675
- import { randomUUID as randomUUID14 } from "crypto";
36272
+ import { randomUUID as randomUUID15 } from "crypto";
36273
+
36274
+ // ../../packages/plugin-sdk/src/scope-key.ts
36275
+ import { existsSync as existsSync12 } from "fs";
36276
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
35676
36277
 
35677
36278
  // ../../packages/plugin-sdk/src/suppressions.ts
35678
36279
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
35679
36280
 
35680
36281
  // ../../packages/plugin-sdk/src/throttle.ts
35681
36282
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35682
- import { join as join26 } from "path";
36283
+ import { join as join27 } from "path";
35683
36284
 
35684
36285
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
35685
36286
  import { createHash as createHash6 } from "crypto";
@@ -35701,16 +36302,16 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
35701
36302
 
35702
36303
  // ../../packages/plugin-runtime/src/attached/install-record.ts
35703
36304
  import { readFile as readFile2, stat } from "fs/promises";
35704
- import { basename as basename6, dirname as dirname6, join as join28, resolve as resolve2 } from "path";
36305
+ import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
35705
36306
 
35706
36307
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
35707
36308
  import { readFileSync as readFileSync18 } from "fs";
35708
36309
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
35709
36310
 
35710
36311
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
35711
- import { randomUUID as randomUUID16 } from "crypto";
36312
+ import { randomUUID as randomUUID17 } from "crypto";
35712
36313
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
35713
- import { join as join29 } from "path";
36314
+ import { join as join30 } from "path";
35714
36315
 
35715
36316
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
35716
36317
  import { rename as rename2 } from "fs/promises";
@@ -35720,7 +36321,7 @@ var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
35720
36321
 
35721
36322
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
35722
36323
  import { readFileSync as readFileSync19 } from "fs";
35723
- import { join as join30 } from "path";
36324
+ import { join as join31 } from "path";
35724
36325
  var OUTCOME_KEYS = {
35725
36326
  ok: true,
35726
36327
  unauthorized: true,
@@ -35741,13 +36342,13 @@ import { statSync as statSync9 } from "fs";
35741
36342
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
35742
36343
 
35743
36344
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
35744
- import { randomUUID as randomUUID17 } from "crypto";
36345
+ import { randomUUID as randomUUID18 } from "crypto";
35745
36346
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
35746
- import { join as join31 } from "path";
36347
+ import { join as join32 } from "path";
35747
36348
 
35748
36349
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
35749
36350
  import { readFileSync as readFileSync20 } from "fs";
35750
- import { join as join32 } from "path";
36351
+ import { join as join33 } from "path";
35751
36352
 
35752
36353
  // ../../packages/plugin-runtime/src/attached/status.ts
35753
36354
  var REFUSAL_LINES = {
@@ -35799,9 +36400,6 @@ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
35799
36400
  // ../../packages/plugin-runtime/src/attached/factory.ts
35800
36401
  import { hostname as hostname6 } from "os";
35801
36402
 
35802
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
35803
- import { randomUUID as randomUUID18 } from "crypto";
35804
-
35805
36403
  // ../../packages/plugin-runtime/src/handle-session-start.ts
35806
36404
  import { randomUUID as randomUUID19 } from "crypto";
35807
36405
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;