@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 basename8 = shortcut ? basenameOf(path) : path;
685
+ const basename9 = 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 ? basename8 : path
691
+ shortcut && rule._basenameOnly ? basename9 : 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, resolve3) {
6057
+ function isRecursive(inst, stack, resolve4) {
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, resolve3) {
6047
6064
  let result = NONE;
6048
6065
  const check2 = (child) => {
6049
6066
  if (result !== PROVEN && child?._zod) {
6050
- const answer = isRecursive(child, stack, resolve3);
6067
+ const answer = isRecursive(child, stack, resolve4);
6051
6068
  if (answer > result)
6052
6069
  result = answer;
6053
6070
  }
@@ -6058,7 +6075,7 @@ function isRecursive(inst, stack, resolve3) {
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, resolve3) : NONE;
6078
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve4) : NONE;
6062
6079
  if (child > answer)
6063
6080
  answer = child;
6064
6081
  }
@@ -6122,7 +6139,7 @@ function isRecursive(inst, stack, resolve3) {
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 ?? (resolve3 ? inst._zod.innerType : void 0);
6142
+ const inner = def._cachedInner ?? (resolve4 ? 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,
33253
+ SUM(CASE
33254
+ WHEN e.event_type = 'code_change'
33255
+ AND f.finding_key IS NOT NULL
33256
+ AND latest.status = 'resolved' THEN 1
33257
+ ELSE 0
33258
+ END) AS resolved,
33165
33259
  SUM(CASE
33166
33260
  WHEN e.event_type = 'code_change'
33167
33261
  AND f.finding_key IS NOT NULL
33168
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
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
33169
33269
  ELSE 0
33170
- END) AS open_at_rest
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
 
@@ -35760,6 +35886,82 @@ function escapeRegExp2(value) {
35760
35886
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35761
35887
  }
35762
35888
 
35889
+ // ../../packages/detections/src/format-chars.ts
35890
+ var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
35891
+ var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
35892
+ function normalizeFormatChars(text) {
35893
+ if (!HAS_FORMAT_CHAR.test(text)) return void 0;
35894
+ const normalizedParts = [];
35895
+ const segments = [];
35896
+ let cursor = 0;
35897
+ let normLength = 0;
35898
+ for (const match of text.matchAll(FORMAT_CHAR_GLOBAL)) {
35899
+ const matchStart = match.index;
35900
+ if (matchStart > cursor) {
35901
+ const length = matchStart - cursor;
35902
+ normalizedParts.push(text.slice(cursor, matchStart));
35903
+ segments.push({ normStart: normLength, origStart: cursor, length });
35904
+ normLength += length;
35905
+ }
35906
+ cursor = matchStart + match[0].length;
35907
+ }
35908
+ if (cursor < text.length) {
35909
+ const length = text.length - cursor;
35910
+ normalizedParts.push(text.slice(cursor));
35911
+ segments.push({ normStart: normLength, origStart: cursor, length });
35912
+ }
35913
+ return { normalized: normalizedParts.join(""), segments };
35914
+ }
35915
+ function segmentAt(segments, normPos) {
35916
+ let lo = 0;
35917
+ let hi = segments.length - 1;
35918
+ while (lo < hi) {
35919
+ const mid = lo + hi >> 1;
35920
+ const segment = segments[mid];
35921
+ if (segment !== void 0 && normPos >= segment.normStart + segment.length) {
35922
+ lo = mid + 1;
35923
+ } else {
35924
+ hi = mid;
35925
+ }
35926
+ }
35927
+ const found = segments[lo];
35928
+ if (found === void 0) {
35929
+ throw new Error(`normPos ${String(normPos)} has no covering segment`);
35930
+ }
35931
+ return found;
35932
+ }
35933
+ function mapSpanToOriginal(span, normalization) {
35934
+ const { segments } = normalization;
35935
+ const startSegment = segmentAt(segments, span.start);
35936
+ const start = startSegment.origStart + (span.start - startSegment.normStart);
35937
+ const endSegment = segmentAt(segments, span.end - 1);
35938
+ const end = endSegment.origStart + (span.end - 1 - endSegment.normStart) + 1;
35939
+ return { start, end };
35940
+ }
35941
+ function normalizedOffset(origPos, segments) {
35942
+ let lo = 0;
35943
+ let hi = segments.length;
35944
+ while (lo < hi) {
35945
+ const mid = lo + hi >> 1;
35946
+ const segment = segments[mid];
35947
+ if (segment !== void 0 && segment.origStart + segment.length <= origPos) {
35948
+ lo = mid + 1;
35949
+ } else {
35950
+ hi = mid;
35951
+ }
35952
+ }
35953
+ const found = segments[Math.min(lo, segments.length - 1)];
35954
+ if (found === void 0) return 0;
35955
+ return found.normStart + Math.min(Math.max(0, origPos - found.origStart), found.length);
35956
+ }
35957
+ function mapSpanToNormalized(span, normalization) {
35958
+ const { segments } = normalization;
35959
+ return {
35960
+ start: normalizedOffset(span.start, segments),
35961
+ end: normalizedOffset(span.end, segments)
35962
+ };
35963
+ }
35964
+
35763
35965
  // ../../packages/detections/src/regex-cache.ts
35764
35966
  var singles = /* @__PURE__ */ new WeakMap();
35765
35967
  var keywordLists = /* @__PURE__ */ new WeakMap();
@@ -35921,29 +36123,35 @@ function registerPack(pack) {
35921
36123
  function getLoadedRules() {
35922
36124
  return [...packs.values()].flatMap((p) => p.rules);
35923
36125
  }
35924
- function isCorroborated(candidate, candidates, text) {
36126
+ function spansOverlap(a, b) {
36127
+ return a.start < b.end && a.end > b.start;
36128
+ }
36129
+ function isCorroborated(candidate, candidates, text, normalization) {
35925
36130
  const req = candidate.rule.requiresNearby;
35926
36131
  if (!req) return true;
35927
36132
  const halfWindow = req.windowChars;
35928
- const { start, end } = candidate.match.span;
35929
- const winStart = start - halfWindow;
35930
- const winEnd = end + halfWindow;
36133
+ const ns = candidate.normSpan;
36134
+ const winStart = ns.start - halfWindow;
36135
+ const winEnd = ns.end + halfWindow;
35931
36136
  const categories = req.categories;
35932
36137
  const ruleIds = req.ruleIds;
35933
36138
  if (categories?.length || ruleIds?.length) {
35934
36139
  for (const other of candidates) {
35935
36140
  if (other === candidate) continue;
35936
- const os = other.match.span;
35937
- if (os.end < winStart || os.start > winEnd) continue;
35938
- if (other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category)) {
35939
- return true;
36141
+ if (other.normSpan.end < winStart || other.normSpan.start > winEnd) continue;
36142
+ const relevant = other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category) === true || ruleIds?.includes(other.match.ruleId) === true;
36143
+ if (!relevant) continue;
36144
+ if (other.match.ruleId === candidate.match.ruleId && spansOverlap(other.match.span, candidate.match.span)) {
36145
+ continue;
35940
36146
  }
35941
- if (ruleIds?.includes(other.match.ruleId)) return true;
36147
+ return true;
35942
36148
  }
35943
36149
  }
35944
36150
  const labels = req.labels;
35945
36151
  if (labels && labels.length > 0) {
35946
- const haystack = text.slice(Math.max(0, winStart), winEnd);
36152
+ const { start, end } = candidate.match.span;
36153
+ const haystack = text.slice(Math.max(0, start - halfWindow), end + halfWindow);
36154
+ const normalizedHaystack = normalization === void 0 ? void 0 : normalization.normalized.slice(Math.max(0, winStart), winEnd);
35947
36155
  for (const re of memoizedRegExpList(
35948
36156
  "label",
35949
36157
  req,
@@ -35952,29 +36160,20 @@ function isCorroborated(candidate, candidates, text) {
35952
36160
  return trimmed.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed)}(?![A-Za-z0-9])`, "i");
35953
36161
  })
35954
36162
  )) {
35955
- if (re?.test(haystack)) return true;
36163
+ if (!re) continue;
36164
+ if (re.test(haystack)) return true;
36165
+ if (normalizedHaystack !== void 0 && re.test(normalizedHaystack)) return true;
35956
36166
  }
35957
36167
  }
35958
36168
  return false;
35959
36169
  }
35960
- function extensionOf(filePath) {
35961
- const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
35962
- const dot = base.lastIndexOf(".");
35963
- return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
35964
- }
35965
- function ruleApplies(rule, extension) {
35966
- if (!rule.appliesTo || extension === void 0) return true;
35967
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
35968
- }
35969
- function scan(text, rules, context) {
35970
- const ruleset = rules ?? getLoadedRules();
35971
- const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
36170
+ function buildCandidates(matchText, ruleset, extension) {
35972
36171
  const candidates = [];
35973
36172
  for (const rule of ruleset) {
35974
36173
  if (!ruleApplies(rule, extension)) continue;
35975
- const spans = MATCHERS[rule.matcher.type](text, rule);
36174
+ const spans = MATCHERS[rule.matcher.type](matchText, rule);
35976
36175
  for (const span of spans) {
35977
- const rawMatch = text.slice(span.start, span.end);
36176
+ const rawMatch = matchText.slice(span.start, span.end);
35978
36177
  if (!passesPostValidators(rule, rawMatch)) continue;
35979
36178
  candidates.push({
35980
36179
  rule,
@@ -35985,10 +36184,31 @@ function scan(text, rules, context) {
35985
36184
  span,
35986
36185
  rawMatch,
35987
36186
  confidence: 0.9
35988
- }
36187
+ },
36188
+ // In `matchText`'s own coordinates, which is the normalized text for
36189
+ // a normalized-pass candidate and so already right; an original-pass
36190
+ // candidate on the slow path is re-derived by withNormalizedSpan.
36191
+ normSpan: span
35989
36192
  });
35990
36193
  }
35991
36194
  }
36195
+ return candidates;
36196
+ }
36197
+ function mapCandidateToOriginal(candidate, normalization, text) {
36198
+ const span = mapSpanToOriginal(candidate.match.span, normalization);
36199
+ return {
36200
+ rule: candidate.rule,
36201
+ match: { ...candidate.match, span, rawMatch: text.slice(span.start, span.end) },
36202
+ // Deliberately NOT remapped: `normSpan` is the span the primitive match
36203
+ // was found at in the normalized text, which is exactly the coordinate
36204
+ // space windows are measured in. See the `Candidate` comment.
36205
+ normSpan: candidate.normSpan
36206
+ };
36207
+ }
36208
+ function withNormalizedSpan(candidate, normalization) {
36209
+ return { ...candidate, normSpan: mapSpanToNormalized(candidate.match.span, normalization) };
36210
+ }
36211
+ function gate(candidates, text, normalization) {
35992
36212
  const findings = [];
35993
36213
  for (const candidate of candidates) {
35994
36214
  const req = candidate.rule.requiresNearby;
@@ -35996,7 +36216,7 @@ function scan(text, rules, context) {
35996
36216
  findings.push(candidate.match);
35997
36217
  continue;
35998
36218
  }
35999
- if (!isCorroborated(candidate, candidates, text)) continue;
36219
+ if (!isCorroborated(candidate, candidates, text, normalization)) continue;
36000
36220
  const boost = req.confidenceBoost;
36001
36221
  findings.push(
36002
36222
  boost ? { ...candidate.match, confidence: Math.min(0.99, candidate.match.confidence + boost) } : candidate.match
@@ -36004,6 +36224,81 @@ function scan(text, rules, context) {
36004
36224
  }
36005
36225
  return findings;
36006
36226
  }
36227
+ function closeRegion(open3, text) {
36228
+ const span = { start: open3.start, end: open3.end };
36229
+ return {
36230
+ ruleId: open3.ruleId,
36231
+ category: open3.category,
36232
+ severity: open3.severity,
36233
+ span,
36234
+ rawMatch: text.slice(span.start, span.end),
36235
+ confidence: open3.confidence
36236
+ };
36237
+ }
36238
+ function mergeOverlappingSameRule(findings, text) {
36239
+ if (findings.length === 0) return findings;
36240
+ const groups = /* @__PURE__ */ new Map();
36241
+ const ruleOrder = [];
36242
+ for (const finding of findings) {
36243
+ const group = groups.get(finding.ruleId);
36244
+ if (group) {
36245
+ group.push(finding);
36246
+ } else {
36247
+ groups.set(finding.ruleId, [finding]);
36248
+ ruleOrder.push(finding.ruleId);
36249
+ }
36250
+ }
36251
+ const merged = [];
36252
+ for (const ruleId of ruleOrder) {
36253
+ const group = groups.get(ruleId) ?? [];
36254
+ const sorted = [...group].sort(
36255
+ (a, b) => a.span.start - b.span.start || a.span.end - b.span.end
36256
+ );
36257
+ let open3;
36258
+ for (const finding of sorted) {
36259
+ if (open3 && finding.span.start < open3.end) {
36260
+ open3.end = Math.max(open3.end, finding.span.end);
36261
+ open3.confidence = Math.max(open3.confidence, finding.confidence);
36262
+ continue;
36263
+ }
36264
+ if (open3) merged.push(closeRegion(open3, text));
36265
+ open3 = {
36266
+ start: finding.span.start,
36267
+ end: finding.span.end,
36268
+ confidence: finding.confidence,
36269
+ ruleId: finding.ruleId,
36270
+ category: finding.category,
36271
+ severity: finding.severity
36272
+ };
36273
+ }
36274
+ if (open3) merged.push(closeRegion(open3, text));
36275
+ }
36276
+ return merged;
36277
+ }
36278
+ function extensionOf(filePath) {
36279
+ const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
36280
+ const dot = base.lastIndexOf(".");
36281
+ return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
36282
+ }
36283
+ function ruleApplies(rule, extension) {
36284
+ if (!rule.appliesTo || extension === void 0) return true;
36285
+ return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
36286
+ }
36287
+ function scan(text, rules, context) {
36288
+ const ruleset = rules ?? getLoadedRules();
36289
+ const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
36290
+ const normalization = normalizeFormatChars(text);
36291
+ const originalCandidates = buildCandidates(text, ruleset, extension);
36292
+ if (!normalization) return gate(originalCandidates, text, void 0);
36293
+ const pooledOriginal = originalCandidates.map(
36294
+ (candidate) => withNormalizedSpan(candidate, normalization)
36295
+ );
36296
+ const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
36297
+ (candidate) => mapCandidateToOriginal(candidate, normalization, text)
36298
+ );
36299
+ const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
36300
+ return mergeOverlappingSameRule(findings, text);
36301
+ }
36007
36302
  var SEVERITY_RANK2 = {
36008
36303
  critical: 3,
36009
36304
  high: 2,
@@ -38642,8 +38937,8 @@ function createIsolatedScanner(data, opts = {}) {
38642
38937
  }
38643
38938
  function enqueue(spec) {
38644
38939
  const next = chain.then(
38645
- () => new Promise((resolve3) => {
38646
- spec(resolve3);
38940
+ () => new Promise((resolve4) => {
38941
+ spec(resolve4);
38647
38942
  })
38648
38943
  );
38649
38944
  chain = next.then(
@@ -38654,7 +38949,7 @@ function createIsolatedScanner(data, opts = {}) {
38654
38949
  }
38655
38950
  return {
38656
38951
  scan(text, context, scanOpts) {
38657
- return enqueue((resolve3) => {
38952
+ return enqueue((resolve4) => {
38658
38953
  runOne(
38659
38954
  {
38660
38955
  budgetMs,
@@ -38667,23 +38962,23 @@ function createIsolatedScanner(data, opts = {}) {
38667
38962
  }),
38668
38963
  reply: (message) => {
38669
38964
  if (message.kind !== "result") return false;
38670
- resolve3({ status: "ok", findings: message.findings });
38965
+ resolve4({ status: "ok", findings: message.findings });
38671
38966
  return true;
38672
38967
  }
38673
38968
  },
38674
- resolve3
38969
+ resolve4
38675
38970
  );
38676
38971
  });
38677
38972
  },
38678
38973
  probe(rule) {
38679
- return enqueue((resolve3) => {
38974
+ return enqueue((resolve4) => {
38680
38975
  runOne(
38681
38976
  {
38682
38977
  budgetMs: probeBudgetMs,
38683
38978
  build: (id) => ({ kind: "probe", id, rule }),
38684
38979
  reply: (message) => {
38685
38980
  if (message.kind !== "probed") return false;
38686
- resolve3({
38981
+ resolve4({
38687
38982
  status: "ok",
38688
38983
  verdict: message.verdict,
38689
38984
  worstMs: message.worstMs,
@@ -38692,7 +38987,7 @@ function createIsolatedScanner(data, opts = {}) {
38692
38987
  return true;
38693
38988
  }
38694
38989
  },
38695
- resolve3
38990
+ resolve4
38696
38991
  );
38697
38992
  });
38698
38993
  },
@@ -40023,7 +40318,7 @@ async function send(options) {
40023
40318
  }
40024
40319
  }
40025
40320
  };
40026
- return new Promise((resolve3, reject) => {
40321
+ return new Promise((resolve4, reject) => {
40027
40322
  let settled = false;
40028
40323
  const fail2 = (reason, status) => {
40029
40324
  if (settled) return;
@@ -40049,7 +40344,7 @@ async function send(options) {
40049
40344
  res.on("end", () => {
40050
40345
  if (settled) return;
40051
40346
  settled = true;
40052
- resolve3({
40347
+ resolve4({
40053
40348
  status: res.statusCode ?? 0,
40054
40349
  headers: res.headers,
40055
40350
  body: Buffer.concat(chunks).toString("utf8")
@@ -41045,10 +41340,55 @@ import { spawn } from "child_process";
41045
41340
  import { fileURLToPath as fileURLToPath3 } from "url";
41046
41341
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
41047
41342
 
41343
+ // ../../packages/plugin-runtime/src/attached/install-record.ts
41344
+ import { readFile as readFile2, stat } from "fs/promises";
41345
+ import { basename as basename7, dirname as dirname7, join as join31, resolve as resolve2 } from "path";
41346
+ async function readInstalledVersion(installRoot) {
41347
+ try {
41348
+ const versionDir = resolve2(installRoot);
41349
+ const pluginDir = dirname7(versionDir);
41350
+ const marketplaceDir = dirname7(pluginDir);
41351
+ const cacheDir = dirname7(marketplaceDir);
41352
+ if (basename7(cacheDir) !== "cache") return null;
41353
+ const key = `${basename7(pluginDir)}@${basename7(marketplaceDir)}`;
41354
+ const record2 = JSON.parse(
41355
+ await readFile2(join31(dirname7(cacheDir), "installed_plugins.json"), "utf8")
41356
+ );
41357
+ const plugins = record2?.plugins;
41358
+ if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
41359
+ return null;
41360
+ }
41361
+ const entries = plugins[key];
41362
+ if (!Array.isArray(entries)) return null;
41363
+ let newest = null;
41364
+ for (const entry of entries) {
41365
+ const { version: version2, installPath } = entry ?? {};
41366
+ if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) continue;
41367
+ if (!StorePosturePlugin.shape.installedVersion.safeParse(version2).success) continue;
41368
+ if (newest !== null && compareBinaryVersions(version2, newest) <= 0) continue;
41369
+ if (typeof installPath === "string" && !await exists(installPath)) continue;
41370
+ newest = version2;
41371
+ }
41372
+ return newest;
41373
+ } catch {
41374
+ return null;
41375
+ }
41376
+ }
41377
+ async function exists(path) {
41378
+ try {
41379
+ await stat(path);
41380
+ return true;
41381
+ } catch {
41382
+ return false;
41383
+ }
41384
+ }
41385
+
41048
41386
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
41049
41387
  import { readFileSync as readFileSync20 } from "fs";
41388
+ var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
41050
41389
  function createPluginBlock(build, policyStore) {
41051
41390
  return async () => {
41391
+ const installed = build.installRoot === void 0 ? void 0 : readInstalledVersionBounded(build.installRoot);
41052
41392
  const cached2 = await policyStore.read();
41053
41393
  const fetchedAtMs = cached2?.fetchedAtMs;
41054
41394
  const block = {
@@ -41056,16 +41396,25 @@ function createPluginBlock(build, policyStore) {
41056
41396
  version: build.version,
41057
41397
  ossVersion: build.ossVersion ?? null,
41058
41398
  policyBundleVersion: cached2 !== null && StorePosturePlugin.shape.policyBundleVersion.safeParse(cached2.bundle.version).success ? cached2.bundle.version : null,
41059
- policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null
41399
+ policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null,
41400
+ ...installed === void 0 ? {} : { installedVersion: await installed },
41401
+ buildSchemaVersion: SQLITE_MIGRATIONS.length
41060
41402
  };
41061
41403
  return StorePosturePlugin.safeParse(block).success ? block : void 0;
41062
41404
  };
41063
41405
  }
41406
+ async function readInstalledVersionBounded(installRoot) {
41407
+ try {
41408
+ return await withTimeout(readInstalledVersion(installRoot), INSTALL_RECORD_READ_TIMEOUT_MS);
41409
+ } catch {
41410
+ return null;
41411
+ }
41412
+ }
41064
41413
 
41065
41414
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41066
41415
  import { randomUUID as randomUUID16 } from "crypto";
41067
- import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
41068
- import { join as join31 } from "path";
41416
+ import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
41417
+ import { join as join32 } from "path";
41069
41418
 
41070
41419
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
41071
41420
  import { rename as rename2 } from "fs/promises";
@@ -41073,11 +41422,11 @@ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
41073
41422
  var IMMEDIATE_RETRIES = 8;
41074
41423
  var TIMED_RETRIES = 4;
41075
41424
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
41076
- var delay = (ms) => new Promise((resolve3) => {
41077
- setTimeout(resolve3, ms);
41425
+ var delay = (ms) => new Promise((resolve4) => {
41426
+ setTimeout(resolve4, ms);
41078
41427
  });
41079
- var yieldToLoop = () => new Promise((resolve3) => {
41080
- setImmediate(resolve3);
41428
+ var yieldToLoop = () => new Promise((resolve4) => {
41429
+ setImmediate(resolve4);
41081
41430
  });
41082
41431
  async function publishByRename(tmp, file2, move = rename2) {
41083
41432
  for (let attempt = 1; ; attempt += 1) {
@@ -41094,10 +41443,10 @@ async function publishByRename(tmp, file2, move = rename2) {
41094
41443
 
41095
41444
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
41096
41445
  function createPolicyStore(dir = dataDir()) {
41097
- const file2 = join31(dir, "policy-cache.json");
41446
+ const file2 = join32(dir, "policy-cache.json");
41098
41447
  async function read() {
41099
41448
  try {
41100
- const raw = await readFile2(file2, "utf8");
41449
+ const raw = await readFile3(file2, "utf8");
41101
41450
  const parsed2 = JSON.parse(raw);
41102
41451
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
41103
41452
  const record2 = parsed2;
@@ -41119,7 +41468,7 @@ function createPolicyStore(dir = dataDir()) {
41119
41468
  }
41120
41469
  async function priorRecord() {
41121
41470
  try {
41122
- const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
41471
+ const parsed2 = JSON.parse(await readFile3(file2, "utf8"));
41123
41472
  return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
41124
41473
  } catch {
41125
41474
  return null;
@@ -41165,7 +41514,7 @@ function createPolicyStore(dir = dataDir()) {
41165
41514
 
41166
41515
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
41167
41516
  import { readFileSync as readFileSync21 } from "fs";
41168
- import { join as join32 } from "path";
41517
+ import { join as join33 } from "path";
41169
41518
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
41170
41519
  var OUTCOME_KEYS = {
41171
41520
  ok: true,
@@ -41179,7 +41528,7 @@ var OUTCOME_KEYS = {
41179
41528
  };
41180
41529
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
41181
41530
  function postureReportStatePath(dataDir2) {
41182
- return join32(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41531
+ return join33(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41183
41532
  }
41184
41533
  function writePostureReportState(dataDir2, state) {
41185
41534
  try {
@@ -41358,12 +41707,12 @@ function readStorePosture(dbPath2) {
41358
41707
 
41359
41708
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
41360
41709
  import { randomUUID as randomUUID17 } from "crypto";
41361
- import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
41362
- import { join as join33 } from "path";
41710
+ import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
41711
+ import { join as join34 } from "path";
41363
41712
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
41364
41713
  function createPostureStore(dir = settingsDir(), legacyDir) {
41365
- const file2 = join33(dir, "posture-state.json");
41366
- const legacyFile = legacyDir === void 0 ? null : join33(legacyDir, "posture-state.json");
41714
+ const file2 = join34(dir, "posture-state.json");
41715
+ const legacyFile = legacyDir === void 0 ? null : join34(legacyDir, "posture-state.json");
41367
41716
  async function persist(state) {
41368
41717
  await ensureDataDir(dir);
41369
41718
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -41378,7 +41727,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
41378
41727
  async function readFrom(path) {
41379
41728
  let raw;
41380
41729
  try {
41381
- raw = await readFile3(path, "utf8");
41730
+ raw = await readFile4(path, "utf8");
41382
41731
  } catch (err) {
41383
41732
  const code = err.code;
41384
41733
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -41432,7 +41781,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
41432
41781
 
41433
41782
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
41434
41783
  import { readFileSync as readFileSync22 } from "fs";
41435
- import { join as join34 } from "path";
41784
+ import { join as join35 } from "path";
41436
41785
 
41437
41786
  // ../../packages/plugin-runtime/src/attached/status.ts
41438
41787
  var REFUSAL_LINES = {
@@ -41509,12 +41858,12 @@ var StandaloneDataGateway = class {
41509
41858
  // reconciler drops the whole pass and recovers it idempotently on the next read.
41510
41859
  recordLlmCalls(inputs) {
41511
41860
  if (inputs.length === 0) return Promise.resolve();
41512
- return new Promise((resolve3, reject) => {
41861
+ return new Promise((resolve4, reject) => {
41513
41862
  try {
41514
41863
  this.db.auditEvents.runInTransaction(() => {
41515
41864
  for (const input2 of inputs) this.db.auditEvents.insertLlmCall(input2);
41516
41865
  });
41517
- resolve3();
41866
+ resolve4();
41518
41867
  } catch (err) {
41519
41868
  reject(err instanceof Error ? err : new Error(String(err)));
41520
41869
  }
@@ -41526,12 +41875,12 @@ var StandaloneDataGateway = class {
41526
41875
  // drops the whole pass and recovers it idempotently next time.
41527
41876
  recordToolCalls(inputs) {
41528
41877
  if (inputs.length === 0) return Promise.resolve();
41529
- return new Promise((resolve3, reject) => {
41878
+ return new Promise((resolve4, reject) => {
41530
41879
  try {
41531
41880
  this.db.auditEvents.runInTransaction(() => {
41532
41881
  for (const input2 of inputs) this.writeToolCall(input2);
41533
41882
  });
41534
- resolve3();
41883
+ resolve4();
41535
41884
  } catch (err) {
41536
41885
  reject(err instanceof Error ? err : new Error(String(err)));
41537
41886
  }
@@ -41928,9 +42277,9 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
41928
42277
  // src/history/transcripts.ts
41929
42278
  import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync6, readFileSync as readFileSync23, readSync as readSync2, statSync as statSync10 } from "fs";
41930
42279
  import { homedir as homedir3 } from "os";
41931
- import { join as join35 } from "path";
42280
+ import { join as join36 } from "path";
41932
42281
  function transcriptsDir(home) {
41933
- return join35(home ?? homedir3(), ".codex", "sessions");
42282
+ return join36(home ?? homedir3(), ".codex", "sessions");
41934
42283
  }
41935
42284
  var DAY_MS5 = 24 * 60 * 60 * 1e3;
41936
42285
 
@@ -41945,7 +42294,7 @@ import {
41945
42294
  statSync as statSync11,
41946
42295
  writeFileSync as writeFileSync10
41947
42296
  } from "fs";
41948
- import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join36, relative, resolve as resolve2 } from "path";
42297
+ import { basename as basename8, dirname as dirname8, isAbsolute as isAbsolute2, join as join37, relative, resolve as resolve3 } from "path";
41949
42298
  var REDACTED_PLACEHOLDER = "[REDACTED:SECRET]";
41950
42299
  function platformRedactionScope(home) {
41951
42300
  return { artifactRoots: [transcriptsDir(home)] };
@@ -41964,7 +42313,7 @@ function isWithinRoot(realTarget, root) {
41964
42313
  return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
41965
42314
  }
41966
42315
  function resolveRedactableArtifact(filePath, scope) {
41967
- const realTarget = realPathOrNull(resolve2(filePath));
42316
+ const realTarget = realPathOrNull(resolve3(filePath));
41968
42317
  if (realTarget === null) return null;
41969
42318
  return scope.artifactRoots.some((root) => isWithinRoot(realTarget, root)) ? realTarget : null;
41970
42319
  }
@@ -41981,8 +42330,8 @@ function isProcessAlive(pid) {
41981
42330
  }
41982
42331
  }
41983
42332
  function sweepStrandedTemps(realPath) {
41984
- const dir = dirname7(realPath);
41985
- const prefix = `${basename7(realPath)}.`;
42333
+ const dir = dirname8(realPath);
42334
+ const prefix = `${basename8(realPath)}.`;
41986
42335
  let names;
41987
42336
  try {
41988
42337
  names = readdirSync7(dir);
@@ -41996,7 +42345,7 @@ function sweepStrandedTemps(realPath) {
41996
42345
  const pid = Number(pidPart);
41997
42346
  if (pid !== process.pid && isProcessAlive(pid)) continue;
41998
42347
  try {
41999
- const stranded = join36(dir, name);
42348
+ const stranded = join37(dir, name);
42000
42349
  if (!lstatSync4(stranded).isFile()) continue;
42001
42350
  rmSync8(stranded, { force: true });
42002
42351
  } catch {