@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.
package/scripts/sync.js CHANGED
@@ -32,9 +32,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
  mod
33
33
  ));
34
34
 
35
- // ../../node_modules/.pnpm/ignore@7.0.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;
@@ -999,6 +1006,10 @@ var SQLITE_MIGRATIONS = [
999
1006
  {
1000
1007
  tag: "0035_share_destination_provider_id",
1001
1008
  sql: "ALTER TABLE `share_destination` ADD `provider_id` text;"
1009
+ },
1010
+ {
1011
+ tag: "0036_secret_vault_identity_fingerprint",
1012
+ 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"
1002
1013
  }
1003
1014
  ];
1004
1015
 
@@ -1008,6 +1019,12 @@ var HOUR_MS = 60 * MINUTE_MS;
1008
1019
  var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1009
1020
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1010
1021
 
1022
+ // ../../packages/schema/src/invisible-padding.ts
1023
+ var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
1024
+ function stripInvisiblePadding(text) {
1025
+ return text.replace(INVISIBLE_PADDING, "");
1026
+ }
1027
+
1011
1028
  // ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
1012
1029
  var external_exports = {};
1013
1030
  __export(external_exports, {
@@ -6034,7 +6051,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6034
6051
  var NONE = 0;
6035
6052
  var ASSUMED = 1;
6036
6053
  var PROVEN = 2;
6037
- function isRecursive(inst, stack, resolve2) {
6054
+ function isRecursive(inst, stack, resolve3) {
6038
6055
  const cached2 = recursive.get(inst);
6039
6056
  if (cached2 !== void 0)
6040
6057
  return cached2 ? PROVEN : NONE;
@@ -6044,7 +6061,7 @@ function isRecursive(inst, stack, resolve2) {
6044
6061
  let result = NONE;
6045
6062
  const check2 = (child) => {
6046
6063
  if (result !== PROVEN && child?._zod) {
6047
- const answer = isRecursive(child, stack, resolve2);
6064
+ const answer = isRecursive(child, stack, resolve3);
6048
6065
  if (answer > result)
6049
6066
  result = answer;
6050
6067
  }
@@ -6055,7 +6072,7 @@ function isRecursive(inst, stack, resolve2) {
6055
6072
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6056
6073
  if (spread && !desc.enumerable)
6057
6074
  continue;
6058
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
6075
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6059
6076
  if (child > answer)
6060
6077
  answer = child;
6061
6078
  }
@@ -6119,7 +6136,7 @@ function isRecursive(inst, stack, resolve2) {
6119
6136
  break;
6120
6137
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6121
6138
  case "lazy": {
6122
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
6139
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6123
6140
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6124
6141
  break;
6125
6142
  }
@@ -23400,7 +23417,29 @@ var StorePosturePlugin = external_exports.object({
23400
23417
  */
23401
23418
  policyBundleVersion: external_exports.string().max(200).nullable(),
23402
23419
  /** Epoch millis, on the CLIENT clock, of that fetch. */
23403
- policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
23420
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
23421
+ /**
23422
+ * The newest version the host's own install record holds for this plugin —
23423
+ * what is on disk. After an update it leads `version` (the running copy) by
23424
+ * one launch. Null when no usable version can be read: no install record
23425
+ * (a plugin run from a checkout), no entry with a valid version, or every
23426
+ * such entry names an `installPath` that no longer exists; OPTIONAL, not
23427
+ * required, so a build that predates the member keeps getting its 200.
23428
+ * Bounded like `version`.
23429
+ */
23430
+ installedVersion: external_exports.string().max(64).nullable().optional(),
23431
+ /**
23432
+ * The local-store schema version this running build migrates a store to:
23433
+ * the number of store migrations it carries, the count it stamps into
23434
+ * `PRAGMA user_version`. A snapshot whose `schemaVersion` is above it
23435
+ * usually describes a store a newer build migrated. It is a hint, not a
23436
+ * verdict: the stamp is write-only, so a store whose count ran past this
23437
+ * build's while this build knows every migration in its ledger reads above
23438
+ * it too, which is why describeStoreSkew decides skew on ledger tags and
23439
+ * never on the count. OPTIONAL for the same reason as `installedVersion`;
23440
+ * bounded like `schemaVersion`.
23441
+ */
23442
+ buildSchemaVersion: external_exports.number().int().min(0).max(MAX_INT4).optional()
23404
23443
  }).meta({ id: "StorePosturePlugin" });
23405
23444
  var StorePostureSnapshot = external_exports.object({
23406
23445
  deviceId: external_exports.guid(),
@@ -25043,10 +25082,15 @@ var ParsedPointer = external_exports.object({
25043
25082
  });
25044
25083
  var VaultEntry = external_exports.object({
25045
25084
  pointerId: external_exports.string(),
25046
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
25047
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
25048
- // independently of the vault encryption key below.
25085
+ // The keyed HMAC of the EXACT raw bytes under `exception.key`, and the epoch it
25086
+ // was derived under. The vault's own dedupe key: a value and its invisibly
25087
+ // padded twin are two rows. It rotates independently of the vault encryption
25088
+ // key below. Never matched against an exception or grant.
25049
25089
  valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25090
+ // The same HMAC over the raw with invisible padding removed: the identity a
25091
+ // reveal-to-model grant and every exception match on. Shared by a value and
25092
+ // its padded twin.
25093
+ valueIdentityFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25050
25094
  fingerprintKeyVersion: external_exports.number().int().positive(),
25051
25095
  // The vault-key epoch this row's ciphertext was sealed under.
25052
25096
  keyVersion: external_exports.number().int().positive(),
@@ -25619,10 +25663,18 @@ var SeveritySummaryItem = external_exports.object({
25619
25663
  count: external_exports.number().int().nonnegative(),
25620
25664
  // Resolution-aware breakdown (optional, additive). Populated once findings
25621
25665
  // carry lifecycle state: `caught` = handled in-flight (enforced); `openAtRest`
25622
- // = still open with no in-flight enforcement (needs remediation). Absent on the
25623
- // legacy count-only response until the resolution feature lands.
25666
+ // = still open with no in-flight enforcement (needs remediation); `dismissed`
25667
+ // = closed by a human judgement rather than a fix — visible, but not counted as
25668
+ // needing remediation. The three are disjoint. Absent on the legacy count-only
25669
+ // response until the resolution feature lands.
25624
25670
  caught: external_exports.number().int().nonnegative().optional(),
25625
- openAtRest: external_exports.number().int().nonnegative().optional()
25671
+ openAtRest: external_exports.number().int().nonnegative().optional(),
25672
+ dismissed: external_exports.number().int().nonnegative().optional(),
25673
+ // The two halves of `caught`, for a reader that wants them apart: `handled` =
25674
+ // in-flight findings an enforcement action already contained; `resolved` =
25675
+ // at-rest findings closed out by fixing them. `handled + resolved === caught`.
25676
+ handled: external_exports.number().int().nonnegative().optional(),
25677
+ resolved: external_exports.number().int().nonnegative().optional()
25626
25678
  }).meta({ id: "SeveritySummaryItem" });
25627
25679
  var SeveritySummaryResponse = external_exports.object({
25628
25680
  // Sum of bySeverity[].count.
@@ -25630,6 +25682,9 @@ var SeveritySummaryResponse = external_exports.object({
25630
25682
  // Findings still open at rest (sum of bySeverity[].openAtRest). Optional and
25631
25683
  // additive — absent on the legacy response until the resolution feature lands.
25632
25684
  needsRemediation: external_exports.number().int().nonnegative().optional(),
25685
+ // Findings a user dismissed (sum of bySeverity[].dismissed). Excluded from
25686
+ // needsRemediation, and kept visible here so an accepted risk is not erased.
25687
+ dismissed: external_exports.number().int().nonnegative().optional(),
25633
25688
  // All four severity levels are always present (count may be 0).
25634
25689
  bySeverity: external_exports.array(SeveritySummaryItem)
25635
25690
  }).meta({ id: "SeveritySummaryResponse" });
@@ -26247,11 +26302,11 @@ function repairOrRefuseMode(file2) {
26247
26302
  const link = lstatSync2(file2, { throwIfNoEntry: false });
26248
26303
  if (link === void 0) return "absent";
26249
26304
  if (link.isSymbolicLink()) return "untrusted";
26250
- const stat = statSync(file2, { throwIfNoEntry: false });
26251
- if (stat === void 0) return "absent";
26305
+ const stat2 = statSync(file2, { throwIfNoEntry: false });
26306
+ if (stat2 === void 0) return "absent";
26252
26307
  const uid = process.getuid?.();
26253
- if (uid !== void 0 && stat.uid !== uid) return "untrusted";
26254
- if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
26308
+ if (uid !== void 0 && stat2.uid !== uid) return "untrusted";
26309
+ if (process.platform !== "win32" && (stat2.mode & 511) !== DATA_FILE_MODE) {
26255
26310
  try {
26256
26311
  chmodSync2(file2, DATA_FILE_MODE);
26257
26312
  } catch {
@@ -26263,9 +26318,9 @@ function repairOrRefuseMode(file2) {
26263
26318
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26264
26319
  const file2 = controlPlaneCredentialPath(settingsDir2);
26265
26320
  let raw;
26266
- const gate = repairOrRefuseMode(file2);
26267
- if (gate === "absent") return { usable: false, reason: "absent" };
26268
- if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
26321
+ const gate2 = repairOrRefuseMode(file2);
26322
+ if (gate2 === "absent") return { usable: false, reason: "absent" };
26323
+ if (gate2 === "untrusted") return { usable: false, reason: "untrusted-file" };
26269
26324
  try {
26270
26325
  raw = readFileSync(file2, "utf8");
26271
26326
  } catch (err) {
@@ -32410,7 +32465,10 @@ var SqliteResolutionsRepository = class {
32410
32465
  * Insert many dispositions as ONE transaction — all of them or none.
32411
32466
  *
32412
32467
  * A dashboard dismissal closes every open finding of a rule, which is one
32413
- * write per key; run loose, a fault partway leaves half a rule closed with
32468
+ * write per key. It reaches this through
32469
+ * `LocalDatabase.dismissOpenFindingsForRule`, which calls it inside the
32470
+ * transaction that selected the keys, so there it runs as a SAVEPOINT of
32471
+ * that transaction. Run loose, a fault partway leaves half a rule closed with
32414
32472
  * nothing recording that the other half was meant to be. The caller then has
32415
32473
  * no way to tell a partial run from a complete one, because the card it
32416
32474
  * refreshes into just shows a smaller number either way.
@@ -32630,6 +32688,7 @@ function toSighting(row) {
32630
32688
  var SELECT_COLUMNS = `
32631
32689
  pointer_id AS pointerId,
32632
32690
  value_fingerprint AS valueFingerprint,
32691
+ value_identity_fingerprint AS valueIdentityFingerprint,
32633
32692
  fingerprint_key_version AS fingerprintKeyVersion,
32634
32693
  key_version AS keyVersion,
32635
32694
  format_version AS formatVersion,
@@ -32654,13 +32713,13 @@ var SqliteSecretVaultRepository = class {
32654
32713
  this.db = db;
32655
32714
  this.insertStmt = db.prepare(
32656
32715
  `INSERT INTO secret_vault (
32657
- pointer_id, value_fingerprint, fingerprint_key_version, key_version,
32658
- format_version, category, rule_id, masked_match, provider,
32716
+ pointer_id, value_fingerprint, value_identity_fingerprint,
32717
+ fingerprint_key_version, key_version, format_version, category, rule_id, masked_match, provider,
32659
32718
  ciphertext, nonce, auth_tag,
32660
32719
  user_authorized, occurrence_count, first_seen, last_seen
32661
32720
  ) VALUES (
32662
- :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
32663
- :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32721
+ :pointerId, :valueFingerprint, :valueIdentityFingerprint,
32722
+ :fingerprintKeyVersion, :keyVersion, :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32664
32723
  :ciphertext, :nonce, :authTag,
32665
32724
  :userAuthorized, 1, :now, :now
32666
32725
  )`
@@ -32685,7 +32744,13 @@ var SqliteSecretVaultRepository = class {
32685
32744
  );
32686
32745
  this.refreshFingerprintStmt = db.prepare(
32687
32746
  `UPDATE secret_vault
32688
- SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
32747
+ SET value_fingerprint = :valueFingerprint,
32748
+ value_identity_fingerprint = :valueIdentityFingerprint,
32749
+ fingerprint_key_version = :fingerprintKeyVersion
32750
+ WHERE pointer_id = :pointerId`
32751
+ );
32752
+ this.setIdentityStmt = db.prepare(
32753
+ `UPDATE secret_vault SET value_identity_fingerprint = :valueIdentityFingerprint
32689
32754
  WHERE pointer_id = :pointerId`
32690
32755
  );
32691
32756
  this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
@@ -32702,6 +32767,7 @@ var SqliteSecretVaultRepository = class {
32702
32767
  listStmt;
32703
32768
  replaceCiphertextStmt;
32704
32769
  refreshFingerprintStmt;
32770
+ setIdentityStmt;
32705
32771
  deleteByPointerStmt;
32706
32772
  derefStmt;
32707
32773
  /**
@@ -32732,6 +32798,7 @@ var SqliteSecretVaultRepository = class {
32732
32798
  bindParams({
32733
32799
  pointerId: input2.pointerId,
32734
32800
  valueFingerprint: input2.valueFingerprint,
32801
+ valueIdentityFingerprint: input2.valueIdentityFingerprint,
32735
32802
  fingerprintKeyVersion: input2.fingerprintKeyVersion,
32736
32803
  keyVersion: input2.keyVersion,
32737
32804
  formatVersion: input2.formatVersion ?? POINTER_FORMAT_VERSION,
@@ -32793,7 +32860,15 @@ var SqliteSecretVaultRepository = class {
32793
32860
  replaceCiphertext(pointerId, next) {
32794
32861
  this.replaceCiphertextStmt.run({ pointerId, ...next });
32795
32862
  }
32796
- /** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
32863
+ /**
32864
+ * Correct an entry's identity fingerprint in place, leaving its exact
32865
+ * fingerprint and key epoch alone. For a row whose identity column still holds
32866
+ * the exact value copied in by the migration that added it.
32867
+ */
32868
+ setIdentityFingerprint(pointerId, valueIdentityFingerprint) {
32869
+ this.setIdentityStmt.run({ pointerId, valueIdentityFingerprint });
32870
+ }
32871
+ /** Re-derive an entry's fingerprints under a new fingerprint-key epoch. */
32797
32872
  refreshFingerprint(pointerId, next) {
32798
32873
  this.refreshFingerprintStmt.run({ pointerId, ...next });
32799
32874
  }
@@ -32924,7 +32999,7 @@ var SqliteSecretVaultRepository = class {
32924
32999
  `SELECT ${INVENTORY_COLUMNS},
32925
33000
  (SELECT e.id FROM exceptions e
32926
33001
  WHERE e.rule_id = v.rule_id
32927
- AND e.value_fingerprint = v.value_fingerprint
33002
+ AND e.value_fingerprint = v.value_identity_fingerprint
32928
33003
  AND e.key_version = v.fingerprint_key_version
32929
33004
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32930
33005
  LIMIT 1) AS grant_id
@@ -32967,7 +33042,7 @@ var SqliteSecretVaultRepository = class {
32967
33042
  `SELECT ${INVENTORY_COLUMNS},
32968
33043
  (SELECT e.id FROM exceptions e
32969
33044
  WHERE e.rule_id = v.rule_id
32970
- AND e.value_fingerprint = v.value_fingerprint
33045
+ AND e.value_fingerprint = v.value_identity_fingerprint
32971
33046
  AND e.key_version = v.fingerprint_key_version
32972
33047
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32973
33048
  LIMIT 1) AS grant_id
@@ -33071,6 +33146,18 @@ var OPEN_AT_REST_FINDINGS_SQL = `FROM inspection_findings f
33071
33146
  OR latest.status IS NULL
33072
33147
  OR latest.status NOT IN ('resolved', 'dismissed')
33073
33148
  )`;
33149
+ function selectOpenFindingKeysForRule(db, ruleId) {
33150
+ const rows = allRows(
33151
+ db.prepare(
33152
+ `SELECT DISTINCT f.finding_key AS finding_key
33153
+ ${OPEN_AT_REST_FINDINGS_SQL}
33154
+ AND d.rule_id = :ruleId
33155
+ AND f.finding_key IS NOT NULL`
33156
+ ),
33157
+ { ruleId }
33158
+ );
33159
+ return rows.map((r) => r.finding_key);
33160
+ }
33074
33161
  var SEVERITIES = ["critical", "high", "medium", "low"];
33075
33162
  var ACTION_TO_KIND = {
33076
33163
  block: "blocked",
@@ -33127,16 +33214,16 @@ var SqliteSecurityRepository = class {
33127
33214
  // findings are caught only once their latest disposition is resolved,
33128
33215
  // otherwise they are open-at-rest.
33129
33216
  //
33130
- // NOTE for future manual-resolution writers: only latest status
33131
- // 'resolved' counts as caught above. When acknowledged/dismissed/
33132
- // false-positive manual dispositions land, this must keep filtering by
33133
- // status/method — 'acknowledged' is accepted risk, not a fix, and must NOT
33134
- // be bucketed as caught alongside 'resolved'.
33217
+ // Only latest status 'resolved' counts as caught above. 'dismissed' is its
33218
+ // own bucket: a judgement rather than a fix, so it is neither caught nor
33219
+ // needing remediation, and stays countable. A further manual disposition
33220
+ // (acknowledged, false-positive) must be placed deliberately — 'acknowledged'
33221
+ // is accepted risk, not a fix, and must NOT be bucketed as caught.
33135
33222
  //
33136
33223
  // Legacy at-rest findings from pre-branch scans carry finding_key = NULL —
33137
33224
  // the resolution lifecycle is keyed by finding_key, so it can never attach a
33138
33225
  // disposition to (or clear) one of these on re-scan. They are excluded from
33139
- // both caught and openAtRest (untracked, not "needs remediation forever"),
33226
+ // all three buckets (untracked, not "needs remediation forever"),
33140
33227
  // but still counted in total/count below — this keeps this predicate
33141
33228
  // consistent with SqliteResolutionsRepository.openAtRestKeysForPath, which
33142
33229
  // already filters `finding_key IS NOT NULL`.
@@ -33159,12 +33246,25 @@ var SqliteSecurityRepository = class {
33159
33246
  WHEN latest.status = 'resolved' THEN 1
33160
33247
  ELSE 0
33161
33248
  END) AS caught,
33249
+ SUM(CASE WHEN e.event_type != 'code_change' THEN 1 ELSE 0 END) AS handled,
33162
33250
  SUM(CASE
33163
33251
  WHEN e.event_type = 'code_change'
33164
33252
  AND f.finding_key IS NOT NULL
33165
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
33253
+ AND latest.status = 'resolved' THEN 1
33166
33254
  ELSE 0
33167
- END) AS open_at_rest
33255
+ END) AS resolved,
33256
+ SUM(CASE
33257
+ WHEN e.event_type = 'code_change'
33258
+ AND f.finding_key IS NOT NULL
33259
+ AND (latest.status IS NULL
33260
+ OR latest.status NOT IN ('resolved', 'dismissed')) THEN 1
33261
+ ELSE 0
33262
+ END) AS open_at_rest,
33263
+ SUM(CASE
33264
+ WHEN e.event_type = 'code_change'
33265
+ AND latest.status = 'dismissed' THEN 1
33266
+ ELSE 0
33267
+ END) AS dismissed
33168
33268
  FROM inspection_findings f
33169
33269
  JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
33170
33270
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -33179,11 +33279,15 @@ var SqliteSecurityRepository = class {
33179
33279
  severity,
33180
33280
  count: byRow.get(severity)?.count ?? 0,
33181
33281
  caught: byRow.get(severity)?.caught ?? 0,
33182
- openAtRest: byRow.get(severity)?.open_at_rest ?? 0
33282
+ handled: byRow.get(severity)?.handled ?? 0,
33283
+ resolved: byRow.get(severity)?.resolved ?? 0,
33284
+ openAtRest: byRow.get(severity)?.open_at_rest ?? 0,
33285
+ dismissed: byRow.get(severity)?.dismissed ?? 0
33183
33286
  }));
33184
33287
  const total = bySeverity.reduce((sum, s) => sum + s.count, 0);
33185
33288
  const needsRemediation = bySeverity.reduce((sum, s) => sum + s.openAtRest, 0);
33186
- return Promise.resolve({ total, needsRemediation, bySeverity });
33289
+ const dismissed = bySeverity.reduce((sum, s) => sum + s.dismissed, 0);
33290
+ return Promise.resolve({ total, needsRemediation, dismissed, bySeverity });
33187
33291
  }
33188
33292
  // Range is echoed but does not change the result today — coverage is a constant
33189
33293
  // business fact (see SCAN_COVERAGE), not a measured per-window metric. Order
@@ -33500,10 +33604,10 @@ var SqliteSecurityRepository = class {
33500
33604
  * machine, and the second reported "no recommendations" over live exposure.
33501
33605
  *
33502
33606
  * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
33503
- * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
33504
- * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
33505
- * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
33506
- * The two answer different questions and only this one has to match a link.
33607
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. It
33608
+ * differs from `severitySummary`'s `openAtRest` only in including untracked
33609
+ * legacy rows, which that bucket leaves out; dismissed is excluded from both.
33610
+ * Only this one has to match a link.
33507
33611
  *
33508
33612
  * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
33509
33613
  * whole-store scope costs a grouped scan rather than a row per finding.
@@ -33531,6 +33635,8 @@ var SqliteSecurityRepository = class {
33531
33635
  /**
33532
33636
  * The distinct `finding_key`s behind ONE rule's {@link recommendationInputs}
33533
33637
  * tally — what a dashboard dismissal of that row writes a disposition for.
33638
+ * The dismissal itself does not call this: it reads the same set through
33639
+ * {@link selectOpenFindingKeysForRule}, inside its own write transaction.
33534
33640
  *
33535
33641
  * It shares {@link OPEN_AT_REST_FINDINGS_SQL} with the count rather than
33536
33642
  * restating the predicate, because a dismissal has to act on exactly the set
@@ -33547,16 +33653,7 @@ var SqliteSecurityRepository = class {
33547
33653
  * this set SMALLER than the tally, never larger.
33548
33654
  */
33549
33655
  openFindingKeysForRule(ruleId) {
33550
- const rows = allRows(
33551
- this.db.prepare(
33552
- `SELECT DISTINCT f.finding_key AS finding_key
33553
- ${OPEN_AT_REST_FINDINGS_SQL}
33554
- AND d.rule_id = :ruleId
33555
- AND f.finding_key IS NOT NULL`
33556
- ),
33557
- { ruleId }
33558
- );
33559
- return Promise.resolve(rows.map((r) => r.finding_key));
33656
+ return Promise.resolve(selectOpenFindingKeysForRule(this.db, ruleId));
33560
33657
  }
33561
33658
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
33562
33659
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
@@ -34602,6 +34699,31 @@ function openLocalDatabase(dir, options = {}) {
34602
34699
  );
34603
34700
  });
34604
34701
  }
34702
+ function dismissOpenFindingsForRule(ruleId, disposition) {
34703
+ let dismissed = 0;
34704
+ withTransaction(
34705
+ db,
34706
+ () => {
34707
+ const keys = selectOpenFindingKeysForRule(db, ruleId);
34708
+ resolutions.insertResolutions(
34709
+ keys.map((findingKey) => ({
34710
+ findingKey,
34711
+ status: "dismissed",
34712
+ method: disposition.method,
34713
+ resolvedAt: disposition.resolvedAt,
34714
+ evidence: disposition.evidence
34715
+ }))
34716
+ );
34717
+ dismissed = keys.length;
34718
+ },
34719
+ // IMMEDIATE takes the write lock at BEGIN, before the select, which is
34720
+ // what keeps a concurrent resolve out of the gap. It also makes waiting
34721
+ // on a busy writer an ordinary busy_timeout wait rather than a
34722
+ // read-to-write upgrade SQLite refuses to retry.
34723
+ "IMMEDIATE"
34724
+ );
34725
+ return dismissed;
34726
+ }
34605
34727
  function recordCapture(event, detected) {
34606
34728
  failOpenTransaction(db, () => {
34607
34729
  const sessionId = event.metadata?.sessionId;
@@ -34785,6 +34907,7 @@ function openLocalDatabase(dir, options = {}) {
34785
34907
  inspectionDefinitions,
34786
34908
  inspectionFindings,
34787
34909
  recordCapture,
34910
+ dismissOpenFindingsForRule,
34788
34911
  markCaptureDelivered,
34789
34912
  markCaptureOwed,
34790
34913
  markAuditEventsDelivered,
@@ -35001,6 +35124,9 @@ function loadOrCreateFingerprintKey(dataDir2) {
35001
35124
  });
35002
35125
  }
35003
35126
  function fingerprintValue(key, raw) {
35127
+ return exactFingerprintValue(key, stripInvisiblePadding(raw));
35128
+ }
35129
+ function exactFingerprintValue(key, raw) {
35004
35130
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
35005
35131
  }
35006
35132
 
@@ -35171,7 +35297,7 @@ async function send(options) {
35171
35297
  }
35172
35298
  }
35173
35299
  };
35174
- return new Promise((resolve2, reject) => {
35300
+ return new Promise((resolve3, reject) => {
35175
35301
  let settled = false;
35176
35302
  const fail = (reason, status) => {
35177
35303
  if (settled) return;
@@ -35197,7 +35323,7 @@ async function send(options) {
35197
35323
  res.on("end", () => {
35198
35324
  if (settled) return;
35199
35325
  settled = true;
35200
- resolve2({
35326
+ resolve3({
35201
35327
  status: res.statusCode ?? 0,
35202
35328
  headers: res.headers,
35203
35329
  body: Buffer.concat(chunks).toString("utf8")
@@ -36753,11 +36879,11 @@ var EXACT_KIND_BY_BASENAME = {
36753
36879
  "composer.json": "composer.json",
36754
36880
  "packages.config": "packages.config"
36755
36881
  };
36756
- function manifestKindOf(basename7) {
36757
- if (LOCKFILE_BASENAMES.has(basename7)) return null;
36758
- const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename7) ? EXACT_KIND_BY_BASENAME[basename7] : void 0;
36882
+ function manifestKindOf(basename8) {
36883
+ if (LOCKFILE_BASENAMES.has(basename8)) return null;
36884
+ const exact = Object.hasOwn(EXACT_KIND_BY_BASENAME, basename8) ? EXACT_KIND_BY_BASENAME[basename8] : void 0;
36759
36885
  if (exact !== void 0) return exact;
36760
- if (basename7.endsWith(".csproj")) return "csproj";
36886
+ if (basename8.endsWith(".csproj")) return "csproj";
36761
36887
  return null;
36762
36888
  }
36763
36889
  function extractManifestSdks(text, kind) {
@@ -37235,6 +37361,82 @@ function escapeRegExp2(value) {
37235
37361
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
37236
37362
  }
37237
37363
 
37364
+ // ../../packages/detections/src/format-chars.ts
37365
+ var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
37366
+ var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
37367
+ function normalizeFormatChars(text) {
37368
+ if (!HAS_FORMAT_CHAR.test(text)) return void 0;
37369
+ const normalizedParts = [];
37370
+ const segments = [];
37371
+ let cursor = 0;
37372
+ let normLength = 0;
37373
+ for (const match of text.matchAll(FORMAT_CHAR_GLOBAL)) {
37374
+ const matchStart = match.index;
37375
+ if (matchStart > cursor) {
37376
+ const length = matchStart - cursor;
37377
+ normalizedParts.push(text.slice(cursor, matchStart));
37378
+ segments.push({ normStart: normLength, origStart: cursor, length });
37379
+ normLength += length;
37380
+ }
37381
+ cursor = matchStart + match[0].length;
37382
+ }
37383
+ if (cursor < text.length) {
37384
+ const length = text.length - cursor;
37385
+ normalizedParts.push(text.slice(cursor));
37386
+ segments.push({ normStart: normLength, origStart: cursor, length });
37387
+ }
37388
+ return { normalized: normalizedParts.join(""), segments };
37389
+ }
37390
+ function segmentAt(segments, normPos) {
37391
+ let lo = 0;
37392
+ let hi = segments.length - 1;
37393
+ while (lo < hi) {
37394
+ const mid = lo + hi >> 1;
37395
+ const segment = segments[mid];
37396
+ if (segment !== void 0 && normPos >= segment.normStart + segment.length) {
37397
+ lo = mid + 1;
37398
+ } else {
37399
+ hi = mid;
37400
+ }
37401
+ }
37402
+ const found = segments[lo];
37403
+ if (found === void 0) {
37404
+ throw new Error(`normPos ${String(normPos)} has no covering segment`);
37405
+ }
37406
+ return found;
37407
+ }
37408
+ function mapSpanToOriginal(span, normalization) {
37409
+ const { segments } = normalization;
37410
+ const startSegment = segmentAt(segments, span.start);
37411
+ const start = startSegment.origStart + (span.start - startSegment.normStart);
37412
+ const endSegment = segmentAt(segments, span.end - 1);
37413
+ const end = endSegment.origStart + (span.end - 1 - endSegment.normStart) + 1;
37414
+ return { start, end };
37415
+ }
37416
+ function normalizedOffset(origPos, segments) {
37417
+ let lo = 0;
37418
+ let hi = segments.length;
37419
+ while (lo < hi) {
37420
+ const mid = lo + hi >> 1;
37421
+ const segment = segments[mid];
37422
+ if (segment !== void 0 && segment.origStart + segment.length <= origPos) {
37423
+ lo = mid + 1;
37424
+ } else {
37425
+ hi = mid;
37426
+ }
37427
+ }
37428
+ const found = segments[Math.min(lo, segments.length - 1)];
37429
+ if (found === void 0) return 0;
37430
+ return found.normStart + Math.min(Math.max(0, origPos - found.origStart), found.length);
37431
+ }
37432
+ function mapSpanToNormalized(span, normalization) {
37433
+ const { segments } = normalization;
37434
+ return {
37435
+ start: normalizedOffset(span.start, segments),
37436
+ end: normalizedOffset(span.end, segments)
37437
+ };
37438
+ }
37439
+
37238
37440
  // ../../packages/detections/src/regex-cache.ts
37239
37441
  var singles = /* @__PURE__ */ new WeakMap();
37240
37442
  var keywordLists = /* @__PURE__ */ new WeakMap();
@@ -37396,29 +37598,35 @@ function registerPack(pack) {
37396
37598
  function getLoadedRules() {
37397
37599
  return [...packs.values()].flatMap((p) => p.rules);
37398
37600
  }
37399
- function isCorroborated(candidate, candidates, text) {
37601
+ function spansOverlap(a, b) {
37602
+ return a.start < b.end && a.end > b.start;
37603
+ }
37604
+ function isCorroborated(candidate, candidates, text, normalization) {
37400
37605
  const req = candidate.rule.requiresNearby;
37401
37606
  if (!req) return true;
37402
37607
  const halfWindow = req.windowChars;
37403
- const { start, end } = candidate.match.span;
37404
- const winStart = start - halfWindow;
37405
- const winEnd = end + halfWindow;
37608
+ const ns = candidate.normSpan;
37609
+ const winStart = ns.start - halfWindow;
37610
+ const winEnd = ns.end + halfWindow;
37406
37611
  const categories = req.categories;
37407
37612
  const ruleIds = req.ruleIds;
37408
37613
  if (categories?.length || ruleIds?.length) {
37409
37614
  for (const other of candidates) {
37410
37615
  if (other === candidate) continue;
37411
- const os = other.match.span;
37412
- if (os.end < winStart || os.start > winEnd) continue;
37413
- if (other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category)) {
37414
- return true;
37616
+ if (other.normSpan.end < winStart || other.normSpan.start > winEnd) continue;
37617
+ const relevant = other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category) === true || ruleIds?.includes(other.match.ruleId) === true;
37618
+ if (!relevant) continue;
37619
+ if (other.match.ruleId === candidate.match.ruleId && spansOverlap(other.match.span, candidate.match.span)) {
37620
+ continue;
37415
37621
  }
37416
- if (ruleIds?.includes(other.match.ruleId)) return true;
37622
+ return true;
37417
37623
  }
37418
37624
  }
37419
37625
  const labels = req.labels;
37420
37626
  if (labels && labels.length > 0) {
37421
- const haystack = text.slice(Math.max(0, winStart), winEnd);
37627
+ const { start, end } = candidate.match.span;
37628
+ const haystack = text.slice(Math.max(0, start - halfWindow), end + halfWindow);
37629
+ const normalizedHaystack = normalization === void 0 ? void 0 : normalization.normalized.slice(Math.max(0, winStart), winEnd);
37422
37630
  for (const re of memoizedRegExpList(
37423
37631
  "label",
37424
37632
  req,
@@ -37427,29 +37635,20 @@ function isCorroborated(candidate, candidates, text) {
37427
37635
  return trimmed.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed)}(?![A-Za-z0-9])`, "i");
37428
37636
  })
37429
37637
  )) {
37430
- if (re?.test(haystack)) return true;
37638
+ if (!re) continue;
37639
+ if (re.test(haystack)) return true;
37640
+ if (normalizedHaystack !== void 0 && re.test(normalizedHaystack)) return true;
37431
37641
  }
37432
37642
  }
37433
37643
  return false;
37434
37644
  }
37435
- function extensionOf(filePath) {
37436
- const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
37437
- const dot = base.lastIndexOf(".");
37438
- return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
37439
- }
37440
- function ruleApplies(rule, extension) {
37441
- if (!rule.appliesTo || extension === void 0) return true;
37442
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
37443
- }
37444
- function scan(text, rules, context) {
37445
- const ruleset = rules ?? getLoadedRules();
37446
- const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
37645
+ function buildCandidates(matchText, ruleset, extension) {
37447
37646
  const candidates = [];
37448
37647
  for (const rule of ruleset) {
37449
37648
  if (!ruleApplies(rule, extension)) continue;
37450
- const spans = MATCHERS[rule.matcher.type](text, rule);
37649
+ const spans = MATCHERS[rule.matcher.type](matchText, rule);
37451
37650
  for (const span of spans) {
37452
- const rawMatch = text.slice(span.start, span.end);
37651
+ const rawMatch = matchText.slice(span.start, span.end);
37453
37652
  if (!passesPostValidators(rule, rawMatch)) continue;
37454
37653
  candidates.push({
37455
37654
  rule,
@@ -37460,10 +37659,31 @@ function scan(text, rules, context) {
37460
37659
  span,
37461
37660
  rawMatch,
37462
37661
  confidence: 0.9
37463
- }
37662
+ },
37663
+ // In `matchText`'s own coordinates, which is the normalized text for
37664
+ // a normalized-pass candidate and so already right; an original-pass
37665
+ // candidate on the slow path is re-derived by withNormalizedSpan.
37666
+ normSpan: span
37464
37667
  });
37465
37668
  }
37466
37669
  }
37670
+ return candidates;
37671
+ }
37672
+ function mapCandidateToOriginal(candidate, normalization, text) {
37673
+ const span = mapSpanToOriginal(candidate.match.span, normalization);
37674
+ return {
37675
+ rule: candidate.rule,
37676
+ match: { ...candidate.match, span, rawMatch: text.slice(span.start, span.end) },
37677
+ // Deliberately NOT remapped: `normSpan` is the span the primitive match
37678
+ // was found at in the normalized text, which is exactly the coordinate
37679
+ // space windows are measured in. See the `Candidate` comment.
37680
+ normSpan: candidate.normSpan
37681
+ };
37682
+ }
37683
+ function withNormalizedSpan(candidate, normalization) {
37684
+ return { ...candidate, normSpan: mapSpanToNormalized(candidate.match.span, normalization) };
37685
+ }
37686
+ function gate(candidates, text, normalization) {
37467
37687
  const findings = [];
37468
37688
  for (const candidate of candidates) {
37469
37689
  const req = candidate.rule.requiresNearby;
@@ -37471,7 +37691,7 @@ function scan(text, rules, context) {
37471
37691
  findings.push(candidate.match);
37472
37692
  continue;
37473
37693
  }
37474
- if (!isCorroborated(candidate, candidates, text)) continue;
37694
+ if (!isCorroborated(candidate, candidates, text, normalization)) continue;
37475
37695
  const boost = req.confidenceBoost;
37476
37696
  findings.push(
37477
37697
  boost ? { ...candidate.match, confidence: Math.min(0.99, candidate.match.confidence + boost) } : candidate.match
@@ -37479,6 +37699,81 @@ function scan(text, rules, context) {
37479
37699
  }
37480
37700
  return findings;
37481
37701
  }
37702
+ function closeRegion(open3, text) {
37703
+ const span = { start: open3.start, end: open3.end };
37704
+ return {
37705
+ ruleId: open3.ruleId,
37706
+ category: open3.category,
37707
+ severity: open3.severity,
37708
+ span,
37709
+ rawMatch: text.slice(span.start, span.end),
37710
+ confidence: open3.confidence
37711
+ };
37712
+ }
37713
+ function mergeOverlappingSameRule(findings, text) {
37714
+ if (findings.length === 0) return findings;
37715
+ const groups = /* @__PURE__ */ new Map();
37716
+ const ruleOrder = [];
37717
+ for (const finding of findings) {
37718
+ const group = groups.get(finding.ruleId);
37719
+ if (group) {
37720
+ group.push(finding);
37721
+ } else {
37722
+ groups.set(finding.ruleId, [finding]);
37723
+ ruleOrder.push(finding.ruleId);
37724
+ }
37725
+ }
37726
+ const merged = [];
37727
+ for (const ruleId of ruleOrder) {
37728
+ const group = groups.get(ruleId) ?? [];
37729
+ const sorted = [...group].sort(
37730
+ (a, b) => a.span.start - b.span.start || a.span.end - b.span.end
37731
+ );
37732
+ let open3;
37733
+ for (const finding of sorted) {
37734
+ if (open3 && finding.span.start < open3.end) {
37735
+ open3.end = Math.max(open3.end, finding.span.end);
37736
+ open3.confidence = Math.max(open3.confidence, finding.confidence);
37737
+ continue;
37738
+ }
37739
+ if (open3) merged.push(closeRegion(open3, text));
37740
+ open3 = {
37741
+ start: finding.span.start,
37742
+ end: finding.span.end,
37743
+ confidence: finding.confidence,
37744
+ ruleId: finding.ruleId,
37745
+ category: finding.category,
37746
+ severity: finding.severity
37747
+ };
37748
+ }
37749
+ if (open3) merged.push(closeRegion(open3, text));
37750
+ }
37751
+ return merged;
37752
+ }
37753
+ function extensionOf(filePath) {
37754
+ const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
37755
+ const dot = base.lastIndexOf(".");
37756
+ return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
37757
+ }
37758
+ function ruleApplies(rule, extension) {
37759
+ if (!rule.appliesTo || extension === void 0) return true;
37760
+ return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
37761
+ }
37762
+ function scan(text, rules, context) {
37763
+ const ruleset = rules ?? getLoadedRules();
37764
+ const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
37765
+ const normalization = normalizeFormatChars(text);
37766
+ const originalCandidates = buildCandidates(text, ruleset, extension);
37767
+ if (!normalization) return gate(originalCandidates, text, void 0);
37768
+ const pooledOriginal = originalCandidates.map(
37769
+ (candidate) => withNormalizedSpan(candidate, normalization)
37770
+ );
37771
+ const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
37772
+ (candidate) => mapCandidateToOriginal(candidate, normalization, text)
37773
+ );
37774
+ const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
37775
+ return mergeOverlappingSameRule(findings, text);
37776
+ }
37482
37777
  var SEVERITY_RANK2 = {
37483
37778
  critical: 3,
37484
37779
  high: 2,
@@ -40124,8 +40419,8 @@ function createIsolatedScanner(data, opts = {}) {
40124
40419
  }
40125
40420
  function enqueue(spec) {
40126
40421
  const next = chain.then(
40127
- () => new Promise((resolve2) => {
40128
- spec(resolve2);
40422
+ () => new Promise((resolve3) => {
40423
+ spec(resolve3);
40129
40424
  })
40130
40425
  );
40131
40426
  chain = next.then(
@@ -40136,7 +40431,7 @@ function createIsolatedScanner(data, opts = {}) {
40136
40431
  }
40137
40432
  return {
40138
40433
  scan(text, context, scanOpts) {
40139
- return enqueue((resolve2) => {
40434
+ return enqueue((resolve3) => {
40140
40435
  runOne(
40141
40436
  {
40142
40437
  budgetMs,
@@ -40149,23 +40444,23 @@ function createIsolatedScanner(data, opts = {}) {
40149
40444
  }),
40150
40445
  reply: (message) => {
40151
40446
  if (message.kind !== "result") return false;
40152
- resolve2({ status: "ok", findings: message.findings });
40447
+ resolve3({ status: "ok", findings: message.findings });
40153
40448
  return true;
40154
40449
  }
40155
40450
  },
40156
- resolve2
40451
+ resolve3
40157
40452
  );
40158
40453
  });
40159
40454
  },
40160
40455
  probe(rule) {
40161
- return enqueue((resolve2) => {
40456
+ return enqueue((resolve3) => {
40162
40457
  runOne(
40163
40458
  {
40164
40459
  budgetMs: probeBudgetMs,
40165
40460
  build: (id) => ({ kind: "probe", id, rule }),
40166
40461
  reply: (message) => {
40167
40462
  if (message.kind !== "probed") return false;
40168
- resolve2({
40463
+ resolve3({
40169
40464
  status: "ok",
40170
40465
  verdict: message.verdict,
40171
40466
  worstMs: message.worstMs,
@@ -40174,7 +40469,7 @@ function createIsolatedScanner(data, opts = {}) {
40174
40469
  return true;
40175
40470
  }
40176
40471
  },
40177
- resolve2
40472
+ resolve3
40178
40473
  );
40179
40474
  });
40180
40475
  },
@@ -41673,10 +41968,55 @@ import { spawn } from "child_process";
41673
41968
  import { fileURLToPath as fileURLToPath2 } from "url";
41674
41969
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
41675
41970
 
41971
+ // ../../packages/plugin-runtime/src/attached/install-record.ts
41972
+ import { readFile as readFile2, stat } from "fs/promises";
41973
+ import { basename as basename6, dirname as dirname6, join as join28, resolve as resolve2 } from "path";
41974
+ async function readInstalledVersion(installRoot) {
41975
+ try {
41976
+ const versionDir = resolve2(installRoot);
41977
+ const pluginDir = dirname6(versionDir);
41978
+ const marketplaceDir = dirname6(pluginDir);
41979
+ const cacheDir = dirname6(marketplaceDir);
41980
+ if (basename6(cacheDir) !== "cache") return null;
41981
+ const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
41982
+ const record2 = JSON.parse(
41983
+ await readFile2(join28(dirname6(cacheDir), "installed_plugins.json"), "utf8")
41984
+ );
41985
+ const plugins = record2?.plugins;
41986
+ if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
41987
+ return null;
41988
+ }
41989
+ const entries = plugins[key];
41990
+ if (!Array.isArray(entries)) return null;
41991
+ let newest = null;
41992
+ for (const entry of entries) {
41993
+ const { version: version2, installPath } = entry ?? {};
41994
+ if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) continue;
41995
+ if (!StorePosturePlugin.shape.installedVersion.safeParse(version2).success) continue;
41996
+ if (newest !== null && compareBinaryVersions(version2, newest) <= 0) continue;
41997
+ if (typeof installPath === "string" && !await exists(installPath)) continue;
41998
+ newest = version2;
41999
+ }
42000
+ return newest;
42001
+ } catch {
42002
+ return null;
42003
+ }
42004
+ }
42005
+ async function exists(path) {
42006
+ try {
42007
+ await stat(path);
42008
+ return true;
42009
+ } catch {
42010
+ return false;
42011
+ }
42012
+ }
42013
+
41676
42014
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
41677
42015
  import { readFileSync as readFileSync18 } from "fs";
42016
+ var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
41678
42017
  function createPluginBlock(build, policyStore) {
41679
42018
  return async () => {
42019
+ const installed = build.installRoot === void 0 ? void 0 : readInstalledVersionBounded(build.installRoot);
41680
42020
  const cached2 = await policyStore.read();
41681
42021
  const fetchedAtMs = cached2?.fetchedAtMs;
41682
42022
  const block = {
@@ -41684,16 +42024,25 @@ function createPluginBlock(build, policyStore) {
41684
42024
  version: build.version,
41685
42025
  ossVersion: build.ossVersion ?? null,
41686
42026
  policyBundleVersion: cached2 !== null && StorePosturePlugin.shape.policyBundleVersion.safeParse(cached2.bundle.version).success ? cached2.bundle.version : null,
41687
- policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null
42027
+ policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null,
42028
+ ...installed === void 0 ? {} : { installedVersion: await installed },
42029
+ buildSchemaVersion: SQLITE_MIGRATIONS.length
41688
42030
  };
41689
42031
  return StorePosturePlugin.safeParse(block).success ? block : void 0;
41690
42032
  };
41691
42033
  }
42034
+ async function readInstalledVersionBounded(installRoot) {
42035
+ try {
42036
+ return await withTimeout(readInstalledVersion(installRoot), INSTALL_RECORD_READ_TIMEOUT_MS);
42037
+ } catch {
42038
+ return null;
42039
+ }
42040
+ }
41692
42041
 
41693
42042
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41694
42043
  import { randomUUID as randomUUID16 } from "crypto";
41695
- import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
41696
- import { join as join28 } from "path";
42044
+ import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42045
+ import { join as join29 } from "path";
41697
42046
 
41698
42047
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
41699
42048
  import { rename as rename2 } from "fs/promises";
@@ -41701,11 +42050,11 @@ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
41701
42050
  var IMMEDIATE_RETRIES = 8;
41702
42051
  var TIMED_RETRIES = 4;
41703
42052
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
41704
- var delay = (ms) => new Promise((resolve2) => {
41705
- setTimeout(resolve2, ms);
42053
+ var delay = (ms) => new Promise((resolve3) => {
42054
+ setTimeout(resolve3, ms);
41706
42055
  });
41707
- var yieldToLoop = () => new Promise((resolve2) => {
41708
- setImmediate(resolve2);
42056
+ var yieldToLoop = () => new Promise((resolve3) => {
42057
+ setImmediate(resolve3);
41709
42058
  });
41710
42059
  async function publishByRename(tmp, file2, move = rename2) {
41711
42060
  for (let attempt = 1; ; attempt += 1) {
@@ -41722,10 +42071,10 @@ async function publishByRename(tmp, file2, move = rename2) {
41722
42071
 
41723
42072
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41724
42073
  function createPolicyStore(dir = dataDir()) {
41725
- const file2 = join28(dir, "policy-cache.json");
42074
+ const file2 = join29(dir, "policy-cache.json");
41726
42075
  async function read() {
41727
42076
  try {
41728
- const raw = await readFile2(file2, "utf8");
42077
+ const raw = await readFile3(file2, "utf8");
41729
42078
  const parsed2 = JSON.parse(raw);
41730
42079
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
41731
42080
  const record2 = parsed2;
@@ -41747,7 +42096,7 @@ function createPolicyStore(dir = dataDir()) {
41747
42096
  }
41748
42097
  async function priorRecord() {
41749
42098
  try {
41750
- const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
42099
+ const parsed2 = JSON.parse(await readFile3(file2, "utf8"));
41751
42100
  return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
41752
42101
  } catch {
41753
42102
  return null;
@@ -41842,7 +42191,7 @@ async function runPolicySync(deps) {
41842
42191
 
41843
42192
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
41844
42193
  import { readFileSync as readFileSync19 } from "fs";
41845
- import { join as join29 } from "path";
42194
+ import { join as join30 } from "path";
41846
42195
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
41847
42196
  var OUTCOME_KEYS = {
41848
42197
  ok: true,
@@ -41856,7 +42205,7 @@ var OUTCOME_KEYS = {
41856
42205
  };
41857
42206
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
41858
42207
  function postureReportStatePath(dataDir2) {
41859
- return join29(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42208
+ return join30(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41860
42209
  }
41861
42210
  function writePostureReportState(dataDir2, state) {
41862
42211
  try {
@@ -42035,12 +42384,12 @@ function readStorePosture(dbPath2) {
42035
42384
 
42036
42385
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42037
42386
  import { randomUUID as randomUUID17 } from "crypto";
42038
- import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42039
- import { join as join30 } from "path";
42387
+ import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42388
+ import { join as join31 } from "path";
42040
42389
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42041
42390
  function createPostureStore(dir = settingsDir(), legacyDir) {
42042
- const file2 = join30(dir, "posture-state.json");
42043
- const legacyFile = legacyDir === void 0 ? null : join30(legacyDir, "posture-state.json");
42391
+ const file2 = join31(dir, "posture-state.json");
42392
+ const legacyFile = legacyDir === void 0 ? null : join31(legacyDir, "posture-state.json");
42044
42393
  async function persist(state) {
42045
42394
  await ensureDataDir(dir);
42046
42395
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -42055,7 +42404,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42055
42404
  async function readFrom(path) {
42056
42405
  let raw;
42057
42406
  try {
42058
- raw = await readFile3(path, "utf8");
42407
+ raw = await readFile4(path, "utf8");
42059
42408
  } catch (err) {
42060
42409
  const code = err.code;
42061
42410
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -42109,10 +42458,10 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42109
42458
 
42110
42459
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42111
42460
  import { readFileSync as readFileSync20 } from "fs";
42112
- import { join as join31 } from "path";
42461
+ import { join as join32 } from "path";
42113
42462
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
42114
42463
  function syncStatePath(dataDir2) {
42115
- return join31(dataDir2, SYNC_STATE_FILENAME);
42464
+ return join32(dataDir2, SYNC_STATE_FILENAME);
42116
42465
  }
42117
42466
  function writeSyncState(dataDir2, result) {
42118
42467
  try {
@@ -42221,12 +42570,12 @@ var StandaloneDataGateway = class {
42221
42570
  // reconciler drops the whole pass and recovers it idempotently on the next read.
42222
42571
  recordLlmCalls(inputs) {
42223
42572
  if (inputs.length === 0) return Promise.resolve();
42224
- return new Promise((resolve2, reject) => {
42573
+ return new Promise((resolve3, reject) => {
42225
42574
  try {
42226
42575
  this.db.auditEvents.runInTransaction(() => {
42227
42576
  for (const input2 of inputs) this.db.auditEvents.insertLlmCall(input2);
42228
42577
  });
42229
- resolve2();
42578
+ resolve3();
42230
42579
  } catch (err) {
42231
42580
  reject(err instanceof Error ? err : new Error(String(err)));
42232
42581
  }
@@ -42238,12 +42587,12 @@ var StandaloneDataGateway = class {
42238
42587
  // drops the whole pass and recovers it idempotently next time.
42239
42588
  recordToolCalls(inputs) {
42240
42589
  if (inputs.length === 0) return Promise.resolve();
42241
- return new Promise((resolve2, reject) => {
42590
+ return new Promise((resolve3, reject) => {
42242
42591
  try {
42243
42592
  this.db.auditEvents.runInTransaction(() => {
42244
42593
  for (const input2 of inputs) this.writeToolCall(input2);
42245
42594
  });
42246
- resolve2();
42595
+ resolve3();
42247
42596
  } catch (err) {
42248
42597
  reject(err instanceof Error ? err : new Error(String(err)));
42249
42598
  }
@@ -42639,7 +42988,7 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
42639
42988
 
42640
42989
  // ../../packages/scanner/src/discover.ts
42641
42990
  import { readdirSync as readdirSync5 } from "fs";
42642
- import { join as join32 } from "path";
42991
+ import { join as join33 } from "path";
42643
42992
 
42644
42993
  // ../../packages/scanner/src/constants.ts
42645
42994
  var COMMON_SKIP_DIRS = ["node_modules", "__pycache__", ".venv", "venv", ".cache"];
@@ -42660,7 +43009,7 @@ var DISCOVER_SKIP = /* @__PURE__ */ new Set([
42660
43009
  ]);
42661
43010
 
42662
43011
  // ../../packages/scanner/src/render.ts
42663
- import { basename as basename6, relative } from "path";
43012
+ import { basename as basename7, relative } from "path";
42664
43013
 
42665
43014
  // ../../packages/scanner/src/scan.ts
42666
43015
  import { existsSync as existsSync12, readFileSync as readFileSync22 } from "fs";
@@ -42671,7 +43020,7 @@ import { statSync as statSync11 } from "fs";
42671
43020
 
42672
43021
  // ../../packages/scanner/src/walk.ts
42673
43022
  import { readdirSync as readdirSync6, readFileSync as readFileSync21, statSync as statSync10 } from "fs";
42674
- import { extname, join as join33, relative as relative2, sep as sep4 } from "path";
43023
+ import { extname, join as join34, relative as relative2, sep as sep4 } from "path";
42675
43024
  var import_ignore2 = __toESM(require_ignore(), 1);
42676
43025
  var SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
42677
43026
  ".ts",
@@ -42722,7 +43071,7 @@ function* walkTree(rootDir, opts = {}) {
42722
43071
  );
42723
43072
  for (const entry of dirents) {
42724
43073
  const name = entry.name;
42725
- const fullPath = join33(dir, name);
43074
+ const fullPath = join34(dir, name);
42726
43075
  if (entry.isDirectory()) {
42727
43076
  const skipState = evaluateIgnore(dirSkipLayers, dirRel, name, true);
42728
43077
  if (skipState !== "unignored" && (SKIP_DIRS.has(name) || skipState === "ignored")) {