@akasecurity/ai-tc-codex 0.9.14 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,9 +32,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
  mod
33
33
  ));
34
34
 
35
- // ../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js
35
+ // ../../node_modules/.pnpm/ignore@7.0.10/node_modules/ignore/index.js
36
36
  var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js"(exports, module) {
37
+ "../../node_modules/.pnpm/ignore@7.0.10/node_modules/ignore/index.js"(exports, module) {
38
38
  "use strict";
39
39
  function makeArray(subject) {
40
40
  return Array.isArray(subject) ? subject : [subject];
@@ -429,6 +429,13 @@ var require_ignore = __commonJS({
429
429
  }
430
430
  };
431
431
  var WILDCARD = "[^\\/]*";
432
+ var separatorAfter = (run, at) => {
433
+ let separator = EMPTY;
434
+ for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
435
+ separator += run[index].single;
436
+ }
437
+ return separator;
438
+ };
432
439
  var pinWildcards = (source) => {
433
440
  if (source.indexOf(WILDCARD) < 0) {
434
441
  return source;
@@ -498,7 +505,7 @@ var require_ignore = __commonJS({
498
505
  out += token.single;
499
506
  return;
500
507
  }
501
- out += at === lastWildcard ? WILDCARD : `(?:(?!${run[at + 1].single})[^\\/])*`;
508
+ out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
502
509
  });
503
510
  run = [];
504
511
  };
@@ -675,13 +682,13 @@ var require_ignore = __commonJS({
675
682
  const rules = this._rules;
676
683
  const { length } = rules;
677
684
  const shortcut = this._basenameCount * 2 >= length;
678
- const basename7 = shortcut ? basenameOf(path) : path;
685
+ const basename8 = shortcut ? basenameOf(path) : path;
679
686
  for (let index = 0; index < length; index++) {
680
687
  const rule = rules[index];
681
688
  const { negative } = rule;
682
689
  const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
683
690
  if (!skip && rule[mode].test(
684
- shortcut && rule._basenameOnly ? basename7 : path
691
+ shortcut && rule._basenameOnly ? basename8 : path
685
692
  )) {
686
693
  ignored = !negative;
687
694
  unignored = negative;
@@ -1002,6 +1009,10 @@ var SQLITE_MIGRATIONS = [
1002
1009
  {
1003
1010
  tag: "0035_share_destination_provider_id",
1004
1011
  sql: "ALTER TABLE `share_destination` ADD `provider_id` text;"
1012
+ },
1013
+ {
1014
+ tag: "0036_secret_vault_identity_fingerprint",
1015
+ 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"
1005
1016
  }
1006
1017
  ];
1007
1018
 
@@ -1011,6 +1022,12 @@ var HOUR_MS = 60 * MINUTE_MS;
1011
1022
  var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1012
1023
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1013
1024
 
1025
+ // ../../packages/schema/src/invisible-padding.ts
1026
+ var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
1027
+ function stripInvisiblePadding(text) {
1028
+ return text.replace(INVISIBLE_PADDING, "");
1029
+ }
1030
+
1014
1031
  // ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
1015
1032
  var external_exports = {};
1016
1033
  __export(external_exports, {
@@ -6037,7 +6054,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6037
6054
  var NONE = 0;
6038
6055
  var ASSUMED = 1;
6039
6056
  var PROVEN = 2;
6040
- function isRecursive(inst, stack, resolve2) {
6057
+ function isRecursive(inst, stack, resolve3) {
6041
6058
  const cached2 = recursive.get(inst);
6042
6059
  if (cached2 !== void 0)
6043
6060
  return cached2 ? PROVEN : NONE;
@@ -6047,7 +6064,7 @@ function isRecursive(inst, stack, resolve2) {
6047
6064
  let result = NONE;
6048
6065
  const check2 = (child) => {
6049
6066
  if (result !== PROVEN && child?._zod) {
6050
- const answer = isRecursive(child, stack, resolve2);
6067
+ const answer = isRecursive(child, stack, resolve3);
6051
6068
  if (answer > result)
6052
6069
  result = answer;
6053
6070
  }
@@ -6058,7 +6075,7 @@ function isRecursive(inst, stack, resolve2) {
6058
6075
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6059
6076
  if (spread && !desc.enumerable)
6060
6077
  continue;
6061
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
6078
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6062
6079
  if (child > answer)
6063
6080
  answer = child;
6064
6081
  }
@@ -6122,7 +6139,7 @@ function isRecursive(inst, stack, resolve2) {
6122
6139
  break;
6123
6140
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6124
6141
  case "lazy": {
6125
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
6142
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6126
6143
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6127
6144
  break;
6128
6145
  }
@@ -23403,7 +23420,29 @@ var StorePosturePlugin = external_exports.object({
23403
23420
  */
23404
23421
  policyBundleVersion: external_exports.string().max(200).nullable(),
23405
23422
  /** Epoch millis, on the CLIENT clock, of that fetch. */
23406
- policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
23423
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
23424
+ /**
23425
+ * The newest version the host's own install record holds for this plugin —
23426
+ * what is on disk. After an update it leads `version` (the running copy) by
23427
+ * one launch. Null when no usable version can be read: no install record
23428
+ * (a plugin run from a checkout), no entry with a valid version, or every
23429
+ * such entry names an `installPath` that no longer exists; OPTIONAL, not
23430
+ * required, so a build that predates the member keeps getting its 200.
23431
+ * Bounded like `version`.
23432
+ */
23433
+ installedVersion: external_exports.string().max(64).nullable().optional(),
23434
+ /**
23435
+ * The local-store schema version this running build migrates a store to:
23436
+ * the number of store migrations it carries, the count it stamps into
23437
+ * `PRAGMA user_version`. A snapshot whose `schemaVersion` is above it
23438
+ * usually describes a store a newer build migrated. It is a hint, not a
23439
+ * verdict: the stamp is write-only, so a store whose count ran past this
23440
+ * build's while this build knows every migration in its ledger reads above
23441
+ * it too, which is why describeStoreSkew decides skew on ledger tags and
23442
+ * never on the count. OPTIONAL for the same reason as `installedVersion`;
23443
+ * bounded like `schemaVersion`.
23444
+ */
23445
+ buildSchemaVersion: external_exports.number().int().min(0).max(MAX_INT4).optional()
23407
23446
  }).meta({ id: "StorePosturePlugin" });
23408
23447
  var StorePostureSnapshot = external_exports.object({
23409
23448
  deviceId: external_exports.guid(),
@@ -25046,10 +25085,15 @@ var ParsedPointer = external_exports.object({
25046
25085
  });
25047
25086
  var VaultEntry = external_exports.object({
25048
25087
  pointerId: external_exports.string(),
25049
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
25050
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
25051
- // independently of the vault encryption key below.
25088
+ // The keyed HMAC of the EXACT raw bytes under `exception.key`, and the epoch it
25089
+ // was derived under. The vault's own dedupe key: a value and its invisibly
25090
+ // padded twin are two rows. It rotates independently of the vault encryption
25091
+ // key below. Never matched against an exception or grant.
25052
25092
  valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25093
+ // The same HMAC over the raw with invisible padding removed: the identity a
25094
+ // reveal-to-model grant and every exception match on. Shared by a value and
25095
+ // its padded twin.
25096
+ valueIdentityFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25053
25097
  fingerprintKeyVersion: external_exports.number().int().positive(),
25054
25098
  // The vault-key epoch this row's ciphertext was sealed under.
25055
25099
  keyVersion: external_exports.number().int().positive(),
@@ -25622,10 +25666,18 @@ var SeveritySummaryItem = external_exports.object({
25622
25666
  count: external_exports.number().int().nonnegative(),
25623
25667
  // Resolution-aware breakdown (optional, additive). Populated once findings
25624
25668
  // carry lifecycle state: `caught` = handled in-flight (enforced); `openAtRest`
25625
- // = still open with no in-flight enforcement (needs remediation). Absent on the
25626
- // legacy count-only response until the resolution feature lands.
25669
+ // = still open with no in-flight enforcement (needs remediation); `dismissed`
25670
+ // = closed by a human judgement rather than a fix — visible, but not counted as
25671
+ // needing remediation. The three are disjoint. Absent on the legacy count-only
25672
+ // response until the resolution feature lands.
25627
25673
  caught: external_exports.number().int().nonnegative().optional(),
25628
- openAtRest: external_exports.number().int().nonnegative().optional()
25674
+ openAtRest: external_exports.number().int().nonnegative().optional(),
25675
+ dismissed: external_exports.number().int().nonnegative().optional(),
25676
+ // The two halves of `caught`, for a reader that wants them apart: `handled` =
25677
+ // in-flight findings an enforcement action already contained; `resolved` =
25678
+ // at-rest findings closed out by fixing them. `handled + resolved === caught`.
25679
+ handled: external_exports.number().int().nonnegative().optional(),
25680
+ resolved: external_exports.number().int().nonnegative().optional()
25629
25681
  }).meta({ id: "SeveritySummaryItem" });
25630
25682
  var SeveritySummaryResponse = external_exports.object({
25631
25683
  // Sum of bySeverity[].count.
@@ -25633,6 +25685,9 @@ var SeveritySummaryResponse = external_exports.object({
25633
25685
  // Findings still open at rest (sum of bySeverity[].openAtRest). Optional and
25634
25686
  // additive — absent on the legacy response until the resolution feature lands.
25635
25687
  needsRemediation: external_exports.number().int().nonnegative().optional(),
25688
+ // Findings a user dismissed (sum of bySeverity[].dismissed). Excluded from
25689
+ // needsRemediation, and kept visible here so an accepted risk is not erased.
25690
+ dismissed: external_exports.number().int().nonnegative().optional(),
25636
25691
  // All four severity levels are always present (count may be 0).
25637
25692
  bySeverity: external_exports.array(SeveritySummaryItem)
25638
25693
  }).meta({ id: "SeveritySummaryResponse" });
@@ -26250,11 +26305,11 @@ function repairOrRefuseMode(file2) {
26250
26305
  const link = lstatSync2(file2, { throwIfNoEntry: false });
26251
26306
  if (link === void 0) return "absent";
26252
26307
  if (link.isSymbolicLink()) return "untrusted";
26253
- const stat = statSync(file2, { throwIfNoEntry: false });
26254
- if (stat === void 0) return "absent";
26308
+ const stat2 = statSync(file2, { throwIfNoEntry: false });
26309
+ if (stat2 === void 0) return "absent";
26255
26310
  const uid = process.getuid?.();
26256
- if (uid !== void 0 && stat.uid !== uid) return "untrusted";
26257
- if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
26311
+ if (uid !== void 0 && stat2.uid !== uid) return "untrusted";
26312
+ if (process.platform !== "win32" && (stat2.mode & 511) !== DATA_FILE_MODE) {
26258
26313
  try {
26259
26314
  chmodSync2(file2, DATA_FILE_MODE);
26260
26315
  } catch {
@@ -26266,9 +26321,9 @@ function repairOrRefuseMode(file2) {
26266
26321
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26267
26322
  const file2 = controlPlaneCredentialPath(settingsDir2);
26268
26323
  let raw;
26269
- const gate = repairOrRefuseMode(file2);
26270
- if (gate === "absent") return { usable: false, reason: "absent" };
26271
- if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
26324
+ const gate2 = repairOrRefuseMode(file2);
26325
+ if (gate2 === "absent") return { usable: false, reason: "absent" };
26326
+ if (gate2 === "untrusted") return { usable: false, reason: "untrusted-file" };
26272
26327
  try {
26273
26328
  raw = readFileSync(file2, "utf8");
26274
26329
  } catch (err) {
@@ -32413,7 +32468,10 @@ var SqliteResolutionsRepository = class {
32413
32468
  * Insert many dispositions as ONE transaction — all of them or none.
32414
32469
  *
32415
32470
  * A dashboard dismissal closes every open finding of a rule, which is one
32416
- * write per key; run loose, a fault partway leaves half a rule closed with
32471
+ * write per key. It reaches this through
32472
+ * `LocalDatabase.dismissOpenFindingsForRule`, which calls it inside the
32473
+ * transaction that selected the keys, so there it runs as a SAVEPOINT of
32474
+ * that transaction. Run loose, a fault partway leaves half a rule closed with
32417
32475
  * nothing recording that the other half was meant to be. The caller then has
32418
32476
  * no way to tell a partial run from a complete one, because the card it
32419
32477
  * refreshes into just shows a smaller number either way.
@@ -32633,6 +32691,7 @@ function toSighting(row) {
32633
32691
  var SELECT_COLUMNS = `
32634
32692
  pointer_id AS pointerId,
32635
32693
  value_fingerprint AS valueFingerprint,
32694
+ value_identity_fingerprint AS valueIdentityFingerprint,
32636
32695
  fingerprint_key_version AS fingerprintKeyVersion,
32637
32696
  key_version AS keyVersion,
32638
32697
  format_version AS formatVersion,
@@ -32657,13 +32716,13 @@ var SqliteSecretVaultRepository = class {
32657
32716
  this.db = db;
32658
32717
  this.insertStmt = db.prepare(
32659
32718
  `INSERT INTO secret_vault (
32660
- pointer_id, value_fingerprint, fingerprint_key_version, key_version,
32661
- format_version, category, rule_id, masked_match, provider,
32719
+ pointer_id, value_fingerprint, value_identity_fingerprint,
32720
+ fingerprint_key_version, key_version, format_version, category, rule_id, masked_match, provider,
32662
32721
  ciphertext, nonce, auth_tag,
32663
32722
  user_authorized, occurrence_count, first_seen, last_seen
32664
32723
  ) VALUES (
32665
- :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
32666
- :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32724
+ :pointerId, :valueFingerprint, :valueIdentityFingerprint,
32725
+ :fingerprintKeyVersion, :keyVersion, :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32667
32726
  :ciphertext, :nonce, :authTag,
32668
32727
  :userAuthorized, 1, :now, :now
32669
32728
  )`
@@ -32688,7 +32747,13 @@ var SqliteSecretVaultRepository = class {
32688
32747
  );
32689
32748
  this.refreshFingerprintStmt = db.prepare(
32690
32749
  `UPDATE secret_vault
32691
- SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
32750
+ SET value_fingerprint = :valueFingerprint,
32751
+ value_identity_fingerprint = :valueIdentityFingerprint,
32752
+ fingerprint_key_version = :fingerprintKeyVersion
32753
+ WHERE pointer_id = :pointerId`
32754
+ );
32755
+ this.setIdentityStmt = db.prepare(
32756
+ `UPDATE secret_vault SET value_identity_fingerprint = :valueIdentityFingerprint
32692
32757
  WHERE pointer_id = :pointerId`
32693
32758
  );
32694
32759
  this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
@@ -32705,6 +32770,7 @@ var SqliteSecretVaultRepository = class {
32705
32770
  listStmt;
32706
32771
  replaceCiphertextStmt;
32707
32772
  refreshFingerprintStmt;
32773
+ setIdentityStmt;
32708
32774
  deleteByPointerStmt;
32709
32775
  derefStmt;
32710
32776
  /**
@@ -32735,6 +32801,7 @@ var SqliteSecretVaultRepository = class {
32735
32801
  bindParams({
32736
32802
  pointerId: input2.pointerId,
32737
32803
  valueFingerprint: input2.valueFingerprint,
32804
+ valueIdentityFingerprint: input2.valueIdentityFingerprint,
32738
32805
  fingerprintKeyVersion: input2.fingerprintKeyVersion,
32739
32806
  keyVersion: input2.keyVersion,
32740
32807
  formatVersion: input2.formatVersion ?? POINTER_FORMAT_VERSION,
@@ -32796,7 +32863,15 @@ var SqliteSecretVaultRepository = class {
32796
32863
  replaceCiphertext(pointerId, next) {
32797
32864
  this.replaceCiphertextStmt.run({ pointerId, ...next });
32798
32865
  }
32799
- /** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
32866
+ /**
32867
+ * Correct an entry's identity fingerprint in place, leaving its exact
32868
+ * fingerprint and key epoch alone. For a row whose identity column still holds
32869
+ * the exact value copied in by the migration that added it.
32870
+ */
32871
+ setIdentityFingerprint(pointerId, valueIdentityFingerprint) {
32872
+ this.setIdentityStmt.run({ pointerId, valueIdentityFingerprint });
32873
+ }
32874
+ /** Re-derive an entry's fingerprints under a new fingerprint-key epoch. */
32800
32875
  refreshFingerprint(pointerId, next) {
32801
32876
  this.refreshFingerprintStmt.run({ pointerId, ...next });
32802
32877
  }
@@ -32927,7 +33002,7 @@ var SqliteSecretVaultRepository = class {
32927
33002
  `SELECT ${INVENTORY_COLUMNS},
32928
33003
  (SELECT e.id FROM exceptions e
32929
33004
  WHERE e.rule_id = v.rule_id
32930
- AND e.value_fingerprint = v.value_fingerprint
33005
+ AND e.value_fingerprint = v.value_identity_fingerprint
32931
33006
  AND e.key_version = v.fingerprint_key_version
32932
33007
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32933
33008
  LIMIT 1) AS grant_id
@@ -32970,7 +33045,7 @@ var SqliteSecretVaultRepository = class {
32970
33045
  `SELECT ${INVENTORY_COLUMNS},
32971
33046
  (SELECT e.id FROM exceptions e
32972
33047
  WHERE e.rule_id = v.rule_id
32973
- AND e.value_fingerprint = v.value_fingerprint
33048
+ AND e.value_fingerprint = v.value_identity_fingerprint
32974
33049
  AND e.key_version = v.fingerprint_key_version
32975
33050
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32976
33051
  LIMIT 1) AS grant_id
@@ -33074,6 +33149,18 @@ var OPEN_AT_REST_FINDINGS_SQL = `FROM inspection_findings f
33074
33149
  OR latest.status IS NULL
33075
33150
  OR latest.status NOT IN ('resolved', 'dismissed')
33076
33151
  )`;
33152
+ function selectOpenFindingKeysForRule(db, ruleId) {
33153
+ const rows = allRows(
33154
+ db.prepare(
33155
+ `SELECT DISTINCT f.finding_key AS finding_key
33156
+ ${OPEN_AT_REST_FINDINGS_SQL}
33157
+ AND d.rule_id = :ruleId
33158
+ AND f.finding_key IS NOT NULL`
33159
+ ),
33160
+ { ruleId }
33161
+ );
33162
+ return rows.map((r) => r.finding_key);
33163
+ }
33077
33164
  var SEVERITIES = ["critical", "high", "medium", "low"];
33078
33165
  var ACTION_TO_KIND = {
33079
33166
  block: "blocked",
@@ -33130,16 +33217,16 @@ var SqliteSecurityRepository = class {
33130
33217
  // findings are caught only once their latest disposition is resolved,
33131
33218
  // otherwise they are open-at-rest.
33132
33219
  //
33133
- // NOTE for future manual-resolution writers: only latest status
33134
- // 'resolved' counts as caught above. When acknowledged/dismissed/
33135
- // false-positive manual dispositions land, this must keep filtering by
33136
- // status/method — 'acknowledged' is accepted risk, not a fix, and must NOT
33137
- // be bucketed as caught alongside 'resolved'.
33220
+ // Only latest status 'resolved' counts as caught above. 'dismissed' is its
33221
+ // own bucket: a judgement rather than a fix, so it is neither caught nor
33222
+ // needing remediation, and stays countable. A further manual disposition
33223
+ // (acknowledged, false-positive) must be placed deliberately — 'acknowledged'
33224
+ // is accepted risk, not a fix, and must NOT be bucketed as caught.
33138
33225
  //
33139
33226
  // Legacy at-rest findings from pre-branch scans carry finding_key = NULL —
33140
33227
  // the resolution lifecycle is keyed by finding_key, so it can never attach a
33141
33228
  // disposition to (or clear) one of these on re-scan. They are excluded from
33142
- // both caught and openAtRest (untracked, not "needs remediation forever"),
33229
+ // all three buckets (untracked, not "needs remediation forever"),
33143
33230
  // but still counted in total/count below — this keeps this predicate
33144
33231
  // consistent with SqliteResolutionsRepository.openAtRestKeysForPath, which
33145
33232
  // already filters `finding_key IS NOT NULL`.
@@ -33162,12 +33249,25 @@ var SqliteSecurityRepository = class {
33162
33249
  WHEN latest.status = 'resolved' THEN 1
33163
33250
  ELSE 0
33164
33251
  END) AS caught,
33252
+ SUM(CASE WHEN e.event_type != 'code_change' THEN 1 ELSE 0 END) AS handled,
33165
33253
  SUM(CASE
33166
33254
  WHEN e.event_type = 'code_change'
33167
33255
  AND f.finding_key IS NOT NULL
33168
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
33256
+ AND latest.status = 'resolved' THEN 1
33169
33257
  ELSE 0
33170
- END) AS open_at_rest
33258
+ END) AS resolved,
33259
+ SUM(CASE
33260
+ WHEN e.event_type = 'code_change'
33261
+ AND f.finding_key IS NOT NULL
33262
+ AND (latest.status IS NULL
33263
+ OR latest.status NOT IN ('resolved', 'dismissed')) THEN 1
33264
+ ELSE 0
33265
+ END) AS open_at_rest,
33266
+ SUM(CASE
33267
+ WHEN e.event_type = 'code_change'
33268
+ AND latest.status = 'dismissed' THEN 1
33269
+ ELSE 0
33270
+ END) AS dismissed
33171
33271
  FROM inspection_findings f
33172
33272
  JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
33173
33273
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -33182,11 +33282,15 @@ var SqliteSecurityRepository = class {
33182
33282
  severity,
33183
33283
  count: byRow.get(severity)?.count ?? 0,
33184
33284
  caught: byRow.get(severity)?.caught ?? 0,
33185
- openAtRest: byRow.get(severity)?.open_at_rest ?? 0
33285
+ handled: byRow.get(severity)?.handled ?? 0,
33286
+ resolved: byRow.get(severity)?.resolved ?? 0,
33287
+ openAtRest: byRow.get(severity)?.open_at_rest ?? 0,
33288
+ dismissed: byRow.get(severity)?.dismissed ?? 0
33186
33289
  }));
33187
33290
  const total = bySeverity.reduce((sum, s) => sum + s.count, 0);
33188
33291
  const needsRemediation = bySeverity.reduce((sum, s) => sum + s.openAtRest, 0);
33189
- return Promise.resolve({ total, needsRemediation, bySeverity });
33292
+ const dismissed = bySeverity.reduce((sum, s) => sum + s.dismissed, 0);
33293
+ return Promise.resolve({ total, needsRemediation, dismissed, bySeverity });
33190
33294
  }
33191
33295
  // Range is echoed but does not change the result today — coverage is a constant
33192
33296
  // business fact (see SCAN_COVERAGE), not a measured per-window metric. Order
@@ -33503,10 +33607,10 @@ var SqliteSecurityRepository = class {
33503
33607
  * machine, and the second reported "no recommendations" over live exposure.
33504
33608
  *
33505
33609
  * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
33506
- * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
33507
- * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
33508
- * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
33509
- * The two answer different questions and only this one has to match a link.
33610
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. It
33611
+ * differs from `severitySummary`'s `openAtRest` only in including untracked
33612
+ * legacy rows, which that bucket leaves out; dismissed is excluded from both.
33613
+ * Only this one has to match a link.
33510
33614
  *
33511
33615
  * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
33512
33616
  * whole-store scope costs a grouped scan rather than a row per finding.
@@ -33534,6 +33638,8 @@ var SqliteSecurityRepository = class {
33534
33638
  /**
33535
33639
  * The distinct `finding_key`s behind ONE rule's {@link recommendationInputs}
33536
33640
  * tally — what a dashboard dismissal of that row writes a disposition for.
33641
+ * The dismissal itself does not call this: it reads the same set through
33642
+ * {@link selectOpenFindingKeysForRule}, inside its own write transaction.
33537
33643
  *
33538
33644
  * It shares {@link OPEN_AT_REST_FINDINGS_SQL} with the count rather than
33539
33645
  * restating the predicate, because a dismissal has to act on exactly the set
@@ -33550,16 +33656,7 @@ var SqliteSecurityRepository = class {
33550
33656
  * this set SMALLER than the tally, never larger.
33551
33657
  */
33552
33658
  openFindingKeysForRule(ruleId) {
33553
- const rows = allRows(
33554
- this.db.prepare(
33555
- `SELECT DISTINCT f.finding_key AS finding_key
33556
- ${OPEN_AT_REST_FINDINGS_SQL}
33557
- AND d.rule_id = :ruleId
33558
- AND f.finding_key IS NOT NULL`
33559
- ),
33560
- { ruleId }
33561
- );
33562
- return Promise.resolve(rows.map((r) => r.finding_key));
33659
+ return Promise.resolve(selectOpenFindingKeysForRule(this.db, ruleId));
33563
33660
  }
33564
33661
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
33565
33662
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
@@ -34605,6 +34702,31 @@ function openLocalDatabase(dir, options = {}) {
34605
34702
  );
34606
34703
  });
34607
34704
  }
34705
+ function dismissOpenFindingsForRule(ruleId, disposition) {
34706
+ let dismissed = 0;
34707
+ withTransaction(
34708
+ db,
34709
+ () => {
34710
+ const keys = selectOpenFindingKeysForRule(db, ruleId);
34711
+ resolutions.insertResolutions(
34712
+ keys.map((findingKey) => ({
34713
+ findingKey,
34714
+ status: "dismissed",
34715
+ method: disposition.method,
34716
+ resolvedAt: disposition.resolvedAt,
34717
+ evidence: disposition.evidence
34718
+ }))
34719
+ );
34720
+ dismissed = keys.length;
34721
+ },
34722
+ // IMMEDIATE takes the write lock at BEGIN, before the select, which is
34723
+ // what keeps a concurrent resolve out of the gap. It also makes waiting
34724
+ // on a busy writer an ordinary busy_timeout wait rather than a
34725
+ // read-to-write upgrade SQLite refuses to retry.
34726
+ "IMMEDIATE"
34727
+ );
34728
+ return dismissed;
34729
+ }
34608
34730
  function recordCapture(event, detected) {
34609
34731
  failOpenTransaction(db, () => {
34610
34732
  const sessionId = event.metadata?.sessionId;
@@ -34788,6 +34910,7 @@ function openLocalDatabase(dir, options = {}) {
34788
34910
  inspectionDefinitions,
34789
34911
  inspectionFindings,
34790
34912
  recordCapture,
34913
+ dismissOpenFindingsForRule,
34791
34914
  markCaptureDelivered,
34792
34915
  markCaptureOwed,
34793
34916
  markAuditEventsDelivered,
@@ -35004,6 +35127,9 @@ function loadOrCreateFingerprintKey(dataDir2) {
35004
35127
  });
35005
35128
  }
35006
35129
  function fingerprintValue(key, raw) {
35130
+ return exactFingerprintValue(key, stripInvisiblePadding(raw));
35131
+ }
35132
+ function exactFingerprintValue(key, raw) {
35007
35133
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
35008
35134
  }
35009
35135
 
@@ -36264,11 +36390,11 @@ var EXACT_KIND_BY_BASENAME = {
36264
36390
  "composer.json": "composer.json",
36265
36391
  "packages.config": "packages.config"
36266
36392
  };
36267
- function manifestKindOf(basename7) {
36268
- if (LOCKFILE_BASENAMES.has(basename7)) return null;
36269
- const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename7) ? EXACT_KIND_BY_BASENAME[basename7] : void 0;
36393
+ function manifestKindOf(basename8) {
36394
+ if (LOCKFILE_BASENAMES.has(basename8)) return null;
36395
+ const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename8) ? EXACT_KIND_BY_BASENAME[basename8] : void 0;
36270
36396
  if (exact !== void 0) return exact;
36271
- if (basename7.endsWith(".csproj")) return "csproj";
36397
+ if (basename8.endsWith(".csproj")) return "csproj";
36272
36398
  return null;
36273
36399
  }
36274
36400
  function extractManifestSdks(text, kind) {
@@ -36746,6 +36872,82 @@ function escapeRegExp2(value) {
36746
36872
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36747
36873
  }
36748
36874
 
36875
+ // ../../packages/detections/src/format-chars.ts
36876
+ var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
36877
+ var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
36878
+ function normalizeFormatChars(text) {
36879
+ if (!HAS_FORMAT_CHAR.test(text)) return void 0;
36880
+ const normalizedParts = [];
36881
+ const segments = [];
36882
+ let cursor = 0;
36883
+ let normLength = 0;
36884
+ for (const match of text.matchAll(FORMAT_CHAR_GLOBAL)) {
36885
+ const matchStart = match.index;
36886
+ if (matchStart > cursor) {
36887
+ const length = matchStart - cursor;
36888
+ normalizedParts.push(text.slice(cursor, matchStart));
36889
+ segments.push({ normStart: normLength, origStart: cursor, length });
36890
+ normLength += length;
36891
+ }
36892
+ cursor = matchStart + match[0].length;
36893
+ }
36894
+ if (cursor < text.length) {
36895
+ const length = text.length - cursor;
36896
+ normalizedParts.push(text.slice(cursor));
36897
+ segments.push({ normStart: normLength, origStart: cursor, length });
36898
+ }
36899
+ return { normalized: normalizedParts.join(""), segments };
36900
+ }
36901
+ function segmentAt(segments, normPos) {
36902
+ let lo = 0;
36903
+ let hi = segments.length - 1;
36904
+ while (lo < hi) {
36905
+ const mid = lo + hi >> 1;
36906
+ const segment = segments[mid];
36907
+ if (segment !== void 0 && normPos >= segment.normStart + segment.length) {
36908
+ lo = mid + 1;
36909
+ } else {
36910
+ hi = mid;
36911
+ }
36912
+ }
36913
+ const found = segments[lo];
36914
+ if (found === void 0) {
36915
+ throw new Error(`normPos ${String(normPos)} has no covering segment`);
36916
+ }
36917
+ return found;
36918
+ }
36919
+ function mapSpanToOriginal(span, normalization) {
36920
+ const { segments } = normalization;
36921
+ const startSegment = segmentAt(segments, span.start);
36922
+ const start = startSegment.origStart + (span.start - startSegment.normStart);
36923
+ const endSegment = segmentAt(segments, span.end - 1);
36924
+ const end = endSegment.origStart + (span.end - 1 - endSegment.normStart) + 1;
36925
+ return { start, end };
36926
+ }
36927
+ function normalizedOffset(origPos, segments) {
36928
+ let lo = 0;
36929
+ let hi = segments.length;
36930
+ while (lo < hi) {
36931
+ const mid = lo + hi >> 1;
36932
+ const segment = segments[mid];
36933
+ if (segment !== void 0 && segment.origStart + segment.length <= origPos) {
36934
+ lo = mid + 1;
36935
+ } else {
36936
+ hi = mid;
36937
+ }
36938
+ }
36939
+ const found = segments[Math.min(lo, segments.length - 1)];
36940
+ if (found === void 0) return 0;
36941
+ return found.normStart + Math.min(Math.max(0, origPos - found.origStart), found.length);
36942
+ }
36943
+ function mapSpanToNormalized(span, normalization) {
36944
+ const { segments } = normalization;
36945
+ return {
36946
+ start: normalizedOffset(span.start, segments),
36947
+ end: normalizedOffset(span.end, segments)
36948
+ };
36949
+ }
36950
+
36749
36951
  // ../../packages/detections/src/regex-cache.ts
36750
36952
  var singles = /* @__PURE__ */ new WeakMap();
36751
36953
  var keywordLists = /* @__PURE__ */ new WeakMap();
@@ -36907,29 +37109,35 @@ function registerPack(pack) {
36907
37109
  function getLoadedRules() {
36908
37110
  return [...packs.values()].flatMap((p) => p.rules);
36909
37111
  }
36910
- function isCorroborated(candidate, candidates, text) {
37112
+ function spansOverlap(a, b) {
37113
+ return a.start < b.end && a.end > b.start;
37114
+ }
37115
+ function isCorroborated(candidate, candidates, text, normalization) {
36911
37116
  const req = candidate.rule.requiresNearby;
36912
37117
  if (!req) return true;
36913
37118
  const halfWindow = req.windowChars;
36914
- const { start, end } = candidate.match.span;
36915
- const winStart = start - halfWindow;
36916
- const winEnd = end + halfWindow;
37119
+ const ns = candidate.normSpan;
37120
+ const winStart = ns.start - halfWindow;
37121
+ const winEnd = ns.end + halfWindow;
36917
37122
  const categories = req.categories;
36918
37123
  const ruleIds = req.ruleIds;
36919
37124
  if (categories?.length || ruleIds?.length) {
36920
37125
  for (const other of candidates) {
36921
37126
  if (other === candidate) continue;
36922
- const os = other.match.span;
36923
- if (os.end < winStart || os.start > winEnd) continue;
36924
- if (other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category)) {
36925
- return true;
37127
+ if (other.normSpan.end < winStart || other.normSpan.start > winEnd) continue;
37128
+ const relevant = other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category) === true || ruleIds?.includes(other.match.ruleId) === true;
37129
+ if (!relevant) continue;
37130
+ if (other.match.ruleId === candidate.match.ruleId && spansOverlap(other.match.span, candidate.match.span)) {
37131
+ continue;
36926
37132
  }
36927
- if (ruleIds?.includes(other.match.ruleId)) return true;
37133
+ return true;
36928
37134
  }
36929
37135
  }
36930
37136
  const labels = req.labels;
36931
37137
  if (labels && labels.length > 0) {
36932
- const haystack = text.slice(Math.max(0, winStart), winEnd);
37138
+ const { start, end } = candidate.match.span;
37139
+ const haystack = text.slice(Math.max(0, start - halfWindow), end + halfWindow);
37140
+ const normalizedHaystack = normalization === void 0 ? void 0 : normalization.normalized.slice(Math.max(0, winStart), winEnd);
36933
37141
  for (const re of memoizedRegExpList(
36934
37142
  "label",
36935
37143
  req,
@@ -36938,29 +37146,20 @@ function isCorroborated(candidate, candidates, text) {
36938
37146
  return trimmed.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed)}(?![A-Za-z0-9])`, "i");
36939
37147
  })
36940
37148
  )) {
36941
- if (re?.test(haystack)) return true;
37149
+ if (!re) continue;
37150
+ if (re.test(haystack)) return true;
37151
+ if (normalizedHaystack !== void 0 && re.test(normalizedHaystack)) return true;
36942
37152
  }
36943
37153
  }
36944
37154
  return false;
36945
37155
  }
36946
- function extensionOf(filePath) {
36947
- const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
36948
- const dot = base.lastIndexOf(".");
36949
- return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
36950
- }
36951
- function ruleApplies(rule, extension) {
36952
- if (!rule.appliesTo || extension === void 0) return true;
36953
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
36954
- }
36955
- function scan(text, rules, context) {
36956
- const ruleset = rules ?? getLoadedRules();
36957
- const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
37156
+ function buildCandidates(matchText, ruleset, extension) {
36958
37157
  const candidates = [];
36959
37158
  for (const rule of ruleset) {
36960
37159
  if (!ruleApplies(rule, extension)) continue;
36961
- const spans = MATCHERS[rule.matcher.type](text, rule);
37160
+ const spans = MATCHERS[rule.matcher.type](matchText, rule);
36962
37161
  for (const span of spans) {
36963
- const rawMatch = text.slice(span.start, span.end);
37162
+ const rawMatch = matchText.slice(span.start, span.end);
36964
37163
  if (!passesPostValidators(rule, rawMatch)) continue;
36965
37164
  candidates.push({
36966
37165
  rule,
@@ -36971,10 +37170,31 @@ function scan(text, rules, context) {
36971
37170
  span,
36972
37171
  rawMatch,
36973
37172
  confidence: 0.9
36974
- }
37173
+ },
37174
+ // In `matchText`'s own coordinates, which is the normalized text for
37175
+ // a normalized-pass candidate and so already right; an original-pass
37176
+ // candidate on the slow path is re-derived by withNormalizedSpan.
37177
+ normSpan: span
36975
37178
  });
36976
37179
  }
36977
37180
  }
37181
+ return candidates;
37182
+ }
37183
+ function mapCandidateToOriginal(candidate, normalization, text) {
37184
+ const span = mapSpanToOriginal(candidate.match.span, normalization);
37185
+ return {
37186
+ rule: candidate.rule,
37187
+ match: { ...candidate.match, span, rawMatch: text.slice(span.start, span.end) },
37188
+ // Deliberately NOT remapped: `normSpan` is the span the primitive match
37189
+ // was found at in the normalized text, which is exactly the coordinate
37190
+ // space windows are measured in. See the `Candidate` comment.
37191
+ normSpan: candidate.normSpan
37192
+ };
37193
+ }
37194
+ function withNormalizedSpan(candidate, normalization) {
37195
+ return { ...candidate, normSpan: mapSpanToNormalized(candidate.match.span, normalization) };
37196
+ }
37197
+ function gate(candidates, text, normalization) {
36978
37198
  const findings = [];
36979
37199
  for (const candidate of candidates) {
36980
37200
  const req = candidate.rule.requiresNearby;
@@ -36982,7 +37202,7 @@ function scan(text, rules, context) {
36982
37202
  findings.push(candidate.match);
36983
37203
  continue;
36984
37204
  }
36985
- if (!isCorroborated(candidate, candidates, text)) continue;
37205
+ if (!isCorroborated(candidate, candidates, text, normalization)) continue;
36986
37206
  const boost = req.confidenceBoost;
36987
37207
  findings.push(
36988
37208
  boost ? { ...candidate.match, confidence: Math.min(0.99, candidate.match.confidence + boost) } : candidate.match
@@ -36990,6 +37210,81 @@ function scan(text, rules, context) {
36990
37210
  }
36991
37211
  return findings;
36992
37212
  }
37213
+ function closeRegion(open3, text) {
37214
+ const span = { start: open3.start, end: open3.end };
37215
+ return {
37216
+ ruleId: open3.ruleId,
37217
+ category: open3.category,
37218
+ severity: open3.severity,
37219
+ span,
37220
+ rawMatch: text.slice(span.start, span.end),
37221
+ confidence: open3.confidence
37222
+ };
37223
+ }
37224
+ function mergeOverlappingSameRule(findings, text) {
37225
+ if (findings.length === 0) return findings;
37226
+ const groups = /* @__PURE__ */ new Map();
37227
+ const ruleOrder = [];
37228
+ for (const finding of findings) {
37229
+ const group = groups.get(finding.ruleId);
37230
+ if (group) {
37231
+ group.push(finding);
37232
+ } else {
37233
+ groups.set(finding.ruleId, [finding]);
37234
+ ruleOrder.push(finding.ruleId);
37235
+ }
37236
+ }
37237
+ const merged = [];
37238
+ for (const ruleId of ruleOrder) {
37239
+ const group = groups.get(ruleId) ?? [];
37240
+ const sorted = [...group].sort(
37241
+ (a, b) => a.span.start - b.span.start || a.span.end - b.span.end
37242
+ );
37243
+ let open3;
37244
+ for (const finding of sorted) {
37245
+ if (open3 && finding.span.start < open3.end) {
37246
+ open3.end = Math.max(open3.end, finding.span.end);
37247
+ open3.confidence = Math.max(open3.confidence, finding.confidence);
37248
+ continue;
37249
+ }
37250
+ if (open3) merged.push(closeRegion(open3, text));
37251
+ open3 = {
37252
+ start: finding.span.start,
37253
+ end: finding.span.end,
37254
+ confidence: finding.confidence,
37255
+ ruleId: finding.ruleId,
37256
+ category: finding.category,
37257
+ severity: finding.severity
37258
+ };
37259
+ }
37260
+ if (open3) merged.push(closeRegion(open3, text));
37261
+ }
37262
+ return merged;
37263
+ }
37264
+ function extensionOf(filePath) {
37265
+ const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
37266
+ const dot = base.lastIndexOf(".");
37267
+ return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
37268
+ }
37269
+ function ruleApplies(rule, extension) {
37270
+ if (!rule.appliesTo || extension === void 0) return true;
37271
+ return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
37272
+ }
37273
+ function scan(text, rules, context) {
37274
+ const ruleset = rules ?? getLoadedRules();
37275
+ const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
37276
+ const normalization = normalizeFormatChars(text);
37277
+ const originalCandidates = buildCandidates(text, ruleset, extension);
37278
+ if (!normalization) return gate(originalCandidates, text, void 0);
37279
+ const pooledOriginal = originalCandidates.map(
37280
+ (candidate) => withNormalizedSpan(candidate, normalization)
37281
+ );
37282
+ const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
37283
+ (candidate) => mapCandidateToOriginal(candidate, normalization, text)
37284
+ );
37285
+ const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
37286
+ return mergeOverlappingSameRule(findings, text);
37287
+ }
36993
37288
  var SEVERITY_RANK2 = {
36994
37289
  critical: 3,
36995
37290
  high: 2,
@@ -39635,8 +39930,8 @@ function createIsolatedScanner(data, opts = {}) {
39635
39930
  }
39636
39931
  function enqueue(spec) {
39637
39932
  const next = chain.then(
39638
- () => new Promise((resolve2) => {
39639
- spec(resolve2);
39933
+ () => new Promise((resolve3) => {
39934
+ spec(resolve3);
39640
39935
  })
39641
39936
  );
39642
39937
  chain = next.then(
@@ -39647,7 +39942,7 @@ function createIsolatedScanner(data, opts = {}) {
39647
39942
  }
39648
39943
  return {
39649
39944
  scan(text, context, scanOpts) {
39650
- return enqueue((resolve2) => {
39945
+ return enqueue((resolve3) => {
39651
39946
  runOne(
39652
39947
  {
39653
39948
  budgetMs,
@@ -39660,23 +39955,23 @@ function createIsolatedScanner(data, opts = {}) {
39660
39955
  }),
39661
39956
  reply: (message) => {
39662
39957
  if (message.kind !== "result") return false;
39663
- resolve2({ status: "ok", findings: message.findings });
39958
+ resolve3({ status: "ok", findings: message.findings });
39664
39959
  return true;
39665
39960
  }
39666
39961
  },
39667
- resolve2
39962
+ resolve3
39668
39963
  );
39669
39964
  });
39670
39965
  },
39671
39966
  probe(rule) {
39672
- return enqueue((resolve2) => {
39967
+ return enqueue((resolve3) => {
39673
39968
  runOne(
39674
39969
  {
39675
39970
  budgetMs: probeBudgetMs,
39676
39971
  build: (id) => ({ kind: "probe", id, rule }),
39677
39972
  reply: (message) => {
39678
39973
  if (message.kind !== "probed") return false;
39679
- resolve2({
39974
+ resolve3({
39680
39975
  status: "ok",
39681
39976
  verdict: message.verdict,
39682
39977
  worstMs: message.worstMs,
@@ -39685,7 +39980,7 @@ function createIsolatedScanner(data, opts = {}) {
39685
39980
  return true;
39686
39981
  }
39687
39982
  },
39688
- resolve2
39983
+ resolve3
39689
39984
  );
39690
39985
  });
39691
39986
  },
@@ -40732,7 +41027,7 @@ async function send(options) {
40732
41027
  }
40733
41028
  }
40734
41029
  };
40735
- return new Promise((resolve2, reject) => {
41030
+ return new Promise((resolve3, reject) => {
40736
41031
  let settled = false;
40737
41032
  const fail = (reason, status) => {
40738
41033
  if (settled) return;
@@ -40758,7 +41053,7 @@ async function send(options) {
40758
41053
  res.on("end", () => {
40759
41054
  if (settled) return;
40760
41055
  settled = true;
40761
- resolve2({
41056
+ resolve3({
40762
41057
  status: res.statusCode ?? 0,
40763
41058
  headers: res.headers,
40764
41059
  body: Buffer.concat(chunks).toString("utf8")
@@ -41754,10 +42049,55 @@ import { spawn } from "child_process";
41754
42049
  import { fileURLToPath as fileURLToPath2 } from "url";
41755
42050
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
41756
42051
 
42052
+ // ../../packages/plugin-runtime/src/attached/install-record.ts
42053
+ import { readFile as readFile2, stat } from "fs/promises";
42054
+ import { basename as basename7, dirname as dirname6, join as join29, resolve as resolve2 } from "path";
42055
+ async function readInstalledVersion(installRoot) {
42056
+ try {
42057
+ const versionDir = resolve2(installRoot);
42058
+ const pluginDir = dirname6(versionDir);
42059
+ const marketplaceDir = dirname6(pluginDir);
42060
+ const cacheDir = dirname6(marketplaceDir);
42061
+ if (basename7(cacheDir) !== "cache") return null;
42062
+ const key = `${basename7(pluginDir)}@${basename7(marketplaceDir)}`;
42063
+ const record2 = JSON.parse(
42064
+ await readFile2(join29(dirname6(cacheDir), "installed_plugins.json"), "utf8")
42065
+ );
42066
+ const plugins = record2?.plugins;
42067
+ if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
42068
+ return null;
42069
+ }
42070
+ const entries = plugins[key];
42071
+ if (!Array.isArray(entries)) return null;
42072
+ let newest = null;
42073
+ for (const entry of entries) {
42074
+ const { version: version2, installPath } = entry ?? {};
42075
+ if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) continue;
42076
+ if (!StorePosturePlugin.shape.installedVersion.safeParse(version2).success) continue;
42077
+ if (newest !== null && compareBinaryVersions(version2, newest) <= 0) continue;
42078
+ if (typeof installPath === "string" && !await exists(installPath)) continue;
42079
+ newest = version2;
42080
+ }
42081
+ return newest;
42082
+ } catch {
42083
+ return null;
42084
+ }
42085
+ }
42086
+ async function exists(path) {
42087
+ try {
42088
+ await stat(path);
42089
+ return true;
42090
+ } catch {
42091
+ return false;
42092
+ }
42093
+ }
42094
+
41757
42095
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
41758
42096
  import { readFileSync as readFileSync18 } from "fs";
42097
+ var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
41759
42098
  function createPluginBlock(build, policyStore) {
41760
42099
  return async () => {
42100
+ const installed = build.installRoot === void 0 ? void 0 : readInstalledVersionBounded(build.installRoot);
41761
42101
  const cached2 = await policyStore.read();
41762
42102
  const fetchedAtMs = cached2?.fetchedAtMs;
41763
42103
  const block = {
@@ -41765,16 +42105,25 @@ function createPluginBlock(build, policyStore) {
41765
42105
  version: build.version,
41766
42106
  ossVersion: build.ossVersion ?? null,
41767
42107
  policyBundleVersion: cached2 !== null && StorePosturePlugin.shape.policyBundleVersion.safeParse(cached2.bundle.version).success ? cached2.bundle.version : null,
41768
- policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null
42108
+ policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null,
42109
+ ...installed === void 0 ? {} : { installedVersion: await installed },
42110
+ buildSchemaVersion: SQLITE_MIGRATIONS.length
41769
42111
  };
41770
42112
  return StorePosturePlugin.safeParse(block).success ? block : void 0;
41771
42113
  };
41772
42114
  }
42115
+ async function readInstalledVersionBounded(installRoot) {
42116
+ try {
42117
+ return await withTimeout(readInstalledVersion(installRoot), INSTALL_RECORD_READ_TIMEOUT_MS);
42118
+ } catch {
42119
+ return null;
42120
+ }
42121
+ }
41773
42122
 
41774
42123
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41775
42124
  import { randomUUID as randomUUID16 } from "crypto";
41776
- import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
41777
- import { join as join29 } from "path";
42125
+ import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42126
+ import { join as join30 } from "path";
41778
42127
 
41779
42128
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
41780
42129
  import { rename as rename2 } from "fs/promises";
@@ -41782,11 +42131,11 @@ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
41782
42131
  var IMMEDIATE_RETRIES = 8;
41783
42132
  var TIMED_RETRIES = 4;
41784
42133
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
41785
- var delay = (ms) => new Promise((resolve2) => {
41786
- setTimeout(resolve2, ms);
42134
+ var delay = (ms) => new Promise((resolve3) => {
42135
+ setTimeout(resolve3, ms);
41787
42136
  });
41788
- var yieldToLoop = () => new Promise((resolve2) => {
41789
- setImmediate(resolve2);
42137
+ var yieldToLoop = () => new Promise((resolve3) => {
42138
+ setImmediate(resolve3);
41790
42139
  });
41791
42140
  async function publishByRename(tmp, file2, move = rename2) {
41792
42141
  for (let attempt = 1; ; attempt += 1) {
@@ -41803,10 +42152,10 @@ async function publishByRename(tmp, file2, move = rename2) {
41803
42152
 
41804
42153
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41805
42154
  function createPolicyStore(dir = dataDir()) {
41806
- const file2 = join29(dir, "policy-cache.json");
42155
+ const file2 = join30(dir, "policy-cache.json");
41807
42156
  async function read() {
41808
42157
  try {
41809
- const raw = await readFile2(file2, "utf8");
42158
+ const raw = await readFile3(file2, "utf8");
41810
42159
  const parsed2 = JSON.parse(raw);
41811
42160
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
41812
42161
  const record2 = parsed2;
@@ -41828,7 +42177,7 @@ function createPolicyStore(dir = dataDir()) {
41828
42177
  }
41829
42178
  async function priorRecord() {
41830
42179
  try {
41831
- const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
42180
+ const parsed2 = JSON.parse(await readFile3(file2, "utf8"));
41832
42181
  return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
41833
42182
  } catch {
41834
42183
  return null;
@@ -41874,7 +42223,7 @@ function createPolicyStore(dir = dataDir()) {
41874
42223
 
41875
42224
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
41876
42225
  import { readFileSync as readFileSync19 } from "fs";
41877
- import { join as join30 } from "path";
42226
+ import { join as join31 } from "path";
41878
42227
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
41879
42228
  var OUTCOME_KEYS = {
41880
42229
  ok: true,
@@ -41888,7 +42237,7 @@ var OUTCOME_KEYS = {
41888
42237
  };
41889
42238
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
41890
42239
  function postureReportStatePath(dataDir2) {
41891
- return join30(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42240
+ return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41892
42241
  }
41893
42242
  function writePostureReportState(dataDir2, state) {
41894
42243
  try {
@@ -42067,12 +42416,12 @@ function readStorePosture(dbPath2) {
42067
42416
 
42068
42417
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42069
42418
  import { randomUUID as randomUUID17 } from "crypto";
42070
- import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42071
- import { join as join31 } from "path";
42419
+ import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42420
+ import { join as join32 } from "path";
42072
42421
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42073
42422
  function createPostureStore(dir = settingsDir(), legacyDir) {
42074
- const file2 = join31(dir, "posture-state.json");
42075
- const legacyFile = legacyDir === void 0 ? null : join31(legacyDir, "posture-state.json");
42423
+ const file2 = join32(dir, "posture-state.json");
42424
+ const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
42076
42425
  async function persist(state) {
42077
42426
  await ensureDataDir(dir);
42078
42427
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -42087,7 +42436,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42087
42436
  async function readFrom(path) {
42088
42437
  let raw;
42089
42438
  try {
42090
- raw = await readFile3(path, "utf8");
42439
+ raw = await readFile4(path, "utf8");
42091
42440
  } catch (err) {
42092
42441
  const code = err.code;
42093
42442
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -42141,7 +42490,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42141
42490
 
42142
42491
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42143
42492
  import { readFileSync as readFileSync20 } from "fs";
42144
- import { join as join32 } from "path";
42493
+ import { join as join33 } from "path";
42145
42494
 
42146
42495
  // ../../packages/plugin-runtime/src/attached/status.ts
42147
42496
  var REFUSAL_LINES = {
@@ -42218,12 +42567,12 @@ var StandaloneDataGateway = class {
42218
42567
  // reconciler drops the whole pass and recovers it idempotently on the next read.
42219
42568
  recordLlmCalls(inputs) {
42220
42569
  if (inputs.length === 0) return Promise.resolve();
42221
- return new Promise((resolve2, reject) => {
42570
+ return new Promise((resolve3, reject) => {
42222
42571
  try {
42223
42572
  this.db.auditEvents.runInTransaction(() => {
42224
42573
  for (const input2 of inputs) this.db.auditEvents.insertLlmCall(input2);
42225
42574
  });
42226
- resolve2();
42575
+ resolve3();
42227
42576
  } catch (err) {
42228
42577
  reject(err instanceof Error ? err : new Error(String(err)));
42229
42578
  }
@@ -42235,12 +42584,12 @@ var StandaloneDataGateway = class {
42235
42584
  // drops the whole pass and recovers it idempotently next time.
42236
42585
  recordToolCalls(inputs) {
42237
42586
  if (inputs.length === 0) return Promise.resolve();
42238
- return new Promise((resolve2, reject) => {
42587
+ return new Promise((resolve3, reject) => {
42239
42588
  try {
42240
42589
  this.db.auditEvents.runInTransaction(() => {
42241
42590
  for (const input2 of inputs) this.writeToolCall(input2);
42242
42591
  });
42243
- resolve2();
42592
+ resolve3();
42244
42593
  } catch (err) {
42245
42594
  reject(err instanceof Error ? err : new Error(String(err)));
42246
42595
  }
@@ -42639,7 +42988,7 @@ import { statSync as statSync11 } from "fs";
42639
42988
 
42640
42989
  // ../../packages/scanner/src/walk.ts
42641
42990
  import { readdirSync as readdirSync6, readFileSync as readFileSync21, statSync as statSync10 } from "fs";
42642
- import { extname, join as join33, relative as relative2, sep as sep4 } from "path";
42991
+ import { extname, join as join34, relative as relative2, sep as sep4 } from "path";
42643
42992
  var import_ignore2 = __toESM(require_ignore(), 1);
42644
42993
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
42645
42994
  ".ts",
@@ -42690,7 +43039,7 @@ function* walkTree(rootDir, opts = {}) {
42690
43039
  );
42691
43040
  for (const entry of dirents) {
42692
43041
  const name = entry.name;
42693
- const fullPath = join33(dir, name);
43042
+ const fullPath = join34(dir, name);
42694
43043
  if (entry.isDirectory()) {
42695
43044
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
42696
43045
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {