@akasecurity/ai-tc-codex 0.9.7 → 0.9.8

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.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH = "/";
53
+ var SLASH2 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH).filter(Boolean);
425
+ const slices = path.split(SLASH2).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH) + SLASH,
429
+ slices.join(SLASH2) + SLASH2,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH).filter(Boolean);
445
+ slices = path.split(SLASH2).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH) + SLASH,
452
+ slices.join(SLASH2) + SLASH2,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,16 +492,15 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/backfill.ts
495
- import { fileURLToPath as fileURLToPath2 } from "url";
495
+ import { fileURLToPath as fileURLToPath3 } from "url";
496
496
 
497
497
  // ../../packages/plugin-sdk/src/config.ts
498
- import { existsSync as existsSync5 } from "fs";
499
- import { join as join8 } from "path";
498
+ import { existsSync as existsSync6 } from "fs";
499
+ import { join as join10 } from "path";
500
500
 
501
- // ../../packages/persistence/src/database.ts
502
- import { randomUUID as randomUUID10 } from "crypto";
503
- import { join as join2, sep } from "path";
504
- import { DatabaseSync } from "node:sqlite";
501
+ // ../../packages/persistence/src/control-plane-credential.ts
502
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync2, statSync } from "fs";
503
+ import { join } from "path";
505
504
 
506
505
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
507
506
  var SQLITE_MIGRATIONS = [
@@ -16208,6 +16207,125 @@ var ConfigScanRecord = external_exports.object({
16208
16207
  findings: external_exports.array(ConfigPostureFindingInput).optional()
16209
16208
  });
16210
16209
 
16210
+ // ../../packages/schema/src/zod/control-plane.ts
16211
+ var ATTACHED_CREDENTIAL_FILENAME = "control-plane-credential.json";
16212
+ var ATTACHED_CREDENTIAL_SPEC_VERSION = 1;
16213
+ var AttachedCredential = external_exports.object({
16214
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SPEC_VERSION),
16215
+ // The control-plane endpoint this credential was minted against.
16216
+ endpoint: external_exports.string().min(1),
16217
+ // The bearer credential itself. Never logged, never rendered — status
16218
+ // surfaces show `keyPrefix` and nothing else.
16219
+ apiKey: external_exports.string().min(1),
16220
+ // First few characters of the key, safe to display so a user can match the
16221
+ // credential against their organization's key list.
16222
+ keyPrefix: external_exports.string().min(1).max(16).optional(),
16223
+ mintedAt: external_exports.iso.datetime().optional()
16224
+ });
16225
+ var MAX_DATE_MS = 253402300799999;
16226
+ var MAX_INT4 = 2147483647;
16227
+ var StorePosturePack = external_exports.object({
16228
+ packId: external_exports.string().min(1),
16229
+ // 'namespace/packId'
16230
+ version: external_exports.string().min(1),
16231
+ enabled: external_exports.boolean(),
16232
+ // Stringified pass-through of the local store's `installed_packs.updated_at`
16233
+ // — the column format is store-version-dependent (epoch millis vs ISO), so
16234
+ // the wire shape assumes neither.
16235
+ updatedAt: external_exports.string().nullable()
16236
+ }).meta({ id: "StorePosturePack" });
16237
+ var StorePosturePolicyCounts = external_exports.object({
16238
+ total: external_exports.number().int().min(0),
16239
+ disabled: external_exports.number().int().min(0),
16240
+ // Exhaustive per-action map; the builder pre-fills every action with 0.
16241
+ //
16242
+ // Spelled out member-by-member rather than `z.record(ActionTaken, …)`. Zod
16243
+ // enforces exhaustiveness either way, but z.record emits `propertyNames` +
16244
+ // `additionalProperties` into a generated schema document, and a type
16245
+ // generator renders THAT with every key optional — a sender built against
16246
+ // the generated type would typecheck and still be rejected at runtime. An
16247
+ // explicit object emits `properties` + `required`, so generated types
16248
+ // demand all five.
16249
+ //
16250
+ // `satisfies Record<ActionTaken, …>` keeps the link to the enum: adding an
16251
+ // ActionTaken member is a COMPILE error here instead of silent drift.
16252
+ // `.strict()` is load-bearing — it rejects an unknown action key, which a
16253
+ // bare object would silently STRIP, accepting a miscounted map as valid.
16254
+ byAction: external_exports.object({
16255
+ warn: external_exports.number().int().min(0),
16256
+ redact: external_exports.number().int().min(0),
16257
+ block: external_exports.number().int().min(0),
16258
+ allow: external_exports.number().int().min(0),
16259
+ log: external_exports.number().int().min(0)
16260
+ }).strict()
16261
+ }).meta({ id: "StorePosturePolicyCounts" });
16262
+ var StorePosturePlugin = external_exports.object({
16263
+ /** Package name of the reporting plugin. */
16264
+ package: external_exports.string().min(1).max(200),
16265
+ version: external_exports.string().min(1).max(64),
16266
+ /** Version of the bundled core, when the build records one separately. */
16267
+ ossVersion: external_exports.string().max(64).nullable(),
16268
+ /**
16269
+ * `version` of the policy bundle this machine last fetched. Bounded at 200
16270
+ * rather than the 64 a bare sha256 hex digest needs today, so a later
16271
+ * format with an algorithm prefix does not start rejecting the channel.
16272
+ */
16273
+ policyBundleVersion: external_exports.string().max(200).nullable(),
16274
+ /** Epoch millis, on the CLIENT clock, of that fetch. */
16275
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
16276
+ }).meta({ id: "StorePosturePlugin" });
16277
+ var StorePostureSnapshot = external_exports.object({
16278
+ deviceId: external_exports.guid(),
16279
+ hostname: external_exports.string().min(1).max(253),
16280
+ // Epoch millis on the CLIENT clock. Bounded by what a receiving store
16281
+ // accepts (see MAX_DATE_MS), not by what a JavaScript Date can hold.
16282
+ capturedAt: external_exports.number().int().min(0).max(MAX_DATE_MS),
16283
+ // False is a measurement, not an error state: "no local store exists on
16284
+ // this machine".
16285
+ storePresent: external_exports.boolean(),
16286
+ schemaVersion: external_exports.number().int().min(0).max(MAX_INT4).nullable(),
16287
+ // PRAGMA user_version
16288
+ findingsTotal: external_exports.number().int().min(0).max(MAX_INT4),
16289
+ // Epoch millis, bounded like `capturedAt` — see MAX_DATE_MS on what that
16290
+ // bound does and does not do. Worth stating for these two specifically:
16291
+ // they are read from the local store's own ROWS rather than from this
16292
+ // machine's clock, so a damaged or hand-edited store is enough to produce
16293
+ // an out-of-range value with no clock skew involved.
16294
+ findingsFirstAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16295
+ findingsLastAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16296
+ packs: external_exports.array(StorePosturePack).max(500),
16297
+ policyCounts: StorePosturePolicyCounts,
16298
+ // OPTIONAL, not nullable: a reporter that predates this member keeps
16299
+ // getting its 200 without a payload change.
16300
+ plugin: StorePosturePlugin.optional()
16301
+ }).meta({ id: "StorePostureSnapshot" });
16302
+ var CAPTURE_VERSION_PREFIX = "capture/";
16303
+ var RecordAuditEventRequest = AuditEventInput.extend({
16304
+ inspections: external_exports.array(ToolCallInspection).default([])
16305
+ }).refine((v) => v.inspections.every((i) => !i.ruleVersion.startsWith(CAPTURE_VERSION_PREFIX)), {
16306
+ message: `inspections[].ruleVersion must not start with \`${CAPTURE_VERSION_PREFIX}\` \u2014 that namespace is reserved for capture definitions the control plane mints itself`,
16307
+ path: ["inspections"]
16308
+ }).meta({ id: "RecordAuditEventRequest" });
16309
+ var IngestAck = external_exports.object({
16310
+ accepted: external_exports.number().int().nonnegative(),
16311
+ duplicates: external_exports.number().int().nonnegative()
16312
+ });
16313
+ var PRINTABLE = /^[^\p{Cc}\p{Cf}]*$/u;
16314
+ var printable = (max) => external_exports.string().max(max).regex(PRINTABLE, "must not contain control characters");
16315
+ var PluginWhoami = external_exports.object({
16316
+ tenantName: printable(200),
16317
+ userEmail: printable(320),
16318
+ role: printable(64),
16319
+ keyKind: printable(64),
16320
+ serverTime: printable(64)
16321
+ });
16322
+ var ControlPlaneErrorBody = external_exports.object({
16323
+ error: external_exports.object({
16324
+ code: external_exports.string().optional(),
16325
+ message: external_exports.string().optional()
16326
+ }).optional()
16327
+ });
16328
+
16211
16329
  // ../../packages/schema/src/zod/registry.ts
16212
16330
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
16213
16331
  var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -16510,15 +16628,15 @@ function summaryToDetectionListItem(s) {
16510
16628
  }
16511
16629
  function rowToDetectionDetail(row, findingsLast30d, update) {
16512
16630
  const rules = row.rules.flatMap((r) => {
16513
- const parsed = Matcher.safeParse(r.matcher);
16514
- if (!parsed.success) return [];
16631
+ const parsed2 = Matcher.safeParse(r.matcher);
16632
+ if (!parsed2.success) return [];
16515
16633
  return [
16516
16634
  {
16517
16635
  id: r.id,
16518
16636
  name: r.name,
16519
16637
  category: r.category,
16520
16638
  severity: r.severity,
16521
- matcher: parsed.data
16639
+ matcher: parsed2.data
16522
16640
  }
16523
16641
  ];
16524
16642
  });
@@ -17164,8 +17282,8 @@ function toApiAction(dbVal) {
17164
17282
  }
17165
17283
  function toApiCategory(dbVal) {
17166
17284
  if (dbVal === "code_context") return "source_code";
17167
- const parsed = FindingCategory.safeParse(dbVal);
17168
- return parsed.success ? parsed.data : "custom";
17285
+ const parsed2 = FindingCategory.safeParse(dbVal);
17286
+ return parsed2.success ? parsed2.data : "custom";
17169
17287
  }
17170
17288
  function toApiProvider(sourceTool) {
17171
17289
  return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
@@ -17795,6 +17913,9 @@ var WorkspaceSettings = external_exports.object({
17795
17913
  function defaultWorkspaceSettings() {
17796
17914
  return WorkspaceSettings.parse({});
17797
17915
  }
17916
+ function isAttached(settings) {
17917
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
17918
+ }
17798
17919
  function toInventoryRow(input, id, now) {
17799
17920
  return {
17800
17921
  id,
@@ -18062,8 +18183,8 @@ function builtinPolicyIsReversible(id) {
18062
18183
  return BUILTIN_POLICY_SPECS[id].reversible;
18063
18184
  }
18064
18185
  function policyIdIsReversible(policyId) {
18065
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18066
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18186
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18187
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18067
18188
  return builtinPolicyIsReversible(id);
18068
18189
  }
18069
18190
  var DEFAULT_ACTIONS = Object.fromEntries(
@@ -18074,8 +18195,8 @@ var BUILTIN_POLICIES = Object.fromEntries(
18074
18195
  );
18075
18196
  var DEFAULT_PACK_POLICY_ID = "monitor";
18076
18197
  function policyIdToAction(policyId) {
18077
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18078
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18198
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18199
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18079
18200
  return BUILTIN_POLICIES[id].action;
18080
18201
  }
18081
18202
  var UsedByItem = external_exports.object({
@@ -18518,53 +18639,6 @@ function reviewSeverityRank(reasons) {
18518
18639
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
18519
18640
  }
18520
18641
 
18521
- // ../../packages/persistence/src/ids.ts
18522
- import { createHash } from "crypto";
18523
- function sha256Hex(input) {
18524
- return createHash("sha256").update(input).digest("hex");
18525
- }
18526
- function inventoryId(objectType, identityKey) {
18527
- return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18528
- }
18529
- function sourceProjectId(url2) {
18530
- return sha256Hex(canonicalIdentity(["source_project", url2]));
18531
- }
18532
- function classifiedDataId(cls) {
18533
- return sha256Hex(canonicalIdentity(["classified_data", cls]));
18534
- }
18535
- function inspectionDefinitionId(ruleId, version2) {
18536
- return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18537
- }
18538
- function llmCallId(sessionId, messageId) {
18539
- return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18540
- }
18541
- function toolCallId(sessionId, toolUseId) {
18542
- return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18543
- }
18544
- function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18545
- return sha256Hex(
18546
- canonicalIdentity([
18547
- "inspection_finding",
18548
- auditEventId,
18549
- ruleId,
18550
- String(spanStart),
18551
- String(spanEnd)
18552
- ])
18553
- );
18554
- }
18555
- var NO_SESSION = "no_session";
18556
- var NO_PATH = "no_path";
18557
- function captureId(sessionId, contentHash, filePath = null) {
18558
- return sha256Hex(
18559
- canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18560
- );
18561
- }
18562
-
18563
- // ../../packages/persistence/src/internal/snapshot.ts
18564
- import { randomUUID } from "crypto";
18565
- import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync2, statSync } from "fs";
18566
- import { basename, dirname, join } from "path";
18567
-
18568
18642
  // ../../packages/persistence/src/paths.ts
18569
18643
  import {
18570
18644
  chmodSync,
@@ -18615,6 +18689,23 @@ function tightenPerms(file2) {
18615
18689
  function writeExclusiveOwnerOnlySync(file2, data) {
18616
18690
  writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
18617
18691
  }
18692
+ function writeOwnerOnlyFileSync(file2, data) {
18693
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
18694
+ try {
18695
+ rmSync(tmp, { force: true });
18696
+ } catch {
18697
+ }
18698
+ try {
18699
+ writeExclusiveOwnerOnlySync(tmp, data);
18700
+ renameSync(tmp, file2);
18701
+ } finally {
18702
+ try {
18703
+ rmSync(tmp, { force: true });
18704
+ } catch {
18705
+ }
18706
+ }
18707
+ tightenFile(file2);
18708
+ }
18618
18709
  function classifyOccupant(file2) {
18619
18710
  try {
18620
18711
  if (lstatSync(file2).isSymbolicLink()) return { kind: "symlink" };
@@ -18673,7 +18764,123 @@ function publishByLink(tmp, file2, data) {
18673
18764
  }
18674
18765
  }
18675
18766
 
18767
+ // ../../packages/persistence/src/control-plane-credential.ts
18768
+ function controlPlaneCredentialPath(settingsDir2) {
18769
+ return join(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
18770
+ }
18771
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
18772
+ function isSafeEndpoint(endpoint) {
18773
+ let parsed2;
18774
+ try {
18775
+ parsed2 = new URL(endpoint);
18776
+ } catch {
18777
+ return false;
18778
+ }
18779
+ if (parsed2.protocol === "https:") return true;
18780
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
18781
+ }
18782
+ function repairOrRefuseMode(file2) {
18783
+ const link = lstatSync2(file2, { throwIfNoEntry: false });
18784
+ if (link === void 0) return "absent";
18785
+ if (link.isSymbolicLink()) return "untrusted";
18786
+ const stat = statSync(file2, { throwIfNoEntry: false });
18787
+ if (stat === void 0) return "absent";
18788
+ const uid = process.getuid?.();
18789
+ if (uid !== void 0 && stat.uid !== uid) return "untrusted";
18790
+ if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
18791
+ try {
18792
+ chmodSync2(file2, DATA_FILE_MODE);
18793
+ } catch {
18794
+ return "untrusted";
18795
+ }
18796
+ }
18797
+ return "ok";
18798
+ }
18799
+ function readControlPlaneCredentialState(settingsDir2, connection) {
18800
+ const file2 = controlPlaneCredentialPath(settingsDir2);
18801
+ let raw;
18802
+ const gate = repairOrRefuseMode(file2);
18803
+ if (gate === "absent") return { usable: false, reason: "absent" };
18804
+ if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
18805
+ try {
18806
+ raw = readFileSync(file2, "utf8");
18807
+ } catch (err) {
18808
+ const code = err.code;
18809
+ return { usable: false, reason: code === "ENOENT" ? "absent" : "unreadable" };
18810
+ }
18811
+ let parsed2;
18812
+ try {
18813
+ parsed2 = JSON.parse(raw);
18814
+ } catch {
18815
+ return { usable: false, reason: "malformed" };
18816
+ }
18817
+ const result = AttachedCredential.safeParse(parsed2);
18818
+ if (!result.success) return { usable: false, reason: "malformed" };
18819
+ if (!isSafeEndpoint(result.data.endpoint)) {
18820
+ return { usable: false, reason: "unsafe-endpoint" };
18821
+ }
18822
+ if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
18823
+ return {
18824
+ usable: false,
18825
+ reason: "endpoint-mismatch",
18826
+ credentialEndpoint: result.data.endpoint,
18827
+ settingsEndpoint: connection.endpoint
18828
+ };
18829
+ }
18830
+ return { usable: true, credential: result.data };
18831
+ }
18832
+
18833
+ // ../../packages/persistence/src/database.ts
18834
+ import { randomUUID as randomUUID10 } from "crypto";
18835
+ import { join as join3, sep } from "path";
18836
+ import { DatabaseSync } from "node:sqlite";
18837
+
18838
+ // ../../packages/persistence/src/ids.ts
18839
+ import { createHash } from "crypto";
18840
+ function sha256Hex(input) {
18841
+ return createHash("sha256").update(input).digest("hex");
18842
+ }
18843
+ function inventoryId(objectType, identityKey) {
18844
+ return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18845
+ }
18846
+ function sourceProjectId(url2) {
18847
+ return sha256Hex(canonicalIdentity(["source_project", url2]));
18848
+ }
18849
+ function classifiedDataId(cls) {
18850
+ return sha256Hex(canonicalIdentity(["classified_data", cls]));
18851
+ }
18852
+ function inspectionDefinitionId(ruleId, version2) {
18853
+ return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18854
+ }
18855
+ function llmCallId(sessionId, messageId) {
18856
+ return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18857
+ }
18858
+ function toolCallId(sessionId, toolUseId) {
18859
+ return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18860
+ }
18861
+ function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18862
+ return sha256Hex(
18863
+ canonicalIdentity([
18864
+ "inspection_finding",
18865
+ auditEventId,
18866
+ ruleId,
18867
+ String(spanStart),
18868
+ String(spanEnd)
18869
+ ])
18870
+ );
18871
+ }
18872
+ var NO_SESSION = "no_session";
18873
+ var NO_PATH = "no_path";
18874
+ function captureId(sessionId, contentHash, filePath = null) {
18875
+ return sha256Hex(
18876
+ canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18877
+ );
18878
+ }
18879
+
18676
18880
  // ../../packages/persistence/src/internal/snapshot.ts
18881
+ import { randomUUID } from "crypto";
18882
+ import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync3, statSync as statSync2 } from "fs";
18883
+ import { basename, dirname, join as join2 } from "path";
18677
18884
  function backupPath(file2, tag) {
18678
18885
  return `${file2}.${tag}.${String(Date.now())}.${randomUUID().slice(0, 8)}.bak`;
18679
18886
  }
@@ -18683,15 +18890,15 @@ var STAGED_NAME_SUFFIX = `.bak${SNAPSHOT_STAGING_SUFFIX}`;
18683
18890
  var SNAPSHOT_STAGING_COPY = "copy";
18684
18891
  function createSnapshotStaging(backup) {
18685
18892
  const stage = `${backup}${SNAPSHOT_STAGING_SUFFIX}`;
18686
- rmSync2(stage, { recursive: true, force: true });
18893
+ rmSync3(stage, { recursive: true, force: true });
18687
18894
  mkdirOwnerOnlySync(stage);
18688
18895
  tightenDir(stage);
18689
- return { stage, copy: join(stage, SNAPSHOT_STAGING_COPY) };
18896
+ return { stage, copy: join2(stage, SNAPSHOT_STAGING_COPY) };
18690
18897
  }
18691
18898
  function idleMs(entry) {
18692
- for (const candidate of [join(entry, SNAPSHOT_STAGING_COPY), entry]) {
18899
+ for (const candidate of [join2(entry, SNAPSHOT_STAGING_COPY), entry]) {
18693
18900
  try {
18694
- return Date.now() - statSync(candidate).mtimeMs;
18901
+ return Date.now() - statSync2(candidate).mtimeMs;
18695
18902
  } catch {
18696
18903
  }
18697
18904
  }
@@ -18708,11 +18915,11 @@ function reapStalePartials(file2) {
18708
18915
  }
18709
18916
  for (const name of entries) {
18710
18917
  if (!name.startsWith(prefix) || !name.endsWith(STAGED_NAME_SUFFIX)) continue;
18711
- const staging = join(dir, name);
18918
+ const staging = join2(dir, name);
18712
18919
  try {
18713
18920
  const idle = idleMs(staging);
18714
18921
  if (idle !== null && idle > STALE_PARTIAL_MS) {
18715
- rmSync2(staging, { recursive: true, force: true });
18922
+ rmSync3(staging, { recursive: true, force: true });
18716
18923
  }
18717
18924
  } catch {
18718
18925
  }
@@ -18726,13 +18933,13 @@ function snapshotStore(db, backup) {
18726
18933
  renameSync2(copy, backup);
18727
18934
  } catch (error51) {
18728
18935
  try {
18729
- rmSync2(stage, { recursive: true, force: true });
18936
+ rmSync3(stage, { recursive: true, force: true });
18730
18937
  } catch {
18731
18938
  }
18732
18939
  throw error51;
18733
18940
  }
18734
18941
  try {
18735
- rmSync2(stage, { recursive: true, force: true });
18942
+ rmSync3(stage, { recursive: true, force: true });
18736
18943
  } catch {
18737
18944
  }
18738
18945
  }
@@ -18747,7 +18954,7 @@ function moveStoreAside(file2, backup) {
18747
18954
  renameSync2(sidecar, moved);
18748
18955
  undo.push([moved, sidecar]);
18749
18956
  } catch {
18750
- rmSync2(sidecar, { force: true });
18957
+ rmSync3(sidecar, { force: true });
18751
18958
  }
18752
18959
  }
18753
18960
  } catch (error51) {
@@ -18763,14 +18970,14 @@ function moveStoreAside(file2, backup) {
18763
18970
  }
18764
18971
  function discardStore(file2, backup) {
18765
18972
  try {
18766
- rmSync2(file2, { force: true });
18973
+ rmSync3(file2, { force: true });
18767
18974
  for (const sidecar of dbSidecars(file2)) {
18768
- rmSync2(sidecar, { force: true });
18975
+ rmSync3(sidecar, { force: true });
18769
18976
  }
18770
18977
  } catch (error51) {
18771
18978
  if (existsSync(file2)) {
18772
18979
  try {
18773
- rmSync2(backup, { force: true });
18980
+ rmSync3(backup, { force: true });
18774
18981
  } catch {
18775
18982
  }
18776
18983
  }
@@ -19002,10 +19209,31 @@ function applyMigrations(db, file2) {
19002
19209
  if (drained) applyLegacyDropMigration(db, file2);
19003
19210
  }
19004
19211
  }
19212
+ function readLegacyTables(db) {
19213
+ let holdsRows = false;
19214
+ const marks = [];
19215
+ for (const table of ["events", "findings"]) {
19216
+ try {
19217
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
19218
+ if (row === void 0) {
19219
+ holdsRows = true;
19220
+ marks.push(`${table}:unreadable`);
19221
+ continue;
19222
+ }
19223
+ if (row.n > 0) holdsRows = true;
19224
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
19225
+ } catch {
19226
+ holdsRows = true;
19227
+ marks.push(`${table}:unreadable`);
19228
+ }
19229
+ }
19230
+ return { holdsRows, mark: marks.join("|") };
19231
+ }
19005
19232
  function applyLegacyDropMigration(db, file2) {
19006
19233
  const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
19007
19234
  if (!migration) return;
19008
- if (file2) {
19235
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
19236
+ if (file2 !== void 0 && before?.holdsRows === true) {
19009
19237
  try {
19010
19238
  backupBeforeLegacyDrop(db, file2);
19011
19239
  } catch (error51) {
@@ -19019,6 +19247,12 @@ function applyLegacyDropMigration(db, file2) {
19019
19247
  () => {
19020
19248
  const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
19021
19249
  if (alreadyDropped) return;
19250
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
19251
+ akaWarn(
19252
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
19253
+ );
19254
+ return;
19255
+ }
19022
19256
  for (const statement of splitStatements(migration.sql)) {
19023
19257
  db.exec(statement);
19024
19258
  }
@@ -19373,8 +19607,8 @@ function safeJson(s, fallback) {
19373
19607
  function parseJsonObject(s) {
19374
19608
  if (s == null) return void 0;
19375
19609
  try {
19376
- const parsed = JSON.parse(s);
19377
- if (typeof parsed === "object" && parsed !== null) return parsed;
19610
+ const parsed2 = JSON.parse(s);
19611
+ if (typeof parsed2 === "object" && parsed2 !== null) return parsed2;
19378
19612
  } catch {
19379
19613
  }
19380
19614
  return void 0;
@@ -19385,16 +19619,16 @@ function encodeKeysetCursor(payload) {
19385
19619
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
19386
19620
  }
19387
19621
  function decodeKeysetCursor(cursor) {
19388
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19389
- if (parsed !== void 0 && "startedAtMs" in parsed && "id" in parsed && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19622
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19623
+ if (parsed2 !== void 0 && "startedAtMs" in parsed2 && "id" in parsed2 && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19390
19624
  // resumes from is epoch millis, and a payload carrying ±Infinity or a
19391
19625
  // fraction binds cleanly rather than failing — returning an EMPTY page with
19392
19626
  // a null cursor, which a caller reads as "end of list". That is the one
19393
19627
  // outcome a cursor that does not decode must never produce, since the
19394
19628
  // documented behaviour above is to restart from the top. (`1e999` is valid
19395
19629
  // JSON and parses to Infinity; a bare `NaN` is not, so it cannot arrive.)
19396
- Number.isInteger(parsed.startedAtMs) && typeof parsed.id === "string") {
19397
- return parsed;
19630
+ Number.isInteger(parsed2.startedAtMs) && typeof parsed2.id === "string") {
19631
+ return parsed2;
19398
19632
  }
19399
19633
  return null;
19400
19634
  }
@@ -19459,18 +19693,18 @@ var DB_EVENT_TYPE_TO_KIND = {
19459
19693
  };
19460
19694
  function safeParseStringArray(raw) {
19461
19695
  if (!raw) return [];
19462
- const parsed = safeJson(raw, null);
19463
- return Array.isArray(parsed) ? parsed : [];
19696
+ const parsed2 = safeJson(raw, null);
19697
+ return Array.isArray(parsed2) ? parsed2 : [];
19464
19698
  }
19465
19699
  var DEFAULT_HARNESS = HARNESS.ClaudeCode;
19466
19700
  function toHarness(raw) {
19467
- const parsed = Harness.safeParse(raw);
19468
- return parsed.success ? parsed.data : DEFAULT_HARNESS;
19701
+ const parsed2 = Harness.safeParse(raw);
19702
+ return parsed2.success ? parsed2.data : DEFAULT_HARNESS;
19469
19703
  }
19470
19704
  function resolveLifecycle(row, lastActivityMs, nowMs) {
19471
19705
  if (row.status) {
19472
- const parsed = SessionStatus.safeParse(row.status);
19473
- if (parsed.success) return { status: parsed.data, endedAtMs: row.ended_at };
19706
+ const parsed2 = SessionStatus.safeParse(row.status);
19707
+ if (parsed2.success) return { status: parsed2.data, endedAtMs: row.ended_at };
19474
19708
  }
19475
19709
  if (row.ended_at !== null) return { status: "completed", endedAtMs: row.ended_at };
19476
19710
  if (lastActivityMs >= nowMs - LIVE_ACTIVITY_WINDOW_MS) {
@@ -20429,9 +20663,9 @@ var SqliteDetectionsRepository = class {
20429
20663
  const ruleIds = /* @__PURE__ */ new Set();
20430
20664
  for (const r of rows) {
20431
20665
  if (intToBool(r.enabled)) active += 1;
20432
- const parsed = parseRules(r.rulesJson);
20433
- rules += parsed.length;
20434
- for (const rule of parsed) {
20666
+ const parsed2 = parseRules(r.rulesJson);
20667
+ rules += parsed2.length;
20668
+ for (const rule of parsed2) {
20435
20669
  if (typeof rule.id === "string") ruleIds.add(rule.id);
20436
20670
  }
20437
20671
  }
@@ -20965,12 +21199,12 @@ function encodeGroupCursor(group) {
20965
21199
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
20966
21200
  }
20967
21201
  function decodeGroupCursor(cursor) {
20968
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
20969
- if (parsed !== void 0 && typeof parsed.sev === "string" && typeof parsed.t === "string" && typeof parsed.id === "string") {
21202
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
21203
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.id === "string") {
20970
21204
  return {
20971
- severity: parsed.sev,
20972
- latestDetectedAt: parsed.t,
20973
- id: parsed.id
21205
+ severity: parsed2.sev,
21206
+ latestDetectedAt: parsed2.t,
21207
+ id: parsed2.id
20974
21208
  };
20975
21209
  }
20976
21210
  return null;
@@ -22104,16 +22338,16 @@ var SqliteInstalledPacksRepository = class {
22104
22338
  continue;
22105
22339
  }
22106
22340
  for (const entry of raw) {
22107
- const parsed = Rule.safeParse(entry);
22108
- if (parsed.success) {
22109
- out.rules.push(parsed.data);
22110
- out.ruleActions.set(parsed.data.id, action);
22111
- out.ruleVersions.set(parsed.data.id, row.version);
22112
- if (reversible) out.reversibleRules.add(parsed.data.id);
22113
- else out.reversibleRules.delete(parsed.data.id);
22341
+ const parsed2 = Rule.safeParse(entry);
22342
+ if (parsed2.success) {
22343
+ out.rules.push(parsed2.data);
22344
+ out.ruleActions.set(parsed2.data.id, action);
22345
+ out.ruleVersions.set(parsed2.data.id, row.version);
22346
+ if (reversible) out.reversibleRules.add(parsed2.data.id);
22347
+ else out.reversibleRules.delete(parsed2.data.id);
22114
22348
  } else {
22115
22349
  out.invalidRules += 1;
22116
- reject(pack, printableRuleId(entry), firstIssueReason(parsed.error));
22350
+ reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
22117
22351
  }
22118
22352
  }
22119
22353
  }
@@ -23503,15 +23737,15 @@ function encodeReuseCursor(payload) {
23503
23737
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
23504
23738
  }
23505
23739
  function decodeReuseCursor(cursor) {
23506
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23507
- if (parsed !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23740
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23741
+ if (parsed2 !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23508
23742
  // ±Infinity or a fraction binds cleanly and returns an EMPTY page with a
23509
23743
  // null cursor, which the caller reads as "end of list" — the one outcome a
23510
23744
  // malformed cursor must never produce, since restarting from the top is the
23511
23745
  // documented behaviour and the only recoverable one. (`1e999` is valid JSON
23512
23746
  // and parses to Infinity; a bare `NaN` is not, so it cannot arrive here.)
23513
- Number.isInteger(parsed.occurrences) && typeof parsed.pointerId === "string") {
23514
- return { occurrences: parsed.occurrences, pointerId: parsed.pointerId };
23747
+ Number.isInteger(parsed2.occurrences) && typeof parsed2.pointerId === "string") {
23748
+ return { occurrences: parsed2.occurrences, pointerId: parsed2.pointerId };
23515
23749
  }
23516
23750
  return null;
23517
23751
  }
@@ -25240,7 +25474,7 @@ function openAndInitialize(file2) {
25240
25474
  }
25241
25475
  function openLocalDatabase(dir) {
25242
25476
  ensureDataDirSync(dir);
25243
- const file2 = join2(dir, DB_FILENAME);
25477
+ const file2 = join3(dir, DB_FILENAME);
25244
25478
  reapStalePartials(file2);
25245
25479
  const {
25246
25480
  db,
@@ -25476,9 +25710,9 @@ import {
25476
25710
  closeSync,
25477
25711
  existsSync as existsSync2,
25478
25712
  openSync,
25479
- readFileSync,
25480
- rmSync as rmSync3,
25481
- statSync as statSync2,
25713
+ readFileSync as readFileSync2,
25714
+ rmSync as rmSync4,
25715
+ statSync as statSync3,
25482
25716
  writeFileSync as writeFileSync2
25483
25717
  } from "fs";
25484
25718
  import { hostname as hostname3 } from "os";
@@ -25496,20 +25730,20 @@ function computeFindingKey(input) {
25496
25730
 
25497
25731
  // ../../packages/persistence/src/fingerprint.ts
25498
25732
  import { createHmac, randomBytes } from "crypto";
25499
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
25500
- import { join as join3 } from "path";
25733
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
25734
+ import { join as join4 } from "path";
25501
25735
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25502
25736
  var EXCEPTION_KEY_FILENAME = "exception.key";
25503
25737
  var KEY_MATERIAL_BYTES = 32;
25504
25738
  function keyFilePath(dataDir2) {
25505
- return join3(dataDir2, EXCEPTION_KEY_FILENAME);
25739
+ return join4(dataDir2, EXCEPTION_KEY_FILENAME);
25506
25740
  }
25507
25741
  function parseKeyFile(raw) {
25508
- const parsed = JSON.parse(raw);
25509
- if (typeof parsed !== "object" || parsed === null) {
25742
+ const parsed2 = JSON.parse(raw);
25743
+ if (typeof parsed2 !== "object" || parsed2 === null) {
25510
25744
  throw new Error("exception key file is corrupt: not a JSON object");
25511
25745
  }
25512
- const { version: version2, material } = parsed;
25746
+ const { version: version2, material } = parsed2;
25513
25747
  if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
25514
25748
  throw new Error("exception key file is corrupt: bad version");
25515
25749
  }
@@ -25540,7 +25774,7 @@ var FloorUnreadableError = class extends Error {
25540
25774
  }
25541
25775
  };
25542
25776
  function storedKeyVersionFloor(dataDir2) {
25543
- const file2 = join3(dataDir2, DB_FILENAME);
25777
+ const file2 = join4(dataDir2, DB_FILENAME);
25544
25778
  if (!existsSync3(file2)) return 0;
25545
25779
  let db;
25546
25780
  try {
@@ -25595,7 +25829,7 @@ function occupantMessage(file2, kind) {
25595
25829
  function readFingerprintKey(dataDir2) {
25596
25830
  let raw;
25597
25831
  try {
25598
- raw = readFileSync2(keyFilePath(dataDir2), "utf8");
25832
+ raw = readFileSync3(keyFilePath(dataDir2), "utf8");
25599
25833
  } catch (err) {
25600
25834
  if (err.code === "ENOENT") return null;
25601
25835
  throw err instanceof Error ? err : new Error(String(err));
@@ -25621,18 +25855,22 @@ function fingerprintValue(key, raw) {
25621
25855
  import { renameSync as renameSync3 } from "fs";
25622
25856
  import { mkdir } from "fs/promises";
25623
25857
  import { homedir } from "os";
25624
- import { join as join4 } from "path";
25858
+ import { join as join5 } from "path";
25625
25859
  function defaultDataDir() {
25626
- return join4(homedir(), ".aka");
25860
+ return join5(homedir(), ".aka");
25627
25861
  }
25628
25862
  function settingsDir(base = defaultDataDir()) {
25629
- return join4(base, "settings");
25863
+ return join5(base, "settings");
25630
25864
  }
25631
25865
  function dataDir(base = defaultDataDir()) {
25632
- return join4(base, "data");
25866
+ return join5(base, "data");
25633
25867
  }
25634
25868
  function dbPath(base = defaultDataDir()) {
25635
- return join4(dataDir(base), "aka.db");
25869
+ return join5(dataDir(base), "aka.db");
25870
+ }
25871
+ async function ensureDataDir(dir = defaultDataDir()) {
25872
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
25873
+ tightenDir(dir);
25636
25874
  }
25637
25875
  function ensureLayoutDirSync(dir = defaultDataDir()) {
25638
25876
  ensureDataDirSync(dir);
@@ -25645,8 +25883,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25645
25883
  for (const { name, dest } of moves) {
25646
25884
  try {
25647
25885
  ensureDataDirSync(dest);
25648
- const moved = join4(dest, name);
25649
- renameSync3(join4(base, name), moved);
25886
+ const moved = join5(dest, name);
25887
+ renameSync3(join5(base, name), moved);
25650
25888
  tightenFile(moved);
25651
25889
  } catch {
25652
25890
  }
@@ -25654,7 +25892,7 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25654
25892
  }
25655
25893
 
25656
25894
  // ../../packages/persistence/src/managed-settings.ts
25657
- import { readFileSync as readFileSync3 } from "fs";
25895
+ import { readFileSync as readFileSync4 } from "fs";
25658
25896
  import { posix, win32 } from "path";
25659
25897
  function managedSettingsPaths(platform2 = process.platform) {
25660
25898
  if (platform2 === "darwin") {
@@ -25672,14 +25910,14 @@ function readManagedSettings(paths = managedSettingsPaths()) {
25672
25910
  for (const path of paths) {
25673
25911
  let text;
25674
25912
  try {
25675
- text = readFileSync3(path, "utf8");
25913
+ text = readFileSync4(path, "utf8");
25676
25914
  } catch {
25677
25915
  continue;
25678
25916
  }
25679
25917
  const record2 = parseJsonObject(text);
25680
25918
  if (!record2) continue;
25681
- const parsed = ManagedSettings.safeParse(record2);
25682
- if (parsed.success) return parsed.data;
25919
+ const parsed2 = ManagedSettings.safeParse(record2);
25920
+ if (parsed2.success) return parsed2.data;
25683
25921
  }
25684
25922
  return null;
25685
25923
  }
@@ -25719,14 +25957,14 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
25719
25957
  }
25720
25958
 
25721
25959
  // ../../packages/persistence/src/settings.ts
25722
- import { readFileSync as readFileSync4 } from "fs";
25723
- import { join as join5 } from "path";
25960
+ import { readFileSync as readFileSync5 } from "fs";
25961
+ import { join as join6 } from "path";
25724
25962
  var SETTINGS_FILENAME = "settings.json";
25725
25963
  function readWorkspaceSettings(base = defaultDataDir()) {
25726
25964
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
25727
25965
  }
25728
25966
  function readUserSettings(base) {
25729
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
25967
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
25730
25968
  if (!record2) return defaultWorkspaceSettings();
25731
25969
  try {
25732
25970
  return WorkspaceSettings.parse(record2);
@@ -25737,13 +25975,17 @@ function readUserSettings(base) {
25737
25975
  function readJson(file2) {
25738
25976
  let text;
25739
25977
  try {
25740
- text = readFileSync4(file2, "utf8");
25978
+ text = readFileSync5(file2, "utf8");
25741
25979
  } catch {
25742
25980
  return null;
25743
25981
  }
25744
25982
  return parseJsonObject(text) ?? null;
25745
25983
  }
25746
25984
 
25985
+ // ../../packages/persistence/src/store-symlinks.ts
25986
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
25987
+ import { dirname as dirname2, join as join7, resolve } from "path";
25988
+
25747
25989
  // ../../packages/persistence/src/vault/crypto.ts
25748
25990
  import {
25749
25991
  createCipheriv,
@@ -25756,20 +25998,20 @@ import {
25756
25998
  // ../../packages/persistence/src/vault/key-provider.ts
25757
25999
  import { execFileSync } from "child_process";
25758
26000
  import { randomBytes as randomBytes2 } from "crypto";
25759
- import { chmodSync as chmodSync2, readFileSync as readFileSync5, renameSync as renameSync4, rmSync as rmSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
25760
- import { join as join6 } from "path";
26001
+ import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
26002
+ import { join as join8 } from "path";
25761
26003
 
25762
26004
  // ../../packages/persistence/src/vault/vault.ts
25763
26005
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
25764
26006
 
25765
26007
  // ../../packages/persistence/src/warn-era-cap.ts
25766
- import { existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
25767
- import { join as join7 } from "path";
26008
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
26009
+ import { join as join9 } from "path";
25768
26010
  var MARKER = "warn-era-capped";
25769
26011
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25770
26012
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
25771
- const marker = join7(dataDir2, MARKER);
25772
- if (existsSync4(marker)) return { capped: 0, skipped: "already-run" };
26013
+ const marker = join9(dataDir2, MARKER);
26014
+ if (existsSync5(marker)) return { capped: 0, skipped: "already-run" };
25773
26015
  const capped = db.policies.capCategoryActions();
25774
26016
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
25775
26017
  `, { mode: DATA_FILE_MODE });
@@ -25810,8 +26052,8 @@ function hostOf(url2) {
25810
26052
  }
25811
26053
  }
25812
26054
  function resolveProvider() {
25813
- const parsed = ProviderEnvSchema.safeParse(process.env);
25814
- const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
26055
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
26056
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
25815
26057
  if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
25816
26058
  if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
25817
26059
  const baseUrl = env.ANTHROPIC_BASE_URL;
@@ -25828,8 +26070,8 @@ function resolveProvider() {
25828
26070
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
25829
26071
  try {
25830
26072
  ensureLayoutDirSync(base);
25831
- const settingsFile = join8(settingsDir(base), "settings.json");
25832
- if (existsSync5(settingsFile)) tightenFile(settingsFile);
26073
+ const settingsFile = join10(settingsDir(base), "settings.json");
26074
+ if (existsSync6(settingsFile)) tightenFile(settingsFile);
25833
26075
  } catch {
25834
26076
  }
25835
26077
  migrateLegacyLayout(base);
@@ -25852,9 +26094,9 @@ function resolveProviderSafe(resolveProviderFn) {
25852
26094
  }
25853
26095
 
25854
26096
  // ../../packages/plugin-sdk/src/config-inventory.ts
25855
- import { readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync, statSync as statSync5 } from "fs";
26097
+ import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
25856
26098
  import { homedir as homedir2 } from "os";
25857
- import { basename as basename3, join as join10 } from "path";
26099
+ import { basename as basename3, join as join12 } from "path";
25858
26100
 
25859
26101
  // ../../packages/detections/src/egress/registry.ts
25860
26102
  var EXTRACTOR_VERSION = "1";
@@ -27631,10 +27873,10 @@ var localhost_ref_default = {
27631
27873
  severity: "low",
27632
27874
  matcher: {
27633
27875
  type: "regex",
27634
- pattern: "\\b(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1)\\b",
27876
+ pattern: "(?<![A-Za-z0-9_])(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|(?<![A-Za-z0-9_]\\[)::1(?!:|\\.[0-9]))(?![A-Za-z0-9_])",
27635
27877
  flags: "g"
27636
27878
  },
27637
- examples: ["localhost", "127.0.0.1"]
27879
+ examples: ["localhost", "127.0.0.1", "0.0.0.0", "::1"]
27638
27880
  };
27639
27881
 
27640
27882
  // ../../rules/core-code-context/stack-trace.json
@@ -28985,8 +29227,8 @@ function scanText(text, ruleVersions) {
28985
29227
  }
28986
29228
 
28987
29229
  // ../../packages/plugin-sdk/src/repo.ts
28988
- import { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync4 } from "fs";
28989
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join9, sep as sep2 } from "path";
29230
+ import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
29231
+ import { basename as basename2, dirname as dirname3, isAbsolute, join as join11, sep as sep2 } from "path";
28990
29232
  function resolveRepoIdentity(cwd) {
28991
29233
  try {
28992
29234
  const root = findGitRoot(cwd);
@@ -29008,36 +29250,36 @@ function resolveRepoIdentity(cwd) {
29008
29250
  function findGitRoot(start) {
29009
29251
  let dir = start;
29010
29252
  for (; ; ) {
29011
- if (existsSync6(join9(dir, ".git"))) return dir;
29012
- const parent = dirname2(dir);
29253
+ if (existsSync7(join11(dir, ".git"))) return dir;
29254
+ const parent = dirname3(dir);
29013
29255
  if (parent === dir) return void 0;
29014
29256
  dir = parent;
29015
29257
  }
29016
29258
  }
29017
29259
  function resolveGitContext(root) {
29018
- const dotGit = join9(root, ".git");
29260
+ const dotGit = join11(root, ".git");
29019
29261
  try {
29020
- if (statSync4(dotGit).isDirectory()) {
29021
- return { configPath: join9(dotGit, "config"), headRoot: root };
29262
+ if (statSync6(dotGit).isDirectory()) {
29263
+ return { configPath: join11(dotGit, "config"), headRoot: root };
29022
29264
  }
29023
29265
  } catch {
29024
29266
  return void 0;
29025
29267
  }
29026
29268
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
29027
29269
  if (!target) return void 0;
29028
- const gitdir = isAbsolute(target) ? target : join9(root, target);
29029
- if (existsSync6(join9(gitdir, "config"))) {
29030
- return { configPath: join9(gitdir, "config"), headRoot: root };
29270
+ const gitdir = isAbsolute(target) ? target : join11(root, target);
29271
+ if (existsSync7(join11(gitdir, "config"))) {
29272
+ return { configPath: join11(gitdir, "config"), headRoot: root };
29031
29273
  }
29032
- const commonRaw = safeRead(join9(gitdir, "commondir"))?.trim();
29274
+ const commonRaw = safeRead(join11(gitdir, "commondir"))?.trim();
29033
29275
  if (!commonRaw) return void 0;
29034
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join9(gitdir, commonRaw);
29035
- const headRoot = basename2(commonGitDir) === ".git" ? dirname2(commonGitDir) : root;
29036
- return { configPath: join9(commonGitDir, "config"), headRoot };
29276
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join11(gitdir, commonRaw);
29277
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
29278
+ return { configPath: join11(commonGitDir, "config"), headRoot };
29037
29279
  }
29038
29280
  function safeRead(path) {
29039
29281
  try {
29040
- return readFileSync6(path, "utf8");
29282
+ return readFileSync7(path, "utf8");
29041
29283
  } catch {
29042
29284
  return void 0;
29043
29285
  }
@@ -29098,7 +29340,7 @@ function buildIngestEvent(input) {
29098
29340
  }
29099
29341
 
29100
29342
  // ../../packages/plugin-sdk/src/isolated-scan.ts
29101
- import { existsSync as existsSync7 } from "fs";
29343
+ import { existsSync as existsSync8 } from "fs";
29102
29344
  import { fileURLToPath } from "url";
29103
29345
  import { Worker } from "worker_threads";
29104
29346
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -29112,7 +29354,7 @@ function resolveWorkerUrl() {
29112
29354
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
29113
29355
  const candidate = new URL(name, import.meta.url);
29114
29356
  try {
29115
- if (existsSync7(fileURLToPath(candidate))) {
29357
+ if (existsSync8(fileURLToPath(candidate))) {
29116
29358
  resolvedWorkerUrl = candidate;
29117
29359
  return candidate;
29118
29360
  }
@@ -29297,8 +29539,8 @@ function createIsolatedScanner(data, opts = {}) {
29297
29539
  }
29298
29540
  function enqueue(spec) {
29299
29541
  const next = chain.then(
29300
- () => new Promise((resolve) => {
29301
- spec(resolve);
29542
+ () => new Promise((resolve2) => {
29543
+ spec(resolve2);
29302
29544
  })
29303
29545
  );
29304
29546
  chain = next.then(
@@ -29309,7 +29551,7 @@ function createIsolatedScanner(data, opts = {}) {
29309
29551
  }
29310
29552
  return {
29311
29553
  scan(text, context, scanOpts) {
29312
- return enqueue((resolve) => {
29554
+ return enqueue((resolve2) => {
29313
29555
  runOne(
29314
29556
  {
29315
29557
  budgetMs,
@@ -29322,23 +29564,23 @@ function createIsolatedScanner(data, opts = {}) {
29322
29564
  }),
29323
29565
  reply: (message) => {
29324
29566
  if (message.kind !== "result") return false;
29325
- resolve({ status: "ok", findings: message.findings });
29567
+ resolve2({ status: "ok", findings: message.findings });
29326
29568
  return true;
29327
29569
  }
29328
29570
  },
29329
- resolve
29571
+ resolve2
29330
29572
  );
29331
29573
  });
29332
29574
  },
29333
29575
  probe(rule) {
29334
- return enqueue((resolve) => {
29576
+ return enqueue((resolve2) => {
29335
29577
  runOne(
29336
29578
  {
29337
29579
  budgetMs: probeBudgetMs,
29338
29580
  build: (id) => ({ kind: "probe", id, rule }),
29339
29581
  reply: (message) => {
29340
29582
  if (message.kind !== "probed") return false;
29341
- resolve({
29583
+ resolve2({
29342
29584
  status: "ok",
29343
29585
  verdict: message.verdict,
29344
29586
  worstMs: message.worstMs,
@@ -29347,7 +29589,7 @@ function createIsolatedScanner(data, opts = {}) {
29347
29589
  return true;
29348
29590
  }
29349
29591
  },
29350
- resolve
29592
+ resolve2
29351
29593
  );
29352
29594
  });
29353
29595
  },
@@ -29577,8 +29819,8 @@ function createGuardedScanner(partition, gateway, opts) {
29577
29819
 
29578
29820
  // ../../packages/plugin-sdk/src/ignore-layers.ts
29579
29821
  var import_ignore = __toESM(require_ignore(), 1);
29580
- import { readFileSync as readFileSync8 } from "fs";
29581
- import { join as join11 } from "path";
29822
+ import { readFileSync as readFileSync9 } from "fs";
29823
+ import { join as join13 } from "path";
29582
29824
 
29583
29825
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
29584
29826
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -29610,16 +29852,16 @@ function resolveInventoryContext(input) {
29610
29852
  }
29611
29853
 
29612
29854
  // ../../packages/plugin-sdk/src/nudge.ts
29613
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
29614
- import { join as join12 } from "path";
29855
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
29856
+ import { join as join14 } from "path";
29615
29857
 
29616
29858
  // ../../packages/plugin-sdk/src/paths.ts
29617
- import { readdirSync as readdirSync3, realpathSync as realpathSync2 } from "fs";
29618
- import { basename as basename4, dirname as dirname3, sep as sep3 } from "path";
29859
+ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
29860
+ import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
29619
29861
 
29620
29862
  // ../../packages/plugin-sdk/src/project-files.ts
29621
- import { existsSync as existsSync8, readdirSync as readdirSync4 } from "fs";
29622
- import { basename as basename5, join as join13 } from "path";
29863
+ import { existsSync as existsSync9, readdirSync as readdirSync4 } from "fs";
29864
+ import { basename as basename5, join as join15 } from "path";
29623
29865
 
29624
29866
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
29625
29867
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -30040,12 +30282,12 @@ function createPluginRuntime(gateway, settings, opts) {
30040
30282
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
30041
30283
 
30042
30284
  // ../../packages/plugin-sdk/src/throttle.ts
30043
- import { mkdirSync as mkdirSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
30044
- import { join as join14 } from "path";
30285
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
30286
+ import { join as join16 } from "path";
30045
30287
 
30046
30288
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
30047
30289
  import { writeFileSync as writeFileSync7 } from "fs";
30048
- import { join as join15 } from "path";
30290
+ import { join as join17 } from "path";
30049
30291
 
30050
30292
  // ../../packages/setup-wizard/src/triage/merge.ts
30051
30293
  var RANK = Object.fromEntries(
@@ -30053,9 +30295,9 @@ var RANK = Object.fromEntries(
30053
30295
  );
30054
30296
 
30055
30297
  // ../../packages/setup-wizard/src/triage/plan-file.ts
30056
- import { mkdtempSync, readFileSync as readFileSync10, rmdirSync, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "fs";
30298
+ import { mkdtempSync, readFileSync as readFileSync11, rmdirSync, rmSync as rmSync6, writeFileSync as writeFileSync8 } from "fs";
30057
30299
  import { tmpdir } from "os";
30058
- import { basename as basename6, dirname as dirname4, join as join16 } from "path";
30300
+ import { basename as basename6, dirname as dirname5, join as join18 } from "path";
30059
30301
  var SuppressionEntrySchema = external_exports.object({
30060
30302
  ruleId: external_exports.string(),
30061
30303
  category: DetectionCategory,
@@ -30099,8 +30341,1198 @@ var PersistedPlanSchema = external_exports.object({
30099
30341
  // ../../packages/setup-wizard/src/triage/writeback.ts
30100
30342
  var TRIAGE_STATUSES = ["complete", "complete:no-history", "skipped:no-consent"];
30101
30343
 
30102
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
30344
+ // ../../packages/plugin-runtime/src/attached/failure.ts
30345
+ function statusOf(err) {
30346
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
30347
+ const { status } = err;
30348
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
30349
+ return status >= 100 && status <= 599 ? status : null;
30350
+ }
30351
+ function classifyFailure(err) {
30352
+ switch (statusOf(err)) {
30353
+ case 401:
30354
+ return "unauthorized";
30355
+ case 403:
30356
+ return "forbidden";
30357
+ default:
30358
+ return "unreachable";
30359
+ }
30360
+ }
30361
+
30362
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
30363
+ import { readFileSync as readFileSync12 } from "fs";
30364
+ import { join as join19 } from "path";
30365
+ var FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
30366
+ function forwardDropsPath(dataDir2) {
30367
+ return join19(dataDir2, FORWARD_DROPS_FILENAME);
30368
+ }
30369
+ function recordForwardDrops(dataDir2, count, nowMs) {
30370
+ if (count <= 0) return;
30371
+ try {
30372
+ ensureDataDirSync(dataDir2);
30373
+ const previous = readForwardDrops(dataDir2);
30374
+ const next = {
30375
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
30376
+ lastDropAtMs: nowMs
30377
+ };
30378
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
30379
+ `);
30380
+ } catch {
30381
+ }
30382
+ }
30383
+ function readForwardDrops(dataDir2) {
30384
+ try {
30385
+ const parsed2 = JSON.parse(readFileSync12(forwardDropsPath(dataDir2), "utf8"));
30386
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30387
+ const record2 = parsed2;
30388
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
30389
+ return null;
30390
+ }
30391
+ if (record2.droppedForwards <= 0) return null;
30392
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
30393
+ return null;
30394
+ }
30395
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
30396
+ } catch {
30397
+ return null;
30398
+ }
30399
+ }
30400
+
30401
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30103
30402
  import { randomUUID as randomUUID15 } from "crypto";
30403
+ import { readFileSync as readFileSync13 } from "fs";
30404
+ import { readFile, rename, writeFile } from "fs/promises";
30405
+ import { join as join20 } from "path";
30406
+
30407
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
30408
+ var REQUEST_TIMEOUT_MS = 2e3;
30409
+ function withTimeout(promise2, ms) {
30410
+ let timer;
30411
+ const timeout = new Promise((_, reject) => {
30412
+ timer = setTimeout(() => {
30413
+ reject(new Error("attached gateway request timed out"));
30414
+ }, ms);
30415
+ });
30416
+ promise2.catch(() => void 0);
30417
+ return Promise.race([promise2, timeout]).finally(() => {
30418
+ clearTimeout(timer);
30419
+ });
30420
+ }
30421
+
30422
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30423
+ function isInvalidRequest(err) {
30424
+ return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
30425
+ }
30426
+ var FORWARD_BUDGET_MS = 1500;
30427
+ var DECISION_PATH_BUDGET_MS = 800;
30428
+ var BREAKER_FAILURE_THRESHOLD = 3;
30429
+ var BREAKER_COOLDOWN_MS = 3e4;
30430
+ var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
30431
+ var FAILURES = /* @__PURE__ */ new Set([
30432
+ "unauthorized",
30433
+ "forbidden",
30434
+ "unreachable"
30435
+ ]);
30436
+ var FORWARD_STATE_FILENAME = "attached-state.json";
30437
+ var STATE_FILENAME = FORWARD_STATE_FILENAME;
30438
+ function parseBreakerState(raw, nowMs) {
30439
+ try {
30440
+ const parsed2 = JSON.parse(raw);
30441
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30442
+ const record2 = parsed2;
30443
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
30444
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
30445
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
30446
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
30447
+ } catch {
30448
+ return null;
30449
+ }
30450
+ }
30451
+ function createForwardPolicy(deps) {
30452
+ const now = deps.now ?? (() => Date.now());
30453
+ const file2 = join20(deps.dir, STATE_FILENAME);
30454
+ let state = null;
30455
+ let loading = null;
30456
+ async function readState() {
30457
+ let raw;
30458
+ try {
30459
+ raw = await readFile(file2, "utf8");
30460
+ } catch {
30461
+ return { ...CLOSED };
30462
+ }
30463
+ return parseBreakerState(raw, now()) ?? { ...CLOSED };
30464
+ }
30465
+ async function load() {
30466
+ if (state !== null) return state;
30467
+ loading ??= readState().then((loaded) => {
30468
+ state = loaded;
30469
+ loading = null;
30470
+ return loaded;
30471
+ });
30472
+ return loading;
30473
+ }
30474
+ async function persist(next) {
30475
+ state = next;
30476
+ try {
30477
+ await ensureDataDir(deps.dir);
30478
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
30479
+ await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
30480
+ await rename(tmp, file2);
30481
+ } catch {
30482
+ }
30483
+ }
30484
+ return {
30485
+ async run(op, opts) {
30486
+ const budget = opts?.decisionPath === true ? DECISION_PATH_BUDGET_MS : FORWARD_BUDGET_MS;
30487
+ let current;
30488
+ try {
30489
+ current = await load();
30490
+ } catch {
30491
+ current = { ...CLOSED };
30492
+ }
30493
+ const at = now();
30494
+ if (current.openedAtMs !== null) {
30495
+ if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
30496
+ return { ok: false, reason: "breaker-open" };
30497
+ }
30498
+ await persist({
30499
+ consecutiveFailures: current.consecutiveFailures,
30500
+ openedAtMs: at,
30501
+ lastFailure: current.lastFailure
30502
+ });
30503
+ }
30504
+ try {
30505
+ const value = await withTimeout(op(), budget);
30506
+ if (current.openedAtMs !== null || current.consecutiveFailures > 0) {
30507
+ await persist({ ...CLOSED });
30508
+ }
30509
+ return { ok: true, value };
30510
+ } catch (err) {
30511
+ if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
30512
+ const reason = classifyFailure(err);
30513
+ const failures = current.consecutiveFailures + 1;
30514
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
30515
+ await persist({
30516
+ consecutiveFailures: failures,
30517
+ openedAtMs: shouldOpen ? now() : null,
30518
+ lastFailure: reason
30519
+ });
30520
+ return { ok: false, reason };
30521
+ }
30522
+ }
30523
+ };
30524
+ }
30525
+
30526
+ // ../../packages/plugin-runtime/src/attached/gateway.ts
30527
+ var ACTION_STRENGTH = {
30528
+ allow: 0,
30529
+ log: 1,
30530
+ warn: 2,
30531
+ redact: 3,
30532
+ block: 4
30533
+ };
30534
+ function ruleCategoryMap(wireRules, localRules) {
30535
+ const map2 = /* @__PURE__ */ new Map();
30536
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
30537
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
30538
+ for (const pack of bundledDetections()) {
30539
+ for (const rule of pack.rules) map2.set(rule.id, rule.category);
30540
+ }
30541
+ return map2;
30542
+ }
30543
+ function strongerOf(a, b) {
30544
+ if (a === null) return b;
30545
+ if (b === null) return a;
30546
+ return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
30547
+ }
30548
+ function policyKey(policy) {
30549
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
30550
+ }
30551
+ function floorFor(policy, categoryByRuleId) {
30552
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
30553
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
30554
+ }
30555
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
30556
+ const merged = /* @__PURE__ */ new Map();
30557
+ const disabled = [];
30558
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
30559
+ for (const policy of remotePolicies) {
30560
+ if (!policy.enabled) continue;
30561
+ if (!("category" in policy.target)) continue;
30562
+ if (remoteCategoryAction.has(policy.target.category)) continue;
30563
+ const floor = floorFor(policy, categoryByRuleId);
30564
+ remoteCategoryAction.set(
30565
+ policy.target.category,
30566
+ floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
30567
+ );
30568
+ }
30569
+ for (const policy of localPolicies) {
30570
+ if (!policy.enabled) {
30571
+ disabled.push(policy);
30572
+ continue;
30573
+ }
30574
+ const key = policyKey(policy);
30575
+ if (merged.has(key)) continue;
30576
+ let remoteFloor = null;
30577
+ if ("ruleId" in policy.target) {
30578
+ const category = categoryByRuleId.get(policy.target.ruleId);
30579
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
30580
+ }
30581
+ merged.set(
30582
+ key,
30583
+ remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
30584
+ );
30585
+ }
30586
+ const localCategoryAction = /* @__PURE__ */ new Map();
30587
+ for (const policy of merged.values()) {
30588
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
30589
+ }
30590
+ for (const policy of remotePolicies) {
30591
+ if (!policy.enabled) {
30592
+ disabled.push(policy);
30593
+ continue;
30594
+ }
30595
+ const key = policyKey(policy);
30596
+ const floor = floorFor(policy, categoryByRuleId);
30597
+ let localFloor = null;
30598
+ if ("ruleId" in policy.target) {
30599
+ const category = categoryByRuleId.get(policy.target.ruleId);
30600
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
30601
+ }
30602
+ const effectiveFloor = strongerOf(floor, localFloor);
30603
+ const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
30604
+ const existing = merged.get(key);
30605
+ if (existing === void 0) {
30606
+ merged.set(key, clamped);
30607
+ continue;
30608
+ }
30609
+ if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
30610
+ merged.set(key, clamped);
30611
+ }
30612
+ }
30613
+ return [...merged.values(), ...disabled];
30614
+ }
30615
+ var AttachedDataGateway = class {
30616
+ constructor(deps) {
30617
+ this.deps = deps;
30618
+ }
30619
+ deps;
30620
+ /**
30621
+ * The control plane's OWN resolution of this session's inventory, captured by
30622
+ * ensureInventory. Null until the first successful forward — and it stays
30623
+ * null for the whole session when the control plane is unreachable, which is fine:
30624
+ * reKeyForForward then leaves the event's ids alone and the control plane resolves
30625
+ * what it can from the descriptors it already has.
30626
+ */
30627
+ remoteInventory = null;
30628
+ // ---------------------------------------------------------------------
30629
+ // Writes: local first, then forward.
30630
+ // ---------------------------------------------------------------------
30631
+ async recordCapture(record2) {
30632
+ await this.deps.local.recordCapture(record2);
30633
+ await this.deps.forward.run(
30634
+ () => this.deps.client.ingestEvents({
30635
+ events: [record2.event],
30636
+ ...record2.dedupe ? { dedupe: record2.dedupe } : {}
30637
+ }),
30638
+ { decisionPath: true }
30639
+ );
30640
+ }
30641
+ async ensureInventory(ctx) {
30642
+ const resolved = await this.deps.local.ensureInventory(ctx);
30643
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
30644
+ this.remoteInventory = remote.ok ? remote.value : null;
30645
+ const snapshot = await (async () => {
30646
+ try {
30647
+ return await this.deps.posture?.prepare() ?? null;
30648
+ } catch {
30649
+ return null;
30650
+ }
30651
+ })();
30652
+ if (snapshot) {
30653
+ try {
30654
+ await withTimeout(
30655
+ this.deps.posture?.send(snapshot) ?? Promise.resolve(),
30656
+ REQUEST_TIMEOUT_MS
30657
+ );
30658
+ } catch {
30659
+ }
30660
+ }
30661
+ return resolved;
30662
+ }
30663
+ // The id is minted CLIENT-side and stored verbatim: the control plane does NOT
30664
+ // re-key it. `pgAuditValues` writes `id: event.id` and carries tenancy in
30665
+ // its own scoping columns, so the device and the forwarded copy
30666
+ // share one id space — which is what makes a re-post idempotent at all.
30667
+ //
30668
+ // Re-posts collapse via `onConflictDoUpdate` on the `id` PK, guarded by
30669
+ // `setWhere eventType = 'session'` (NOT onConflictDoNothing). That guard is
30670
+ // what makes an attached retry safe: a capture-stubbed session row can still
30671
+ // be HEALED by the authoritative root, while a duplicate non-session event —
30672
+ // a retried tool_call, exactly this path — can never stomp a populated row.
30673
+ async recordAuditEvent(event) {
30674
+ await this.deps.local.recordAuditEvent(event);
30675
+ await this.deps.forward.run(
30676
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
30677
+ );
30678
+ }
30679
+ // Attached `llm_call` is written locally by the inner gateway, then routed to
30680
+ // the control plane through the existing `recordAuditEvent` ingest (no dedicated
30681
+ // client method yet) by pre-building the audit event from the natural key.
30682
+ // The forward goes DIRECTLY to the client rather than through this.recordAuditEvent,
30683
+ // which would write the event to the local store a second time.
30684
+ async recordLlmCall(input) {
30685
+ await this.deps.local.recordLlmCall(input);
30686
+ await this.deps.forward.run(
30687
+ () => this.deps.client.recordAuditEvent(
30688
+ reKeyForForward(llmAuditEvent(input), this.remoteInventory)
30689
+ )
30690
+ );
30691
+ }
30692
+ /**
30693
+ * Forward one batch, item by item, under ONE aggregate deadline.
30694
+ *
30695
+ * Per-item budgets bound each request and nothing bounded their sum — see
30696
+ * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
30697
+ * rather than sent: the local write has already succeeded, so every caller
30698
+ * has a correct result to return, and a drop is the outcome this path is
30699
+ * built to accept (G8) where a blown hook timeout is not.
30700
+ *
30701
+ * Serial rather than concurrent on purpose. Firing N requests at once would
30702
+ * trade a latency problem for a burst the plane's own per-key rate limiting
30703
+ * would answer with the refusals the breaker then counts.
30704
+ *
30705
+ * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
30706
+ * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
30707
+ * lets status call the forward unhealthy; this path returns BEFORE `run` is
30708
+ * reached, so without the tally in `forward-drops.ts` a slow-but-answering
30709
+ * plane produces no failures, keeps the breaker closed, renders a healthy
30710
+ * block, and discards the tail of every batch indefinitely.
30711
+ */
30712
+ async forwardBatch(inputs, toEvent) {
30713
+ const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
30714
+ for (let i = 0; i < inputs.length; i += 1) {
30715
+ const now = Date.now();
30716
+ if (now >= deadline) {
30717
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
30718
+ return;
30719
+ }
30720
+ const input = inputs[i];
30721
+ await this.deps.forward.run(
30722
+ () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input), this.remoteInventory))
30723
+ );
30724
+ }
30725
+ }
30726
+ // Delegated as a BATCH rather than looped over recordLlmCall: the inner
30727
+ // gateway may write the whole batch in one local transaction, and looping
30728
+ // here would replace that with N separate local writes.
30729
+ async recordLlmCalls(inputs) {
30730
+ await this.deps.local.recordLlmCalls(inputs);
30731
+ await this.forwardBatch(inputs, (input) => llmAuditEvent(input));
30732
+ }
30733
+ // `input.inspections` (secrets detected client-side in the tool's masked
30734
+ // target) ride along on the request's `inspections` field — the control plane
30735
+ // persists each as an inspection_findings row linked to this audit event
30736
+ // (see RecordAuditEventRequest in @akasecurity/schema). The masked
30737
+ // `target` already rides `input.attributes`, so no raw secret leaks either
30738
+ // way — this only stops the FINDING row itself from being dropped.
30739
+ async recordToolCalls(inputs) {
30740
+ await this.deps.local.recordToolCalls(inputs);
30741
+ await this.forwardBatch(inputs, (input) => toolAuditEvent(input));
30742
+ }
30743
+ // Forwarded as a `config_scan` audit event: there is no dedicated
30744
+ // config-scan ingest endpoint, and the audit-event door is the one the
30745
+ // control plane already opens for client-minted, idempotent records.
30746
+ //
30747
+ // ONLY `scanEvent` CROSSES, and unlike `recordCapture` the plane cannot
30748
+ // re-derive the rest. A `ConfigScanRecord` is four things committed together
30749
+ // locally — the inventory `items`, this audit event, and the posture
30750
+ // `definitions`/`findings` that reference it — and three of them stay on the
30751
+ // device. Say that plainly rather than let the asymmetry with `recordCapture`
30752
+ // read as the same argument: there, findings are omitted BECAUSE the plane
30753
+ // re-derives them from `Event.content`; here there is no content to re-derive
30754
+ // from, so what is omitted is simply not sent.
30755
+ //
30756
+ // That is the wire contract as it stands rather than an oversight to patch
30757
+ // here. `items` has no route at all, and `RecordAuditEventRequest.inspections`
30758
+ // is documented as tool-call findings — widening it to carry config-scan
30759
+ // findings is an egress change (a posture finding's `maskedMatch` holds the
30760
+ // matched command) and a decision about what an attached deployment is
30761
+ // entitled to, not a bug fix. An attached machine's config posture therefore
30762
+ // reaches the plane as the event only; the dashboard's own view of it is the
30763
+ // local store.
30764
+ async recordConfigScan(record2) {
30765
+ await this.deps.local.recordConfigScan(record2);
30766
+ await this.deps.forward.run(
30767
+ () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
30768
+ );
30769
+ }
30770
+ async recordBlockedDetection(entry) {
30771
+ return this.deps.local.recordBlockedDetection(entry);
30772
+ }
30773
+ /**
30774
+ * LOCAL-ONLY, deliberately. The shares API is read-plus-decision-override
30775
+ * with no egress ingest endpoint, so there is nothing to forward to; adding a
30776
+ * forward here would be inventing a wire contract that does not exist. The
30777
+ * local write is the whole operation, and its summary is the real one — the
30778
+ * scanner reads a throw as a FAILED WRITE and skips its ledger commit, so
30779
+ * returning the inner gateway's result keeps the retry semantics honest.
30780
+ */
30781
+ async recordProjectEgress(input) {
30782
+ return this.deps.local.recordProjectEgress(input);
30783
+ }
30784
+ // ---------------------------------------------------------------------
30785
+ // Reads and device-local ledgers: pure delegation.
30786
+ // ---------------------------------------------------------------------
30787
+ async configInventoryReport() {
30788
+ return this.deps.local.configInventoryReport();
30789
+ }
30790
+ async readSessionProvider(sessionId) {
30791
+ return this.deps.local.readSessionProvider(sessionId);
30792
+ }
30793
+ async facets() {
30794
+ return this.deps.local.facets();
30795
+ }
30796
+ /**
30797
+ * Delegated UNMODIFIED — including its refusals.
30798
+ *
30799
+ * This is a fail-secure boundary: it decides whether an approved exception
30800
+ * lets a blocked action through. Under local-first the local store owns the
30801
+ * exception ledger, so the honest answer is whatever it says; wrapping this
30802
+ * in a fallback (`catch { return true }`, or defaulting on a timeout) would
30803
+ * turn a store error into a granted bypass. If the inner gateway rejects,
30804
+ * this rejects, and the runtime's own handling decides — which is asserted
30805
+ * end-to-end through runtime.capture rather than here.
30806
+ */
30807
+ async consumeException(id) {
30808
+ return this.deps.local.consumeException(id);
30809
+ }
30810
+ async recentFindings(opts) {
30811
+ return this.deps.local.recentFindings(opts);
30812
+ }
30813
+ async healthSummary() {
30814
+ return this.deps.local.healthSummary();
30815
+ }
30816
+ async activityByDay(days) {
30817
+ return this.deps.local.activityByDay(days);
30818
+ }
30819
+ async tokenReports() {
30820
+ return this.deps.local.tokenReports();
30821
+ }
30822
+ async knownContentHashes() {
30823
+ return this.deps.local.knownContentHashes();
30824
+ }
30825
+ async scanLedger(rulesetHash) {
30826
+ return this.deps.local.scanLedger(rulesetHash);
30827
+ }
30828
+ async recordScanned(entries) {
30829
+ return this.deps.local.recordScanned(entries);
30830
+ }
30831
+ async getRuleProbeVerdict(ruleKey) {
30832
+ return this.deps.local.getRuleProbeVerdict(ruleKey);
30833
+ }
30834
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
30835
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2);
30836
+ }
30837
+ async openAtRestKeysForPath(path) {
30838
+ return this.deps.local.openAtRestKeysForPath(path);
30839
+ }
30840
+ async resolvedAtRestKeysForPath(path) {
30841
+ return this.deps.local.resolvedAtRestKeysForPath(path);
30842
+ }
30843
+ async insertResolution(input) {
30844
+ return this.deps.local.insertResolution(input);
30845
+ }
30846
+ async close() {
30847
+ return this.deps.local.close();
30848
+ }
30849
+ // ---------------------------------------------------------------------
30850
+ // Policy
30851
+ // ---------------------------------------------------------------------
30852
+ async getPolicyBundle() {
30853
+ const local = await this.deps.local.getPolicyBundle();
30854
+ const cached2 = await (async () => {
30855
+ try {
30856
+ return await this.deps.readCachedBundle();
30857
+ } catch {
30858
+ return null;
30859
+ }
30860
+ })();
30861
+ if (cached2 === null) return local;
30862
+ const byRuleId = /* @__PURE__ */ new Map();
30863
+ for (const rule of [...local.rules ?? [], ...cached2.rules ?? []]) {
30864
+ if (!byRuleId.has(rule.id)) byRuleId.set(rule.id, rule);
30865
+ }
30866
+ const rules = [...byRuleId.values()];
30867
+ return {
30868
+ ...local,
30869
+ // The remote version identifies the composed bundle for the poller.
30870
+ version: cached2.version,
30871
+ rules,
30872
+ policies: mergeRaiseOnly(
30873
+ local.policies,
30874
+ cached2.policies,
30875
+ ruleCategoryMap(cached2.rules, local.rules)
30876
+ ),
30877
+ customKeywords: [...local.customKeywords, ...cached2.customKeywords]
30878
+ // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
30879
+ // snapshot) and is taken from the LOCAL bundle only — never from the wire
30880
+ // or the on-disk cache. Honoring a cached one would hand the control plane, or
30881
+ // anything able to write policy-cache.json, a kill-switch over the
30882
+ // compiled-in bundled packs: `{ rulesComplete: true, rules: [] }` would
30883
+ // zero local detection. Spread from `local` above, and deliberately not
30884
+ // re-read from `cached` here.
30885
+ //
30886
+ // THREE MORE OF THE CACHED BUNDLE'S FIELDS ARE DROPPED, each on purpose,
30887
+ // and each named here so a reader can tell a decision from an omission:
30888
+ //
30889
+ // `exceptions` — an exception SUPPRESSES a detection, so honoring
30890
+ // one from an unsigned on-disk cache would let
30891
+ // anything able to write that file turn rules off.
30892
+ // Every other field this merge accepts can only
30893
+ // RAISE enforcement; this is the one that cannot,
30894
+ // so it stays local-only until the bundle is
30895
+ // signed. Exceptions remain a device-local ledger.
30896
+ // `reversibleRuleIds` — the Redact & Vault archetype makes a redaction
30897
+ // recoverable, which is a CUSTODY change: it puts
30898
+ // the detected value in the local vault instead of
30899
+ // destroying it. Taking that instruction from the
30900
+ // cache would let a remote party turn one-way
30901
+ // redaction into retention. Dropping it keeps the
30902
+ // one-way behaviour, which the schema itself calls
30903
+ // "the safe direction to default".
30904
+ // `ruleVersions` — remote rules fall back to their own spec version.
30905
+ // Cosmetic rather than protective: it only affects
30906
+ // how a finding is version-attributed, and the two
30907
+ // sides may therefore attribute org rules
30908
+ // differently. Worth carrying once there is a
30909
+ // reader that needs it; nothing reads it today.
30910
+ };
30911
+ }
30912
+ // ---------------------------------------------------------------------
30913
+ // LocalStoreMaintenance — by delegation (D3).
30914
+ //
30915
+ // Implementing these is what actually closes the skipped-local-maintenance
30916
+ // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
30917
+ // any object carrying all five, so the composite qualifies and SessionStart
30918
+ // runs maintenance on the device's real store.
30919
+ //
30920
+ // ⚠ Two of the five are SYNCHRONOUS and must stay that way. `handle-session-start`
30921
+ // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
30922
+ // return value directly; declaring them `async` here would hand those call
30923
+ // sites a Promise and silently break both.
30924
+ // ---------------------------------------------------------------------
30925
+ async sweepTerminalExceptions(retentionMs) {
30926
+ return this.deps.local.sweepTerminalExceptions(retentionMs);
30927
+ }
30928
+ capWarnEraEnforcement(policyMode) {
30929
+ return this.deps.local.capWarnEraEnforcement(policyMode);
30930
+ }
30931
+ async recordProjectFiles(projectId, scan2) {
30932
+ return this.deps.local.recordProjectFiles(projectId, scan2);
30933
+ }
30934
+ async reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot) {
30935
+ return this.deps.local.reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot);
30936
+ }
30937
+ staleBinaryNotice(currentVersion) {
30938
+ return this.deps.local.staleBinaryNotice(currentVersion);
30939
+ }
30940
+ };
30941
+ function reKeyForForward(event, remote) {
30942
+ if (remote === null) {
30943
+ const stripped = { ...event };
30944
+ delete stripped.hostId;
30945
+ delete stripped.harnessId;
30946
+ delete stripped.sourceProjectId;
30947
+ return stripped;
30948
+ }
30949
+ const rekeyed = { ...event };
30950
+ delete rekeyed.hostId;
30951
+ delete rekeyed.harnessId;
30952
+ delete rekeyed.sourceProjectId;
30953
+ if (remote.hostId !== void 0) rekeyed.hostId = remote.hostId;
30954
+ if (remote.harnessId !== void 0) rekeyed.harnessId = remote.harnessId;
30955
+ if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
30956
+ return rekeyed;
30957
+ }
30958
+ var BATCH_FORWARD_BUDGET_MS = 3e3;
30959
+ function llmAuditEvent(input) {
30960
+ return {
30961
+ id: llmCallId(input.sessionId, input.messageId),
30962
+ eventType: "llm_call",
30963
+ startedAt: input.startedAt,
30964
+ parentId: input.parentId,
30965
+ rootSessionId: input.rootSessionId,
30966
+ attributes: input.attributes
30967
+ };
30968
+ }
30969
+ function toolAuditEvent(input) {
30970
+ return {
30971
+ id: toolCallId(input.sessionId, input.toolUseId),
30972
+ eventType: "tool_call",
30973
+ startedAt: input.startedAt,
30974
+ parentId: input.parentId,
30975
+ rootSessionId: input.rootSessionId,
30976
+ attributes: input.attributes,
30977
+ inspections: input.inspections
30978
+ };
30979
+ }
30980
+
30981
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
30982
+ import { randomUUID as randomUUID16 } from "crypto";
30983
+ import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
30984
+ import { join as join21 } from "path";
30985
+
30986
+ // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
30987
+ import { rename as rename2 } from "fs/promises";
30988
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
30989
+ var ATTEMPTS = 5;
30990
+ var delay = (ms) => new Promise((resolve2) => {
30991
+ setTimeout(resolve2, ms);
30992
+ });
30993
+ async function publishByRename(tmp, file2, move = rename2) {
30994
+ for (let attempt = 1; ; attempt += 1) {
30995
+ try {
30996
+ await move(tmp, file2);
30997
+ return;
30998
+ } catch (err) {
30999
+ const code = err.code;
31000
+ if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
31001
+ await delay(attempt * 10);
31002
+ }
31003
+ }
31004
+ }
31005
+
31006
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
31007
+ function createPolicyStore(dir = dataDir()) {
31008
+ const file2 = join21(dir, "policy-cache.json");
31009
+ async function read() {
31010
+ try {
31011
+ const raw = await readFile2(file2, "utf8");
31012
+ const parsed2 = JSON.parse(raw);
31013
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
31014
+ const record2 = parsed2;
31015
+ const bundle = PolicyBundle.parse(record2.bundle);
31016
+ const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
31017
+ const etag = typeof record2.etag === "string" ? record2.etag : void 0;
31018
+ return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
31019
+ } catch {
31020
+ return null;
31021
+ }
31022
+ }
31023
+ async function write(bundle, etag) {
31024
+ await ensureDataDir(dir);
31025
+ const stored = {
31026
+ bundle,
31027
+ fetchedAtMs: Date.now(),
31028
+ ...etag === void 0 ? {} : { etag }
31029
+ };
31030
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
31031
+ try {
31032
+ await writeFile2(tmp, JSON.stringify(stored), {
31033
+ encoding: "utf8",
31034
+ mode: DATA_FILE_MODE,
31035
+ flag: "wx"
31036
+ });
31037
+ await publishByRename(tmp, file2);
31038
+ } catch (err) {
31039
+ await rm(tmp, { force: true }).catch(() => void 0);
31040
+ throw err;
31041
+ }
31042
+ }
31043
+ return { read, write, file: file2 };
31044
+ }
31045
+
31046
+ // ../../packages/remote/src/http.ts
31047
+ import { request as httpRequest } from "http";
31048
+ import { request as httpsRequest } from "https";
31049
+ var DEFAULT_TIMEOUT_MS = 1e4;
31050
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
31051
+ var RemoteRequestError = class extends Error {
31052
+ constructor(status) {
31053
+ super(`control-plane request failed with status ${String(status)}`);
31054
+ this.status = status;
31055
+ this.name = "RemoteRequestError";
31056
+ }
31057
+ status;
31058
+ };
31059
+ var RemoteRequestInvalid = class extends Error {
31060
+ constructor(route, cause) {
31061
+ super(`refusing to send a malformed body to ${route}`);
31062
+ this.cause = cause;
31063
+ this.name = "RemoteRequestInvalid";
31064
+ }
31065
+ cause;
31066
+ };
31067
+ var RemoteResponseInvalid = class extends Error {
31068
+ constructor(route, detail) {
31069
+ super(`control plane answered ${route} with ${detail}`);
31070
+ this.name = "RemoteResponseInvalid";
31071
+ }
31072
+ };
31073
+ var RemoteTransportError = class extends Error {
31074
+ /**
31075
+ * The status the peer sent, when headers arrived and only the BODY was
31076
+ * refused.
31077
+ *
31078
+ * Undefined for the ordinary case this class was written for — no answer at
31079
+ * all. It exists because two paths reject after a status has already been
31080
+ * delivered: an oversized body and an aborted response. Discarding it there
31081
+ * reported a deployment answering 401 with a verbose body as a network
31082
+ * outage, which sends the reader to look at their network instead of their
31083
+ * credential.
31084
+ */
31085
+ constructor(reason, status) {
31086
+ super(`control-plane request did not complete: ${reason}`);
31087
+ this.status = status;
31088
+ this.name = "RemoteTransportError";
31089
+ }
31090
+ status;
31091
+ };
31092
+ async function send(options) {
31093
+ const url2 = new URL(options.url);
31094
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
31095
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
31096
+ const requestOptions = {
31097
+ method: options.method,
31098
+ headers: {
31099
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
31100
+ // last they win, and two of the values below are ones no caller may
31101
+ // replace: `x-api-key` is the credential, and `content-length` is the
31102
+ // byte count that stops a multi-byte body being truncated by the
31103
+ // receiver. `SendOptions.headers` is a free-form record on an exported
31104
+ // function, so "no caller does that today" is not the guarantee to rely
31105
+ // on. The one header any caller actually passes — `if-none-match` on the
31106
+ // conditional GET — is untouched by this order.
31107
+ ...options.headers,
31108
+ // The credential. One header, matching what the deployment authenticates
31109
+ // on; a second copy in an `Authorization` header would be one more place
31110
+ // it can be logged by an intermediary for no gain.
31111
+ "x-api-key": options.apiKey,
31112
+ accept: "application/json",
31113
+ ...options.body === void 0 ? {} : {
31114
+ "content-type": "application/json",
31115
+ // Byte length, not string length: a multi-byte body sent with a
31116
+ // character count is truncated by the receiver.
31117
+ "content-length": String(Buffer.byteLength(options.body))
31118
+ }
31119
+ }
31120
+ };
31121
+ return new Promise((resolve2, reject) => {
31122
+ let settled = false;
31123
+ const fail = (reason, status) => {
31124
+ if (settled) return;
31125
+ settled = true;
31126
+ reject(new RemoteTransportError(reason, status));
31127
+ };
31128
+ const req = send_(url2, requestOptions, (res) => {
31129
+ const chunks = [];
31130
+ let size = 0;
31131
+ res.on("data", (chunk) => {
31132
+ size += chunk.length;
31133
+ if (size > MAX_RESPONSE_BYTES) {
31134
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
31135
+ res.destroy();
31136
+ req.destroy();
31137
+ return;
31138
+ }
31139
+ chunks.push(chunk);
31140
+ });
31141
+ res.on("aborted", () => {
31142
+ fail("the response was aborted", res.statusCode);
31143
+ });
31144
+ res.on("end", () => {
31145
+ if (settled) return;
31146
+ settled = true;
31147
+ resolve2({
31148
+ status: res.statusCode ?? 0,
31149
+ headers: res.headers,
31150
+ body: Buffer.concat(chunks).toString("utf8")
31151
+ });
31152
+ });
31153
+ });
31154
+ const deadline = setTimeout(() => {
31155
+ fail(`no response within ${String(timeoutMs)}ms`);
31156
+ req.destroy();
31157
+ }, timeoutMs);
31158
+ deadline.unref();
31159
+ req.on("upgrade", (_res, socket) => {
31160
+ fail("the deployment answered with a protocol upgrade");
31161
+ socket.destroy();
31162
+ });
31163
+ req.on("close", () => {
31164
+ fail("the connection closed before a response was read");
31165
+ clearTimeout(deadline);
31166
+ });
31167
+ req.on("error", (err) => {
31168
+ fail(err.message);
31169
+ });
31170
+ if (options.body !== void 0) req.write(options.body);
31171
+ req.end();
31172
+ });
31173
+ }
31174
+
31175
+ // ../../packages/remote/src/client.ts
31176
+ var ROUTES = {
31177
+ events: "/v1/events",
31178
+ auditEvents: "/v1/audit-events",
31179
+ inventory: "/v1/inventory",
31180
+ storePosture: "/v1/store-posture",
31181
+ policyBundle: "/v1/policy-bundle",
31182
+ whoami: "/v1/plugin/whoami"
31183
+ };
31184
+ function headerValue(response, name) {
31185
+ const raw = response.headers[name];
31186
+ if (raw === void 0) return void 0;
31187
+ return Array.isArray(raw) ? raw[0] : raw;
31188
+ }
31189
+ function okBody(response) {
31190
+ if (response.status < 200 || response.status >= 300) {
31191
+ throw new RemoteRequestError(response.status);
31192
+ }
31193
+ return response.body;
31194
+ }
31195
+ function parsed(schema, body, route) {
31196
+ let json2;
31197
+ try {
31198
+ json2 = JSON.parse(body);
31199
+ } catch {
31200
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
31201
+ }
31202
+ const result = schema.safeParse(json2);
31203
+ if (!result.success) {
31204
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
31205
+ }
31206
+ return result.data;
31207
+ }
31208
+ function withoutTrailingSlashes(endpoint) {
31209
+ let end = endpoint.length;
31210
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
31211
+ return endpoint.slice(0, end);
31212
+ }
31213
+ var SLASH = "/".charCodeAt(0);
31214
+ function createRemoteClient(options) {
31215
+ const base = withoutTrailingSlashes(options.endpoint);
31216
+ const url2 = (route) => `${base}${route}`;
31217
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
31218
+ return {
31219
+ async ingestEvents(batch) {
31220
+ const response = await send({
31221
+ ...common,
31222
+ method: "POST",
31223
+ url: url2(ROUTES.events),
31224
+ body: JSON.stringify(batch)
31225
+ });
31226
+ return parsed(IngestAck, okBody(response), ROUTES.events);
31227
+ },
31228
+ async ingestInventory(context) {
31229
+ const response = await send({
31230
+ ...common,
31231
+ method: "POST",
31232
+ url: url2(ROUTES.inventory),
31233
+ body: JSON.stringify(context)
31234
+ });
31235
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
31236
+ },
31237
+ async recordAuditEvent(event) {
31238
+ const validated = RecordAuditEventRequest.safeParse(event);
31239
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
31240
+ const submission = validated.data;
31241
+ const response = await send({
31242
+ ...common,
31243
+ method: "POST",
31244
+ url: url2(ROUTES.auditEvents),
31245
+ body: JSON.stringify(submission)
31246
+ });
31247
+ okBody(response);
31248
+ },
31249
+ async reportStorePosture(snapshot) {
31250
+ const response = await send({
31251
+ ...common,
31252
+ method: "POST",
31253
+ url: url2(ROUTES.storePosture),
31254
+ body: JSON.stringify(snapshot)
31255
+ });
31256
+ okBody(response);
31257
+ },
31258
+ async getPolicyBundle(etag) {
31259
+ const response = await send({
31260
+ ...common,
31261
+ method: "GET",
31262
+ url: url2(ROUTES.policyBundle),
31263
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
31264
+ });
31265
+ if (response.status === 304) {
31266
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
31267
+ }
31268
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
31269
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
31270
+ },
31271
+ async whoami() {
31272
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
31273
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
31274
+ }
31275
+ };
31276
+ }
31277
+
31278
+ // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
31279
+ var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
31280
+ function createPostureReporter(deps) {
31281
+ async function prepare() {
31282
+ try {
31283
+ const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
31284
+ if (state === null) return null;
31285
+ const nowMs = deps.now();
31286
+ const elapsed = nowMs - state.lastAttemptedAtMs;
31287
+ if (elapsed >= 0 && elapsed < POSTURE_REPORT_INTERVAL_MS) return null;
31288
+ try {
31289
+ await withTimeout(deps.store.markAttempted(state.deviceId, nowMs), REQUEST_TIMEOUT_MS);
31290
+ } catch {
31291
+ }
31292
+ const { readError, ...measurement } = deps.readStore();
31293
+ if (readError) return null;
31294
+ let plugin;
31295
+ try {
31296
+ plugin = await deps.pluginBlock?.();
31297
+ } catch {
31298
+ plugin = void 0;
31299
+ }
31300
+ return {
31301
+ deviceId: state.deviceId,
31302
+ hostname: deps.hostname(),
31303
+ capturedAt: nowMs,
31304
+ ...measurement,
31305
+ // Omit the key rather than spread an explicit `undefined` —
31306
+ // exactOptionalPropertyTypes distinguishes the two, and the bridge in
31307
+ // factory.ts keys on presence.
31308
+ ...plugin === void 0 ? {} : { plugin }
31309
+ };
31310
+ } catch {
31311
+ return null;
31312
+ }
31313
+ }
31314
+ async function send2(snapshot) {
31315
+ try {
31316
+ await deps.report(snapshot);
31317
+ } catch {
31318
+ }
31319
+ }
31320
+ return { prepare, send: send2 };
31321
+ }
31322
+
31323
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31324
+ import { statSync as statSync9 } from "fs";
31325
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31326
+
31327
+ // ../../packages/plugin-runtime/src/attached/action-counts.ts
31328
+ function emptyActionCounts() {
31329
+ return Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
31330
+ }
31331
+ function isActionTaken(value) {
31332
+ return ACTION_TAKEN_KEYS.includes(value);
31333
+ }
31334
+
31335
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31336
+ var CAPTURE_EVENT_TYPES_SQL2 = `('prompt','response','code_change','tool_use')`;
31337
+ function isSchemaAbsent(err) {
31338
+ return err instanceof Error && /no such table/i.test(err.message);
31339
+ }
31340
+ function emptyReadout(readError = false) {
31341
+ const byAction = emptyActionCounts();
31342
+ return {
31343
+ storePresent: false,
31344
+ schemaVersion: null,
31345
+ findingsTotal: 0,
31346
+ findingsFirstAt: null,
31347
+ findingsLastAt: null,
31348
+ packs: [],
31349
+ policyCounts: { total: 0, disabled: 0, byAction },
31350
+ readError
31351
+ };
31352
+ }
31353
+ function readStorePosture(dbPath2) {
31354
+ try {
31355
+ statSync9(dbPath2);
31356
+ } catch (err) {
31357
+ const code = err.code;
31358
+ if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
31359
+ return emptyReadout(true);
31360
+ }
31361
+ let db = null;
31362
+ let version2 = null;
31363
+ let packs2 = [];
31364
+ let policyCounts = {
31365
+ total: 0,
31366
+ disabled: 0,
31367
+ byAction: emptyActionCounts()
31368
+ };
31369
+ let findingsTotal = 0;
31370
+ let findingsFirstAt = null;
31371
+ let findingsLastAt = null;
31372
+ const currentReadout = () => ({
31373
+ storePresent: true,
31374
+ schemaVersion: version2,
31375
+ findingsTotal,
31376
+ findingsFirstAt,
31377
+ findingsLastAt,
31378
+ packs: packs2,
31379
+ policyCounts,
31380
+ readError: false
31381
+ });
31382
+ try {
31383
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
31384
+ db.exec("PRAGMA busy_timeout = 2000");
31385
+ version2 = db.prepare("PRAGMA user_version").get().user_version;
31386
+ try {
31387
+ const packRows = db.prepare(
31388
+ `SELECT namespace, pack_id, version, enabled, updated_at FROM installed_packs ORDER BY namespace, pack_id`
31389
+ ).all();
31390
+ packs2 = packRows.map((r) => ({
31391
+ packId: `${r.namespace}/${r.pack_id}`,
31392
+ version: r.version,
31393
+ enabled: r.enabled !== 0,
31394
+ updatedAt: r.updated_at == null ? null : String(r.updated_at)
31395
+ }));
31396
+ } catch (err) {
31397
+ if (!isSchemaAbsent(err)) throw err;
31398
+ }
31399
+ try {
31400
+ const policyRows = db.prepare(`SELECT action, enabled FROM policies`).all();
31401
+ const byAction = emptyActionCounts();
31402
+ let disabled = 0;
31403
+ for (const row of policyRows) {
31404
+ if (row.enabled === 0) disabled += 1;
31405
+ if (isActionTaken(row.action)) byAction[row.action] += 1;
31406
+ }
31407
+ policyCounts = { total: policyRows.length, disabled, byAction };
31408
+ } catch (err) {
31409
+ if (!isSchemaAbsent(err)) throw err;
31410
+ }
31411
+ try {
31412
+ const agg = db.prepare(
31413
+ `SELECT count(*) AS n, min(f.first_detected_at) AS firstAt, max(f.first_detected_at) AS lastAt
31414
+ FROM inspection_findings f JOIN audit_events e ON e.id = f.audit_event_id
31415
+ WHERE e.event_type IN ${CAPTURE_EVENT_TYPES_SQL2}`
31416
+ ).get();
31417
+ findingsTotal = agg.n;
31418
+ findingsFirstAt = agg.firstAt;
31419
+ findingsLastAt = agg.lastAt;
31420
+ } catch (err) {
31421
+ if (!isSchemaAbsent(err)) throw err;
31422
+ }
31423
+ return currentReadout();
31424
+ } catch {
31425
+ return emptyReadout(true);
31426
+ } finally {
31427
+ try {
31428
+ db?.close();
31429
+ } catch {
31430
+ }
31431
+ }
31432
+ }
31433
+
31434
+ // ../../packages/plugin-runtime/src/attached/posture-store.ts
31435
+ import { randomUUID as randomUUID17 } from "crypto";
31436
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
31437
+ import { join as join22 } from "path";
31438
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31439
+ function createPostureStore(dir = settingsDir(), legacyDir) {
31440
+ const file2 = join22(dir, "posture-state.json");
31441
+ const legacyFile = legacyDir === void 0 ? null : join22(legacyDir, "posture-state.json");
31442
+ async function persist(state) {
31443
+ await ensureDataDir(dir);
31444
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
31445
+ try {
31446
+ await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
31447
+ await publishByRename(tmp, file2);
31448
+ } catch (err) {
31449
+ await rm2(tmp, { force: true }).catch(() => void 0);
31450
+ throw err;
31451
+ }
31452
+ }
31453
+ async function readFrom(path) {
31454
+ let raw;
31455
+ try {
31456
+ raw = await readFile3(path, "utf8");
31457
+ } catch (err) {
31458
+ const code = err.code;
31459
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
31460
+ throw err;
31461
+ }
31462
+ try {
31463
+ const parsed2 = JSON.parse(raw);
31464
+ if (typeof parsed2 === "object" && parsed2 !== null) {
31465
+ const record2 = parsed2;
31466
+ if (typeof record2.deviceId === "string" && UUID_RE.test(record2.deviceId)) {
31467
+ const stamp = typeof record2.lastAttemptedAtMs === "number" ? record2.lastAttemptedAtMs : typeof record2.lastReportedAtMs === "number" ? record2.lastReportedAtMs : 0;
31468
+ return { deviceId: record2.deviceId, lastAttemptedAtMs: stamp };
31469
+ }
31470
+ }
31471
+ } catch {
31472
+ }
31473
+ return null;
31474
+ }
31475
+ async function read() {
31476
+ const current = await readFrom(file2);
31477
+ if (current) return current;
31478
+ const legacy = legacyFile === null || legacyFile === file2 ? null : await readFrom(legacyFile).catch(() => null);
31479
+ if (legacy) {
31480
+ try {
31481
+ await persist(legacy);
31482
+ } catch {
31483
+ }
31484
+ return legacy;
31485
+ }
31486
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
31487
+ try {
31488
+ await ensureDataDir(dir);
31489
+ if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
31490
+ } catch {
31491
+ return null;
31492
+ }
31493
+ const winner = await readFrom(file2).catch(() => null);
31494
+ if (winner) return winner;
31495
+ try {
31496
+ await persist(fresh);
31497
+ } catch {
31498
+ return null;
31499
+ }
31500
+ return fresh;
31501
+ }
31502
+ async function markAttempted(deviceId, atMs) {
31503
+ await persist({ deviceId, lastAttemptedAtMs: atMs });
31504
+ }
31505
+ return { read, markAttempted, file: file2 };
31506
+ }
31507
+
31508
+ // ../../packages/plugin-runtime/src/attached/sync-state.ts
31509
+ import { readFileSync as readFileSync14 } from "fs";
31510
+ import { join as join23 } from "path";
31511
+
31512
+ // ../../packages/plugin-runtime/src/attached/status.ts
31513
+ var REFUSAL_LINES = {
31514
+ unauthorized: "KEY REJECTED \u2014 re-attach with a valid plugin key",
31515
+ forbidden: "ACCESS REFUSED \u2014 key is valid but not permitted; ask your org admin"
31516
+ };
31517
+ var OUTCOME_LINES = {
31518
+ ok: "policy synced",
31519
+ "not-modified": "policy up to date",
31520
+ unauthorized: REFUSAL_LINES.unauthorized,
31521
+ forbidden: REFUSAL_LINES.forbidden,
31522
+ unreachable: "control plane unreachable at last attempt",
31523
+ "invalid-bundle": "control plane sent a policy bundle this build cannot read"
31524
+ };
31525
+
31526
+ // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
31527
+ import { spawn } from "child_process";
31528
+ import { fileURLToPath as fileURLToPath2 } from "url";
31529
+ var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
31530
+
31531
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31532
+ import { hostname as hostname5 } from "os";
31533
+
31534
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31535
+ import { randomUUID as randomUUID18 } from "crypto";
30104
31536
 
30105
31537
  // ../../packages/plugin-runtime/src/recorder.ts
30106
31538
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -30141,12 +31573,12 @@ var StandaloneDataGateway = class {
30141
31573
  // reconciler drops the whole pass and recovers it idempotently on the next read.
30142
31574
  recordLlmCalls(inputs) {
30143
31575
  if (inputs.length === 0) return Promise.resolve();
30144
- return new Promise((resolve, reject) => {
31576
+ return new Promise((resolve2, reject) => {
30145
31577
  try {
30146
31578
  this.db.auditEvents.runInTransaction(() => {
30147
31579
  for (const input of inputs) this.db.auditEvents.insertLlmCall(input);
30148
31580
  });
30149
- resolve();
31581
+ resolve2();
30150
31582
  } catch (err) {
30151
31583
  reject(err instanceof Error ? err : new Error(String(err)));
30152
31584
  }
@@ -30158,12 +31590,12 @@ var StandaloneDataGateway = class {
30158
31590
  // drops the whole pass and recovers it idempotently next time.
30159
31591
  recordToolCalls(inputs) {
30160
31592
  if (inputs.length === 0) return Promise.resolve();
30161
- return new Promise((resolve, reject) => {
31593
+ return new Promise((resolve2, reject) => {
30162
31594
  try {
30163
31595
  this.db.auditEvents.runInTransaction(() => {
30164
31596
  for (const input of inputs) this.writeToolCall(input);
30165
31597
  });
30166
- resolve();
31598
+ resolve2();
30167
31599
  } catch (err) {
30168
31600
  reject(err instanceof Error ? err : new Error(String(err)));
30169
31601
  }
@@ -30305,7 +31737,7 @@ var StandaloneDataGateway = class {
30305
31737
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
30306
31738
  const installed = this.installedScanRules();
30307
31739
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
30308
- id: randomUUID15(),
31740
+ id: randomUUID18(),
30309
31741
  scope: "global",
30310
31742
  target: { ruleId },
30311
31743
  action,
@@ -30459,23 +31891,69 @@ var StandaloneDataGateway = class {
30459
31891
  }
30460
31892
  };
30461
31893
 
31894
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31895
+ function resolveGatewayForConfig(config2, meta3) {
31896
+ const local = new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
31897
+ try {
31898
+ if (!isAttached(config2.settings)) return local;
31899
+ const connection = config2.settings.controlPlane;
31900
+ if (connection === void 0) return local;
31901
+ const state = readControlPlaneCredentialState(config2.settingsDir, connection);
31902
+ if (!state.usable) return local;
31903
+ const client = createRemoteClient({
31904
+ endpoint: connection.endpoint,
31905
+ apiKey: state.credential.apiKey
31906
+ });
31907
+ const store = createPolicyStore(config2.dataDir);
31908
+ const postureStore = createPostureStore(config2.settingsDir, config2.dataDir);
31909
+ const forward = createForwardPolicy({ dir: config2.dataDir });
31910
+ return new AttachedDataGateway({
31911
+ local,
31912
+ client,
31913
+ dataDir: config2.dataDir,
31914
+ readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
31915
+ forward,
31916
+ posture: createPostureReporter({
31917
+ // THROUGH THE BREAKER, and wrapped HERE rather than around
31918
+ // `PostureReporter.send`. The reporter swallows every error by
31919
+ // contract, so a wrap outside it would hand `forward.run` a resolved
31920
+ // promise for a send that failed — recording a SUCCESS, clearing
31921
+ // `consecutiveFailures` and `lastFailure`, and telling `aka status` the
31922
+ // forward recovered when nothing did. Wrapping the raw client call puts
31923
+ // the breaker above the swallow, where it can see the truth.
31924
+ //
31925
+ // What it buys: once the breaker is open — the plane already confirmed
31926
+ // down by the gateway's own writes — this stops paying a request
31927
+ // timeout per throttle interval to re-learn it.
31928
+ report: (snapshot) => forward.run(() => client.reportStorePosture(snapshot)).then(() => void 0),
31929
+ store: postureStore,
31930
+ readStore: () => readStorePosture(config2.dbPath),
31931
+ hostname: () => hostname5(),
31932
+ now: () => Date.now()
31933
+ })
31934
+ });
31935
+ } catch {
31936
+ return local;
31937
+ }
31938
+ }
31939
+
30462
31940
  // ../../packages/plugin-runtime/src/resolve.ts
30463
- var standaloneGatewayFactory = (config2, meta3) => new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
30464
- var defaultGatewayFactory = standaloneGatewayFactory;
31941
+ var configuredGatewayFactory = (config2, meta3) => resolveGatewayForConfig(config2, meta3);
31942
+ var defaultGatewayFactory = configuredGatewayFactory;
30465
31943
  function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFactory) {
30466
31944
  return gatewayFactory(config2, meta3);
30467
31945
  }
30468
31946
 
30469
31947
  // ../../packages/plugin-runtime/src/handle-session-start.ts
30470
- import { randomUUID as randomUUID16 } from "crypto";
31948
+ import { randomUUID as randomUUID19 } from "crypto";
30471
31949
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
30472
31950
 
30473
31951
  // src/history/transcripts.ts
30474
- import { closeSync as closeSync2, openSync as openSync2, readdirSync as readdirSync5, readFileSync as readFileSync11, readSync, statSync as statSync7 } from "fs";
31952
+ import { closeSync as closeSync2, openSync as openSync2, readdirSync as readdirSync5, readFileSync as readFileSync15, readSync, statSync as statSync10 } from "fs";
30475
31953
  import { homedir as homedir3 } from "os";
30476
- import { join as join17 } from "path";
31954
+ import { join as join24 } from "path";
30477
31955
  function transcriptsDir(home) {
30478
- return join17(home ?? homedir3(), ".codex", "sessions");
31956
+ return join24(home ?? homedir3(), ".codex", "sessions");
30479
31957
  }
30480
31958
  function isRecord(value) {
30481
31959
  return typeof value === "object" && value !== null;
@@ -30714,7 +32192,7 @@ function* walkJsonlFiles(dir, depth = 0) {
30714
32192
  return;
30715
32193
  }
30716
32194
  for (const entry of entries) {
30717
- const full = join17(dir, entry.name);
32195
+ const full = join24(dir, entry.name);
30718
32196
  if (entry.isDirectory()) {
30719
32197
  yield* walkJsonlFiles(full, depth + 1);
30720
32198
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -30725,8 +32203,8 @@ function* walkJsonlFiles(dir, depth = 0) {
30725
32203
  function* iterateFileContents(dir) {
30726
32204
  for (const filePath of walkJsonlFiles(dir)) {
30727
32205
  try {
30728
- statSync7(filePath);
30729
- yield { content: readFileSync11(filePath, "utf8"), filePath };
32206
+ statSync10(filePath);
32207
+ yield { content: readFileSync15(filePath, "utf8"), filePath };
30730
32208
  } catch {
30731
32209
  }
30732
32210
  }
@@ -30840,11 +32318,11 @@ import {
30840
32318
  fstatSync,
30841
32319
  mkdirSync as mkdirSync4,
30842
32320
  openSync as openSync3,
30843
- readFileSync as readFileSync12,
32321
+ readFileSync as readFileSync16,
30844
32322
  readSync as readSync2,
30845
32323
  writeFileSync as writeFileSync9
30846
32324
  } from "fs";
30847
- import { join as join18 } from "path";
32325
+ import { join as join25 } from "path";
30848
32326
 
30849
32327
  // src/history/usage.ts
30850
32328
  var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";
@@ -31144,7 +32622,7 @@ async function runBackfill(deps) {
31144
32622
  }
31145
32623
  }
31146
32624
  }
31147
- if (process.argv[1] && fileURLToPath2(import.meta.url) === process.argv[1]) {
32625
+ if (process.argv[1] && fileURLToPath3(import.meta.url) === process.argv[1]) {
31148
32626
  const triage = process.argv.includes("--triage");
31149
32627
  const startedAt = Date.now();
31150
32628
  await runBackfill({
@@ -31162,9 +32640,9 @@ if (process.argv[1] && fileURLToPath2(import.meta.url) === process.argv[1]) {
31162
32640
  guard: { beforeMs: startedAt }
31163
32641
  });
31164
32642
  if (process.stdout.writableLength > 0) {
31165
- await new Promise((resolve) => {
32643
+ await new Promise((resolve2) => {
31166
32644
  process.stdout.write("", () => {
31167
- resolve();
32645
+ resolve2();
31168
32646
  });
31169
32647
  });
31170
32648
  }