@akasecurity/ai-tc-codex 0.9.14 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,9 +32,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
  mod
33
33
  ));
34
34
 
35
- // ../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js
35
+ // ../../node_modules/.pnpm/ignore@7.0.10/node_modules/ignore/index.js
36
36
  var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js"(exports, module) {
37
+ "../../node_modules/.pnpm/ignore@7.0.10/node_modules/ignore/index.js"(exports, module) {
38
38
  "use strict";
39
39
  function makeArray(subject) {
40
40
  return Array.isArray(subject) ? subject : [subject];
@@ -429,6 +429,13 @@ var require_ignore = __commonJS({
429
429
  }
430
430
  };
431
431
  var WILDCARD = "[^\\/]*";
432
+ var separatorAfter = (run, at) => {
433
+ let separator = EMPTY;
434
+ for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
435
+ separator += run[index].single;
436
+ }
437
+ return separator;
438
+ };
432
439
  var pinWildcards = (source) => {
433
440
  if (source.indexOf(WILDCARD) < 0) {
434
441
  return source;
@@ -498,7 +505,7 @@ var require_ignore = __commonJS({
498
505
  out += token.single;
499
506
  return;
500
507
  }
501
- out += at === lastWildcard ? WILDCARD : `(?:(?!${run[at + 1].single})[^\\/])*`;
508
+ out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
502
509
  });
503
510
  run = [];
504
511
  };
@@ -675,13 +682,13 @@ var require_ignore = __commonJS({
675
682
  const rules = this._rules;
676
683
  const { length } = rules;
677
684
  const shortcut = this._basenameCount * 2 >= length;
678
- const basename7 = shortcut ? basenameOf(path) : path;
685
+ const basename8 = shortcut ? basenameOf(path) : path;
679
686
  for (let index = 0; index < length; index++) {
680
687
  const rule = rules[index];
681
688
  const { negative } = rule;
682
689
  const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
683
690
  if (!skip && rule[mode].test(
684
- shortcut && rule._basenameOnly ? basename7 : path
691
+ shortcut && rule._basenameOnly ? basename8 : path
685
692
  )) {
686
693
  ignored = !negative;
687
694
  unignored = negative;
@@ -1005,6 +1012,10 @@ var SQLITE_MIGRATIONS = [
1005
1012
  {
1006
1013
  tag: "0035_share_destination_provider_id",
1007
1014
  sql: "ALTER TABLE `share_destination` ADD `provider_id` text;"
1015
+ },
1016
+ {
1017
+ tag: "0036_secret_vault_identity_fingerprint",
1018
+ 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"
1008
1019
  }
1009
1020
  ];
1010
1021
 
@@ -1014,6 +1025,12 @@ var HOUR_MS = 60 * MINUTE_MS;
1014
1025
  var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1015
1026
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1016
1027
 
1028
+ // ../../packages/schema/src/invisible-padding.ts
1029
+ var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
1030
+ function stripInvisiblePadding(text) {
1031
+ return text.replace(INVISIBLE_PADDING, "");
1032
+ }
1033
+
1017
1034
  // ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
1018
1035
  var external_exports = {};
1019
1036
  __export(external_exports, {
@@ -6040,7 +6057,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6040
6057
  var NONE = 0;
6041
6058
  var ASSUMED = 1;
6042
6059
  var PROVEN = 2;
6043
- function isRecursive(inst, stack, resolve2) {
6060
+ function isRecursive(inst, stack, resolve3) {
6044
6061
  const cached2 = recursive.get(inst);
6045
6062
  if (cached2 !== void 0)
6046
6063
  return cached2 ? PROVEN : NONE;
@@ -6050,7 +6067,7 @@ function isRecursive(inst, stack, resolve2) {
6050
6067
  let result = NONE;
6051
6068
  const check2 = (child) => {
6052
6069
  if (result !== PROVEN && child?._zod) {
6053
- const answer = isRecursive(child, stack, resolve2);
6070
+ const answer = isRecursive(child, stack, resolve3);
6054
6071
  if (answer > result)
6055
6072
  result = answer;
6056
6073
  }
@@ -6061,7 +6078,7 @@ function isRecursive(inst, stack, resolve2) {
6061
6078
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6062
6079
  if (spread && !desc.enumerable)
6063
6080
  continue;
6064
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
6081
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6065
6082
  if (child > answer)
6066
6083
  answer = child;
6067
6084
  }
@@ -6125,7 +6142,7 @@ function isRecursive(inst, stack, resolve2) {
6125
6142
  break;
6126
6143
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6127
6144
  case "lazy": {
6128
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
6145
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6129
6146
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6130
6147
  break;
6131
6148
  }
@@ -23409,7 +23426,29 @@ var StorePosturePlugin = external_exports.object({
23409
23426
  */
23410
23427
  policyBundleVersion: external_exports.string().max(200).nullable(),
23411
23428
  /** Epoch millis, on the CLIENT clock, of that fetch. */
23412
- policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
23429
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
23430
+ /**
23431
+ * The newest version the host's own install record holds for this plugin —
23432
+ * what is on disk. After an update it leads `version` (the running copy) by
23433
+ * one launch. Null when no usable version can be read: no install record
23434
+ * (a plugin run from a checkout), no entry with a valid version, or every
23435
+ * such entry names an `installPath` that no longer exists; OPTIONAL, not
23436
+ * required, so a build that predates the member keeps getting its 200.
23437
+ * Bounded like `version`.
23438
+ */
23439
+ installedVersion: external_exports.string().max(64).nullable().optional(),
23440
+ /**
23441
+ * The local-store schema version this running build migrates a store to:
23442
+ * the number of store migrations it carries, the count it stamps into
23443
+ * `PRAGMA user_version`. A snapshot whose `schemaVersion` is above it
23444
+ * usually describes a store a newer build migrated. It is a hint, not a
23445
+ * verdict: the stamp is write-only, so a store whose count ran past this
23446
+ * build's while this build knows every migration in its ledger reads above
23447
+ * it too, which is why describeStoreSkew decides skew on ledger tags and
23448
+ * never on the count. OPTIONAL for the same reason as `installedVersion`;
23449
+ * bounded like `schemaVersion`.
23450
+ */
23451
+ buildSchemaVersion: external_exports.number().int().min(0).max(MAX_INT4).optional()
23413
23452
  }).meta({ id: "StorePosturePlugin" });
23414
23453
  var StorePostureSnapshot = external_exports.object({
23415
23454
  deviceId: external_exports.guid(),
@@ -25052,10 +25091,15 @@ var ParsedPointer = external_exports.object({
25052
25091
  });
25053
25092
  var VaultEntry = external_exports.object({
25054
25093
  pointerId: external_exports.string(),
25055
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
25056
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
25057
- // independently of the vault encryption key below.
25094
+ // The keyed HMAC of the EXACT raw bytes under `exception.key`, and the epoch it
25095
+ // was derived under. The vault's own dedupe key: a value and its invisibly
25096
+ // padded twin are two rows. It rotates independently of the vault encryption
25097
+ // key below. Never matched against an exception or grant.
25058
25098
  valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25099
+ // The same HMAC over the raw with invisible padding removed: the identity a
25100
+ // reveal-to-model grant and every exception match on. Shared by a value and
25101
+ // its padded twin.
25102
+ valueIdentityFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25059
25103
  fingerprintKeyVersion: external_exports.number().int().positive(),
25060
25104
  // The vault-key epoch this row's ciphertext was sealed under.
25061
25105
  keyVersion: external_exports.number().int().positive(),
@@ -25628,10 +25672,18 @@ var SeveritySummaryItem = external_exports.object({
25628
25672
  count: external_exports.number().int().nonnegative(),
25629
25673
  // Resolution-aware breakdown (optional, additive). Populated once findings
25630
25674
  // carry lifecycle state: `caught` = handled in-flight (enforced); `openAtRest`
25631
- // = still open with no in-flight enforcement (needs remediation). Absent on the
25632
- // legacy count-only response until the resolution feature lands.
25675
+ // = still open with no in-flight enforcement (needs remediation); `dismissed`
25676
+ // = closed by a human judgement rather than a fix — visible, but not counted as
25677
+ // needing remediation. The three are disjoint. Absent on the legacy count-only
25678
+ // response until the resolution feature lands.
25633
25679
  caught: external_exports.number().int().nonnegative().optional(),
25634
- openAtRest: external_exports.number().int().nonnegative().optional()
25680
+ openAtRest: external_exports.number().int().nonnegative().optional(),
25681
+ dismissed: external_exports.number().int().nonnegative().optional(),
25682
+ // The two halves of `caught`, for a reader that wants them apart: `handled` =
25683
+ // in-flight findings an enforcement action already contained; `resolved` =
25684
+ // at-rest findings closed out by fixing them. `handled + resolved === caught`.
25685
+ handled: external_exports.number().int().nonnegative().optional(),
25686
+ resolved: external_exports.number().int().nonnegative().optional()
25635
25687
  }).meta({ id: "SeveritySummaryItem" });
25636
25688
  var SeveritySummaryResponse = external_exports.object({
25637
25689
  // Sum of bySeverity[].count.
@@ -25639,6 +25691,9 @@ var SeveritySummaryResponse = external_exports.object({
25639
25691
  // Findings still open at rest (sum of bySeverity[].openAtRest). Optional and
25640
25692
  // additive — absent on the legacy response until the resolution feature lands.
25641
25693
  needsRemediation: external_exports.number().int().nonnegative().optional(),
25694
+ // Findings a user dismissed (sum of bySeverity[].dismissed). Excluded from
25695
+ // needsRemediation, and kept visible here so an accepted risk is not erased.
25696
+ dismissed: external_exports.number().int().nonnegative().optional(),
25642
25697
  // All four severity levels are always present (count may be 0).
25643
25698
  bySeverity: external_exports.array(SeveritySummaryItem)
25644
25699
  }).meta({ id: "SeveritySummaryResponse" });
@@ -26256,11 +26311,11 @@ function repairOrRefuseMode(file2) {
26256
26311
  const link = lstatSync2(file2, { throwIfNoEntry: false });
26257
26312
  if (link === void 0) return "absent";
26258
26313
  if (link.isSymbolicLink()) return "untrusted";
26259
- const stat = statSync(file2, { throwIfNoEntry: false });
26260
- if (stat === void 0) return "absent";
26314
+ const stat2 = statSync(file2, { throwIfNoEntry: false });
26315
+ if (stat2 === void 0) return "absent";
26261
26316
  const uid = process.getuid?.();
26262
- if (uid !== void 0 && stat.uid !== uid) return "untrusted";
26263
- if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
26317
+ if (uid !== void 0 && stat2.uid !== uid) return "untrusted";
26318
+ if (process.platform !== "win32" && (stat2.mode & 511) !== DATA_FILE_MODE) {
26264
26319
  try {
26265
26320
  chmodSync2(file2, DATA_FILE_MODE);
26266
26321
  } catch {
@@ -26272,9 +26327,9 @@ function repairOrRefuseMode(file2) {
26272
26327
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26273
26328
  const file2 = controlPlaneCredentialPath(settingsDir2);
26274
26329
  let raw;
26275
- const gate = repairOrRefuseMode(file2);
26276
- if (gate === "absent") return { usable: false, reason: "absent" };
26277
- if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
26330
+ const gate2 = repairOrRefuseMode(file2);
26331
+ if (gate2 === "absent") return { usable: false, reason: "absent" };
26332
+ if (gate2 === "untrusted") return { usable: false, reason: "untrusted-file" };
26278
26333
  try {
26279
26334
  raw = readFileSync(file2, "utf8");
26280
26335
  } catch (err) {
@@ -32419,7 +32474,10 @@ var SqliteResolutionsRepository = class {
32419
32474
  * Insert many dispositions as ONE transaction — all of them or none.
32420
32475
  *
32421
32476
  * A dashboard dismissal closes every open finding of a rule, which is one
32422
- * write per key; run loose, a fault partway leaves half a rule closed with
32477
+ * write per key. It reaches this through
32478
+ * `LocalDatabase.dismissOpenFindingsForRule`, which calls it inside the
32479
+ * transaction that selected the keys, so there it runs as a SAVEPOINT of
32480
+ * that transaction. Run loose, a fault partway leaves half a rule closed with
32423
32481
  * nothing recording that the other half was meant to be. The caller then has
32424
32482
  * no way to tell a partial run from a complete one, because the card it
32425
32483
  * refreshes into just shows a smaller number either way.
@@ -32639,6 +32697,7 @@ function toSighting(row) {
32639
32697
  var SELECT_COLUMNS = `
32640
32698
  pointer_id AS pointerId,
32641
32699
  value_fingerprint AS valueFingerprint,
32700
+ value_identity_fingerprint AS valueIdentityFingerprint,
32642
32701
  fingerprint_key_version AS fingerprintKeyVersion,
32643
32702
  key_version AS keyVersion,
32644
32703
  format_version AS formatVersion,
@@ -32663,13 +32722,13 @@ var SqliteSecretVaultRepository = class {
32663
32722
  this.db = db;
32664
32723
  this.insertStmt = db.prepare(
32665
32724
  `INSERT INTO secret_vault (
32666
- pointer_id, value_fingerprint, fingerprint_key_version, key_version,
32667
- format_version, category, rule_id, masked_match, provider,
32725
+ pointer_id, value_fingerprint, value_identity_fingerprint,
32726
+ fingerprint_key_version, key_version, format_version, category, rule_id, masked_match, provider,
32668
32727
  ciphertext, nonce, auth_tag,
32669
32728
  user_authorized, occurrence_count, first_seen, last_seen
32670
32729
  ) VALUES (
32671
- :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
32672
- :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32730
+ :pointerId, :valueFingerprint, :valueIdentityFingerprint,
32731
+ :fingerprintKeyVersion, :keyVersion, :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32673
32732
  :ciphertext, :nonce, :authTag,
32674
32733
  :userAuthorized, 1, :now, :now
32675
32734
  )`
@@ -32694,7 +32753,13 @@ var SqliteSecretVaultRepository = class {
32694
32753
  );
32695
32754
  this.refreshFingerprintStmt = db.prepare(
32696
32755
  `UPDATE secret_vault
32697
- SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
32756
+ SET value_fingerprint = :valueFingerprint,
32757
+ value_identity_fingerprint = :valueIdentityFingerprint,
32758
+ fingerprint_key_version = :fingerprintKeyVersion
32759
+ WHERE pointer_id = :pointerId`
32760
+ );
32761
+ this.setIdentityStmt = db.prepare(
32762
+ `UPDATE secret_vault SET value_identity_fingerprint = :valueIdentityFingerprint
32698
32763
  WHERE pointer_id = :pointerId`
32699
32764
  );
32700
32765
  this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
@@ -32711,6 +32776,7 @@ var SqliteSecretVaultRepository = class {
32711
32776
  listStmt;
32712
32777
  replaceCiphertextStmt;
32713
32778
  refreshFingerprintStmt;
32779
+ setIdentityStmt;
32714
32780
  deleteByPointerStmt;
32715
32781
  derefStmt;
32716
32782
  /**
@@ -32741,6 +32807,7 @@ var SqliteSecretVaultRepository = class {
32741
32807
  bindParams({
32742
32808
  pointerId: input2.pointerId,
32743
32809
  valueFingerprint: input2.valueFingerprint,
32810
+ valueIdentityFingerprint: input2.valueIdentityFingerprint,
32744
32811
  fingerprintKeyVersion: input2.fingerprintKeyVersion,
32745
32812
  keyVersion: input2.keyVersion,
32746
32813
  formatVersion: input2.formatVersion ?? POINTER_FORMAT_VERSION,
@@ -32802,7 +32869,15 @@ var SqliteSecretVaultRepository = class {
32802
32869
  replaceCiphertext(pointerId, next) {
32803
32870
  this.replaceCiphertextStmt.run({ pointerId, ...next });
32804
32871
  }
32805
- /** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
32872
+ /**
32873
+ * Correct an entry's identity fingerprint in place, leaving its exact
32874
+ * fingerprint and key epoch alone. For a row whose identity column still holds
32875
+ * the exact value copied in by the migration that added it.
32876
+ */
32877
+ setIdentityFingerprint(pointerId, valueIdentityFingerprint) {
32878
+ this.setIdentityStmt.run({ pointerId, valueIdentityFingerprint });
32879
+ }
32880
+ /** Re-derive an entry's fingerprints under a new fingerprint-key epoch. */
32806
32881
  refreshFingerprint(pointerId, next) {
32807
32882
  this.refreshFingerprintStmt.run({ pointerId, ...next });
32808
32883
  }
@@ -32933,7 +33008,7 @@ var SqliteSecretVaultRepository = class {
32933
33008
  `SELECT ${INVENTORY_COLUMNS},
32934
33009
  (SELECT e.id FROM exceptions e
32935
33010
  WHERE e.rule_id = v.rule_id
32936
- AND e.value_fingerprint = v.value_fingerprint
33011
+ AND e.value_fingerprint = v.value_identity_fingerprint
32937
33012
  AND e.key_version = v.fingerprint_key_version
32938
33013
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32939
33014
  LIMIT 1) AS grant_id
@@ -32976,7 +33051,7 @@ var SqliteSecretVaultRepository = class {
32976
33051
  `SELECT ${INVENTORY_COLUMNS},
32977
33052
  (SELECT e.id FROM exceptions e
32978
33053
  WHERE e.rule_id = v.rule_id
32979
- AND e.value_fingerprint = v.value_fingerprint
33054
+ AND e.value_fingerprint = v.value_identity_fingerprint
32980
33055
  AND e.key_version = v.fingerprint_key_version
32981
33056
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32982
33057
  LIMIT 1) AS grant_id
@@ -33080,6 +33155,18 @@ var OPEN_AT_REST_FINDINGS_SQL = `FROM inspection_findings f
33080
33155
  OR latest.status IS NULL
33081
33156
  OR latest.status NOT IN ('resolved', 'dismissed')
33082
33157
  )`;
33158
+ function selectOpenFindingKeysForRule(db, ruleId) {
33159
+ const rows = allRows(
33160
+ db.prepare(
33161
+ `SELECT DISTINCT f.finding_key AS finding_key
33162
+ ${OPEN_AT_REST_FINDINGS_SQL}
33163
+ AND d.rule_id = :ruleId
33164
+ AND f.finding_key IS NOT NULL`
33165
+ ),
33166
+ { ruleId }
33167
+ );
33168
+ return rows.map((r) => r.finding_key);
33169
+ }
33083
33170
  var SEVERITIES = ["critical", "high", "medium", "low"];
33084
33171
  var ACTION_TO_KIND = {
33085
33172
  block: "blocked",
@@ -33136,16 +33223,16 @@ var SqliteSecurityRepository = class {
33136
33223
  // findings are caught only once their latest disposition is resolved,
33137
33224
  // otherwise they are open-at-rest.
33138
33225
  //
33139
- // NOTE for future manual-resolution writers: only latest status
33140
- // 'resolved' counts as caught above. When acknowledged/dismissed/
33141
- // false-positive manual dispositions land, this must keep filtering by
33142
- // status/method — 'acknowledged' is accepted risk, not a fix, and must NOT
33143
- // be bucketed as caught alongside 'resolved'.
33226
+ // Only latest status 'resolved' counts as caught above. 'dismissed' is its
33227
+ // own bucket: a judgement rather than a fix, so it is neither caught nor
33228
+ // needing remediation, and stays countable. A further manual disposition
33229
+ // (acknowledged, false-positive) must be placed deliberately — 'acknowledged'
33230
+ // is accepted risk, not a fix, and must NOT be bucketed as caught.
33144
33231
  //
33145
33232
  // Legacy at-rest findings from pre-branch scans carry finding_key = NULL —
33146
33233
  // the resolution lifecycle is keyed by finding_key, so it can never attach a
33147
33234
  // disposition to (or clear) one of these on re-scan. They are excluded from
33148
- // both caught and openAtRest (untracked, not "needs remediation forever"),
33235
+ // all three buckets (untracked, not "needs remediation forever"),
33149
33236
  // but still counted in total/count below — this keeps this predicate
33150
33237
  // consistent with SqliteResolutionsRepository.openAtRestKeysForPath, which
33151
33238
  // already filters `finding_key IS NOT NULL`.
@@ -33168,12 +33255,25 @@ var SqliteSecurityRepository = class {
33168
33255
  WHEN latest.status = 'resolved' THEN 1
33169
33256
  ELSE 0
33170
33257
  END) AS caught,
33258
+ SUM(CASE WHEN e.event_type != 'code_change' THEN 1 ELSE 0 END) AS handled,
33171
33259
  SUM(CASE
33172
33260
  WHEN e.event_type = 'code_change'
33173
33261
  AND f.finding_key IS NOT NULL
33174
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
33262
+ AND latest.status = 'resolved' THEN 1
33175
33263
  ELSE 0
33176
- END) AS open_at_rest
33264
+ END) AS resolved,
33265
+ SUM(CASE
33266
+ WHEN e.event_type = 'code_change'
33267
+ AND f.finding_key IS NOT NULL
33268
+ AND (latest.status IS NULL
33269
+ OR latest.status NOT IN ('resolved', 'dismissed')) THEN 1
33270
+ ELSE 0
33271
+ END) AS open_at_rest,
33272
+ SUM(CASE
33273
+ WHEN e.event_type = 'code_change'
33274
+ AND latest.status = 'dismissed' THEN 1
33275
+ ELSE 0
33276
+ END) AS dismissed
33177
33277
  FROM inspection_findings f
33178
33278
  JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
33179
33279
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -33188,11 +33288,15 @@ var SqliteSecurityRepository = class {
33188
33288
  severity,
33189
33289
  count: byRow.get(severity)?.count ?? 0,
33190
33290
  caught: byRow.get(severity)?.caught ?? 0,
33191
- openAtRest: byRow.get(severity)?.open_at_rest ?? 0
33291
+ handled: byRow.get(severity)?.handled ?? 0,
33292
+ resolved: byRow.get(severity)?.resolved ?? 0,
33293
+ openAtRest: byRow.get(severity)?.open_at_rest ?? 0,
33294
+ dismissed: byRow.get(severity)?.dismissed ?? 0
33192
33295
  }));
33193
33296
  const total = bySeverity.reduce((sum, s) => sum + s.count, 0);
33194
33297
  const needsRemediation = bySeverity.reduce((sum, s) => sum + s.openAtRest, 0);
33195
- return Promise.resolve({ total, needsRemediation, bySeverity });
33298
+ const dismissed = bySeverity.reduce((sum, s) => sum + s.dismissed, 0);
33299
+ return Promise.resolve({ total, needsRemediation, dismissed, bySeverity });
33196
33300
  }
33197
33301
  // Range is echoed but does not change the result today — coverage is a constant
33198
33302
  // business fact (see SCAN_COVERAGE), not a measured per-window metric. Order
@@ -33509,10 +33613,10 @@ var SqliteSecurityRepository = class {
33509
33613
  * machine, and the second reported "no recommendations" over live exposure.
33510
33614
  *
33511
33615
  * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
33512
- * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
33513
- * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
33514
- * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
33515
- * The two answer different questions and only this one has to match a link.
33616
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. It
33617
+ * differs from `severitySummary`'s `openAtRest` only in including untracked
33618
+ * legacy rows, which that bucket leaves out; dismissed is excluded from both.
33619
+ * Only this one has to match a link.
33516
33620
  *
33517
33621
  * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
33518
33622
  * whole-store scope costs a grouped scan rather than a row per finding.
@@ -33540,6 +33644,8 @@ var SqliteSecurityRepository = class {
33540
33644
  /**
33541
33645
  * The distinct `finding_key`s behind ONE rule's {@link recommendationInputs}
33542
33646
  * tally — what a dashboard dismissal of that row writes a disposition for.
33647
+ * The dismissal itself does not call this: it reads the same set through
33648
+ * {@link selectOpenFindingKeysForRule}, inside its own write transaction.
33543
33649
  *
33544
33650
  * It shares {@link OPEN_AT_REST_FINDINGS_SQL} with the count rather than
33545
33651
  * restating the predicate, because a dismissal has to act on exactly the set
@@ -33556,16 +33662,7 @@ var SqliteSecurityRepository = class {
33556
33662
  * this set SMALLER than the tally, never larger.
33557
33663
  */
33558
33664
  openFindingKeysForRule(ruleId) {
33559
- const rows = allRows(
33560
- this.db.prepare(
33561
- `SELECT DISTINCT f.finding_key AS finding_key
33562
- ${OPEN_AT_REST_FINDINGS_SQL}
33563
- AND d.rule_id = :ruleId
33564
- AND f.finding_key IS NOT NULL`
33565
- ),
33566
- { ruleId }
33567
- );
33568
- return Promise.resolve(rows.map((r) => r.finding_key));
33665
+ return Promise.resolve(selectOpenFindingKeysForRule(this.db, ruleId));
33569
33666
  }
33570
33667
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
33571
33668
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
@@ -34611,6 +34708,31 @@ function openLocalDatabase(dir, options = {}) {
34611
34708
  );
34612
34709
  });
34613
34710
  }
34711
+ function dismissOpenFindingsForRule(ruleId, disposition) {
34712
+ let dismissed = 0;
34713
+ withTransaction(
34714
+ db,
34715
+ () => {
34716
+ const keys = selectOpenFindingKeysForRule(db, ruleId);
34717
+ resolutions.insertResolutions(
34718
+ keys.map((findingKey) => ({
34719
+ findingKey,
34720
+ status: "dismissed",
34721
+ method: disposition.method,
34722
+ resolvedAt: disposition.resolvedAt,
34723
+ evidence: disposition.evidence
34724
+ }))
34725
+ );
34726
+ dismissed = keys.length;
34727
+ },
34728
+ // IMMEDIATE takes the write lock at BEGIN, before the select, which is
34729
+ // what keeps a concurrent resolve out of the gap. It also makes waiting
34730
+ // on a busy writer an ordinary busy_timeout wait rather than a
34731
+ // read-to-write upgrade SQLite refuses to retry.
34732
+ "IMMEDIATE"
34733
+ );
34734
+ return dismissed;
34735
+ }
34614
34736
  function recordCapture(event, detected) {
34615
34737
  failOpenTransaction(db, () => {
34616
34738
  const sessionId = event.metadata?.sessionId;
@@ -34794,6 +34916,7 @@ function openLocalDatabase(dir, options = {}) {
34794
34916
  inspectionDefinitions,
34795
34917
  inspectionFindings,
34796
34918
  recordCapture,
34919
+ dismissOpenFindingsForRule,
34797
34920
  markCaptureDelivered,
34798
34921
  markCaptureOwed,
34799
34922
  markAuditEventsDelivered,
@@ -35010,6 +35133,9 @@ function loadOrCreateFingerprintKey(dataDir2) {
35010
35133
  });
35011
35134
  }
35012
35135
  function fingerprintValue(key, raw) {
35136
+ return exactFingerprintValue(key, stripInvisiblePadding(raw));
35137
+ }
35138
+ function exactFingerprintValue(key, raw) {
35013
35139
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
35014
35140
  }
35015
35141
 
@@ -35762,6 +35888,82 @@ function escapeRegExp2(value) {
35762
35888
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35763
35889
  }
35764
35890
 
35891
+ // ../../packages/detections/src/format-chars.ts
35892
+ var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
35893
+ var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
35894
+ function normalizeFormatChars(text) {
35895
+ if (!HAS_FORMAT_CHAR.test(text)) return void 0;
35896
+ const normalizedParts = [];
35897
+ const segments = [];
35898
+ let cursor = 0;
35899
+ let normLength = 0;
35900
+ for (const match of text.matchAll(FORMAT_CHAR_GLOBAL)) {
35901
+ const matchStart = match.index;
35902
+ if (matchStart > cursor) {
35903
+ const length = matchStart - cursor;
35904
+ normalizedParts.push(text.slice(cursor, matchStart));
35905
+ segments.push({ normStart: normLength, origStart: cursor, length });
35906
+ normLength += length;
35907
+ }
35908
+ cursor = matchStart + match[0].length;
35909
+ }
35910
+ if (cursor < text.length) {
35911
+ const length = text.length - cursor;
35912
+ normalizedParts.push(text.slice(cursor));
35913
+ segments.push({ normStart: normLength, origStart: cursor, length });
35914
+ }
35915
+ return { normalized: normalizedParts.join(""), segments };
35916
+ }
35917
+ function segmentAt(segments, normPos) {
35918
+ let lo = 0;
35919
+ let hi = segments.length - 1;
35920
+ while (lo < hi) {
35921
+ const mid = lo + hi >> 1;
35922
+ const segment = segments[mid];
35923
+ if (segment !== void 0 && normPos >= segment.normStart + segment.length) {
35924
+ lo = mid + 1;
35925
+ } else {
35926
+ hi = mid;
35927
+ }
35928
+ }
35929
+ const found = segments[lo];
35930
+ if (found === void 0) {
35931
+ throw new Error(`normPos ${String(normPos)} has no covering segment`);
35932
+ }
35933
+ return found;
35934
+ }
35935
+ function mapSpanToOriginal(span, normalization) {
35936
+ const { segments } = normalization;
35937
+ const startSegment = segmentAt(segments, span.start);
35938
+ const start = startSegment.origStart + (span.start - startSegment.normStart);
35939
+ const endSegment = segmentAt(segments, span.end - 1);
35940
+ const end = endSegment.origStart + (span.end - 1 - endSegment.normStart) + 1;
35941
+ return { start, end };
35942
+ }
35943
+ function normalizedOffset(origPos, segments) {
35944
+ let lo = 0;
35945
+ let hi = segments.length;
35946
+ while (lo < hi) {
35947
+ const mid = lo + hi >> 1;
35948
+ const segment = segments[mid];
35949
+ if (segment !== void 0 && segment.origStart + segment.length <= origPos) {
35950
+ lo = mid + 1;
35951
+ } else {
35952
+ hi = mid;
35953
+ }
35954
+ }
35955
+ const found = segments[Math.min(lo, segments.length - 1)];
35956
+ if (found === void 0) return 0;
35957
+ return found.normStart + Math.min(Math.max(0, origPos - found.origStart), found.length);
35958
+ }
35959
+ function mapSpanToNormalized(span, normalization) {
35960
+ const { segments } = normalization;
35961
+ return {
35962
+ start: normalizedOffset(span.start, segments),
35963
+ end: normalizedOffset(span.end, segments)
35964
+ };
35965
+ }
35966
+
35765
35967
  // ../../packages/detections/src/regex-cache.ts
35766
35968
  var singles = /* @__PURE__ */ new WeakMap();
35767
35969
  var keywordLists = /* @__PURE__ */ new WeakMap();
@@ -35923,29 +36125,35 @@ function registerPack(pack) {
35923
36125
  function getLoadedRules() {
35924
36126
  return [...packs.values()].flatMap((p) => p.rules);
35925
36127
  }
35926
- function isCorroborated(candidate, candidates, text) {
36128
+ function spansOverlap(a, b) {
36129
+ return a.start < b.end && a.end > b.start;
36130
+ }
36131
+ function isCorroborated(candidate, candidates, text, normalization) {
35927
36132
  const req = candidate.rule.requiresNearby;
35928
36133
  if (!req) return true;
35929
36134
  const halfWindow = req.windowChars;
35930
- const { start, end } = candidate.match.span;
35931
- const winStart = start - halfWindow;
35932
- const winEnd = end + halfWindow;
36135
+ const ns = candidate.normSpan;
36136
+ const winStart = ns.start - halfWindow;
36137
+ const winEnd = ns.end + halfWindow;
35933
36138
  const categories = req.categories;
35934
36139
  const ruleIds = req.ruleIds;
35935
36140
  if (categories?.length || ruleIds?.length) {
35936
36141
  for (const other of candidates) {
35937
36142
  if (other === candidate) continue;
35938
- const os = other.match.span;
35939
- if (os.end < winStart || os.start > winEnd) continue;
35940
- if (other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category)) {
35941
- return true;
36143
+ if (other.normSpan.end < winStart || other.normSpan.start > winEnd) continue;
36144
+ const relevant = other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category) === true || ruleIds?.includes(other.match.ruleId) === true;
36145
+ if (!relevant) continue;
36146
+ if (other.match.ruleId === candidate.match.ruleId && spansOverlap(other.match.span, candidate.match.span)) {
36147
+ continue;
35942
36148
  }
35943
- if (ruleIds?.includes(other.match.ruleId)) return true;
36149
+ return true;
35944
36150
  }
35945
36151
  }
35946
36152
  const labels = req.labels;
35947
36153
  if (labels && labels.length > 0) {
35948
- const haystack = text.slice(Math.max(0, winStart), winEnd);
36154
+ const { start, end } = candidate.match.span;
36155
+ const haystack = text.slice(Math.max(0, start - halfWindow), end + halfWindow);
36156
+ const normalizedHaystack = normalization === void 0 ? void 0 : normalization.normalized.slice(Math.max(0, winStart), winEnd);
35949
36157
  for (const re of memoizedRegExpList(
35950
36158
  "label",
35951
36159
  req,
@@ -35954,29 +36162,20 @@ function isCorroborated(candidate, candidates, text) {
35954
36162
  return trimmed.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed)}(?![A-Za-z0-9])`, "i");
35955
36163
  })
35956
36164
  )) {
35957
- if (re?.test(haystack)) return true;
36165
+ if (!re) continue;
36166
+ if (re.test(haystack)) return true;
36167
+ if (normalizedHaystack !== void 0 && re.test(normalizedHaystack)) return true;
35958
36168
  }
35959
36169
  }
35960
36170
  return false;
35961
36171
  }
35962
- function extensionOf(filePath) {
35963
- const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
35964
- const dot = base.lastIndexOf(".");
35965
- return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
35966
- }
35967
- function ruleApplies(rule, extension) {
35968
- if (!rule.appliesTo || extension === void 0) return true;
35969
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
35970
- }
35971
- function scan(text, rules, context) {
35972
- const ruleset = rules ?? getLoadedRules();
35973
- const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
36172
+ function buildCandidates(matchText, ruleset, extension) {
35974
36173
  const candidates = [];
35975
36174
  for (const rule of ruleset) {
35976
36175
  if (!ruleApplies(rule, extension)) continue;
35977
- const spans = MATCHERS[rule.matcher.type](text, rule);
36176
+ const spans = MATCHERS[rule.matcher.type](matchText, rule);
35978
36177
  for (const span of spans) {
35979
- const rawMatch = text.slice(span.start, span.end);
36178
+ const rawMatch = matchText.slice(span.start, span.end);
35980
36179
  if (!passesPostValidators(rule, rawMatch)) continue;
35981
36180
  candidates.push({
35982
36181
  rule,
@@ -35987,10 +36186,31 @@ function scan(text, rules, context) {
35987
36186
  span,
35988
36187
  rawMatch,
35989
36188
  confidence: 0.9
35990
- }
36189
+ },
36190
+ // In `matchText`'s own coordinates, which is the normalized text for
36191
+ // a normalized-pass candidate and so already right; an original-pass
36192
+ // candidate on the slow path is re-derived by withNormalizedSpan.
36193
+ normSpan: span
35991
36194
  });
35992
36195
  }
35993
36196
  }
36197
+ return candidates;
36198
+ }
36199
+ function mapCandidateToOriginal(candidate, normalization, text) {
36200
+ const span = mapSpanToOriginal(candidate.match.span, normalization);
36201
+ return {
36202
+ rule: candidate.rule,
36203
+ match: { ...candidate.match, span, rawMatch: text.slice(span.start, span.end) },
36204
+ // Deliberately NOT remapped: `normSpan` is the span the primitive match
36205
+ // was found at in the normalized text, which is exactly the coordinate
36206
+ // space windows are measured in. See the `Candidate` comment.
36207
+ normSpan: candidate.normSpan
36208
+ };
36209
+ }
36210
+ function withNormalizedSpan(candidate, normalization) {
36211
+ return { ...candidate, normSpan: mapSpanToNormalized(candidate.match.span, normalization) };
36212
+ }
36213
+ function gate(candidates, text, normalization) {
35994
36214
  const findings = [];
35995
36215
  for (const candidate of candidates) {
35996
36216
  const req = candidate.rule.requiresNearby;
@@ -35998,7 +36218,7 @@ function scan(text, rules, context) {
35998
36218
  findings.push(candidate.match);
35999
36219
  continue;
36000
36220
  }
36001
- if (!isCorroborated(candidate, candidates, text)) continue;
36221
+ if (!isCorroborated(candidate, candidates, text, normalization)) continue;
36002
36222
  const boost = req.confidenceBoost;
36003
36223
  findings.push(
36004
36224
  boost ? { ...candidate.match, confidence: Math.min(0.99, candidate.match.confidence + boost) } : candidate.match
@@ -36006,6 +36226,81 @@ function scan(text, rules, context) {
36006
36226
  }
36007
36227
  return findings;
36008
36228
  }
36229
+ function closeRegion(open3, text) {
36230
+ const span = { start: open3.start, end: open3.end };
36231
+ return {
36232
+ ruleId: open3.ruleId,
36233
+ category: open3.category,
36234
+ severity: open3.severity,
36235
+ span,
36236
+ rawMatch: text.slice(span.start, span.end),
36237
+ confidence: open3.confidence
36238
+ };
36239
+ }
36240
+ function mergeOverlappingSameRule(findings, text) {
36241
+ if (findings.length === 0) return findings;
36242
+ const groups = /* @__PURE__ */ new Map();
36243
+ const ruleOrder = [];
36244
+ for (const finding of findings) {
36245
+ const group = groups.get(finding.ruleId);
36246
+ if (group) {
36247
+ group.push(finding);
36248
+ } else {
36249
+ groups.set(finding.ruleId, [finding]);
36250
+ ruleOrder.push(finding.ruleId);
36251
+ }
36252
+ }
36253
+ const merged = [];
36254
+ for (const ruleId of ruleOrder) {
36255
+ const group = groups.get(ruleId) ?? [];
36256
+ const sorted = [...group].sort(
36257
+ (a, b) => a.span.start - b.span.start || a.span.end - b.span.end
36258
+ );
36259
+ let open3;
36260
+ for (const finding of sorted) {
36261
+ if (open3 && finding.span.start < open3.end) {
36262
+ open3.end = Math.max(open3.end, finding.span.end);
36263
+ open3.confidence = Math.max(open3.confidence, finding.confidence);
36264
+ continue;
36265
+ }
36266
+ if (open3) merged.push(closeRegion(open3, text));
36267
+ open3 = {
36268
+ start: finding.span.start,
36269
+ end: finding.span.end,
36270
+ confidence: finding.confidence,
36271
+ ruleId: finding.ruleId,
36272
+ category: finding.category,
36273
+ severity: finding.severity
36274
+ };
36275
+ }
36276
+ if (open3) merged.push(closeRegion(open3, text));
36277
+ }
36278
+ return merged;
36279
+ }
36280
+ function extensionOf(filePath) {
36281
+ const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
36282
+ const dot = base.lastIndexOf(".");
36283
+ return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
36284
+ }
36285
+ function ruleApplies(rule, extension) {
36286
+ if (!rule.appliesTo || extension === void 0) return true;
36287
+ return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
36288
+ }
36289
+ function scan(text, rules, context) {
36290
+ const ruleset = rules ?? getLoadedRules();
36291
+ const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
36292
+ const normalization = normalizeFormatChars(text);
36293
+ const originalCandidates = buildCandidates(text, ruleset, extension);
36294
+ if (!normalization) return gate(originalCandidates, text, void 0);
36295
+ const pooledOriginal = originalCandidates.map(
36296
+ (candidate) => withNormalizedSpan(candidate, normalization)
36297
+ );
36298
+ const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
36299
+ (candidate) => mapCandidateToOriginal(candidate, normalization, text)
36300
+ );
36301
+ const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
36302
+ return mergeOverlappingSameRule(findings, text);
36303
+ }
36009
36304
  var SEVERITY_RANK2 = {
36010
36305
  critical: 3,
36011
36306
  high: 2,
@@ -38686,8 +38981,8 @@ function createIsolatedScanner(data, opts = {}) {
38686
38981
  }
38687
38982
  function enqueue(spec) {
38688
38983
  const next = chain.then(
38689
- () => new Promise((resolve2) => {
38690
- spec(resolve2);
38984
+ () => new Promise((resolve3) => {
38985
+ spec(resolve3);
38691
38986
  })
38692
38987
  );
38693
38988
  chain = next.then(
@@ -38698,7 +38993,7 @@ function createIsolatedScanner(data, opts = {}) {
38698
38993
  }
38699
38994
  return {
38700
38995
  scan(text, context, scanOpts) {
38701
- return enqueue((resolve2) => {
38996
+ return enqueue((resolve3) => {
38702
38997
  runOne(
38703
38998
  {
38704
38999
  budgetMs,
@@ -38711,23 +39006,23 @@ function createIsolatedScanner(data, opts = {}) {
38711
39006
  }),
38712
39007
  reply: (message) => {
38713
39008
  if (message.kind !== "result") return false;
38714
- resolve2({ status: "ok", findings: message.findings });
39009
+ resolve3({ status: "ok", findings: message.findings });
38715
39010
  return true;
38716
39011
  }
38717
39012
  },
38718
- resolve2
39013
+ resolve3
38719
39014
  );
38720
39015
  });
38721
39016
  },
38722
39017
  probe(rule) {
38723
- return enqueue((resolve2) => {
39018
+ return enqueue((resolve3) => {
38724
39019
  runOne(
38725
39020
  {
38726
39021
  budgetMs: probeBudgetMs,
38727
39022
  build: (id) => ({ kind: "probe", id, rule }),
38728
39023
  reply: (message) => {
38729
39024
  if (message.kind !== "probed") return false;
38730
- resolve2({
39025
+ resolve3({
38731
39026
  status: "ok",
38732
39027
  verdict: message.verdict,
38733
39028
  worstMs: message.worstMs,
@@ -38736,7 +39031,7 @@ function createIsolatedScanner(data, opts = {}) {
38736
39031
  return true;
38737
39032
  }
38738
39033
  },
38739
- resolve2
39034
+ resolve3
38740
39035
  );
38741
39036
  });
38742
39037
  },
@@ -39737,7 +40032,7 @@ async function send(options) {
39737
40032
  }
39738
40033
  }
39739
40034
  };
39740
- return new Promise((resolve2, reject) => {
40035
+ return new Promise((resolve3, reject) => {
39741
40036
  let settled = false;
39742
40037
  const fail = (reason, status) => {
39743
40038
  if (settled) return;
@@ -39763,7 +40058,7 @@ async function send(options) {
39763
40058
  res.on("end", () => {
39764
40059
  if (settled) return;
39765
40060
  settled = true;
39766
- resolve2({
40061
+ resolve3({
39767
40062
  status: res.statusCode ?? 0,
39768
40063
  headers: res.headers,
39769
40064
  body: Buffer.concat(chunks).toString("utf8")
@@ -40759,8 +41054,52 @@ import { spawn } from "child_process";
40759
41054
  import { fileURLToPath as fileURLToPath2 } from "url";
40760
41055
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
40761
41056
 
41057
+ // ../../packages/plugin-runtime/src/attached/install-record.ts
41058
+ import { readFile as readFile2, stat } from "fs/promises";
41059
+ import { basename as basename7, dirname as dirname7, join as join30, resolve as resolve2 } from "path";
41060
+ async function readInstalledVersion(installRoot) {
41061
+ try {
41062
+ const versionDir = resolve2(installRoot);
41063
+ const pluginDir = dirname7(versionDir);
41064
+ const marketplaceDir = dirname7(pluginDir);
41065
+ const cacheDir = dirname7(marketplaceDir);
41066
+ if (basename7(cacheDir) !== "cache") return null;
41067
+ const key = `${basename7(pluginDir)}@${basename7(marketplaceDir)}`;
41068
+ const record2 = JSON.parse(
41069
+ await readFile2(join30(dirname7(cacheDir), "installed_plugins.json"), "utf8")
41070
+ );
41071
+ const plugins = record2?.plugins;
41072
+ if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
41073
+ return null;
41074
+ }
41075
+ const entries = plugins[key];
41076
+ if (!Array.isArray(entries)) return null;
41077
+ let newest = null;
41078
+ for (const entry of entries) {
41079
+ const { version: version2, installPath } = entry ?? {};
41080
+ if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) continue;
41081
+ if (!StorePosturePlugin.shape.installedVersion.safeParse(version2).success) continue;
41082
+ if (newest !== null && compareBinaryVersions(version2, newest) <= 0) continue;
41083
+ if (typeof installPath === "string" && !await exists(installPath)) continue;
41084
+ newest = version2;
41085
+ }
41086
+ return newest;
41087
+ } catch {
41088
+ return null;
41089
+ }
41090
+ }
41091
+ async function exists(path) {
41092
+ try {
41093
+ await stat(path);
41094
+ return true;
41095
+ } catch {
41096
+ return false;
41097
+ }
41098
+ }
41099
+
40762
41100
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
40763
41101
  import { readFileSync as readFileSync19 } from "fs";
41102
+ var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
40764
41103
  var manifestBuildCache = /* @__PURE__ */ new Map();
40765
41104
  function readManifestBuild(manifestUrl, packageName) {
40766
41105
  const key = manifestUrl.href;
@@ -40778,6 +41117,7 @@ function readManifestBuild(manifestUrl, packageName) {
40778
41117
  }
40779
41118
  function createPluginBlock(build, policyStore) {
40780
41119
  return async () => {
41120
+ const installed = build.installRoot === void 0 ? void 0 : readInstalledVersionBounded(build.installRoot);
40781
41121
  const cached2 = await policyStore.read();
40782
41122
  const fetchedAtMs = cached2?.fetchedAtMs;
40783
41123
  const block = {
@@ -40785,16 +41125,25 @@ function createPluginBlock(build, policyStore) {
40785
41125
  version: build.version,
40786
41126
  ossVersion: build.ossVersion ?? null,
40787
41127
  policyBundleVersion: cached2 !== null && StorePosturePlugin.shape.policyBundleVersion.safeParse(cached2.bundle.version).success ? cached2.bundle.version : null,
40788
- policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null
41128
+ policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null,
41129
+ ...installed === void 0 ? {} : { installedVersion: await installed },
41130
+ buildSchemaVersion: SQLITE_MIGRATIONS.length
40789
41131
  };
40790
41132
  return StorePosturePlugin.safeParse(block).success ? block : void 0;
40791
41133
  };
40792
41134
  }
41135
+ async function readInstalledVersionBounded(installRoot) {
41136
+ try {
41137
+ return await withTimeout(readInstalledVersion(installRoot), INSTALL_RECORD_READ_TIMEOUT_MS);
41138
+ } catch {
41139
+ return null;
41140
+ }
41141
+ }
40793
41142
 
40794
41143
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40795
41144
  import { randomUUID as randomUUID16 } from "crypto";
40796
- import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
40797
- import { join as join30 } from "path";
41145
+ import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
41146
+ import { join as join31 } from "path";
40798
41147
 
40799
41148
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
40800
41149
  import { rename as rename2 } from "fs/promises";
@@ -40802,11 +41151,11 @@ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
40802
41151
  var IMMEDIATE_RETRIES = 8;
40803
41152
  var TIMED_RETRIES = 4;
40804
41153
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
40805
- var delay = (ms) => new Promise((resolve2) => {
40806
- setTimeout(resolve2, ms);
41154
+ var delay = (ms) => new Promise((resolve3) => {
41155
+ setTimeout(resolve3, ms);
40807
41156
  });
40808
- var yieldToLoop = () => new Promise((resolve2) => {
40809
- setImmediate(resolve2);
41157
+ var yieldToLoop = () => new Promise((resolve3) => {
41158
+ setImmediate(resolve3);
40810
41159
  });
40811
41160
  async function publishByRename(tmp, file2, move = rename2) {
40812
41161
  for (let attempt = 1; ; attempt += 1) {
@@ -40823,10 +41172,10 @@ async function publishByRename(tmp, file2, move = rename2) {
40823
41172
 
40824
41173
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40825
41174
  function createPolicyStore(dir = dataDir()) {
40826
- const file2 = join30(dir, "policy-cache.json");
41175
+ const file2 = join31(dir, "policy-cache.json");
40827
41176
  async function read() {
40828
41177
  try {
40829
- const raw = await readFile2(file2, "utf8");
41178
+ const raw = await readFile3(file2, "utf8");
40830
41179
  const parsed2 = JSON.parse(raw);
40831
41180
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
40832
41181
  const record2 = parsed2;
@@ -40848,7 +41197,7 @@ function createPolicyStore(dir = dataDir()) {
40848
41197
  }
40849
41198
  async function priorRecord() {
40850
41199
  try {
40851
- const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
41200
+ const parsed2 = JSON.parse(await readFile3(file2, "utf8"));
40852
41201
  return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
40853
41202
  } catch {
40854
41203
  return null;
@@ -40894,7 +41243,7 @@ function createPolicyStore(dir = dataDir()) {
40894
41243
 
40895
41244
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
40896
41245
  import { readFileSync as readFileSync20 } from "fs";
40897
- import { join as join31 } from "path";
41246
+ import { join as join32 } from "path";
40898
41247
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
40899
41248
  var OUTCOME_KEYS = {
40900
41249
  ok: true,
@@ -40908,7 +41257,7 @@ var OUTCOME_KEYS = {
40908
41257
  };
40909
41258
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
40910
41259
  function postureReportStatePath(dataDir2) {
40911
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41260
+ return join32(dataDir2, POSTURE_REPORT_STATE_FILENAME);
40912
41261
  }
40913
41262
  function writePostureReportState(dataDir2, state) {
40914
41263
  try {
@@ -41087,12 +41436,12 @@ function readStorePosture(dbPath2) {
41087
41436
 
41088
41437
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
41089
41438
  import { randomUUID as randomUUID17 } from "crypto";
41090
- import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
41091
- import { join as join32 } from "path";
41439
+ import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
41440
+ import { join as join33 } from "path";
41092
41441
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
41093
41442
  function createPostureStore(dir = settingsDir(), legacyDir) {
41094
- const file2 = join32(dir, "posture-state.json");
41095
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
41443
+ const file2 = join33(dir, "posture-state.json");
41444
+ const legacyFile = legacyDir === void 0 ? null : join33(legacyDir, "posture-state.json");
41096
41445
  async function persist(state) {
41097
41446
  await ensureDataDir(dir);
41098
41447
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -41107,7 +41456,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
41107
41456
  async function readFrom(path) {
41108
41457
  let raw;
41109
41458
  try {
41110
- raw = await readFile3(path, "utf8");
41459
+ raw = await readFile4(path, "utf8");
41111
41460
  } catch (err) {
41112
41461
  const code = err.code;
41113
41462
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -41161,7 +41510,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
41161
41510
 
41162
41511
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
41163
41512
  import { readFileSync as readFileSync21 } from "fs";
41164
- import { join as join33 } from "path";
41513
+ import { join as join34 } from "path";
41165
41514
 
41166
41515
  // ../../packages/plugin-runtime/src/attached/status.ts
41167
41516
  var REFUSAL_LINES = {
@@ -41238,12 +41587,12 @@ var StandaloneDataGateway = class {
41238
41587
  // reconciler drops the whole pass and recovers it idempotently on the next read.
41239
41588
  recordLlmCalls(inputs) {
41240
41589
  if (inputs.length === 0) return Promise.resolve();
41241
- return new Promise((resolve2, reject) => {
41590
+ return new Promise((resolve3, reject) => {
41242
41591
  try {
41243
41592
  this.db.auditEvents.runInTransaction(() => {
41244
41593
  for (const input2 of inputs) this.db.auditEvents.insertLlmCall(input2);
41245
41594
  });
41246
- resolve2();
41595
+ resolve3();
41247
41596
  } catch (err) {
41248
41597
  reject(err instanceof Error ? err : new Error(String(err)));
41249
41598
  }
@@ -41255,12 +41604,12 @@ var StandaloneDataGateway = class {
41255
41604
  // drops the whole pass and recovers it idempotently next time.
41256
41605
  recordToolCalls(inputs) {
41257
41606
  if (inputs.length === 0) return Promise.resolve();
41258
- return new Promise((resolve2, reject) => {
41607
+ return new Promise((resolve3, reject) => {
41259
41608
  try {
41260
41609
  this.db.auditEvents.runInTransaction(() => {
41261
41610
  for (const input2 of inputs) this.writeToolCall(input2);
41262
41611
  });
41263
- resolve2();
41612
+ resolve3();
41264
41613
  } catch (err) {
41265
41614
  reject(err instanceof Error ? err : new Error(String(err)));
41266
41615
  }
@@ -41657,9 +42006,9 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
41657
42006
  // src/history/transcripts.ts
41658
42007
  import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync22, readSync as readSync2, statSync as statSync10 } from "fs";
41659
42008
  import { homedir as homedir3 } from "os";
41660
- import { join as join34 } from "path";
42009
+ import { join as join35 } from "path";
41661
42010
  function transcriptsDir(home) {
41662
- return join34(home ?? homedir3(), ".codex", "sessions");
42011
+ return join35(home ?? homedir3(), ".codex", "sessions");
41663
42012
  }
41664
42013
  function isRecord(value) {
41665
42014
  return typeof value === "object" && value !== null;
@@ -41898,7 +42247,7 @@ function* walkJsonlFiles(dir, depth = 0) {
41898
42247
  return;
41899
42248
  }
41900
42249
  for (const entry of entries) {
41901
- const full = join34(dir, entry.name);
42250
+ const full = join35(dir, entry.name);
41902
42251
  if (entry.isDirectory()) {
41903
42252
  yield* walkJsonlFiles(full, depth + 1);
41904
42253
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -42035,7 +42384,7 @@ import {
42035
42384
  readSync as readSync3,
42036
42385
  writeFileSync as writeFileSync10
42037
42386
  } from "fs";
42038
- import { join as join35 } from "path";
42387
+ import { join as join36 } from "path";
42039
42388
 
42040
42389
  // src/history/usage.ts
42041
42390
  var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";
@@ -42356,9 +42705,9 @@ if (process.argv[1] && fileURLToPath5(import.meta.url) === process.argv[1]) {
42356
42705
  guard: { beforeMs: startedAt }
42357
42706
  });
42358
42707
  if (process.stdout.writableLength > 0) {
42359
- await new Promise((resolve2) => {
42708
+ await new Promise((resolve3) => {
42360
42709
  process.stdout.write("", () => {
42361
- resolve2();
42710
+ resolve3();
42362
42711
  });
42363
42712
  });
42364
42713
  }