@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;
@@ -1001,6 +1008,10 @@ var SQLITE_MIGRATIONS = [
1001
1008
  {
1002
1009
  tag: "0035_share_destination_provider_id",
1003
1010
  sql: "ALTER TABLE `share_destination` ADD `provider_id` text;"
1011
+ },
1012
+ {
1013
+ tag: "0036_secret_vault_identity_fingerprint",
1014
+ 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"
1004
1015
  }
1005
1016
  ];
1006
1017
 
@@ -6036,7 +6047,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6036
6047
  var NONE = 0;
6037
6048
  var ASSUMED = 1;
6038
6049
  var PROVEN = 2;
6039
- function isRecursive(inst, stack, resolve2) {
6050
+ function isRecursive(inst, stack, resolve3) {
6040
6051
  const cached2 = recursive.get(inst);
6041
6052
  if (cached2 !== void 0)
6042
6053
  return cached2 ? PROVEN : NONE;
@@ -6046,7 +6057,7 @@ function isRecursive(inst, stack, resolve2) {
6046
6057
  let result = NONE;
6047
6058
  const check2 = (child) => {
6048
6059
  if (result !== PROVEN && child?._zod) {
6049
- const answer = isRecursive(child, stack, resolve2);
6060
+ const answer = isRecursive(child, stack, resolve3);
6050
6061
  if (answer > result)
6051
6062
  result = answer;
6052
6063
  }
@@ -6057,7 +6068,7 @@ function isRecursive(inst, stack, resolve2) {
6057
6068
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6058
6069
  if (spread && !desc.enumerable)
6059
6070
  continue;
6060
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
6071
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6061
6072
  if (child > answer)
6062
6073
  answer = child;
6063
6074
  }
@@ -6121,7 +6132,7 @@ function isRecursive(inst, stack, resolve2) {
6121
6132
  break;
6122
6133
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6123
6134
  case "lazy": {
6124
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
6135
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6125
6136
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6126
6137
  break;
6127
6138
  }
@@ -23519,7 +23530,29 @@ var StorePosturePlugin = external_exports.object({
23519
23530
  */
23520
23531
  policyBundleVersion: external_exports.string().max(200).nullable(),
23521
23532
  /** Epoch millis, on the CLIENT clock, of that fetch. */
23522
- policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
23533
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
23534
+ /**
23535
+ * The newest version the host's own install record holds for this plugin —
23536
+ * what is on disk. After an update it leads `version` (the running copy) by
23537
+ * one launch. Null when no usable version can be read: no install record
23538
+ * (a plugin run from a checkout), no entry with a valid version, or every
23539
+ * such entry names an `installPath` that no longer exists; OPTIONAL, not
23540
+ * required, so a build that predates the member keeps getting its 200.
23541
+ * Bounded like `version`.
23542
+ */
23543
+ installedVersion: external_exports.string().max(64).nullable().optional(),
23544
+ /**
23545
+ * The local-store schema version this running build migrates a store to:
23546
+ * the number of store migrations it carries, the count it stamps into
23547
+ * `PRAGMA user_version`. A snapshot whose `schemaVersion` is above it
23548
+ * usually describes a store a newer build migrated. It is a hint, not a
23549
+ * verdict: the stamp is write-only, so a store whose count ran past this
23550
+ * build's while this build knows every migration in its ledger reads above
23551
+ * it too, which is why describeStoreSkew decides skew on ledger tags and
23552
+ * never on the count. OPTIONAL for the same reason as `installedVersion`;
23553
+ * bounded like `schemaVersion`.
23554
+ */
23555
+ buildSchemaVersion: external_exports.number().int().min(0).max(MAX_INT4).optional()
23523
23556
  }).meta({ id: "StorePosturePlugin" });
23524
23557
  var StorePostureSnapshot = external_exports.object({
23525
23558
  deviceId: external_exports.guid(),
@@ -25157,10 +25190,15 @@ var ParsedPointer = external_exports.object({
25157
25190
  });
25158
25191
  var VaultEntry = external_exports.object({
25159
25192
  pointerId: external_exports.string(),
25160
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
25161
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
25162
- // independently of the vault encryption key below.
25193
+ // The keyed HMAC of the EXACT raw bytes under `exception.key`, and the epoch it
25194
+ // was derived under. The vault's own dedupe key: a value and its invisibly
25195
+ // padded twin are two rows. It rotates independently of the vault encryption
25196
+ // key below. Never matched against an exception or grant.
25163
25197
  valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25198
+ // The same HMAC over the raw with invisible padding removed: the identity a
25199
+ // reveal-to-model grant and every exception match on. Shared by a value and
25200
+ // its padded twin.
25201
+ valueIdentityFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
25164
25202
  fingerprintKeyVersion: external_exports.number().int().positive(),
25165
25203
  // The vault-key epoch this row's ciphertext was sealed under.
25166
25204
  keyVersion: external_exports.number().int().positive(),
@@ -25741,10 +25779,18 @@ var SeveritySummaryItem = external_exports.object({
25741
25779
  count: external_exports.number().int().nonnegative(),
25742
25780
  // Resolution-aware breakdown (optional, additive). Populated once findings
25743
25781
  // carry lifecycle state: `caught` = handled in-flight (enforced); `openAtRest`
25744
- // = still open with no in-flight enforcement (needs remediation). Absent on the
25745
- // legacy count-only response until the resolution feature lands.
25782
+ // = still open with no in-flight enforcement (needs remediation); `dismissed`
25783
+ // = closed by a human judgement rather than a fix — visible, but not counted as
25784
+ // needing remediation. The three are disjoint. Absent on the legacy count-only
25785
+ // response until the resolution feature lands.
25746
25786
  caught: external_exports.number().int().nonnegative().optional(),
25747
- openAtRest: external_exports.number().int().nonnegative().optional()
25787
+ openAtRest: external_exports.number().int().nonnegative().optional(),
25788
+ dismissed: external_exports.number().int().nonnegative().optional(),
25789
+ // The two halves of `caught`, for a reader that wants them apart: `handled` =
25790
+ // in-flight findings an enforcement action already contained; `resolved` =
25791
+ // at-rest findings closed out by fixing them. `handled + resolved === caught`.
25792
+ handled: external_exports.number().int().nonnegative().optional(),
25793
+ resolved: external_exports.number().int().nonnegative().optional()
25748
25794
  }).meta({ id: "SeveritySummaryItem" });
25749
25795
  var SeveritySummaryResponse = external_exports.object({
25750
25796
  // Sum of bySeverity[].count.
@@ -25752,6 +25798,9 @@ var SeveritySummaryResponse = external_exports.object({
25752
25798
  // Findings still open at rest (sum of bySeverity[].openAtRest). Optional and
25753
25799
  // additive — absent on the legacy response until the resolution feature lands.
25754
25800
  needsRemediation: external_exports.number().int().nonnegative().optional(),
25801
+ // Findings a user dismissed (sum of bySeverity[].dismissed). Excluded from
25802
+ // needsRemediation, and kept visible here so an accepted risk is not erased.
25803
+ dismissed: external_exports.number().int().nonnegative().optional(),
25755
25804
  // All four severity levels are always present (count may be 0).
25756
25805
  bySeverity: external_exports.array(SeveritySummaryItem)
25757
25806
  }).meta({ id: "SeveritySummaryResponse" });
@@ -26349,11 +26398,11 @@ function repairOrRefuseMode(file2) {
26349
26398
  const link = lstatSync2(file2, { throwIfNoEntry: false });
26350
26399
  if (link === void 0) return "absent";
26351
26400
  if (link.isSymbolicLink()) return "untrusted";
26352
- const stat = statSync(file2, { throwIfNoEntry: false });
26353
- if (stat === void 0) return "absent";
26401
+ const stat2 = statSync(file2, { throwIfNoEntry: false });
26402
+ if (stat2 === void 0) return "absent";
26354
26403
  const uid = process.getuid?.();
26355
- if (uid !== void 0 && stat.uid !== uid) return "untrusted";
26356
- if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
26404
+ if (uid !== void 0 && stat2.uid !== uid) return "untrusted";
26405
+ if (process.platform !== "win32" && (stat2.mode & 511) !== DATA_FILE_MODE) {
26357
26406
  try {
26358
26407
  chmodSync2(file2, DATA_FILE_MODE);
26359
26408
  } catch {
@@ -26369,9 +26418,9 @@ function readControlPlaneCredentialState(settingsDir2, connection) {
26369
26418
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26370
26419
  const file2 = controlPlaneCredentialPath(settingsDir2);
26371
26420
  let raw;
26372
- const gate = repairOrRefuseMode(file2);
26373
- if (gate === "absent") return { usable: false, reason: "absent" };
26374
- if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
26421
+ const gate2 = repairOrRefuseMode(file2);
26422
+ if (gate2 === "absent") return { usable: false, reason: "absent" };
26423
+ if (gate2 === "untrusted") return { usable: false, reason: "untrusted-file" };
26375
26424
  try {
26376
26425
  raw = readFileSync(file2, "utf8");
26377
26426
  } catch (err) {
@@ -32509,7 +32558,10 @@ var SqliteResolutionsRepository = class {
32509
32558
  * Insert many dispositions as ONE transaction — all of them or none.
32510
32559
  *
32511
32560
  * A dashboard dismissal closes every open finding of a rule, which is one
32512
- * write per key; run loose, a fault partway leaves half a rule closed with
32561
+ * write per key. It reaches this through
32562
+ * `LocalDatabase.dismissOpenFindingsForRule`, which calls it inside the
32563
+ * transaction that selected the keys, so there it runs as a SAVEPOINT of
32564
+ * that transaction. Run loose, a fault partway leaves half a rule closed with
32513
32565
  * nothing recording that the other half was meant to be. The caller then has
32514
32566
  * no way to tell a partial run from a complete one, because the card it
32515
32567
  * refreshes into just shows a smaller number either way.
@@ -32729,6 +32781,7 @@ function toSighting(row) {
32729
32781
  var SELECT_COLUMNS = `
32730
32782
  pointer_id AS pointerId,
32731
32783
  value_fingerprint AS valueFingerprint,
32784
+ value_identity_fingerprint AS valueIdentityFingerprint,
32732
32785
  fingerprint_key_version AS fingerprintKeyVersion,
32733
32786
  key_version AS keyVersion,
32734
32787
  format_version AS formatVersion,
@@ -32753,13 +32806,13 @@ var SqliteSecretVaultRepository = class {
32753
32806
  this.db = db;
32754
32807
  this.insertStmt = db.prepare(
32755
32808
  `INSERT INTO secret_vault (
32756
- pointer_id, value_fingerprint, fingerprint_key_version, key_version,
32757
- format_version, category, rule_id, masked_match, provider,
32809
+ pointer_id, value_fingerprint, value_identity_fingerprint,
32810
+ fingerprint_key_version, key_version, format_version, category, rule_id, masked_match, provider,
32758
32811
  ciphertext, nonce, auth_tag,
32759
32812
  user_authorized, occurrence_count, first_seen, last_seen
32760
32813
  ) VALUES (
32761
- :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
32762
- :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32814
+ :pointerId, :valueFingerprint, :valueIdentityFingerprint,
32815
+ :fingerprintKeyVersion, :keyVersion, :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32763
32816
  :ciphertext, :nonce, :authTag,
32764
32817
  :userAuthorized, 1, :now, :now
32765
32818
  )`
@@ -32784,7 +32837,13 @@ var SqliteSecretVaultRepository = class {
32784
32837
  );
32785
32838
  this.refreshFingerprintStmt = db.prepare(
32786
32839
  `UPDATE secret_vault
32787
- SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
32840
+ SET value_fingerprint = :valueFingerprint,
32841
+ value_identity_fingerprint = :valueIdentityFingerprint,
32842
+ fingerprint_key_version = :fingerprintKeyVersion
32843
+ WHERE pointer_id = :pointerId`
32844
+ );
32845
+ this.setIdentityStmt = db.prepare(
32846
+ `UPDATE secret_vault SET value_identity_fingerprint = :valueIdentityFingerprint
32788
32847
  WHERE pointer_id = :pointerId`
32789
32848
  );
32790
32849
  this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
@@ -32801,6 +32860,7 @@ var SqliteSecretVaultRepository = class {
32801
32860
  listStmt;
32802
32861
  replaceCiphertextStmt;
32803
32862
  refreshFingerprintStmt;
32863
+ setIdentityStmt;
32804
32864
  deleteByPointerStmt;
32805
32865
  derefStmt;
32806
32866
  /**
@@ -32831,6 +32891,7 @@ var SqliteSecretVaultRepository = class {
32831
32891
  bindParams({
32832
32892
  pointerId: input2.pointerId,
32833
32893
  valueFingerprint: input2.valueFingerprint,
32894
+ valueIdentityFingerprint: input2.valueIdentityFingerprint,
32834
32895
  fingerprintKeyVersion: input2.fingerprintKeyVersion,
32835
32896
  keyVersion: input2.keyVersion,
32836
32897
  formatVersion: input2.formatVersion ?? POINTER_FORMAT_VERSION,
@@ -32892,7 +32953,15 @@ var SqliteSecretVaultRepository = class {
32892
32953
  replaceCiphertext(pointerId, next) {
32893
32954
  this.replaceCiphertextStmt.run({ pointerId, ...next });
32894
32955
  }
32895
- /** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
32956
+ /**
32957
+ * Correct an entry's identity fingerprint in place, leaving its exact
32958
+ * fingerprint and key epoch alone. For a row whose identity column still holds
32959
+ * the exact value copied in by the migration that added it.
32960
+ */
32961
+ setIdentityFingerprint(pointerId, valueIdentityFingerprint) {
32962
+ this.setIdentityStmt.run({ pointerId, valueIdentityFingerprint });
32963
+ }
32964
+ /** Re-derive an entry's fingerprints under a new fingerprint-key epoch. */
32896
32965
  refreshFingerprint(pointerId, next) {
32897
32966
  this.refreshFingerprintStmt.run({ pointerId, ...next });
32898
32967
  }
@@ -33023,7 +33092,7 @@ var SqliteSecretVaultRepository = class {
33023
33092
  `SELECT ${INVENTORY_COLUMNS},
33024
33093
  (SELECT e.id FROM exceptions e
33025
33094
  WHERE e.rule_id = v.rule_id
33026
- AND e.value_fingerprint = v.value_fingerprint
33095
+ AND e.value_fingerprint = v.value_identity_fingerprint
33027
33096
  AND e.key_version = v.fingerprint_key_version
33028
33097
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
33029
33098
  LIMIT 1) AS grant_id
@@ -33066,7 +33135,7 @@ var SqliteSecretVaultRepository = class {
33066
33135
  `SELECT ${INVENTORY_COLUMNS},
33067
33136
  (SELECT e.id FROM exceptions e
33068
33137
  WHERE e.rule_id = v.rule_id
33069
- AND e.value_fingerprint = v.value_fingerprint
33138
+ AND e.value_fingerprint = v.value_identity_fingerprint
33070
33139
  AND e.key_version = v.fingerprint_key_version
33071
33140
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
33072
33141
  LIMIT 1) AS grant_id
@@ -33170,6 +33239,18 @@ var OPEN_AT_REST_FINDINGS_SQL = `FROM inspection_findings f
33170
33239
  OR latest.status IS NULL
33171
33240
  OR latest.status NOT IN ('resolved', 'dismissed')
33172
33241
  )`;
33242
+ function selectOpenFindingKeysForRule(db, ruleId) {
33243
+ const rows = allRows(
33244
+ db.prepare(
33245
+ `SELECT DISTINCT f.finding_key AS finding_key
33246
+ ${OPEN_AT_REST_FINDINGS_SQL}
33247
+ AND d.rule_id = :ruleId
33248
+ AND f.finding_key IS NOT NULL`
33249
+ ),
33250
+ { ruleId }
33251
+ );
33252
+ return rows.map((r) => r.finding_key);
33253
+ }
33173
33254
  var SEVERITIES = ["critical", "high", "medium", "low"];
33174
33255
  var ACTION_TO_KIND = {
33175
33256
  block: "blocked",
@@ -33226,16 +33307,16 @@ var SqliteSecurityRepository = class {
33226
33307
  // findings are caught only once their latest disposition is resolved,
33227
33308
  // otherwise they are open-at-rest.
33228
33309
  //
33229
- // NOTE for future manual-resolution writers: only latest status
33230
- // 'resolved' counts as caught above. When acknowledged/dismissed/
33231
- // false-positive manual dispositions land, this must keep filtering by
33232
- // status/method — 'acknowledged' is accepted risk, not a fix, and must NOT
33233
- // be bucketed as caught alongside 'resolved'.
33310
+ // Only latest status 'resolved' counts as caught above. 'dismissed' is its
33311
+ // own bucket: a judgement rather than a fix, so it is neither caught nor
33312
+ // needing remediation, and stays countable. A further manual disposition
33313
+ // (acknowledged, false-positive) must be placed deliberately — 'acknowledged'
33314
+ // is accepted risk, not a fix, and must NOT be bucketed as caught.
33234
33315
  //
33235
33316
  // Legacy at-rest findings from pre-branch scans carry finding_key = NULL —
33236
33317
  // the resolution lifecycle is keyed by finding_key, so it can never attach a
33237
33318
  // disposition to (or clear) one of these on re-scan. They are excluded from
33238
- // both caught and openAtRest (untracked, not "needs remediation forever"),
33319
+ // all three buckets (untracked, not "needs remediation forever"),
33239
33320
  // but still counted in total/count below — this keeps this predicate
33240
33321
  // consistent with SqliteResolutionsRepository.openAtRestKeysForPath, which
33241
33322
  // already filters `finding_key IS NOT NULL`.
@@ -33258,12 +33339,25 @@ var SqliteSecurityRepository = class {
33258
33339
  WHEN latest.status = 'resolved' THEN 1
33259
33340
  ELSE 0
33260
33341
  END) AS caught,
33342
+ SUM(CASE WHEN e.event_type != 'code_change' THEN 1 ELSE 0 END) AS handled,
33343
+ SUM(CASE
33344
+ WHEN e.event_type = 'code_change'
33345
+ AND f.finding_key IS NOT NULL
33346
+ AND latest.status = 'resolved' THEN 1
33347
+ ELSE 0
33348
+ END) AS resolved,
33261
33349
  SUM(CASE
33262
33350
  WHEN e.event_type = 'code_change'
33263
33351
  AND f.finding_key IS NOT NULL
33264
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
33352
+ AND (latest.status IS NULL
33353
+ OR latest.status NOT IN ('resolved', 'dismissed')) THEN 1
33354
+ ELSE 0
33355
+ END) AS open_at_rest,
33356
+ SUM(CASE
33357
+ WHEN e.event_type = 'code_change'
33358
+ AND latest.status = 'dismissed' THEN 1
33265
33359
  ELSE 0
33266
- END) AS open_at_rest
33360
+ END) AS dismissed
33267
33361
  FROM inspection_findings f
33268
33362
  JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
33269
33363
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -33278,11 +33372,15 @@ var SqliteSecurityRepository = class {
33278
33372
  severity,
33279
33373
  count: byRow.get(severity)?.count ?? 0,
33280
33374
  caught: byRow.get(severity)?.caught ?? 0,
33281
- openAtRest: byRow.get(severity)?.open_at_rest ?? 0
33375
+ handled: byRow.get(severity)?.handled ?? 0,
33376
+ resolved: byRow.get(severity)?.resolved ?? 0,
33377
+ openAtRest: byRow.get(severity)?.open_at_rest ?? 0,
33378
+ dismissed: byRow.get(severity)?.dismissed ?? 0
33282
33379
  }));
33283
33380
  const total = bySeverity.reduce((sum, s) => sum + s.count, 0);
33284
33381
  const needsRemediation = bySeverity.reduce((sum, s) => sum + s.openAtRest, 0);
33285
- return Promise.resolve({ total, needsRemediation, bySeverity });
33382
+ const dismissed = bySeverity.reduce((sum, s) => sum + s.dismissed, 0);
33383
+ return Promise.resolve({ total, needsRemediation, dismissed, bySeverity });
33286
33384
  }
33287
33385
  // Range is echoed but does not change the result today — coverage is a constant
33288
33386
  // business fact (see SCAN_COVERAGE), not a measured per-window metric. Order
@@ -33599,10 +33697,10 @@ var SqliteSecurityRepository = class {
33599
33697
  * machine, and the second reported "no recommendations" over live exposure.
33600
33698
  *
33601
33699
  * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
33602
- * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
33603
- * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
33604
- * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
33605
- * The two answer different questions and only this one has to match a link.
33700
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. It
33701
+ * differs from `severitySummary`'s `openAtRest` only in including untracked
33702
+ * legacy rows, which that bucket leaves out; dismissed is excluded from both.
33703
+ * Only this one has to match a link.
33606
33704
  *
33607
33705
  * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
33608
33706
  * whole-store scope costs a grouped scan rather than a row per finding.
@@ -33630,6 +33728,8 @@ var SqliteSecurityRepository = class {
33630
33728
  /**
33631
33729
  * The distinct `finding_key`s behind ONE rule's {@link recommendationInputs}
33632
33730
  * tally — what a dashboard dismissal of that row writes a disposition for.
33731
+ * The dismissal itself does not call this: it reads the same set through
33732
+ * {@link selectOpenFindingKeysForRule}, inside its own write transaction.
33633
33733
  *
33634
33734
  * It shares {@link OPEN_AT_REST_FINDINGS_SQL} with the count rather than
33635
33735
  * restating the predicate, because a dismissal has to act on exactly the set
@@ -33646,16 +33746,7 @@ var SqliteSecurityRepository = class {
33646
33746
  * this set SMALLER than the tally, never larger.
33647
33747
  */
33648
33748
  openFindingKeysForRule(ruleId) {
33649
- const rows = allRows(
33650
- this.db.prepare(
33651
- `SELECT DISTINCT f.finding_key AS finding_key
33652
- ${OPEN_AT_REST_FINDINGS_SQL}
33653
- AND d.rule_id = :ruleId
33654
- AND f.finding_key IS NOT NULL`
33655
- ),
33656
- { ruleId }
33657
- );
33658
- return Promise.resolve(rows.map((r) => r.finding_key));
33749
+ return Promise.resolve(selectOpenFindingKeysForRule(this.db, ruleId));
33659
33750
  }
33660
33751
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
33661
33752
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
@@ -34701,6 +34792,31 @@ function openLocalDatabase(dir, options = {}) {
34701
34792
  );
34702
34793
  });
34703
34794
  }
34795
+ function dismissOpenFindingsForRule(ruleId, disposition) {
34796
+ let dismissed = 0;
34797
+ withTransaction(
34798
+ db,
34799
+ () => {
34800
+ const keys = selectOpenFindingKeysForRule(db, ruleId);
34801
+ resolutions.insertResolutions(
34802
+ keys.map((findingKey) => ({
34803
+ findingKey,
34804
+ status: "dismissed",
34805
+ method: disposition.method,
34806
+ resolvedAt: disposition.resolvedAt,
34807
+ evidence: disposition.evidence
34808
+ }))
34809
+ );
34810
+ dismissed = keys.length;
34811
+ },
34812
+ // IMMEDIATE takes the write lock at BEGIN, before the select, which is
34813
+ // what keeps a concurrent resolve out of the gap. It also makes waiting
34814
+ // on a busy writer an ordinary busy_timeout wait rather than a
34815
+ // read-to-write upgrade SQLite refuses to retry.
34816
+ "IMMEDIATE"
34817
+ );
34818
+ return dismissed;
34819
+ }
34704
34820
  function recordCapture(event, detected) {
34705
34821
  failOpenTransaction(db, () => {
34706
34822
  const sessionId = event.metadata?.sessionId;
@@ -34884,6 +35000,7 @@ function openLocalDatabase(dir, options = {}) {
34884
35000
  inspectionDefinitions,
34885
35001
  inspectionFindings,
34886
35002
  recordCapture,
35003
+ dismissOpenFindingsForRule,
34887
35004
  markCaptureDelivered,
34888
35005
  markCaptureOwed,
34889
35006
  markAuditEventsDelivered,
@@ -35226,7 +35343,7 @@ async function send(options) {
35226
35343
  }
35227
35344
  }
35228
35345
  };
35229
- return new Promise((resolve2, reject) => {
35346
+ return new Promise((resolve3, reject) => {
35230
35347
  let settled = false;
35231
35348
  const fail = (reason, status) => {
35232
35349
  if (settled) return;
@@ -35252,7 +35369,7 @@ async function send(options) {
35252
35369
  res.on("end", () => {
35253
35370
  if (settled) return;
35254
35371
  settled = true;
35255
- resolve2({
35372
+ resolve3({
35256
35373
  status: res.statusCode ?? 0,
35257
35374
  headers: res.headers,
35258
35375
  body: Buffer.concat(chunks).toString("utf8")
@@ -36231,6 +36348,82 @@ function escapeRegExp2(value) {
36231
36348
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36232
36349
  }
36233
36350
 
36351
+ // ../../packages/detections/src/format-chars.ts
36352
+ var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
36353
+ var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
36354
+ function normalizeFormatChars(text) {
36355
+ if (!HAS_FORMAT_CHAR.test(text)) return void 0;
36356
+ const normalizedParts = [];
36357
+ const segments = [];
36358
+ let cursor = 0;
36359
+ let normLength = 0;
36360
+ for (const match of text.matchAll(FORMAT_CHAR_GLOBAL)) {
36361
+ const matchStart = match.index;
36362
+ if (matchStart > cursor) {
36363
+ const length = matchStart - cursor;
36364
+ normalizedParts.push(text.slice(cursor, matchStart));
36365
+ segments.push({ normStart: normLength, origStart: cursor, length });
36366
+ normLength += length;
36367
+ }
36368
+ cursor = matchStart + match[0].length;
36369
+ }
36370
+ if (cursor < text.length) {
36371
+ const length = text.length - cursor;
36372
+ normalizedParts.push(text.slice(cursor));
36373
+ segments.push({ normStart: normLength, origStart: cursor, length });
36374
+ }
36375
+ return { normalized: normalizedParts.join(""), segments };
36376
+ }
36377
+ function segmentAt(segments, normPos) {
36378
+ let lo = 0;
36379
+ let hi = segments.length - 1;
36380
+ while (lo < hi) {
36381
+ const mid = lo + hi >> 1;
36382
+ const segment = segments[mid];
36383
+ if (segment !== void 0 && normPos >= segment.normStart + segment.length) {
36384
+ lo = mid + 1;
36385
+ } else {
36386
+ hi = mid;
36387
+ }
36388
+ }
36389
+ const found = segments[lo];
36390
+ if (found === void 0) {
36391
+ throw new Error(`normPos ${String(normPos)} has no covering segment`);
36392
+ }
36393
+ return found;
36394
+ }
36395
+ function mapSpanToOriginal(span, normalization) {
36396
+ const { segments } = normalization;
36397
+ const startSegment = segmentAt(segments, span.start);
36398
+ const start = startSegment.origStart + (span.start - startSegment.normStart);
36399
+ const endSegment = segmentAt(segments, span.end - 1);
36400
+ const end = endSegment.origStart + (span.end - 1 - endSegment.normStart) + 1;
36401
+ return { start, end };
36402
+ }
36403
+ function normalizedOffset(origPos, segments) {
36404
+ let lo = 0;
36405
+ let hi = segments.length;
36406
+ while (lo < hi) {
36407
+ const mid = lo + hi >> 1;
36408
+ const segment = segments[mid];
36409
+ if (segment !== void 0 && segment.origStart + segment.length <= origPos) {
36410
+ lo = mid + 1;
36411
+ } else {
36412
+ hi = mid;
36413
+ }
36414
+ }
36415
+ const found = segments[Math.min(lo, segments.length - 1)];
36416
+ if (found === void 0) return 0;
36417
+ return found.normStart + Math.min(Math.max(0, origPos - found.origStart), found.length);
36418
+ }
36419
+ function mapSpanToNormalized(span, normalization) {
36420
+ const { segments } = normalization;
36421
+ return {
36422
+ start: normalizedOffset(span.start, segments),
36423
+ end: normalizedOffset(span.end, segments)
36424
+ };
36425
+ }
36426
+
36234
36427
  // ../../packages/detections/src/regex-cache.ts
36235
36428
  var singles = /* @__PURE__ */ new WeakMap();
36236
36429
  var keywordLists = /* @__PURE__ */ new WeakMap();
@@ -36392,29 +36585,35 @@ function registerPack(pack) {
36392
36585
  function getLoadedRules() {
36393
36586
  return [...packs.values()].flatMap((p) => p.rules);
36394
36587
  }
36395
- function isCorroborated(candidate, candidates, text) {
36588
+ function spansOverlap(a, b) {
36589
+ return a.start < b.end && a.end > b.start;
36590
+ }
36591
+ function isCorroborated(candidate, candidates, text, normalization) {
36396
36592
  const req = candidate.rule.requiresNearby;
36397
36593
  if (!req) return true;
36398
36594
  const halfWindow = req.windowChars;
36399
- const { start, end } = candidate.match.span;
36400
- const winStart = start - halfWindow;
36401
- const winEnd = end + halfWindow;
36595
+ const ns = candidate.normSpan;
36596
+ const winStart = ns.start - halfWindow;
36597
+ const winEnd = ns.end + halfWindow;
36402
36598
  const categories = req.categories;
36403
36599
  const ruleIds = req.ruleIds;
36404
36600
  if (categories?.length || ruleIds?.length) {
36405
36601
  for (const other of candidates) {
36406
36602
  if (other === candidate) continue;
36407
- const os = other.match.span;
36408
- if (os.end < winStart || os.start > winEnd) continue;
36409
- if (other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category)) {
36410
- return true;
36603
+ if (other.normSpan.end < winStart || other.normSpan.start > winEnd) continue;
36604
+ const relevant = other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category) === true || ruleIds?.includes(other.match.ruleId) === true;
36605
+ if (!relevant) continue;
36606
+ if (other.match.ruleId === candidate.match.ruleId && spansOverlap(other.match.span, candidate.match.span)) {
36607
+ continue;
36411
36608
  }
36412
- if (ruleIds?.includes(other.match.ruleId)) return true;
36609
+ return true;
36413
36610
  }
36414
36611
  }
36415
36612
  const labels = req.labels;
36416
36613
  if (labels && labels.length > 0) {
36417
- const haystack = text.slice(Math.max(0, winStart), winEnd);
36614
+ const { start, end } = candidate.match.span;
36615
+ const haystack = text.slice(Math.max(0, start - halfWindow), end + halfWindow);
36616
+ const normalizedHaystack = normalization === void 0 ? void 0 : normalization.normalized.slice(Math.max(0, winStart), winEnd);
36418
36617
  for (const re of memoizedRegExpList(
36419
36618
  "label",
36420
36619
  req,
@@ -36423,29 +36622,20 @@ function isCorroborated(candidate, candidates, text) {
36423
36622
  return trimmed.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed)}(?![A-Za-z0-9])`, "i");
36424
36623
  })
36425
36624
  )) {
36426
- if (re?.test(haystack)) return true;
36625
+ if (!re) continue;
36626
+ if (re.test(haystack)) return true;
36627
+ if (normalizedHaystack !== void 0 && re.test(normalizedHaystack)) return true;
36427
36628
  }
36428
36629
  }
36429
36630
  return false;
36430
36631
  }
36431
- function extensionOf(filePath) {
36432
- const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
36433
- const dot = base.lastIndexOf(".");
36434
- return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
36435
- }
36436
- function ruleApplies(rule, extension) {
36437
- if (!rule.appliesTo || extension === void 0) return true;
36438
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
36439
- }
36440
- function scan(text, rules, context) {
36441
- const ruleset = rules ?? getLoadedRules();
36442
- const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
36632
+ function buildCandidates(matchText, ruleset, extension) {
36443
36633
  const candidates = [];
36444
36634
  for (const rule of ruleset) {
36445
36635
  if (!ruleApplies(rule, extension)) continue;
36446
- const spans = MATCHERS[rule.matcher.type](text, rule);
36636
+ const spans = MATCHERS[rule.matcher.type](matchText, rule);
36447
36637
  for (const span of spans) {
36448
- const rawMatch = text.slice(span.start, span.end);
36638
+ const rawMatch = matchText.slice(span.start, span.end);
36449
36639
  if (!passesPostValidators(rule, rawMatch)) continue;
36450
36640
  candidates.push({
36451
36641
  rule,
@@ -36456,10 +36646,31 @@ function scan(text, rules, context) {
36456
36646
  span,
36457
36647
  rawMatch,
36458
36648
  confidence: 0.9
36459
- }
36649
+ },
36650
+ // In `matchText`'s own coordinates, which is the normalized text for
36651
+ // a normalized-pass candidate and so already right; an original-pass
36652
+ // candidate on the slow path is re-derived by withNormalizedSpan.
36653
+ normSpan: span
36460
36654
  });
36461
36655
  }
36462
36656
  }
36657
+ return candidates;
36658
+ }
36659
+ function mapCandidateToOriginal(candidate, normalization, text) {
36660
+ const span = mapSpanToOriginal(candidate.match.span, normalization);
36661
+ return {
36662
+ rule: candidate.rule,
36663
+ match: { ...candidate.match, span, rawMatch: text.slice(span.start, span.end) },
36664
+ // Deliberately NOT remapped: `normSpan` is the span the primitive match
36665
+ // was found at in the normalized text, which is exactly the coordinate
36666
+ // space windows are measured in. See the `Candidate` comment.
36667
+ normSpan: candidate.normSpan
36668
+ };
36669
+ }
36670
+ function withNormalizedSpan(candidate, normalization) {
36671
+ return { ...candidate, normSpan: mapSpanToNormalized(candidate.match.span, normalization) };
36672
+ }
36673
+ function gate(candidates, text, normalization) {
36463
36674
  const findings = [];
36464
36675
  for (const candidate of candidates) {
36465
36676
  const req = candidate.rule.requiresNearby;
@@ -36467,7 +36678,7 @@ function scan(text, rules, context) {
36467
36678
  findings.push(candidate.match);
36468
36679
  continue;
36469
36680
  }
36470
- if (!isCorroborated(candidate, candidates, text)) continue;
36681
+ if (!isCorroborated(candidate, candidates, text, normalization)) continue;
36471
36682
  const boost = req.confidenceBoost;
36472
36683
  findings.push(
36473
36684
  boost ? { ...candidate.match, confidence: Math.min(0.99, candidate.match.confidence + boost) } : candidate.match
@@ -36475,6 +36686,81 @@ function scan(text, rules, context) {
36475
36686
  }
36476
36687
  return findings;
36477
36688
  }
36689
+ function closeRegion(open3, text) {
36690
+ const span = { start: open3.start, end: open3.end };
36691
+ return {
36692
+ ruleId: open3.ruleId,
36693
+ category: open3.category,
36694
+ severity: open3.severity,
36695
+ span,
36696
+ rawMatch: text.slice(span.start, span.end),
36697
+ confidence: open3.confidence
36698
+ };
36699
+ }
36700
+ function mergeOverlappingSameRule(findings, text) {
36701
+ if (findings.length === 0) return findings;
36702
+ const groups = /* @__PURE__ */ new Map();
36703
+ const ruleOrder = [];
36704
+ for (const finding2 of findings) {
36705
+ const group = groups.get(finding2.ruleId);
36706
+ if (group) {
36707
+ group.push(finding2);
36708
+ } else {
36709
+ groups.set(finding2.ruleId, [finding2]);
36710
+ ruleOrder.push(finding2.ruleId);
36711
+ }
36712
+ }
36713
+ const merged = [];
36714
+ for (const ruleId of ruleOrder) {
36715
+ const group = groups.get(ruleId) ?? [];
36716
+ const sorted = [...group].sort(
36717
+ (a, b) => a.span.start - b.span.start || a.span.end - b.span.end
36718
+ );
36719
+ let open3;
36720
+ for (const finding2 of sorted) {
36721
+ if (open3 && finding2.span.start < open3.end) {
36722
+ open3.end = Math.max(open3.end, finding2.span.end);
36723
+ open3.confidence = Math.max(open3.confidence, finding2.confidence);
36724
+ continue;
36725
+ }
36726
+ if (open3) merged.push(closeRegion(open3, text));
36727
+ open3 = {
36728
+ start: finding2.span.start,
36729
+ end: finding2.span.end,
36730
+ confidence: finding2.confidence,
36731
+ ruleId: finding2.ruleId,
36732
+ category: finding2.category,
36733
+ severity: finding2.severity
36734
+ };
36735
+ }
36736
+ if (open3) merged.push(closeRegion(open3, text));
36737
+ }
36738
+ return merged;
36739
+ }
36740
+ function extensionOf(filePath) {
36741
+ const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
36742
+ const dot = base.lastIndexOf(".");
36743
+ return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
36744
+ }
36745
+ function ruleApplies(rule, extension) {
36746
+ if (!rule.appliesTo || extension === void 0) return true;
36747
+ return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
36748
+ }
36749
+ function scan(text, rules, context) {
36750
+ const ruleset = rules ?? getLoadedRules();
36751
+ const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
36752
+ const normalization = normalizeFormatChars(text);
36753
+ const originalCandidates = buildCandidates(text, ruleset, extension);
36754
+ if (!normalization) return gate(originalCandidates, text, void 0);
36755
+ const pooledOriginal = originalCandidates.map(
36756
+ (candidate) => withNormalizedSpan(candidate, normalization)
36757
+ );
36758
+ const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
36759
+ (candidate) => mapCandidateToOriginal(candidate, normalization, text)
36760
+ );
36761
+ const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
36762
+ return mergeOverlappingSameRule(findings, text);
36763
+ }
36478
36764
  var SEVERITY_RANK2 = {
36479
36765
  critical: 3,
36480
36766
  high: 2,
@@ -39190,8 +39476,8 @@ function collectConfigFiles(scan2, claudeDir, cwd) {
39190
39476
  }
39191
39477
  function configFileEntry(path, scope, kind) {
39192
39478
  try {
39193
- const stat = statSync7(path);
39194
- return { name: basename4(path), path, scope, kind, updatedAt: stat.mtime.toISOString() };
39479
+ const stat2 = statSync7(path);
39480
+ return { name: basename4(path), path, scope, kind, updatedAt: stat2.mtime.toISOString() };
39195
39481
  } catch {
39196
39482
  return void 0;
39197
39483
  }
@@ -39474,6 +39760,40 @@ import { Worker } from "worker_threads";
39474
39760
  // ../../packages/plugin-sdk/src/hook-fail-opens.ts
39475
39761
  import { readFileSync as readFileSync13 } from "fs";
39476
39762
  import { join as join20 } from "path";
39763
+ var HOOK_FAIL_OPENS_FILENAME = "hook-fail-opens.json";
39764
+ function hookFailOpensPath(dataDir2) {
39765
+ return join20(dataDir2, HOOK_FAIL_OPENS_FILENAME);
39766
+ }
39767
+ function recordHookFailOpen(dataDir2, nowMs) {
39768
+ try {
39769
+ ensureDataDirSync(dataDir2);
39770
+ const previous = readHookFailOpens(dataDir2);
39771
+ const next = {
39772
+ // Saturates at the largest count the reader accepts: one past it would
39773
+ // read back as nothing recorded and restart the tally from one.
39774
+ failOpens: Math.min((previous?.failOpens ?? 0) + 1, Number.MAX_SAFE_INTEGER),
39775
+ lastAtMs: nowMs
39776
+ };
39777
+ writeOwnerOnlyFileSync(hookFailOpensPath(dataDir2), `${JSON.stringify(next)}
39778
+ `);
39779
+ } catch {
39780
+ }
39781
+ }
39782
+ function readHookFailOpens(dataDir2) {
39783
+ try {
39784
+ const parsed2 = JSON.parse(readFileSync13(hookFailOpensPath(dataDir2), "utf8"));
39785
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
39786
+ const record2 = parsed2;
39787
+ if (!isPositiveSafeInteger(record2.failOpens)) return null;
39788
+ if (!isPositiveSafeInteger(record2.lastAtMs)) return null;
39789
+ return { failOpens: record2.failOpens, lastAtMs: record2.lastAtMs };
39790
+ } catch {
39791
+ return null;
39792
+ }
39793
+ }
39794
+ function isPositiveSafeInteger(value) {
39795
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
39796
+ }
39477
39797
 
39478
39798
  // ../../packages/plugin-sdk/src/host-floor.ts
39479
39799
  import { readFileSync as readFileSync15 } from "fs";
@@ -40547,8 +40867,52 @@ function spawnDetached(scriptPath) {
40547
40867
  child.unref();
40548
40868
  }
40549
40869
 
40870
+ // ../../packages/plugin-runtime/src/attached/install-record.ts
40871
+ import { readFile as readFile2, stat } from "fs/promises";
40872
+ import { basename as basename7, dirname as dirname6, join as join28, resolve as resolve2 } from "path";
40873
+ async function readInstalledVersion(installRoot) {
40874
+ try {
40875
+ const versionDir = resolve2(installRoot);
40876
+ const pluginDir = dirname6(versionDir);
40877
+ const marketplaceDir = dirname6(pluginDir);
40878
+ const cacheDir = dirname6(marketplaceDir);
40879
+ if (basename7(cacheDir) !== "cache") return null;
40880
+ const key = `${basename7(pluginDir)}@${basename7(marketplaceDir)}`;
40881
+ const record2 = JSON.parse(
40882
+ await readFile2(join28(dirname6(cacheDir), "installed_plugins.json"), "utf8")
40883
+ );
40884
+ const plugins = record2?.plugins;
40885
+ if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
40886
+ return null;
40887
+ }
40888
+ const entries = plugins[key];
40889
+ if (!Array.isArray(entries)) return null;
40890
+ let newest = null;
40891
+ for (const entry of entries) {
40892
+ const { version: version2, installPath } = entry ?? {};
40893
+ if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) continue;
40894
+ if (!StorePosturePlugin.shape.installedVersion.safeParse(version2).success) continue;
40895
+ if (newest !== null && compareBinaryVersions(version2, newest) <= 0) continue;
40896
+ if (typeof installPath === "string" && !await exists(installPath)) continue;
40897
+ newest = version2;
40898
+ }
40899
+ return newest;
40900
+ } catch {
40901
+ return null;
40902
+ }
40903
+ }
40904
+ async function exists(path) {
40905
+ try {
40906
+ await stat(path);
40907
+ return true;
40908
+ } catch {
40909
+ return false;
40910
+ }
40911
+ }
40912
+
40550
40913
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
40551
40914
  import { readFileSync as readFileSync18 } from "fs";
40915
+ var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
40552
40916
  var manifestBuildCache = /* @__PURE__ */ new Map();
40553
40917
  function readManifestBuild(manifestUrl, packageName) {
40554
40918
  const key = manifestUrl.href;
@@ -40566,6 +40930,7 @@ function readManifestBuild(manifestUrl, packageName) {
40566
40930
  }
40567
40931
  function createPluginBlock(build, policyStore) {
40568
40932
  return async () => {
40933
+ const installed = build.installRoot === void 0 ? void 0 : readInstalledVersionBounded(build.installRoot);
40569
40934
  const cached2 = await policyStore.read();
40570
40935
  const fetchedAtMs = cached2?.fetchedAtMs;
40571
40936
  const block = {
@@ -40573,16 +40938,25 @@ function createPluginBlock(build, policyStore) {
40573
40938
  version: build.version,
40574
40939
  ossVersion: build.ossVersion ?? null,
40575
40940
  policyBundleVersion: cached2 !== null && StorePosturePlugin.shape.policyBundleVersion.safeParse(cached2.bundle.version).success ? cached2.bundle.version : null,
40576
- policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null
40941
+ policyFetchedAt: fetchedAtMs !== void 0 && fetchedAtMs > 0 && StorePosturePlugin.shape.policyFetchedAt.safeParse(fetchedAtMs).success ? fetchedAtMs : null,
40942
+ ...installed === void 0 ? {} : { installedVersion: await installed },
40943
+ buildSchemaVersion: SQLITE_MIGRATIONS.length
40577
40944
  };
40578
40945
  return StorePosturePlugin.safeParse(block).success ? block : void 0;
40579
40946
  };
40580
40947
  }
40948
+ async function readInstalledVersionBounded(installRoot) {
40949
+ try {
40950
+ return await withTimeout(readInstalledVersion(installRoot), INSTALL_RECORD_READ_TIMEOUT_MS);
40951
+ } catch {
40952
+ return null;
40953
+ }
40954
+ }
40581
40955
 
40582
40956
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40583
40957
  import { randomUUID as randomUUID16 } from "crypto";
40584
- import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
40585
- import { join as join28 } from "path";
40958
+ import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
40959
+ import { join as join29 } from "path";
40586
40960
 
40587
40961
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
40588
40962
  import { rename as rename2 } from "fs/promises";
@@ -40590,11 +40964,11 @@ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
40590
40964
  var IMMEDIATE_RETRIES = 8;
40591
40965
  var TIMED_RETRIES = 4;
40592
40966
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
40593
- var delay = (ms) => new Promise((resolve2) => {
40594
- setTimeout(resolve2, ms);
40967
+ var delay = (ms) => new Promise((resolve3) => {
40968
+ setTimeout(resolve3, ms);
40595
40969
  });
40596
- var yieldToLoop = () => new Promise((resolve2) => {
40597
- setImmediate(resolve2);
40970
+ var yieldToLoop = () => new Promise((resolve3) => {
40971
+ setImmediate(resolve3);
40598
40972
  });
40599
40973
  async function publishByRename(tmp, file2, move = rename2) {
40600
40974
  for (let attempt = 1; ; attempt += 1) {
@@ -40611,10 +40985,10 @@ async function publishByRename(tmp, file2, move = rename2) {
40611
40985
 
40612
40986
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
40613
40987
  function createPolicyStore(dir = dataDir()) {
40614
- const file2 = join28(dir, "policy-cache.json");
40988
+ const file2 = join29(dir, "policy-cache.json");
40615
40989
  async function read() {
40616
40990
  try {
40617
- const raw = await readFile2(file2, "utf8");
40991
+ const raw = await readFile3(file2, "utf8");
40618
40992
  const parsed2 = JSON.parse(raw);
40619
40993
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
40620
40994
  const record2 = parsed2;
@@ -40636,7 +41010,7 @@ function createPolicyStore(dir = dataDir()) {
40636
41010
  }
40637
41011
  async function priorRecord() {
40638
41012
  try {
40639
- const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
41013
+ const parsed2 = JSON.parse(await readFile3(file2, "utf8"));
40640
41014
  return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
40641
41015
  } catch {
40642
41016
  return null;
@@ -40682,7 +41056,7 @@ function createPolicyStore(dir = dataDir()) {
40682
41056
 
40683
41057
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
40684
41058
  import { readFileSync as readFileSync19 } from "fs";
40685
- import { join as join29 } from "path";
41059
+ import { join as join30 } from "path";
40686
41060
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
40687
41061
  var OUTCOME_KEYS = {
40688
41062
  ok: true,
@@ -40696,7 +41070,7 @@ var OUTCOME_KEYS = {
40696
41070
  };
40697
41071
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
40698
41072
  function postureReportStatePath(dataDir2) {
40699
- return join29(dataDir2, POSTURE_REPORT_STATE_FILENAME);
41073
+ return join30(dataDir2, POSTURE_REPORT_STATE_FILENAME);
40700
41074
  }
40701
41075
  function writePostureReportState(dataDir2, state) {
40702
41076
  try {
@@ -40875,12 +41249,12 @@ function readStorePosture(dbPath2) {
40875
41249
 
40876
41250
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
40877
41251
  import { randomUUID as randomUUID17 } from "crypto";
40878
- import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
40879
- import { join as join30 } from "path";
41252
+ import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
41253
+ import { join as join31 } from "path";
40880
41254
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40881
41255
  function createPostureStore(dir = settingsDir(), legacyDir) {
40882
- const file2 = join30(dir, "posture-state.json");
40883
- const legacyFile = legacyDir === void 0 ? null : join30(legacyDir, "posture-state.json");
41256
+ const file2 = join31(dir, "posture-state.json");
41257
+ const legacyFile = legacyDir === void 0 ? null : join31(legacyDir, "posture-state.json");
40884
41258
  async function persist(state) {
40885
41259
  await ensureDataDir(dir);
40886
41260
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -40895,7 +41269,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40895
41269
  async function readFrom(path) {
40896
41270
  let raw;
40897
41271
  try {
40898
- raw = await readFile3(path, "utf8");
41272
+ raw = await readFile4(path, "utf8");
40899
41273
  } catch (err) {
40900
41274
  const code = err.code;
40901
41275
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -40949,7 +41323,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
40949
41323
 
40950
41324
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
40951
41325
  import { readFileSync as readFileSync20 } from "fs";
40952
- import { join as join31 } from "path";
41326
+ import { join as join32 } from "path";
40953
41327
 
40954
41328
  // ../../packages/plugin-runtime/src/attached/status.ts
40955
41329
  var REFUSAL_LINES = {
@@ -41070,12 +41444,12 @@ var StandaloneDataGateway = class {
41070
41444
  // reconciler drops the whole pass and recovers it idempotently on the next read.
41071
41445
  recordLlmCalls(inputs) {
41072
41446
  if (inputs.length === 0) return Promise.resolve();
41073
- return new Promise((resolve2, reject) => {
41447
+ return new Promise((resolve3, reject) => {
41074
41448
  try {
41075
41449
  this.db.auditEvents.runInTransaction(() => {
41076
41450
  for (const input2 of inputs) this.db.auditEvents.insertLlmCall(input2);
41077
41451
  });
41078
- resolve2();
41452
+ resolve3();
41079
41453
  } catch (err) {
41080
41454
  reject(err instanceof Error ? err : new Error(String(err)));
41081
41455
  }
@@ -41087,12 +41461,12 @@ var StandaloneDataGateway = class {
41087
41461
  // drops the whole pass and recovers it idempotently next time.
41088
41462
  recordToolCalls(inputs) {
41089
41463
  if (inputs.length === 0) return Promise.resolve();
41090
- return new Promise((resolve2, reject) => {
41464
+ return new Promise((resolve3, reject) => {
41091
41465
  try {
41092
41466
  this.db.auditEvents.runInTransaction(() => {
41093
41467
  for (const input2 of inputs) this.writeToolCall(input2);
41094
41468
  });
41095
- resolve2();
41469
+ resolve3();
41096
41470
  } catch (err) {
41097
41471
  reject(err instanceof Error ? err : new Error(String(err)));
41098
41472
  }
@@ -41633,7 +42007,7 @@ function pluginBuild() {
41633
42007
 
41634
42008
  // src/history/reconcile-trigger.ts
41635
42009
  import { spawn as spawn4 } from "child_process";
41636
- import { dirname as dirname6, join as join33 } from "path";
42010
+ import { dirname as dirname7, join as join34 } from "path";
41637
42011
  import { fileURLToPath as fileURLToPath5 } from "url";
41638
42012
 
41639
42013
  // src/history/tail.ts
@@ -41647,7 +42021,7 @@ import {
41647
42021
  readSync as readSync2,
41648
42022
  writeFileSync as writeFileSync8
41649
42023
  } from "fs";
41650
- import { join as join32 } from "path";
42024
+ import { join as join33 } from "path";
41651
42025
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
41652
42026
  function safeSessionId(sessionId) {
41653
42027
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
@@ -41663,8 +42037,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
41663
42037
  try {
41664
42038
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
41665
42039
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
41666
- const here = dirname6(fileURLToPath5(import.meta.url));
41667
- const child = spawn4(process.execPath, [join33(here, "reconcile.js"), sessionId, transcriptPath], {
42040
+ const here = dirname7(fileURLToPath5(import.meta.url));
42041
+ const child = spawn4(process.execPath, [join34(here, "reconcile.js"), sessionId, transcriptPath], {
41668
42042
  detached: true,
41669
42043
  stdio: "ignore"
41670
42044
  });
@@ -41676,7 +42050,7 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
41676
42050
  // src/history/transcripts.ts
41677
42051
  import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync22, readSync as readSync3, statSync as statSync10 } from "fs";
41678
42052
  import { homedir as homedir3 } from "os";
41679
- import { join as join34 } from "path";
42053
+ import { join as join35 } from "path";
41680
42054
  function isRecord(value) {
41681
42055
  return typeof value === "object" && value !== null;
41682
42056
  }
@@ -41716,14 +42090,14 @@ var DAY_MS5 = 24 * 60 * 60 * 1e3;
41716
42090
  // src/protocol/marker.ts
41717
42091
  import { randomBytes as randomBytes4 } from "crypto";
41718
42092
  import { mkdirSync as mkdirSync6, readFileSync as readFileSync23, renameSync as renameSync5, writeFileSync as writeFileSync9 } from "fs";
41719
- import { join as join35 } from "path";
42093
+ import { join as join36 } from "path";
41720
42094
  var MARKER_FILE = "protocol-marker";
41721
42095
  function mintMarker() {
41722
42096
  return randomBytes4(8).toString("hex");
41723
42097
  }
41724
42098
  function sessionProtocolMarker(dataDir2, sessionId) {
41725
42099
  if (!sessionId) return mintMarker();
41726
- const path = join35(dataDir2, MARKER_FILE);
42100
+ const path = join36(dataDir2, MARKER_FILE);
41727
42101
  try {
41728
42102
  const stored = JSON.parse(readFileSync23(path, "utf8"));
41729
42103
  if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
@@ -41734,7 +42108,7 @@ function sessionProtocolMarker(dataDir2, sessionId) {
41734
42108
  const marker = mintMarker();
41735
42109
  try {
41736
42110
  mkdirSync6(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
41737
- const tmp = join35(dataDir2, `${MARKER_FILE}.tmp`);
42111
+ const tmp = join36(dataDir2, `${MARKER_FILE}.tmp`);
41738
42112
  writeFileSync9(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
41739
42113
  renameSync5(tmp, path);
41740
42114
  } catch {
@@ -41750,7 +42124,7 @@ function standingBrief(opts) {
41750
42124
 
41751
42125
  // src/hooks/shared.ts
41752
42126
  async function readStdin() {
41753
- return new Promise((resolve2) => {
42127
+ return new Promise((resolve3) => {
41754
42128
  let data = "";
41755
42129
  let settled = false;
41756
42130
  const finish = () => {
@@ -41759,7 +42133,7 @@ async function readStdin() {
41759
42133
  clearTimeout(timer);
41760
42134
  process.stdin.removeListener("data", onData);
41761
42135
  process.stdin.removeListener("end", finish);
41762
- resolve2(data);
42136
+ resolve3(data);
41763
42137
  };
41764
42138
  const onData = (chunk) => {
41765
42139
  data += chunk;
@@ -41784,29 +42158,35 @@ function getString(record2, key) {
41784
42158
  return typeof value === "string" ? value : void 0;
41785
42159
  }
41786
42160
  function emit(output2) {
41787
- return new Promise((resolve2) => {
42161
+ return new Promise((resolve3) => {
41788
42162
  let settled = false;
41789
42163
  const finish = () => {
41790
42164
  if (settled) return;
41791
42165
  settled = true;
41792
- resolve2();
42166
+ resolve3();
41793
42167
  };
41794
42168
  process.stdout.on("error", finish);
41795
42169
  process.stdout.write(JSON.stringify(output2), finish);
41796
42170
  });
41797
42171
  }
42172
+ function countFailOpen(base) {
42173
+ try {
42174
+ recordHookFailOpen(dataDir(base), Date.now());
42175
+ } catch {
42176
+ }
42177
+ }
41798
42178
 
41799
42179
  // src/hooks/store-health.ts
41800
42180
  import { mkdirSync as mkdirSync7, readFileSync as readFileSync24, writeFileSync as writeFileSync10 } from "fs";
41801
- import { dirname as dirname7, join as join36 } from "path";
42181
+ import { dirname as dirname8, join as join37 } from "path";
41802
42182
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
41803
42183
  function markerDirs(dataDir2) {
41804
- return [dataDir2, dirname7(dataDir2)];
42184
+ return [dataDir2, dirname8(dataDir2)];
41805
42185
  }
41806
42186
  function alreadyClaimed(dirs, marker, sessionId) {
41807
42187
  return dirs.some((dir) => {
41808
42188
  try {
41809
- return readFileSync24(join36(dir, marker), "utf8") === sessionId;
42189
+ return readFileSync24(join37(dir, marker), "utf8") === sessionId;
41810
42190
  } catch {
41811
42191
  return false;
41812
42192
  }
@@ -41816,7 +42196,7 @@ function recordClaim(dirs, marker, sessionId) {
41816
42196
  for (const dir of dirs) {
41817
42197
  try {
41818
42198
  mkdirSync7(dir, { recursive: true, mode: DATA_DIR_MODE });
41819
- writeFileSync10(join36(dir, marker), sessionId, { mode: DATA_FILE_MODE });
42199
+ writeFileSync10(join37(dir, marker), sessionId, { mode: DATA_FILE_MODE });
41820
42200
  return;
41821
42201
  } catch {
41822
42202
  }
@@ -41841,7 +42221,7 @@ function formatMode(mode) {
41841
42221
  }
41842
42222
  function warnIfStoreRedirected(config2, sessionId, write = (message2) => void process.stderr.write(message2)) {
41843
42223
  try {
41844
- const paths = symlinkedStorePaths(dirname7(config2.dataDir));
42224
+ const paths = symlinkedStorePaths(dirname8(config2.dataDir));
41845
42225
  if (paths.length === 0) return;
41846
42226
  if (!sessionId) {
41847
42227
  write(storeRedirectedMessage(paths));
@@ -41908,5 +42288,6 @@ async function main() {
41908
42288
  try {
41909
42289
  await main();
41910
42290
  } catch {
42291
+ countFailOpen();
41911
42292
  }
41912
42293
  process.exit(0);