@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,13 +492,12 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/remediation/entry.ts
495
- import { readFileSync as readFileSync15 } from "fs";
496
- import { fileURLToPath as fileURLToPath3 } from "url";
495
+ import { readFileSync as readFileSync19 } from "fs";
496
+ import { fileURLToPath as fileURLToPath4 } from "url";
497
497
 
498
- // ../../packages/persistence/src/database.ts
499
- import { randomUUID as randomUUID10 } from "crypto";
500
- import { join as join2, sep } from "path";
501
- import { DatabaseSync } from "node:sqlite";
498
+ // ../../packages/persistence/src/control-plane-credential.ts
499
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync2, statSync } from "fs";
500
+ import { join } from "path";
502
501
 
503
502
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
504
503
  var SQLITE_MIGRATIONS = [
@@ -16202,6 +16201,125 @@ var ConfigScanRecord = external_exports.object({
16202
16201
  findings: external_exports.array(ConfigPostureFindingInput).optional()
16203
16202
  });
16204
16203
 
16204
+ // ../../packages/schema/src/zod/control-plane.ts
16205
+ var ATTACHED_CREDENTIAL_FILENAME = "control-plane-credential.json";
16206
+ var ATTACHED_CREDENTIAL_SPEC_VERSION = 1;
16207
+ var AttachedCredential = external_exports.object({
16208
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SPEC_VERSION),
16209
+ // The control-plane endpoint this credential was minted against.
16210
+ endpoint: external_exports.string().min(1),
16211
+ // The bearer credential itself. Never logged, never rendered — status
16212
+ // surfaces show `keyPrefix` and nothing else.
16213
+ apiKey: external_exports.string().min(1),
16214
+ // First few characters of the key, safe to display so a user can match the
16215
+ // credential against their organization's key list.
16216
+ keyPrefix: external_exports.string().min(1).max(16).optional(),
16217
+ mintedAt: external_exports.iso.datetime().optional()
16218
+ });
16219
+ var MAX_DATE_MS = 253402300799999;
16220
+ var MAX_INT4 = 2147483647;
16221
+ var StorePosturePack = external_exports.object({
16222
+ packId: external_exports.string().min(1),
16223
+ // 'namespace/packId'
16224
+ version: external_exports.string().min(1),
16225
+ enabled: external_exports.boolean(),
16226
+ // Stringified pass-through of the local store's `installed_packs.updated_at`
16227
+ // — the column format is store-version-dependent (epoch millis vs ISO), so
16228
+ // the wire shape assumes neither.
16229
+ updatedAt: external_exports.string().nullable()
16230
+ }).meta({ id: "StorePosturePack" });
16231
+ var StorePosturePolicyCounts = external_exports.object({
16232
+ total: external_exports.number().int().min(0),
16233
+ disabled: external_exports.number().int().min(0),
16234
+ // Exhaustive per-action map; the builder pre-fills every action with 0.
16235
+ //
16236
+ // Spelled out member-by-member rather than `z.record(ActionTaken, …)`. Zod
16237
+ // enforces exhaustiveness either way, but z.record emits `propertyNames` +
16238
+ // `additionalProperties` into a generated schema document, and a type
16239
+ // generator renders THAT with every key optional — a sender built against
16240
+ // the generated type would typecheck and still be rejected at runtime. An
16241
+ // explicit object emits `properties` + `required`, so generated types
16242
+ // demand all five.
16243
+ //
16244
+ // `satisfies Record<ActionTaken, …>` keeps the link to the enum: adding an
16245
+ // ActionTaken member is a COMPILE error here instead of silent drift.
16246
+ // `.strict()` is load-bearing — it rejects an unknown action key, which a
16247
+ // bare object would silently STRIP, accepting a miscounted map as valid.
16248
+ byAction: external_exports.object({
16249
+ warn: external_exports.number().int().min(0),
16250
+ redact: external_exports.number().int().min(0),
16251
+ block: external_exports.number().int().min(0),
16252
+ allow: external_exports.number().int().min(0),
16253
+ log: external_exports.number().int().min(0)
16254
+ }).strict()
16255
+ }).meta({ id: "StorePosturePolicyCounts" });
16256
+ var StorePosturePlugin = external_exports.object({
16257
+ /** Package name of the reporting plugin. */
16258
+ package: external_exports.string().min(1).max(200),
16259
+ version: external_exports.string().min(1).max(64),
16260
+ /** Version of the bundled core, when the build records one separately. */
16261
+ ossVersion: external_exports.string().max(64).nullable(),
16262
+ /**
16263
+ * `version` of the policy bundle this machine last fetched. Bounded at 200
16264
+ * rather than the 64 a bare sha256 hex digest needs today, so a later
16265
+ * format with an algorithm prefix does not start rejecting the channel.
16266
+ */
16267
+ policyBundleVersion: external_exports.string().max(200).nullable(),
16268
+ /** Epoch millis, on the CLIENT clock, of that fetch. */
16269
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
16270
+ }).meta({ id: "StorePosturePlugin" });
16271
+ var StorePostureSnapshot = external_exports.object({
16272
+ deviceId: external_exports.guid(),
16273
+ hostname: external_exports.string().min(1).max(253),
16274
+ // Epoch millis on the CLIENT clock. Bounded by what a receiving store
16275
+ // accepts (see MAX_DATE_MS), not by what a JavaScript Date can hold.
16276
+ capturedAt: external_exports.number().int().min(0).max(MAX_DATE_MS),
16277
+ // False is a measurement, not an error state: "no local store exists on
16278
+ // this machine".
16279
+ storePresent: external_exports.boolean(),
16280
+ schemaVersion: external_exports.number().int().min(0).max(MAX_INT4).nullable(),
16281
+ // PRAGMA user_version
16282
+ findingsTotal: external_exports.number().int().min(0).max(MAX_INT4),
16283
+ // Epoch millis, bounded like `capturedAt` — see MAX_DATE_MS on what that
16284
+ // bound does and does not do. Worth stating for these two specifically:
16285
+ // they are read from the local store's own ROWS rather than from this
16286
+ // machine's clock, so a damaged or hand-edited store is enough to produce
16287
+ // an out-of-range value with no clock skew involved.
16288
+ findingsFirstAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16289
+ findingsLastAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16290
+ packs: external_exports.array(StorePosturePack).max(500),
16291
+ policyCounts: StorePosturePolicyCounts,
16292
+ // OPTIONAL, not nullable: a reporter that predates this member keeps
16293
+ // getting its 200 without a payload change.
16294
+ plugin: StorePosturePlugin.optional()
16295
+ }).meta({ id: "StorePostureSnapshot" });
16296
+ var CAPTURE_VERSION_PREFIX = "capture/";
16297
+ var RecordAuditEventRequest = AuditEventInput.extend({
16298
+ inspections: external_exports.array(ToolCallInspection).default([])
16299
+ }).refine((v) => v.inspections.every((i) => !i.ruleVersion.startsWith(CAPTURE_VERSION_PREFIX)), {
16300
+ message: `inspections[].ruleVersion must not start with \`${CAPTURE_VERSION_PREFIX}\` \u2014 that namespace is reserved for capture definitions the control plane mints itself`,
16301
+ path: ["inspections"]
16302
+ }).meta({ id: "RecordAuditEventRequest" });
16303
+ var IngestAck = external_exports.object({
16304
+ accepted: external_exports.number().int().nonnegative(),
16305
+ duplicates: external_exports.number().int().nonnegative()
16306
+ });
16307
+ var PRINTABLE = /^[^\p{Cc}\p{Cf}]*$/u;
16308
+ var printable = (max) => external_exports.string().max(max).regex(PRINTABLE, "must not contain control characters");
16309
+ var PluginWhoami = external_exports.object({
16310
+ tenantName: printable(200),
16311
+ userEmail: printable(320),
16312
+ role: printable(64),
16313
+ keyKind: printable(64),
16314
+ serverTime: printable(64)
16315
+ });
16316
+ var ControlPlaneErrorBody = external_exports.object({
16317
+ error: external_exports.object({
16318
+ code: external_exports.string().optional(),
16319
+ message: external_exports.string().optional()
16320
+ }).optional()
16321
+ });
16322
+
16205
16323
  // ../../packages/schema/src/zod/registry.ts
16206
16324
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
16207
16325
  var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -16504,15 +16622,15 @@ function summaryToDetectionListItem(s) {
16504
16622
  }
16505
16623
  function rowToDetectionDetail(row, findingsLast30d, update) {
16506
16624
  const rules = row.rules.flatMap((r) => {
16507
- const parsed = Matcher.safeParse(r.matcher);
16508
- if (!parsed.success) return [];
16625
+ const parsed2 = Matcher.safeParse(r.matcher);
16626
+ if (!parsed2.success) return [];
16509
16627
  return [
16510
16628
  {
16511
16629
  id: r.id,
16512
16630
  name: r.name,
16513
16631
  category: r.category,
16514
16632
  severity: r.severity,
16515
- matcher: parsed.data
16633
+ matcher: parsed2.data
16516
16634
  }
16517
16635
  ];
16518
16636
  });
@@ -17158,8 +17276,8 @@ function toApiAction(dbVal) {
17158
17276
  }
17159
17277
  function toApiCategory(dbVal) {
17160
17278
  if (dbVal === "code_context") return "source_code";
17161
- const parsed = FindingCategory.safeParse(dbVal);
17162
- return parsed.success ? parsed.data : "custom";
17279
+ const parsed2 = FindingCategory.safeParse(dbVal);
17280
+ return parsed2.success ? parsed2.data : "custom";
17163
17281
  }
17164
17282
  function toApiProvider(sourceTool) {
17165
17283
  return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
@@ -17789,6 +17907,9 @@ var WorkspaceSettings = external_exports.object({
17789
17907
  function defaultWorkspaceSettings() {
17790
17908
  return WorkspaceSettings.parse({});
17791
17909
  }
17910
+ function isAttached(settings) {
17911
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
17912
+ }
17792
17913
  function toInventoryRow(input, id, now) {
17793
17914
  return {
17794
17915
  id,
@@ -18056,8 +18177,8 @@ function builtinPolicyIsReversible(id) {
18056
18177
  return BUILTIN_POLICY_SPECS[id].reversible;
18057
18178
  }
18058
18179
  function policyIdIsReversible(policyId) {
18059
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18060
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18180
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18181
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18061
18182
  return builtinPolicyIsReversible(id);
18062
18183
  }
18063
18184
  var DEFAULT_ACTIONS = Object.fromEntries(
@@ -18068,8 +18189,8 @@ var BUILTIN_POLICIES = Object.fromEntries(
18068
18189
  );
18069
18190
  var DEFAULT_PACK_POLICY_ID = "monitor";
18070
18191
  function policyIdToAction(policyId) {
18071
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18072
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18192
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18193
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18073
18194
  return BUILTIN_POLICIES[id].action;
18074
18195
  }
18075
18196
  var UsedByItem = external_exports.object({
@@ -18512,53 +18633,6 @@ function reviewSeverityRank(reasons) {
18512
18633
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
18513
18634
  }
18514
18635
 
18515
- // ../../packages/persistence/src/ids.ts
18516
- import { createHash } from "crypto";
18517
- function sha256Hex(input) {
18518
- return createHash("sha256").update(input).digest("hex");
18519
- }
18520
- function inventoryId(objectType, identityKey) {
18521
- return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18522
- }
18523
- function sourceProjectId(url2) {
18524
- return sha256Hex(canonicalIdentity(["source_project", url2]));
18525
- }
18526
- function classifiedDataId(cls) {
18527
- return sha256Hex(canonicalIdentity(["classified_data", cls]));
18528
- }
18529
- function inspectionDefinitionId(ruleId, version2) {
18530
- return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18531
- }
18532
- function llmCallId(sessionId, messageId) {
18533
- return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18534
- }
18535
- function toolCallId(sessionId, toolUseId) {
18536
- return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18537
- }
18538
- function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18539
- return sha256Hex(
18540
- canonicalIdentity([
18541
- "inspection_finding",
18542
- auditEventId,
18543
- ruleId,
18544
- String(spanStart),
18545
- String(spanEnd)
18546
- ])
18547
- );
18548
- }
18549
- var NO_SESSION = "no_session";
18550
- var NO_PATH = "no_path";
18551
- function captureId(sessionId, contentHash, filePath = null) {
18552
- return sha256Hex(
18553
- canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18554
- );
18555
- }
18556
-
18557
- // ../../packages/persistence/src/internal/snapshot.ts
18558
- import { randomUUID } from "crypto";
18559
- import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync2, statSync } from "fs";
18560
- import { basename, dirname, join } from "path";
18561
-
18562
18636
  // ../../packages/persistence/src/paths.ts
18563
18637
  import {
18564
18638
  chmodSync,
@@ -18609,6 +18683,23 @@ function tightenPerms(file2) {
18609
18683
  function writeExclusiveOwnerOnlySync(file2, data) {
18610
18684
  writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
18611
18685
  }
18686
+ function writeOwnerOnlyFileSync(file2, data) {
18687
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
18688
+ try {
18689
+ rmSync(tmp, { force: true });
18690
+ } catch {
18691
+ }
18692
+ try {
18693
+ writeExclusiveOwnerOnlySync(tmp, data);
18694
+ renameSync(tmp, file2);
18695
+ } finally {
18696
+ try {
18697
+ rmSync(tmp, { force: true });
18698
+ } catch {
18699
+ }
18700
+ }
18701
+ tightenFile(file2);
18702
+ }
18612
18703
  function classifyOccupant(file2) {
18613
18704
  try {
18614
18705
  if (lstatSync(file2).isSymbolicLink()) return { kind: "symlink" };
@@ -18667,7 +18758,123 @@ function publishByLink(tmp, file2, data) {
18667
18758
  }
18668
18759
  }
18669
18760
 
18761
+ // ../../packages/persistence/src/control-plane-credential.ts
18762
+ function controlPlaneCredentialPath(settingsDir2) {
18763
+ return join(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
18764
+ }
18765
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
18766
+ function isSafeEndpoint(endpoint) {
18767
+ let parsed2;
18768
+ try {
18769
+ parsed2 = new URL(endpoint);
18770
+ } catch {
18771
+ return false;
18772
+ }
18773
+ if (parsed2.protocol === "https:") return true;
18774
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
18775
+ }
18776
+ function repairOrRefuseMode(file2) {
18777
+ const link = lstatSync2(file2, { throwIfNoEntry: false });
18778
+ if (link === void 0) return "absent";
18779
+ if (link.isSymbolicLink()) return "untrusted";
18780
+ const stat = statSync(file2, { throwIfNoEntry: false });
18781
+ if (stat === void 0) return "absent";
18782
+ const uid = process.getuid?.();
18783
+ if (uid !== void 0 && stat.uid !== uid) return "untrusted";
18784
+ if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
18785
+ try {
18786
+ chmodSync2(file2, DATA_FILE_MODE);
18787
+ } catch {
18788
+ return "untrusted";
18789
+ }
18790
+ }
18791
+ return "ok";
18792
+ }
18793
+ function readControlPlaneCredentialState(settingsDir2, connection) {
18794
+ const file2 = controlPlaneCredentialPath(settingsDir2);
18795
+ let raw;
18796
+ const gate = repairOrRefuseMode(file2);
18797
+ if (gate === "absent") return { usable: false, reason: "absent" };
18798
+ if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
18799
+ try {
18800
+ raw = readFileSync(file2, "utf8");
18801
+ } catch (err) {
18802
+ const code = err.code;
18803
+ return { usable: false, reason: code === "ENOENT" ? "absent" : "unreadable" };
18804
+ }
18805
+ let parsed2;
18806
+ try {
18807
+ parsed2 = JSON.parse(raw);
18808
+ } catch {
18809
+ return { usable: false, reason: "malformed" };
18810
+ }
18811
+ const result = AttachedCredential.safeParse(parsed2);
18812
+ if (!result.success) return { usable: false, reason: "malformed" };
18813
+ if (!isSafeEndpoint(result.data.endpoint)) {
18814
+ return { usable: false, reason: "unsafe-endpoint" };
18815
+ }
18816
+ if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
18817
+ return {
18818
+ usable: false,
18819
+ reason: "endpoint-mismatch",
18820
+ credentialEndpoint: result.data.endpoint,
18821
+ settingsEndpoint: connection.endpoint
18822
+ };
18823
+ }
18824
+ return { usable: true, credential: result.data };
18825
+ }
18826
+
18827
+ // ../../packages/persistence/src/database.ts
18828
+ import { randomUUID as randomUUID10 } from "crypto";
18829
+ import { join as join3, sep } from "path";
18830
+ import { DatabaseSync } from "node:sqlite";
18831
+
18832
+ // ../../packages/persistence/src/ids.ts
18833
+ import { createHash } from "crypto";
18834
+ function sha256Hex(input) {
18835
+ return createHash("sha256").update(input).digest("hex");
18836
+ }
18837
+ function inventoryId(objectType, identityKey) {
18838
+ return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18839
+ }
18840
+ function sourceProjectId(url2) {
18841
+ return sha256Hex(canonicalIdentity(["source_project", url2]));
18842
+ }
18843
+ function classifiedDataId(cls) {
18844
+ return sha256Hex(canonicalIdentity(["classified_data", cls]));
18845
+ }
18846
+ function inspectionDefinitionId(ruleId, version2) {
18847
+ return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18848
+ }
18849
+ function llmCallId(sessionId, messageId) {
18850
+ return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18851
+ }
18852
+ function toolCallId(sessionId, toolUseId) {
18853
+ return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18854
+ }
18855
+ function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18856
+ return sha256Hex(
18857
+ canonicalIdentity([
18858
+ "inspection_finding",
18859
+ auditEventId,
18860
+ ruleId,
18861
+ String(spanStart),
18862
+ String(spanEnd)
18863
+ ])
18864
+ );
18865
+ }
18866
+ var NO_SESSION = "no_session";
18867
+ var NO_PATH = "no_path";
18868
+ function captureId(sessionId, contentHash, filePath = null) {
18869
+ return sha256Hex(
18870
+ canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18871
+ );
18872
+ }
18873
+
18670
18874
  // ../../packages/persistence/src/internal/snapshot.ts
18875
+ import { randomUUID } from "crypto";
18876
+ import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync3, statSync as statSync2 } from "fs";
18877
+ import { basename, dirname, join as join2 } from "path";
18671
18878
  function backupPath(file2, tag) {
18672
18879
  return `${file2}.${tag}.${String(Date.now())}.${randomUUID().slice(0, 8)}.bak`;
18673
18880
  }
@@ -18677,15 +18884,15 @@ var STAGED_NAME_SUFFIX = `.bak${SNAPSHOT_STAGING_SUFFIX}`;
18677
18884
  var SNAPSHOT_STAGING_COPY = "copy";
18678
18885
  function createSnapshotStaging(backup) {
18679
18886
  const stage = `${backup}${SNAPSHOT_STAGING_SUFFIX}`;
18680
- rmSync2(stage, { recursive: true, force: true });
18887
+ rmSync3(stage, { recursive: true, force: true });
18681
18888
  mkdirOwnerOnlySync(stage);
18682
18889
  tightenDir(stage);
18683
- return { stage, copy: join(stage, SNAPSHOT_STAGING_COPY) };
18890
+ return { stage, copy: join2(stage, SNAPSHOT_STAGING_COPY) };
18684
18891
  }
18685
18892
  function idleMs(entry) {
18686
- for (const candidate of [join(entry, SNAPSHOT_STAGING_COPY), entry]) {
18893
+ for (const candidate of [join2(entry, SNAPSHOT_STAGING_COPY), entry]) {
18687
18894
  try {
18688
- return Date.now() - statSync(candidate).mtimeMs;
18895
+ return Date.now() - statSync2(candidate).mtimeMs;
18689
18896
  } catch {
18690
18897
  }
18691
18898
  }
@@ -18702,11 +18909,11 @@ function reapStalePartials(file2) {
18702
18909
  }
18703
18910
  for (const name of entries) {
18704
18911
  if (!name.startsWith(prefix) || !name.endsWith(STAGED_NAME_SUFFIX)) continue;
18705
- const staging = join(dir, name);
18912
+ const staging = join2(dir, name);
18706
18913
  try {
18707
18914
  const idle = idleMs(staging);
18708
18915
  if (idle !== null && idle > STALE_PARTIAL_MS) {
18709
- rmSync2(staging, { recursive: true, force: true });
18916
+ rmSync3(staging, { recursive: true, force: true });
18710
18917
  }
18711
18918
  } catch {
18712
18919
  }
@@ -18720,13 +18927,13 @@ function snapshotStore(db, backup) {
18720
18927
  renameSync2(copy, backup);
18721
18928
  } catch (error51) {
18722
18929
  try {
18723
- rmSync2(stage, { recursive: true, force: true });
18930
+ rmSync3(stage, { recursive: true, force: true });
18724
18931
  } catch {
18725
18932
  }
18726
18933
  throw error51;
18727
18934
  }
18728
18935
  try {
18729
- rmSync2(stage, { recursive: true, force: true });
18936
+ rmSync3(stage, { recursive: true, force: true });
18730
18937
  } catch {
18731
18938
  }
18732
18939
  }
@@ -18741,7 +18948,7 @@ function moveStoreAside(file2, backup) {
18741
18948
  renameSync2(sidecar, moved);
18742
18949
  undo.push([moved, sidecar]);
18743
18950
  } catch {
18744
- rmSync2(sidecar, { force: true });
18951
+ rmSync3(sidecar, { force: true });
18745
18952
  }
18746
18953
  }
18747
18954
  } catch (error51) {
@@ -18757,14 +18964,14 @@ function moveStoreAside(file2, backup) {
18757
18964
  }
18758
18965
  function discardStore(file2, backup) {
18759
18966
  try {
18760
- rmSync2(file2, { force: true });
18967
+ rmSync3(file2, { force: true });
18761
18968
  for (const sidecar of dbSidecars(file2)) {
18762
- rmSync2(sidecar, { force: true });
18969
+ rmSync3(sidecar, { force: true });
18763
18970
  }
18764
18971
  } catch (error51) {
18765
18972
  if (existsSync(file2)) {
18766
18973
  try {
18767
- rmSync2(backup, { force: true });
18974
+ rmSync3(backup, { force: true });
18768
18975
  } catch {
18769
18976
  }
18770
18977
  }
@@ -18996,10 +19203,31 @@ function applyMigrations(db, file2) {
18996
19203
  if (drained) applyLegacyDropMigration(db, file2);
18997
19204
  }
18998
19205
  }
19206
+ function readLegacyTables(db) {
19207
+ let holdsRows = false;
19208
+ const marks = [];
19209
+ for (const table2 of ["events", "findings"]) {
19210
+ try {
19211
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
19212
+ if (row === void 0) {
19213
+ holdsRows = true;
19214
+ marks.push(`${table2}:unreadable`);
19215
+ continue;
19216
+ }
19217
+ if (row.n > 0) holdsRows = true;
19218
+ marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
19219
+ } catch {
19220
+ holdsRows = true;
19221
+ marks.push(`${table2}:unreadable`);
19222
+ }
19223
+ }
19224
+ return { holdsRows, mark: marks.join("|") };
19225
+ }
18999
19226
  function applyLegacyDropMigration(db, file2) {
19000
19227
  const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
19001
19228
  if (!migration) return;
19002
- if (file2) {
19229
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
19230
+ if (file2 !== void 0 && before?.holdsRows === true) {
19003
19231
  try {
19004
19232
  backupBeforeLegacyDrop(db, file2);
19005
19233
  } catch (error51) {
@@ -19013,6 +19241,12 @@ function applyLegacyDropMigration(db, file2) {
19013
19241
  () => {
19014
19242
  const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
19015
19243
  if (alreadyDropped) return;
19244
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
19245
+ akaWarn(
19246
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
19247
+ );
19248
+ return;
19249
+ }
19016
19250
  for (const statement of splitStatements(migration.sql)) {
19017
19251
  db.exec(statement);
19018
19252
  }
@@ -19367,8 +19601,8 @@ function safeJson(s, fallback) {
19367
19601
  function parseJsonObject(s) {
19368
19602
  if (s == null) return void 0;
19369
19603
  try {
19370
- const parsed = JSON.parse(s);
19371
- if (typeof parsed === "object" && parsed !== null) return parsed;
19604
+ const parsed2 = JSON.parse(s);
19605
+ if (typeof parsed2 === "object" && parsed2 !== null) return parsed2;
19372
19606
  } catch {
19373
19607
  }
19374
19608
  return void 0;
@@ -19379,16 +19613,16 @@ function encodeKeysetCursor(payload) {
19379
19613
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
19380
19614
  }
19381
19615
  function decodeKeysetCursor(cursor) {
19382
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19383
- if (parsed !== void 0 && "startedAtMs" in parsed && "id" in parsed && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19616
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19617
+ if (parsed2 !== void 0 && "startedAtMs" in parsed2 && "id" in parsed2 && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19384
19618
  // resumes from is epoch millis, and a payload carrying ±Infinity or a
19385
19619
  // fraction binds cleanly rather than failing — returning an EMPTY page with
19386
19620
  // a null cursor, which a caller reads as "end of list". That is the one
19387
19621
  // outcome a cursor that does not decode must never produce, since the
19388
19622
  // documented behaviour above is to restart from the top. (`1e999` is valid
19389
19623
  // JSON and parses to Infinity; a bare `NaN` is not, so it cannot arrive.)
19390
- Number.isInteger(parsed.startedAtMs) && typeof parsed.id === "string") {
19391
- return parsed;
19624
+ Number.isInteger(parsed2.startedAtMs) && typeof parsed2.id === "string") {
19625
+ return parsed2;
19392
19626
  }
19393
19627
  return null;
19394
19628
  }
@@ -19453,18 +19687,18 @@ var DB_EVENT_TYPE_TO_KIND = {
19453
19687
  };
19454
19688
  function safeParseStringArray(raw) {
19455
19689
  if (!raw) return [];
19456
- const parsed = safeJson(raw, null);
19457
- return Array.isArray(parsed) ? parsed : [];
19690
+ const parsed2 = safeJson(raw, null);
19691
+ return Array.isArray(parsed2) ? parsed2 : [];
19458
19692
  }
19459
19693
  var DEFAULT_HARNESS = HARNESS.ClaudeCode;
19460
19694
  function toHarness(raw) {
19461
- const parsed = Harness.safeParse(raw);
19462
- return parsed.success ? parsed.data : DEFAULT_HARNESS;
19695
+ const parsed2 = Harness.safeParse(raw);
19696
+ return parsed2.success ? parsed2.data : DEFAULT_HARNESS;
19463
19697
  }
19464
19698
  function resolveLifecycle(row, lastActivityMs, nowMs) {
19465
19699
  if (row.status) {
19466
- const parsed = SessionStatus.safeParse(row.status);
19467
- if (parsed.success) return { status: parsed.data, endedAtMs: row.ended_at };
19700
+ const parsed2 = SessionStatus.safeParse(row.status);
19701
+ if (parsed2.success) return { status: parsed2.data, endedAtMs: row.ended_at };
19468
19702
  }
19469
19703
  if (row.ended_at !== null) return { status: "completed", endedAtMs: row.ended_at };
19470
19704
  if (lastActivityMs >= nowMs - LIVE_ACTIVITY_WINDOW_MS) {
@@ -20423,9 +20657,9 @@ var SqliteDetectionsRepository = class {
20423
20657
  const ruleIds = /* @__PURE__ */ new Set();
20424
20658
  for (const r of rows) {
20425
20659
  if (intToBool(r.enabled)) active += 1;
20426
- const parsed = parseRules(r.rulesJson);
20427
- rules += parsed.length;
20428
- for (const rule of parsed) {
20660
+ const parsed2 = parseRules(r.rulesJson);
20661
+ rules += parsed2.length;
20662
+ for (const rule of parsed2) {
20429
20663
  if (typeof rule.id === "string") ruleIds.add(rule.id);
20430
20664
  }
20431
20665
  }
@@ -20959,12 +21193,12 @@ function encodeGroupCursor(group) {
20959
21193
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
20960
21194
  }
20961
21195
  function decodeGroupCursor(cursor) {
20962
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
20963
- if (parsed !== void 0 && typeof parsed.sev === "string" && typeof parsed.t === "string" && typeof parsed.id === "string") {
21196
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
21197
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.id === "string") {
20964
21198
  return {
20965
- severity: parsed.sev,
20966
- latestDetectedAt: parsed.t,
20967
- id: parsed.id
21199
+ severity: parsed2.sev,
21200
+ latestDetectedAt: parsed2.t,
21201
+ id: parsed2.id
20968
21202
  };
20969
21203
  }
20970
21204
  return null;
@@ -22098,16 +22332,16 @@ var SqliteInstalledPacksRepository = class {
22098
22332
  continue;
22099
22333
  }
22100
22334
  for (const entry of raw) {
22101
- const parsed = Rule.safeParse(entry);
22102
- if (parsed.success) {
22103
- out.rules.push(parsed.data);
22104
- out.ruleActions.set(parsed.data.id, action);
22105
- out.ruleVersions.set(parsed.data.id, row.version);
22106
- if (reversible) out.reversibleRules.add(parsed.data.id);
22107
- else out.reversibleRules.delete(parsed.data.id);
22335
+ const parsed2 = Rule.safeParse(entry);
22336
+ if (parsed2.success) {
22337
+ out.rules.push(parsed2.data);
22338
+ out.ruleActions.set(parsed2.data.id, action);
22339
+ out.ruleVersions.set(parsed2.data.id, row.version);
22340
+ if (reversible) out.reversibleRules.add(parsed2.data.id);
22341
+ else out.reversibleRules.delete(parsed2.data.id);
22108
22342
  } else {
22109
22343
  out.invalidRules += 1;
22110
- reject(pack, printableRuleId(entry), firstIssueReason(parsed.error));
22344
+ reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
22111
22345
  }
22112
22346
  }
22113
22347
  }
@@ -23497,15 +23731,15 @@ function encodeReuseCursor(payload) {
23497
23731
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
23498
23732
  }
23499
23733
  function decodeReuseCursor(cursor) {
23500
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23501
- if (parsed !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23734
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23735
+ if (parsed2 !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23502
23736
  // ±Infinity or a fraction binds cleanly and returns an EMPTY page with a
23503
23737
  // null cursor, which the caller reads as "end of list" — the one outcome a
23504
23738
  // malformed cursor must never produce, since restarting from the top is the
23505
23739
  // documented behaviour and the only recoverable one. (`1e999` is valid JSON
23506
23740
  // and parses to Infinity; a bare `NaN` is not, so it cannot arrive here.)
23507
- Number.isInteger(parsed.occurrences) && typeof parsed.pointerId === "string") {
23508
- return { occurrences: parsed.occurrences, pointerId: parsed.pointerId };
23741
+ Number.isInteger(parsed2.occurrences) && typeof parsed2.pointerId === "string") {
23742
+ return { occurrences: parsed2.occurrences, pointerId: parsed2.pointerId };
23509
23743
  }
23510
23744
  return null;
23511
23745
  }
@@ -25234,7 +25468,7 @@ function openAndInitialize(file2) {
25234
25468
  }
25235
25469
  function openLocalDatabase(dir) {
25236
25470
  ensureDataDirSync(dir);
25237
- const file2 = join2(dir, DB_FILENAME);
25471
+ const file2 = join3(dir, DB_FILENAME);
25238
25472
  reapStalePartials(file2);
25239
25473
  const {
25240
25474
  db,
@@ -25470,9 +25704,9 @@ import {
25470
25704
  closeSync,
25471
25705
  existsSync as existsSync2,
25472
25706
  openSync,
25473
- readFileSync,
25474
- rmSync as rmSync3,
25475
- statSync as statSync2,
25707
+ readFileSync as readFileSync2,
25708
+ rmSync as rmSync4,
25709
+ statSync as statSync3,
25476
25710
  writeFileSync as writeFileSync2
25477
25711
  } from "fs";
25478
25712
  import { hostname as hostname3 } from "os";
@@ -25490,20 +25724,20 @@ function computeFindingKey(input) {
25490
25724
 
25491
25725
  // ../../packages/persistence/src/fingerprint.ts
25492
25726
  import { createHmac, randomBytes } from "crypto";
25493
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
25494
- import { join as join3 } from "path";
25727
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
25728
+ import { join as join4 } from "path";
25495
25729
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25496
25730
  var EXCEPTION_KEY_FILENAME = "exception.key";
25497
25731
  var KEY_MATERIAL_BYTES = 32;
25498
25732
  function keyFilePath(dataDir2) {
25499
- return join3(dataDir2, EXCEPTION_KEY_FILENAME);
25733
+ return join4(dataDir2, EXCEPTION_KEY_FILENAME);
25500
25734
  }
25501
25735
  function parseKeyFile(raw) {
25502
- const parsed = JSON.parse(raw);
25503
- if (typeof parsed !== "object" || parsed === null) {
25736
+ const parsed2 = JSON.parse(raw);
25737
+ if (typeof parsed2 !== "object" || parsed2 === null) {
25504
25738
  throw new Error("exception key file is corrupt: not a JSON object");
25505
25739
  }
25506
- const { version: version2, material } = parsed;
25740
+ const { version: version2, material } = parsed2;
25507
25741
  if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
25508
25742
  throw new Error("exception key file is corrupt: bad version");
25509
25743
  }
@@ -25534,7 +25768,7 @@ var FloorUnreadableError = class extends Error {
25534
25768
  }
25535
25769
  };
25536
25770
  function storedKeyVersionFloor(dataDir2) {
25537
- const file2 = join3(dataDir2, DB_FILENAME);
25771
+ const file2 = join4(dataDir2, DB_FILENAME);
25538
25772
  if (!existsSync3(file2)) return 0;
25539
25773
  let db;
25540
25774
  try {
@@ -25589,7 +25823,7 @@ function occupantMessage(file2, kind) {
25589
25823
  function readFingerprintKey(dataDir2) {
25590
25824
  let raw;
25591
25825
  try {
25592
- raw = readFileSync2(keyFilePath(dataDir2), "utf8");
25826
+ raw = readFileSync3(keyFilePath(dataDir2), "utf8");
25593
25827
  } catch (err) {
25594
25828
  if (err.code === "ENOENT") return null;
25595
25829
  throw err instanceof Error ? err : new Error(String(err));
@@ -25615,18 +25849,22 @@ function fingerprintValue(key, raw) {
25615
25849
  import { renameSync as renameSync3 } from "fs";
25616
25850
  import { mkdir } from "fs/promises";
25617
25851
  import { homedir } from "os";
25618
- import { join as join4 } from "path";
25852
+ import { join as join5 } from "path";
25619
25853
  function defaultDataDir() {
25620
- return join4(homedir(), ".aka");
25854
+ return join5(homedir(), ".aka");
25621
25855
  }
25622
25856
  function settingsDir(base = defaultDataDir()) {
25623
- return join4(base, "settings");
25857
+ return join5(base, "settings");
25624
25858
  }
25625
25859
  function dataDir(base = defaultDataDir()) {
25626
- return join4(base, "data");
25860
+ return join5(base, "data");
25627
25861
  }
25628
25862
  function dbPath(base = defaultDataDir()) {
25629
- return join4(dataDir(base), "aka.db");
25863
+ return join5(dataDir(base), "aka.db");
25864
+ }
25865
+ async function ensureDataDir(dir = defaultDataDir()) {
25866
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
25867
+ tightenDir(dir);
25630
25868
  }
25631
25869
  function ensureLayoutDirSync(dir = defaultDataDir()) {
25632
25870
  ensureDataDirSync(dir);
@@ -25639,8 +25877,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25639
25877
  for (const { name, dest } of moves) {
25640
25878
  try {
25641
25879
  ensureDataDirSync(dest);
25642
- const moved = join4(dest, name);
25643
- renameSync3(join4(base, name), moved);
25880
+ const moved = join5(dest, name);
25881
+ renameSync3(join5(base, name), moved);
25644
25882
  tightenFile(moved);
25645
25883
  } catch {
25646
25884
  }
@@ -25648,7 +25886,7 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25648
25886
  }
25649
25887
 
25650
25888
  // ../../packages/persistence/src/managed-settings.ts
25651
- import { readFileSync as readFileSync3 } from "fs";
25889
+ import { readFileSync as readFileSync4 } from "fs";
25652
25890
  import { posix, win32 } from "path";
25653
25891
  function managedSettingsPaths(platform2 = process.platform) {
25654
25892
  if (platform2 === "darwin") {
@@ -25666,14 +25904,14 @@ function readManagedSettings(paths = managedSettingsPaths()) {
25666
25904
  for (const path of paths) {
25667
25905
  let text;
25668
25906
  try {
25669
- text = readFileSync3(path, "utf8");
25907
+ text = readFileSync4(path, "utf8");
25670
25908
  } catch {
25671
25909
  continue;
25672
25910
  }
25673
25911
  const record2 = parseJsonObject(text);
25674
25912
  if (!record2) continue;
25675
- const parsed = ManagedSettings.safeParse(record2);
25676
- if (parsed.success) return parsed.data;
25913
+ const parsed2 = ManagedSettings.safeParse(record2);
25914
+ if (parsed2.success) return parsed2.data;
25677
25915
  }
25678
25916
  return null;
25679
25917
  }
@@ -25713,14 +25951,14 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
25713
25951
  }
25714
25952
 
25715
25953
  // ../../packages/persistence/src/settings.ts
25716
- import { readFileSync as readFileSync4 } from "fs";
25717
- import { join as join5 } from "path";
25954
+ import { readFileSync as readFileSync5 } from "fs";
25955
+ import { join as join6 } from "path";
25718
25956
  var SETTINGS_FILENAME = "settings.json";
25719
25957
  function readWorkspaceSettings(base = defaultDataDir()) {
25720
25958
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
25721
25959
  }
25722
25960
  function readUserSettings(base) {
25723
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
25961
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
25724
25962
  if (!record2) return defaultWorkspaceSettings();
25725
25963
  try {
25726
25964
  return WorkspaceSettings.parse(record2);
@@ -25731,13 +25969,17 @@ function readUserSettings(base) {
25731
25969
  function readJson(file2) {
25732
25970
  let text;
25733
25971
  try {
25734
- text = readFileSync4(file2, "utf8");
25972
+ text = readFileSync5(file2, "utf8");
25735
25973
  } catch {
25736
25974
  return null;
25737
25975
  }
25738
25976
  return parseJsonObject(text) ?? null;
25739
25977
  }
25740
25978
 
25979
+ // ../../packages/persistence/src/store-symlinks.ts
25980
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
25981
+ import { dirname as dirname2, join as join7, resolve } from "path";
25982
+
25741
25983
  // ../../packages/persistence/src/vault/crypto.ts
25742
25984
  import {
25743
25985
  createCipheriv,
@@ -25750,20 +25992,20 @@ import {
25750
25992
  // ../../packages/persistence/src/vault/key-provider.ts
25751
25993
  import { execFileSync } from "child_process";
25752
25994
  import { randomBytes as randomBytes2 } from "crypto";
25753
- import { chmodSync as chmodSync2, readFileSync as readFileSync5, renameSync as renameSync4, rmSync as rmSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
25754
- import { join as join6 } from "path";
25995
+ import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
25996
+ import { join as join8 } from "path";
25755
25997
 
25756
25998
  // ../../packages/persistence/src/vault/vault.ts
25757
25999
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
25758
26000
 
25759
26001
  // ../../packages/persistence/src/warn-era-cap.ts
25760
- import { existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
25761
- import { join as join7 } from "path";
26002
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
26003
+ import { join as join9 } from "path";
25762
26004
  var MARKER = "warn-era-capped";
25763
26005
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25764
26006
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
25765
- const marker = join7(dataDir2, MARKER);
25766
- if (existsSync4(marker)) return { capped: 0, skipped: "already-run" };
26007
+ const marker = join9(dataDir2, MARKER);
26008
+ if (existsSync5(marker)) return { capped: 0, skipped: "already-run" };
25767
26009
  const capped = db.policies.capCategoryActions();
25768
26010
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
25769
26011
  `, { mode: DATA_FILE_MODE });
@@ -25771,8 +26013,8 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25771
26013
  }
25772
26014
 
25773
26015
  // ../../packages/plugin-sdk/src/config.ts
25774
- import { existsSync as existsSync5 } from "fs";
25775
- import { join as join8 } from "path";
26016
+ import { existsSync as existsSync6 } from "fs";
26017
+ import { join as join10 } from "path";
25776
26018
 
25777
26019
  // ../../packages/plugin-sdk/src/provider-env.ts
25778
26020
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -25808,8 +26050,8 @@ function hostOf(url2) {
25808
26050
  }
25809
26051
  }
25810
26052
  function resolveProvider() {
25811
- const parsed = ProviderEnvSchema.safeParse(process.env);
25812
- const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
26053
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
26054
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
25813
26055
  if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
25814
26056
  if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
25815
26057
  const baseUrl = env.ANTHROPIC_BASE_URL;
@@ -25826,8 +26068,8 @@ function resolveProvider() {
25826
26068
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
25827
26069
  try {
25828
26070
  ensureLayoutDirSync(base);
25829
- const settingsFile = join8(settingsDir(base), "settings.json");
25830
- if (existsSync5(settingsFile)) tightenFile(settingsFile);
26071
+ const settingsFile = join10(settingsDir(base), "settings.json");
26072
+ if (existsSync6(settingsFile)) tightenFile(settingsFile);
25831
26073
  } catch {
25832
26074
  }
25833
26075
  migrateLegacyLayout(base);
@@ -25850,9 +26092,9 @@ function resolveProviderSafe(resolveProviderFn) {
25850
26092
  }
25851
26093
 
25852
26094
  // ../../packages/plugin-sdk/src/config-inventory.ts
25853
- import { readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync, statSync as statSync5 } from "fs";
26095
+ import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
25854
26096
  import { homedir as homedir2 } from "os";
25855
- import { basename as basename3, join as join10 } from "path";
26097
+ import { basename as basename3, join as join12 } from "path";
25856
26098
 
25857
26099
  // ../../packages/detections/src/egress/registry.ts
25858
26100
  var EXTRACTOR_VERSION = "1";
@@ -27629,10 +27871,10 @@ var localhost_ref_default = {
27629
27871
  severity: "low",
27630
27872
  matcher: {
27631
27873
  type: "regex",
27632
- pattern: "\\b(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1)\\b",
27874
+ 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_])",
27633
27875
  flags: "g"
27634
27876
  },
27635
- examples: ["localhost", "127.0.0.1"]
27877
+ examples: ["localhost", "127.0.0.1", "0.0.0.0", "::1"]
27636
27878
  };
27637
27879
 
27638
27880
  // ../../rules/core-code-context/stack-trace.json
@@ -28941,8 +29183,8 @@ function bundledDetections() {
28941
29183
  }
28942
29184
 
28943
29185
  // ../../packages/plugin-sdk/src/repo.ts
28944
- import { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync4 } from "fs";
28945
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join9, sep as sep2 } from "path";
29186
+ import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
29187
+ import { basename as basename2, dirname as dirname3, isAbsolute, join as join11, sep as sep2 } from "path";
28946
29188
  function resolveRepo(cwd) {
28947
29189
  try {
28948
29190
  const root = findGitRoot(cwd);
@@ -28964,36 +29206,36 @@ function resolveWorktreeRoot(cwd) {
28964
29206
  function findGitRoot(start) {
28965
29207
  let dir = start;
28966
29208
  for (; ; ) {
28967
- if (existsSync6(join9(dir, ".git"))) return dir;
28968
- const parent = dirname2(dir);
29209
+ if (existsSync7(join11(dir, ".git"))) return dir;
29210
+ const parent = dirname3(dir);
28969
29211
  if (parent === dir) return void 0;
28970
29212
  dir = parent;
28971
29213
  }
28972
29214
  }
28973
29215
  function resolveGitContext(root) {
28974
- const dotGit = join9(root, ".git");
29216
+ const dotGit = join11(root, ".git");
28975
29217
  try {
28976
- if (statSync4(dotGit).isDirectory()) {
28977
- return { configPath: join9(dotGit, "config"), headRoot: root };
29218
+ if (statSync6(dotGit).isDirectory()) {
29219
+ return { configPath: join11(dotGit, "config"), headRoot: root };
28978
29220
  }
28979
29221
  } catch {
28980
29222
  return void 0;
28981
29223
  }
28982
29224
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
28983
29225
  if (!target) return void 0;
28984
- const gitdir = isAbsolute(target) ? target : join9(root, target);
28985
- if (existsSync6(join9(gitdir, "config"))) {
28986
- return { configPath: join9(gitdir, "config"), headRoot: root };
29226
+ const gitdir = isAbsolute(target) ? target : join11(root, target);
29227
+ if (existsSync7(join11(gitdir, "config"))) {
29228
+ return { configPath: join11(gitdir, "config"), headRoot: root };
28987
29229
  }
28988
- const commonRaw = safeRead(join9(gitdir, "commondir"))?.trim();
29230
+ const commonRaw = safeRead(join11(gitdir, "commondir"))?.trim();
28989
29231
  if (!commonRaw) return void 0;
28990
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join9(gitdir, commonRaw);
28991
- const headRoot = basename2(commonGitDir) === ".git" ? dirname2(commonGitDir) : root;
28992
- return { configPath: join9(commonGitDir, "config"), headRoot };
29232
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join11(gitdir, commonRaw);
29233
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
29234
+ return { configPath: join11(commonGitDir, "config"), headRoot };
28993
29235
  }
28994
29236
  function safeRead(path) {
28995
29237
  try {
28996
- return readFileSync6(path, "utf8");
29238
+ return readFileSync7(path, "utf8");
28997
29239
  } catch {
28998
29240
  return void 0;
28999
29241
  }
@@ -29054,7 +29296,7 @@ function buildIngestEvent(input) {
29054
29296
  }
29055
29297
 
29056
29298
  // ../../packages/plugin-sdk/src/isolated-scan.ts
29057
- import { existsSync as existsSync7 } from "fs";
29299
+ import { existsSync as existsSync8 } from "fs";
29058
29300
  import { fileURLToPath } from "url";
29059
29301
  import { Worker } from "worker_threads";
29060
29302
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -29068,7 +29310,7 @@ function resolveWorkerUrl() {
29068
29310
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
29069
29311
  const candidate = new URL(name, import.meta.url);
29070
29312
  try {
29071
- if (existsSync7(fileURLToPath(candidate))) {
29313
+ if (existsSync8(fileURLToPath(candidate))) {
29072
29314
  resolvedWorkerUrl = candidate;
29073
29315
  return candidate;
29074
29316
  }
@@ -29253,8 +29495,8 @@ function createIsolatedScanner(data, opts = {}) {
29253
29495
  }
29254
29496
  function enqueue(spec) {
29255
29497
  const next = chain.then(
29256
- () => new Promise((resolve2) => {
29257
- spec(resolve2);
29498
+ () => new Promise((resolve3) => {
29499
+ spec(resolve3);
29258
29500
  })
29259
29501
  );
29260
29502
  chain = next.then(
@@ -29265,7 +29507,7 @@ function createIsolatedScanner(data, opts = {}) {
29265
29507
  }
29266
29508
  return {
29267
29509
  scan(text, context, scanOpts) {
29268
- return enqueue((resolve2) => {
29510
+ return enqueue((resolve3) => {
29269
29511
  runOne(
29270
29512
  {
29271
29513
  budgetMs,
@@ -29278,23 +29520,23 @@ function createIsolatedScanner(data, opts = {}) {
29278
29520
  }),
29279
29521
  reply: (message) => {
29280
29522
  if (message.kind !== "result") return false;
29281
- resolve2({ status: "ok", findings: message.findings });
29523
+ resolve3({ status: "ok", findings: message.findings });
29282
29524
  return true;
29283
29525
  }
29284
29526
  },
29285
- resolve2
29527
+ resolve3
29286
29528
  );
29287
29529
  });
29288
29530
  },
29289
29531
  probe(rule) {
29290
- return enqueue((resolve2) => {
29532
+ return enqueue((resolve3) => {
29291
29533
  runOne(
29292
29534
  {
29293
29535
  budgetMs: probeBudgetMs,
29294
29536
  build: (id) => ({ kind: "probe", id, rule }),
29295
29537
  reply: (message) => {
29296
29538
  if (message.kind !== "probed") return false;
29297
- resolve2({
29539
+ resolve3({
29298
29540
  status: "ok",
29299
29541
  verdict: message.verdict,
29300
29542
  worstMs: message.worstMs,
@@ -29303,7 +29545,7 @@ function createIsolatedScanner(data, opts = {}) {
29303
29545
  return true;
29304
29546
  }
29305
29547
  },
29306
- resolve2
29548
+ resolve3
29307
29549
  );
29308
29550
  });
29309
29551
  },
@@ -29533,19 +29775,19 @@ function createGuardedScanner(partition, gateway, opts) {
29533
29775
 
29534
29776
  // ../../packages/plugin-sdk/src/ignore-layers.ts
29535
29777
  var import_ignore = __toESM(require_ignore(), 1);
29536
- import { readFileSync as readFileSync8 } from "fs";
29537
- import { join as join11 } from "path";
29778
+ import { readFileSync as readFileSync9 } from "fs";
29779
+ import { join as join13 } from "path";
29538
29780
 
29539
29781
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
29540
29782
  import { arch, hostname as hostname4, platform, release } from "os";
29541
29783
 
29542
29784
  // ../../packages/plugin-sdk/src/nudge.ts
29543
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
29544
- import { join as join12 } from "path";
29785
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
29786
+ import { join as join14 } from "path";
29545
29787
 
29546
29788
  // ../../packages/plugin-sdk/src/paths.ts
29547
- import { readdirSync as readdirSync3, realpathSync as realpathSync2 } from "fs";
29548
- import { basename as basename4, dirname as dirname3, sep as sep3 } from "path";
29789
+ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
29790
+ import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
29549
29791
 
29550
29792
  // ../../packages/plugin-sdk/src/posture.ts
29551
29793
  function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
@@ -29558,8 +29800,8 @@ function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
29558
29800
  }
29559
29801
 
29560
29802
  // ../../packages/plugin-sdk/src/project-files.ts
29561
- import { existsSync as existsSync8, readdirSync as readdirSync4 } from "fs";
29562
- import { basename as basename5, join as join13 } from "path";
29803
+ import { existsSync as existsSync9, readdirSync as readdirSync4 } from "fs";
29804
+ import { basename as basename5, join as join15 } from "path";
29563
29805
 
29564
29806
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
29565
29807
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -29940,8 +30182,8 @@ function createPluginRuntime(gateway, settings, opts) {
29940
30182
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
29941
30183
 
29942
30184
  // ../../packages/plugin-sdk/src/throttle.ts
29943
- import { mkdirSync as mkdirSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
29944
- import { join as join14 } from "path";
30185
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
30186
+ import { join as join16 } from "path";
29945
30187
 
29946
30188
  // ../../packages/setup-wizard/src/remediation/chain.ts
29947
30189
  var REMEDIATION_OPTIONS = [
@@ -29984,7 +30226,7 @@ function routeRemediationOption(option, handlers) {
29984
30226
 
29985
30227
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
29986
30228
  import { writeFileSync as writeFileSync7 } from "fs";
29987
- import { join as join15 } from "path";
30229
+ import { join as join17 } from "path";
29988
30230
  var GENERIC_CONSOLE_PATH = "rotate via the provider's own console";
29989
30231
  var CONSOLE_PATHS = {
29990
30232
  anthropic: "console.anthropic.com \u2192 Settings \u2192 API keys",
@@ -30084,7 +30326,7 @@ function generateRotationChecklist(input) {
30084
30326
  try {
30085
30327
  const target = resolveRotationChecklistTarget(input.cwd);
30086
30328
  targetDirectory = target.directory;
30087
- const filePath = join15(target.directory, "rotation-checklist.md");
30329
+ const filePath = join17(target.directory, "rotation-checklist.md");
30088
30330
  writeRotationChecklist(input.entries, target.directory);
30089
30331
  return {
30090
30332
  status: "written",
@@ -30195,9 +30437,9 @@ var RANK = Object.fromEntries(
30195
30437
  );
30196
30438
 
30197
30439
  // ../../packages/setup-wizard/src/triage/plan-file.ts
30198
- import { mkdtempSync, readFileSync as readFileSync10, rmdirSync, rmSync as rmSync5, writeFileSync as writeFileSync8 } from "fs";
30440
+ import { mkdtempSync, readFileSync as readFileSync11, rmdirSync, rmSync as rmSync6, writeFileSync as writeFileSync8 } from "fs";
30199
30441
  import { tmpdir } from "os";
30200
- import { basename as basename6, dirname as dirname4, join as join16 } from "path";
30442
+ import { basename as basename6, dirname as dirname5, join as join18 } from "path";
30201
30443
  var SuppressionEntrySchema = external_exports.object({
30202
30444
  ruleId: external_exports.string(),
30203
30445
  category: DetectionCategory,
@@ -30341,8 +30583,8 @@ function show(body) {
30341
30583
  }
30342
30584
 
30343
30585
  // src/skills-registry.ts
30344
- import { readdirSync as readdirSync5, readFileSync as readFileSync11 } from "fs";
30345
- import { join as join17 } from "path";
30586
+ import { readdirSync as readdirSync5, readFileSync as readFileSync12 } from "fs";
30587
+ import { join as join19 } from "path";
30346
30588
  import { fileURLToPath as fileURLToPath2 } from "url";
30347
30589
  var SKILLS_DIR = fileURLToPath2(new URL("../skills", import.meta.url));
30348
30590
  function frontmatterName(content) {
@@ -30355,7 +30597,7 @@ function readRegisteredSkills() {
30355
30597
  return readdirSync5(SKILLS_DIR, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
30356
30598
  let content;
30357
30599
  try {
30358
- content = readFileSync11(join17(SKILLS_DIR, entry.name, "SKILL.md"), "utf8");
30600
+ content = readFileSync12(join19(SKILLS_DIR, entry.name, "SKILL.md"), "utf8");
30359
30601
  } catch {
30360
30602
  return [];
30361
30603
  }
@@ -30416,10 +30658,1200 @@ function renderRemediationDecision(findings, moreCount, registry2) {
30416
30658
  }
30417
30659
 
30418
30660
  // src/remediation/surfaced-redact.ts
30661
+ import { readFileSync as readFileSync18 } from "fs";
30662
+
30663
+ // ../../packages/plugin-runtime/src/attached/failure.ts
30664
+ function statusOf(err) {
30665
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
30666
+ const { status } = err;
30667
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
30668
+ return status >= 100 && status <= 599 ? status : null;
30669
+ }
30670
+ function classifyFailure(err) {
30671
+ switch (statusOf(err)) {
30672
+ case 401:
30673
+ return "unauthorized";
30674
+ case 403:
30675
+ return "forbidden";
30676
+ default:
30677
+ return "unreachable";
30678
+ }
30679
+ }
30680
+
30681
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
30682
+ import { readFileSync as readFileSync13 } from "fs";
30683
+ import { join as join20 } from "path";
30684
+ var FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
30685
+ function forwardDropsPath(dataDir2) {
30686
+ return join20(dataDir2, FORWARD_DROPS_FILENAME);
30687
+ }
30688
+ function recordForwardDrops(dataDir2, count, nowMs) {
30689
+ if (count <= 0) return;
30690
+ try {
30691
+ ensureDataDirSync(dataDir2);
30692
+ const previous = readForwardDrops(dataDir2);
30693
+ const next = {
30694
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
30695
+ lastDropAtMs: nowMs
30696
+ };
30697
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
30698
+ `);
30699
+ } catch {
30700
+ }
30701
+ }
30702
+ function readForwardDrops(dataDir2) {
30703
+ try {
30704
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
30705
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30706
+ const record2 = parsed2;
30707
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
30708
+ return null;
30709
+ }
30710
+ if (record2.droppedForwards <= 0) return null;
30711
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
30712
+ return null;
30713
+ }
30714
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
30715
+ } catch {
30716
+ return null;
30717
+ }
30718
+ }
30719
+
30720
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30721
+ import { randomUUID as randomUUID15 } from "crypto";
30419
30722
  import { readFileSync as readFileSync14 } from "fs";
30723
+ import { readFile, rename, writeFile } from "fs/promises";
30724
+ import { join as join21 } from "path";
30725
+
30726
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
30727
+ var REQUEST_TIMEOUT_MS = 2e3;
30728
+ function withTimeout(promise2, ms) {
30729
+ let timer;
30730
+ const timeout = new Promise((_, reject) => {
30731
+ timer = setTimeout(() => {
30732
+ reject(new Error("attached gateway request timed out"));
30733
+ }, ms);
30734
+ });
30735
+ promise2.catch(() => void 0);
30736
+ return Promise.race([promise2, timeout]).finally(() => {
30737
+ clearTimeout(timer);
30738
+ });
30739
+ }
30740
+
30741
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30742
+ function isInvalidRequest(err) {
30743
+ return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
30744
+ }
30745
+ var FORWARD_BUDGET_MS = 1500;
30746
+ var DECISION_PATH_BUDGET_MS = 800;
30747
+ var BREAKER_FAILURE_THRESHOLD = 3;
30748
+ var BREAKER_COOLDOWN_MS = 3e4;
30749
+ var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
30750
+ var FAILURES = /* @__PURE__ */ new Set([
30751
+ "unauthorized",
30752
+ "forbidden",
30753
+ "unreachable"
30754
+ ]);
30755
+ var FORWARD_STATE_FILENAME = "attached-state.json";
30756
+ var STATE_FILENAME = FORWARD_STATE_FILENAME;
30757
+ function parseBreakerState(raw, nowMs) {
30758
+ try {
30759
+ const parsed2 = JSON.parse(raw);
30760
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30761
+ const record2 = parsed2;
30762
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
30763
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
30764
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
30765
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
30766
+ } catch {
30767
+ return null;
30768
+ }
30769
+ }
30770
+ function createForwardPolicy(deps) {
30771
+ const now = deps.now ?? (() => Date.now());
30772
+ const file2 = join21(deps.dir, STATE_FILENAME);
30773
+ let state = null;
30774
+ let loading = null;
30775
+ async function readState() {
30776
+ let raw;
30777
+ try {
30778
+ raw = await readFile(file2, "utf8");
30779
+ } catch {
30780
+ return { ...CLOSED };
30781
+ }
30782
+ return parseBreakerState(raw, now()) ?? { ...CLOSED };
30783
+ }
30784
+ async function load() {
30785
+ if (state !== null) return state;
30786
+ loading ??= readState().then((loaded) => {
30787
+ state = loaded;
30788
+ loading = null;
30789
+ return loaded;
30790
+ });
30791
+ return loading;
30792
+ }
30793
+ async function persist(next) {
30794
+ state = next;
30795
+ try {
30796
+ await ensureDataDir(deps.dir);
30797
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
30798
+ await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
30799
+ await rename(tmp, file2);
30800
+ } catch {
30801
+ }
30802
+ }
30803
+ return {
30804
+ async run(op, opts) {
30805
+ const budget = opts?.decisionPath === true ? DECISION_PATH_BUDGET_MS : FORWARD_BUDGET_MS;
30806
+ let current;
30807
+ try {
30808
+ current = await load();
30809
+ } catch {
30810
+ current = { ...CLOSED };
30811
+ }
30812
+ const at = now();
30813
+ if (current.openedAtMs !== null) {
30814
+ if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
30815
+ return { ok: false, reason: "breaker-open" };
30816
+ }
30817
+ await persist({
30818
+ consecutiveFailures: current.consecutiveFailures,
30819
+ openedAtMs: at,
30820
+ lastFailure: current.lastFailure
30821
+ });
30822
+ }
30823
+ try {
30824
+ const value = await withTimeout(op(), budget);
30825
+ if (current.openedAtMs !== null || current.consecutiveFailures > 0) {
30826
+ await persist({ ...CLOSED });
30827
+ }
30828
+ return { ok: true, value };
30829
+ } catch (err) {
30830
+ if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
30831
+ const reason = classifyFailure(err);
30832
+ const failures = current.consecutiveFailures + 1;
30833
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
30834
+ await persist({
30835
+ consecutiveFailures: failures,
30836
+ openedAtMs: shouldOpen ? now() : null,
30837
+ lastFailure: reason
30838
+ });
30839
+ return { ok: false, reason };
30840
+ }
30841
+ }
30842
+ };
30843
+ }
30844
+
30845
+ // ../../packages/plugin-runtime/src/attached/gateway.ts
30846
+ var ACTION_STRENGTH = {
30847
+ allow: 0,
30848
+ log: 1,
30849
+ warn: 2,
30850
+ redact: 3,
30851
+ block: 4
30852
+ };
30853
+ function ruleCategoryMap(wireRules, localRules) {
30854
+ const map2 = /* @__PURE__ */ new Map();
30855
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
30856
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
30857
+ for (const pack of bundledDetections()) {
30858
+ for (const rule of pack.rules) map2.set(rule.id, rule.category);
30859
+ }
30860
+ return map2;
30861
+ }
30862
+ function strongerOf(a, b) {
30863
+ if (a === null) return b;
30864
+ if (b === null) return a;
30865
+ return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
30866
+ }
30867
+ function policyKey(policy) {
30868
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
30869
+ }
30870
+ function floorFor(policy, categoryByRuleId) {
30871
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
30872
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
30873
+ }
30874
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
30875
+ const merged = /* @__PURE__ */ new Map();
30876
+ const disabled = [];
30877
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
30878
+ for (const policy of remotePolicies) {
30879
+ if (!policy.enabled) continue;
30880
+ if (!("category" in policy.target)) continue;
30881
+ if (remoteCategoryAction.has(policy.target.category)) continue;
30882
+ const floor = floorFor(policy, categoryByRuleId);
30883
+ remoteCategoryAction.set(
30884
+ policy.target.category,
30885
+ floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
30886
+ );
30887
+ }
30888
+ for (const policy of localPolicies) {
30889
+ if (!policy.enabled) {
30890
+ disabled.push(policy);
30891
+ continue;
30892
+ }
30893
+ const key = policyKey(policy);
30894
+ if (merged.has(key)) continue;
30895
+ let remoteFloor = null;
30896
+ if ("ruleId" in policy.target) {
30897
+ const category = categoryByRuleId.get(policy.target.ruleId);
30898
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
30899
+ }
30900
+ merged.set(
30901
+ key,
30902
+ remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
30903
+ );
30904
+ }
30905
+ const localCategoryAction = /* @__PURE__ */ new Map();
30906
+ for (const policy of merged.values()) {
30907
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
30908
+ }
30909
+ for (const policy of remotePolicies) {
30910
+ if (!policy.enabled) {
30911
+ disabled.push(policy);
30912
+ continue;
30913
+ }
30914
+ const key = policyKey(policy);
30915
+ const floor = floorFor(policy, categoryByRuleId);
30916
+ let localFloor = null;
30917
+ if ("ruleId" in policy.target) {
30918
+ const category = categoryByRuleId.get(policy.target.ruleId);
30919
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
30920
+ }
30921
+ const effectiveFloor = strongerOf(floor, localFloor);
30922
+ const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
30923
+ const existing = merged.get(key);
30924
+ if (existing === void 0) {
30925
+ merged.set(key, clamped);
30926
+ continue;
30927
+ }
30928
+ if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
30929
+ merged.set(key, clamped);
30930
+ }
30931
+ }
30932
+ return [...merged.values(), ...disabled];
30933
+ }
30934
+ var AttachedDataGateway = class {
30935
+ constructor(deps) {
30936
+ this.deps = deps;
30937
+ }
30938
+ deps;
30939
+ /**
30940
+ * The control plane's OWN resolution of this session's inventory, captured by
30941
+ * ensureInventory. Null until the first successful forward — and it stays
30942
+ * null for the whole session when the control plane is unreachable, which is fine:
30943
+ * reKeyForForward then leaves the event's ids alone and the control plane resolves
30944
+ * what it can from the descriptors it already has.
30945
+ */
30946
+ remoteInventory = null;
30947
+ // ---------------------------------------------------------------------
30948
+ // Writes: local first, then forward.
30949
+ // ---------------------------------------------------------------------
30950
+ async recordCapture(record2) {
30951
+ await this.deps.local.recordCapture(record2);
30952
+ await this.deps.forward.run(
30953
+ () => this.deps.client.ingestEvents({
30954
+ events: [record2.event],
30955
+ ...record2.dedupe ? { dedupe: record2.dedupe } : {}
30956
+ }),
30957
+ { decisionPath: true }
30958
+ );
30959
+ }
30960
+ async ensureInventory(ctx) {
30961
+ const resolved = await this.deps.local.ensureInventory(ctx);
30962
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
30963
+ this.remoteInventory = remote.ok ? remote.value : null;
30964
+ const snapshot = await (async () => {
30965
+ try {
30966
+ return await this.deps.posture?.prepare() ?? null;
30967
+ } catch {
30968
+ return null;
30969
+ }
30970
+ })();
30971
+ if (snapshot) {
30972
+ try {
30973
+ await withTimeout(
30974
+ this.deps.posture?.send(snapshot) ?? Promise.resolve(),
30975
+ REQUEST_TIMEOUT_MS
30976
+ );
30977
+ } catch {
30978
+ }
30979
+ }
30980
+ return resolved;
30981
+ }
30982
+ // The id is minted CLIENT-side and stored verbatim: the control plane does NOT
30983
+ // re-key it. `pgAuditValues` writes `id: event.id` and carries tenancy in
30984
+ // its own scoping columns, so the device and the forwarded copy
30985
+ // share one id space — which is what makes a re-post idempotent at all.
30986
+ //
30987
+ // Re-posts collapse via `onConflictDoUpdate` on the `id` PK, guarded by
30988
+ // `setWhere eventType = 'session'` (NOT onConflictDoNothing). That guard is
30989
+ // what makes an attached retry safe: a capture-stubbed session row can still
30990
+ // be HEALED by the authoritative root, while a duplicate non-session event —
30991
+ // a retried tool_call, exactly this path — can never stomp a populated row.
30992
+ async recordAuditEvent(event) {
30993
+ await this.deps.local.recordAuditEvent(event);
30994
+ await this.deps.forward.run(
30995
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
30996
+ );
30997
+ }
30998
+ // Attached `llm_call` is written locally by the inner gateway, then routed to
30999
+ // the control plane through the existing `recordAuditEvent` ingest (no dedicated
31000
+ // client method yet) by pre-building the audit event from the natural key.
31001
+ // The forward goes DIRECTLY to the client rather than through this.recordAuditEvent,
31002
+ // which would write the event to the local store a second time.
31003
+ async recordLlmCall(input) {
31004
+ await this.deps.local.recordLlmCall(input);
31005
+ await this.deps.forward.run(
31006
+ () => this.deps.client.recordAuditEvent(
31007
+ reKeyForForward(llmAuditEvent(input), this.remoteInventory)
31008
+ )
31009
+ );
31010
+ }
31011
+ /**
31012
+ * Forward one batch, item by item, under ONE aggregate deadline.
31013
+ *
31014
+ * Per-item budgets bound each request and nothing bounded their sum — see
31015
+ * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
31016
+ * rather than sent: the local write has already succeeded, so every caller
31017
+ * has a correct result to return, and a drop is the outcome this path is
31018
+ * built to accept (G8) where a blown hook timeout is not.
31019
+ *
31020
+ * Serial rather than concurrent on purpose. Firing N requests at once would
31021
+ * trade a latency problem for a burst the plane's own per-key rate limiting
31022
+ * would answer with the refusals the breaker then counts.
31023
+ *
31024
+ * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
31025
+ * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
31026
+ * lets status call the forward unhealthy; this path returns BEFORE `run` is
31027
+ * reached, so without the tally in `forward-drops.ts` a slow-but-answering
31028
+ * plane produces no failures, keeps the breaker closed, renders a healthy
31029
+ * block, and discards the tail of every batch indefinitely.
31030
+ */
31031
+ async forwardBatch(inputs, toEvent) {
31032
+ const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
31033
+ for (let i = 0; i < inputs.length; i += 1) {
31034
+ const now = Date.now();
31035
+ if (now >= deadline) {
31036
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
31037
+ return;
31038
+ }
31039
+ const input = inputs[i];
31040
+ await this.deps.forward.run(
31041
+ () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input), this.remoteInventory))
31042
+ );
31043
+ }
31044
+ }
31045
+ // Delegated as a BATCH rather than looped over recordLlmCall: the inner
31046
+ // gateway may write the whole batch in one local transaction, and looping
31047
+ // here would replace that with N separate local writes.
31048
+ async recordLlmCalls(inputs) {
31049
+ await this.deps.local.recordLlmCalls(inputs);
31050
+ await this.forwardBatch(inputs, (input) => llmAuditEvent(input));
31051
+ }
31052
+ // `input.inspections` (secrets detected client-side in the tool's masked
31053
+ // target) ride along on the request's `inspections` field — the control plane
31054
+ // persists each as an inspection_findings row linked to this audit event
31055
+ // (see RecordAuditEventRequest in @akasecurity/schema). The masked
31056
+ // `target` already rides `input.attributes`, so no raw secret leaks either
31057
+ // way — this only stops the FINDING row itself from being dropped.
31058
+ async recordToolCalls(inputs) {
31059
+ await this.deps.local.recordToolCalls(inputs);
31060
+ await this.forwardBatch(inputs, (input) => toolAuditEvent(input));
31061
+ }
31062
+ // Forwarded as a `config_scan` audit event: there is no dedicated
31063
+ // config-scan ingest endpoint, and the audit-event door is the one the
31064
+ // control plane already opens for client-minted, idempotent records.
31065
+ //
31066
+ // ONLY `scanEvent` CROSSES, and unlike `recordCapture` the plane cannot
31067
+ // re-derive the rest. A `ConfigScanRecord` is four things committed together
31068
+ // locally — the inventory `items`, this audit event, and the posture
31069
+ // `definitions`/`findings` that reference it — and three of them stay on the
31070
+ // device. Say that plainly rather than let the asymmetry with `recordCapture`
31071
+ // read as the same argument: there, findings are omitted BECAUSE the plane
31072
+ // re-derives them from `Event.content`; here there is no content to re-derive
31073
+ // from, so what is omitted is simply not sent.
31074
+ //
31075
+ // That is the wire contract as it stands rather than an oversight to patch
31076
+ // here. `items` has no route at all, and `RecordAuditEventRequest.inspections`
31077
+ // is documented as tool-call findings — widening it to carry config-scan
31078
+ // findings is an egress change (a posture finding's `maskedMatch` holds the
31079
+ // matched command) and a decision about what an attached deployment is
31080
+ // entitled to, not a bug fix. An attached machine's config posture therefore
31081
+ // reaches the plane as the event only; the dashboard's own view of it is the
31082
+ // local store.
31083
+ async recordConfigScan(record2) {
31084
+ await this.deps.local.recordConfigScan(record2);
31085
+ await this.deps.forward.run(
31086
+ () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
31087
+ );
31088
+ }
31089
+ async recordBlockedDetection(entry) {
31090
+ return this.deps.local.recordBlockedDetection(entry);
31091
+ }
31092
+ /**
31093
+ * LOCAL-ONLY, deliberately. The shares API is read-plus-decision-override
31094
+ * with no egress ingest endpoint, so there is nothing to forward to; adding a
31095
+ * forward here would be inventing a wire contract that does not exist. The
31096
+ * local write is the whole operation, and its summary is the real one — the
31097
+ * scanner reads a throw as a FAILED WRITE and skips its ledger commit, so
31098
+ * returning the inner gateway's result keeps the retry semantics honest.
31099
+ */
31100
+ async recordProjectEgress(input) {
31101
+ return this.deps.local.recordProjectEgress(input);
31102
+ }
31103
+ // ---------------------------------------------------------------------
31104
+ // Reads and device-local ledgers: pure delegation.
31105
+ // ---------------------------------------------------------------------
31106
+ async configInventoryReport() {
31107
+ return this.deps.local.configInventoryReport();
31108
+ }
31109
+ async readSessionProvider(sessionId) {
31110
+ return this.deps.local.readSessionProvider(sessionId);
31111
+ }
31112
+ async facets() {
31113
+ return this.deps.local.facets();
31114
+ }
31115
+ /**
31116
+ * Delegated UNMODIFIED — including its refusals.
31117
+ *
31118
+ * This is a fail-secure boundary: it decides whether an approved exception
31119
+ * lets a blocked action through. Under local-first the local store owns the
31120
+ * exception ledger, so the honest answer is whatever it says; wrapping this
31121
+ * in a fallback (`catch { return true }`, or defaulting on a timeout) would
31122
+ * turn a store error into a granted bypass. If the inner gateway rejects,
31123
+ * this rejects, and the runtime's own handling decides — which is asserted
31124
+ * end-to-end through runtime.capture rather than here.
31125
+ */
31126
+ async consumeException(id) {
31127
+ return this.deps.local.consumeException(id);
31128
+ }
31129
+ async recentFindings(opts) {
31130
+ return this.deps.local.recentFindings(opts);
31131
+ }
31132
+ async healthSummary() {
31133
+ return this.deps.local.healthSummary();
31134
+ }
31135
+ async activityByDay(days) {
31136
+ return this.deps.local.activityByDay(days);
31137
+ }
31138
+ async tokenReports() {
31139
+ return this.deps.local.tokenReports();
31140
+ }
31141
+ async knownContentHashes() {
31142
+ return this.deps.local.knownContentHashes();
31143
+ }
31144
+ async scanLedger(rulesetHash) {
31145
+ return this.deps.local.scanLedger(rulesetHash);
31146
+ }
31147
+ async recordScanned(entries) {
31148
+ return this.deps.local.recordScanned(entries);
31149
+ }
31150
+ async getRuleProbeVerdict(ruleKey) {
31151
+ return this.deps.local.getRuleProbeVerdict(ruleKey);
31152
+ }
31153
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
31154
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2);
31155
+ }
31156
+ async openAtRestKeysForPath(path) {
31157
+ return this.deps.local.openAtRestKeysForPath(path);
31158
+ }
31159
+ async resolvedAtRestKeysForPath(path) {
31160
+ return this.deps.local.resolvedAtRestKeysForPath(path);
31161
+ }
31162
+ async insertResolution(input) {
31163
+ return this.deps.local.insertResolution(input);
31164
+ }
31165
+ async close() {
31166
+ return this.deps.local.close();
31167
+ }
31168
+ // ---------------------------------------------------------------------
31169
+ // Policy
31170
+ // ---------------------------------------------------------------------
31171
+ async getPolicyBundle() {
31172
+ const local = await this.deps.local.getPolicyBundle();
31173
+ const cached2 = await (async () => {
31174
+ try {
31175
+ return await this.deps.readCachedBundle();
31176
+ } catch {
31177
+ return null;
31178
+ }
31179
+ })();
31180
+ if (cached2 === null) return local;
31181
+ const byRuleId = /* @__PURE__ */ new Map();
31182
+ for (const rule of [...local.rules ?? [], ...cached2.rules ?? []]) {
31183
+ if (!byRuleId.has(rule.id)) byRuleId.set(rule.id, rule);
31184
+ }
31185
+ const rules = [...byRuleId.values()];
31186
+ return {
31187
+ ...local,
31188
+ // The remote version identifies the composed bundle for the poller.
31189
+ version: cached2.version,
31190
+ rules,
31191
+ policies: mergeRaiseOnly(
31192
+ local.policies,
31193
+ cached2.policies,
31194
+ ruleCategoryMap(cached2.rules, local.rules)
31195
+ ),
31196
+ customKeywords: [...local.customKeywords, ...cached2.customKeywords]
31197
+ // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
31198
+ // snapshot) and is taken from the LOCAL bundle only — never from the wire
31199
+ // or the on-disk cache. Honoring a cached one would hand the control plane, or
31200
+ // anything able to write policy-cache.json, a kill-switch over the
31201
+ // compiled-in bundled packs: `{ rulesComplete: true, rules: [] }` would
31202
+ // zero local detection. Spread from `local` above, and deliberately not
31203
+ // re-read from `cached` here.
31204
+ //
31205
+ // THREE MORE OF THE CACHED BUNDLE'S FIELDS ARE DROPPED, each on purpose,
31206
+ // and each named here so a reader can tell a decision from an omission:
31207
+ //
31208
+ // `exceptions` — an exception SUPPRESSES a detection, so honoring
31209
+ // one from an unsigned on-disk cache would let
31210
+ // anything able to write that file turn rules off.
31211
+ // Every other field this merge accepts can only
31212
+ // RAISE enforcement; this is the one that cannot,
31213
+ // so it stays local-only until the bundle is
31214
+ // signed. Exceptions remain a device-local ledger.
31215
+ // `reversibleRuleIds` — the Redact & Vault archetype makes a redaction
31216
+ // recoverable, which is a CUSTODY change: it puts
31217
+ // the detected value in the local vault instead of
31218
+ // destroying it. Taking that instruction from the
31219
+ // cache would let a remote party turn one-way
31220
+ // redaction into retention. Dropping it keeps the
31221
+ // one-way behaviour, which the schema itself calls
31222
+ // "the safe direction to default".
31223
+ // `ruleVersions` — remote rules fall back to their own spec version.
31224
+ // Cosmetic rather than protective: it only affects
31225
+ // how a finding is version-attributed, and the two
31226
+ // sides may therefore attribute org rules
31227
+ // differently. Worth carrying once there is a
31228
+ // reader that needs it; nothing reads it today.
31229
+ };
31230
+ }
31231
+ // ---------------------------------------------------------------------
31232
+ // LocalStoreMaintenance — by delegation (D3).
31233
+ //
31234
+ // Implementing these is what actually closes the skipped-local-maintenance
31235
+ // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
31236
+ // any object carrying all five, so the composite qualifies and SessionStart
31237
+ // runs maintenance on the device's real store.
31238
+ //
31239
+ // ⚠ Two of the five are SYNCHRONOUS and must stay that way. `handle-session-start`
31240
+ // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
31241
+ // return value directly; declaring them `async` here would hand those call
31242
+ // sites a Promise and silently break both.
31243
+ // ---------------------------------------------------------------------
31244
+ async sweepTerminalExceptions(retentionMs) {
31245
+ return this.deps.local.sweepTerminalExceptions(retentionMs);
31246
+ }
31247
+ capWarnEraEnforcement(policyMode) {
31248
+ return this.deps.local.capWarnEraEnforcement(policyMode);
31249
+ }
31250
+ async recordProjectFiles(projectId, scan2) {
31251
+ return this.deps.local.recordProjectFiles(projectId, scan2);
31252
+ }
31253
+ async reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot) {
31254
+ return this.deps.local.reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot);
31255
+ }
31256
+ staleBinaryNotice(currentVersion) {
31257
+ return this.deps.local.staleBinaryNotice(currentVersion);
31258
+ }
31259
+ };
31260
+ function reKeyForForward(event, remote) {
31261
+ if (remote === null) {
31262
+ const stripped = { ...event };
31263
+ delete stripped.hostId;
31264
+ delete stripped.harnessId;
31265
+ delete stripped.sourceProjectId;
31266
+ return stripped;
31267
+ }
31268
+ const rekeyed = { ...event };
31269
+ delete rekeyed.hostId;
31270
+ delete rekeyed.harnessId;
31271
+ delete rekeyed.sourceProjectId;
31272
+ if (remote.hostId !== void 0) rekeyed.hostId = remote.hostId;
31273
+ if (remote.harnessId !== void 0) rekeyed.harnessId = remote.harnessId;
31274
+ if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
31275
+ return rekeyed;
31276
+ }
31277
+ var BATCH_FORWARD_BUDGET_MS = 3e3;
31278
+ function llmAuditEvent(input) {
31279
+ return {
31280
+ id: llmCallId(input.sessionId, input.messageId),
31281
+ eventType: "llm_call",
31282
+ startedAt: input.startedAt,
31283
+ parentId: input.parentId,
31284
+ rootSessionId: input.rootSessionId,
31285
+ attributes: input.attributes
31286
+ };
31287
+ }
31288
+ function toolAuditEvent(input) {
31289
+ return {
31290
+ id: toolCallId(input.sessionId, input.toolUseId),
31291
+ eventType: "tool_call",
31292
+ startedAt: input.startedAt,
31293
+ parentId: input.parentId,
31294
+ rootSessionId: input.rootSessionId,
31295
+ attributes: input.attributes,
31296
+ inspections: input.inspections
31297
+ };
31298
+ }
31299
+
31300
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
31301
+ import { randomUUID as randomUUID16 } from "crypto";
31302
+ import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
31303
+ import { join as join22 } from "path";
31304
+
31305
+ // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
31306
+ import { rename as rename2 } from "fs/promises";
31307
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
31308
+ var ATTEMPTS = 5;
31309
+ var delay = (ms) => new Promise((resolve3) => {
31310
+ setTimeout(resolve3, ms);
31311
+ });
31312
+ async function publishByRename(tmp, file2, move = rename2) {
31313
+ for (let attempt = 1; ; attempt += 1) {
31314
+ try {
31315
+ await move(tmp, file2);
31316
+ return;
31317
+ } catch (err) {
31318
+ const code = err.code;
31319
+ if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
31320
+ await delay(attempt * 10);
31321
+ }
31322
+ }
31323
+ }
31324
+
31325
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
31326
+ function createPolicyStore(dir = dataDir()) {
31327
+ const file2 = join22(dir, "policy-cache.json");
31328
+ async function read() {
31329
+ try {
31330
+ const raw = await readFile2(file2, "utf8");
31331
+ const parsed2 = JSON.parse(raw);
31332
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
31333
+ const record2 = parsed2;
31334
+ const bundle = PolicyBundle.parse(record2.bundle);
31335
+ const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
31336
+ const etag = typeof record2.etag === "string" ? record2.etag : void 0;
31337
+ return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
31338
+ } catch {
31339
+ return null;
31340
+ }
31341
+ }
31342
+ async function write(bundle, etag) {
31343
+ await ensureDataDir(dir);
31344
+ const stored = {
31345
+ bundle,
31346
+ fetchedAtMs: Date.now(),
31347
+ ...etag === void 0 ? {} : { etag }
31348
+ };
31349
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
31350
+ try {
31351
+ await writeFile2(tmp, JSON.stringify(stored), {
31352
+ encoding: "utf8",
31353
+ mode: DATA_FILE_MODE,
31354
+ flag: "wx"
31355
+ });
31356
+ await publishByRename(tmp, file2);
31357
+ } catch (err) {
31358
+ await rm(tmp, { force: true }).catch(() => void 0);
31359
+ throw err;
31360
+ }
31361
+ }
31362
+ return { read, write, file: file2 };
31363
+ }
31364
+
31365
+ // ../../packages/remote/src/http.ts
31366
+ import { request as httpRequest } from "http";
31367
+ import { request as httpsRequest } from "https";
31368
+ var DEFAULT_TIMEOUT_MS = 1e4;
31369
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
31370
+ var RemoteRequestError = class extends Error {
31371
+ constructor(status) {
31372
+ super(`control-plane request failed with status ${String(status)}`);
31373
+ this.status = status;
31374
+ this.name = "RemoteRequestError";
31375
+ }
31376
+ status;
31377
+ };
31378
+ var RemoteRequestInvalid = class extends Error {
31379
+ constructor(route2, cause) {
31380
+ super(`refusing to send a malformed body to ${route2}`);
31381
+ this.cause = cause;
31382
+ this.name = "RemoteRequestInvalid";
31383
+ }
31384
+ cause;
31385
+ };
31386
+ var RemoteResponseInvalid = class extends Error {
31387
+ constructor(route2, detail) {
31388
+ super(`control plane answered ${route2} with ${detail}`);
31389
+ this.name = "RemoteResponseInvalid";
31390
+ }
31391
+ };
31392
+ var RemoteTransportError = class extends Error {
31393
+ /**
31394
+ * The status the peer sent, when headers arrived and only the BODY was
31395
+ * refused.
31396
+ *
31397
+ * Undefined for the ordinary case this class was written for — no answer at
31398
+ * all. It exists because two paths reject after a status has already been
31399
+ * delivered: an oversized body and an aborted response. Discarding it there
31400
+ * reported a deployment answering 401 with a verbose body as a network
31401
+ * outage, which sends the reader to look at their network instead of their
31402
+ * credential.
31403
+ */
31404
+ constructor(reason, status) {
31405
+ super(`control-plane request did not complete: ${reason}`);
31406
+ this.status = status;
31407
+ this.name = "RemoteTransportError";
31408
+ }
31409
+ status;
31410
+ };
31411
+ async function send(options) {
31412
+ const url2 = new URL(options.url);
31413
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
31414
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
31415
+ const requestOptions = {
31416
+ method: options.method,
31417
+ headers: {
31418
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
31419
+ // last they win, and two of the values below are ones no caller may
31420
+ // replace: `x-api-key` is the credential, and `content-length` is the
31421
+ // byte count that stops a multi-byte body being truncated by the
31422
+ // receiver. `SendOptions.headers` is a free-form record on an exported
31423
+ // function, so "no caller does that today" is not the guarantee to rely
31424
+ // on. The one header any caller actually passes — `if-none-match` on the
31425
+ // conditional GET — is untouched by this order.
31426
+ ...options.headers,
31427
+ // The credential. One header, matching what the deployment authenticates
31428
+ // on; a second copy in an `Authorization` header would be one more place
31429
+ // it can be logged by an intermediary for no gain.
31430
+ "x-api-key": options.apiKey,
31431
+ accept: "application/json",
31432
+ ...options.body === void 0 ? {} : {
31433
+ "content-type": "application/json",
31434
+ // Byte length, not string length: a multi-byte body sent with a
31435
+ // character count is truncated by the receiver.
31436
+ "content-length": String(Buffer.byteLength(options.body))
31437
+ }
31438
+ }
31439
+ };
31440
+ return new Promise((resolve3, reject) => {
31441
+ let settled = false;
31442
+ const fail2 = (reason, status) => {
31443
+ if (settled) return;
31444
+ settled = true;
31445
+ reject(new RemoteTransportError(reason, status));
31446
+ };
31447
+ const req = send_(url2, requestOptions, (res) => {
31448
+ const chunks = [];
31449
+ let size = 0;
31450
+ res.on("data", (chunk) => {
31451
+ size += chunk.length;
31452
+ if (size > MAX_RESPONSE_BYTES) {
31453
+ fail2(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
31454
+ res.destroy();
31455
+ req.destroy();
31456
+ return;
31457
+ }
31458
+ chunks.push(chunk);
31459
+ });
31460
+ res.on("aborted", () => {
31461
+ fail2("the response was aborted", res.statusCode);
31462
+ });
31463
+ res.on("end", () => {
31464
+ if (settled) return;
31465
+ settled = true;
31466
+ resolve3({
31467
+ status: res.statusCode ?? 0,
31468
+ headers: res.headers,
31469
+ body: Buffer.concat(chunks).toString("utf8")
31470
+ });
31471
+ });
31472
+ });
31473
+ const deadline = setTimeout(() => {
31474
+ fail2(`no response within ${String(timeoutMs)}ms`);
31475
+ req.destroy();
31476
+ }, timeoutMs);
31477
+ deadline.unref();
31478
+ req.on("upgrade", (_res, socket) => {
31479
+ fail2("the deployment answered with a protocol upgrade");
31480
+ socket.destroy();
31481
+ });
31482
+ req.on("close", () => {
31483
+ fail2("the connection closed before a response was read");
31484
+ clearTimeout(deadline);
31485
+ });
31486
+ req.on("error", (err) => {
31487
+ fail2(err.message);
31488
+ });
31489
+ if (options.body !== void 0) req.write(options.body);
31490
+ req.end();
31491
+ });
31492
+ }
31493
+
31494
+ // ../../packages/remote/src/client.ts
31495
+ var ROUTES = {
31496
+ events: "/v1/events",
31497
+ auditEvents: "/v1/audit-events",
31498
+ inventory: "/v1/inventory",
31499
+ storePosture: "/v1/store-posture",
31500
+ policyBundle: "/v1/policy-bundle",
31501
+ whoami: "/v1/plugin/whoami"
31502
+ };
31503
+ function headerValue(response, name) {
31504
+ const raw = response.headers[name];
31505
+ if (raw === void 0) return void 0;
31506
+ return Array.isArray(raw) ? raw[0] : raw;
31507
+ }
31508
+ function okBody(response) {
31509
+ if (response.status < 200 || response.status >= 300) {
31510
+ throw new RemoteRequestError(response.status);
31511
+ }
31512
+ return response.body;
31513
+ }
31514
+ function parsed(schema, body, route2) {
31515
+ let json2;
31516
+ try {
31517
+ json2 = JSON.parse(body);
31518
+ } catch {
31519
+ throw new RemoteResponseInvalid(route2, "a body that is not JSON");
31520
+ }
31521
+ const result = schema.safeParse(json2);
31522
+ if (!result.success) {
31523
+ throw new RemoteResponseInvalid(route2, "a body this client cannot read");
31524
+ }
31525
+ return result.data;
31526
+ }
31527
+ function withoutTrailingSlashes(endpoint) {
31528
+ let end = endpoint.length;
31529
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
31530
+ return endpoint.slice(0, end);
31531
+ }
31532
+ var SLASH = "/".charCodeAt(0);
31533
+ function createRemoteClient(options) {
31534
+ const base = withoutTrailingSlashes(options.endpoint);
31535
+ const url2 = (route2) => `${base}${route2}`;
31536
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
31537
+ return {
31538
+ async ingestEvents(batch) {
31539
+ const response = await send({
31540
+ ...common,
31541
+ method: "POST",
31542
+ url: url2(ROUTES.events),
31543
+ body: JSON.stringify(batch)
31544
+ });
31545
+ return parsed(IngestAck, okBody(response), ROUTES.events);
31546
+ },
31547
+ async ingestInventory(context) {
31548
+ const response = await send({
31549
+ ...common,
31550
+ method: "POST",
31551
+ url: url2(ROUTES.inventory),
31552
+ body: JSON.stringify(context)
31553
+ });
31554
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
31555
+ },
31556
+ async recordAuditEvent(event) {
31557
+ const validated = RecordAuditEventRequest.safeParse(event);
31558
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
31559
+ const submission = validated.data;
31560
+ const response = await send({
31561
+ ...common,
31562
+ method: "POST",
31563
+ url: url2(ROUTES.auditEvents),
31564
+ body: JSON.stringify(submission)
31565
+ });
31566
+ okBody(response);
31567
+ },
31568
+ async reportStorePosture(snapshot) {
31569
+ const response = await send({
31570
+ ...common,
31571
+ method: "POST",
31572
+ url: url2(ROUTES.storePosture),
31573
+ body: JSON.stringify(snapshot)
31574
+ });
31575
+ okBody(response);
31576
+ },
31577
+ async getPolicyBundle(etag) {
31578
+ const response = await send({
31579
+ ...common,
31580
+ method: "GET",
31581
+ url: url2(ROUTES.policyBundle),
31582
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
31583
+ });
31584
+ if (response.status === 304) {
31585
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
31586
+ }
31587
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
31588
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
31589
+ },
31590
+ async whoami() {
31591
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
31592
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
31593
+ }
31594
+ };
31595
+ }
31596
+
31597
+ // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
31598
+ var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
31599
+ function createPostureReporter(deps) {
31600
+ async function prepare() {
31601
+ try {
31602
+ const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
31603
+ if (state === null) return null;
31604
+ const nowMs = deps.now();
31605
+ const elapsed = nowMs - state.lastAttemptedAtMs;
31606
+ if (elapsed >= 0 && elapsed < POSTURE_REPORT_INTERVAL_MS) return null;
31607
+ try {
31608
+ await withTimeout(deps.store.markAttempted(state.deviceId, nowMs), REQUEST_TIMEOUT_MS);
31609
+ } catch {
31610
+ }
31611
+ const { readError, ...measurement } = deps.readStore();
31612
+ if (readError) return null;
31613
+ let plugin;
31614
+ try {
31615
+ plugin = await deps.pluginBlock?.();
31616
+ } catch {
31617
+ plugin = void 0;
31618
+ }
31619
+ return {
31620
+ deviceId: state.deviceId,
31621
+ hostname: deps.hostname(),
31622
+ capturedAt: nowMs,
31623
+ ...measurement,
31624
+ // Omit the key rather than spread an explicit `undefined` —
31625
+ // exactOptionalPropertyTypes distinguishes the two, and the bridge in
31626
+ // factory.ts keys on presence.
31627
+ ...plugin === void 0 ? {} : { plugin }
31628
+ };
31629
+ } catch {
31630
+ return null;
31631
+ }
31632
+ }
31633
+ async function send2(snapshot) {
31634
+ try {
31635
+ await deps.report(snapshot);
31636
+ } catch {
31637
+ }
31638
+ }
31639
+ return { prepare, send: send2 };
31640
+ }
31641
+
31642
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31643
+ import { statSync as statSync9 } from "fs";
31644
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31645
+
31646
+ // ../../packages/plugin-runtime/src/attached/action-counts.ts
31647
+ function emptyActionCounts() {
31648
+ return Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
31649
+ }
31650
+ function isActionTaken(value) {
31651
+ return ACTION_TAKEN_KEYS.includes(value);
31652
+ }
31653
+
31654
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31655
+ var CAPTURE_EVENT_TYPES_SQL2 = `('prompt','response','code_change','tool_use')`;
31656
+ function isSchemaAbsent(err) {
31657
+ return err instanceof Error && /no such table/i.test(err.message);
31658
+ }
31659
+ function emptyReadout(readError = false) {
31660
+ const byAction = emptyActionCounts();
31661
+ return {
31662
+ storePresent: false,
31663
+ schemaVersion: null,
31664
+ findingsTotal: 0,
31665
+ findingsFirstAt: null,
31666
+ findingsLastAt: null,
31667
+ packs: [],
31668
+ policyCounts: { total: 0, disabled: 0, byAction },
31669
+ readError
31670
+ };
31671
+ }
31672
+ function readStorePosture(dbPath2) {
31673
+ try {
31674
+ statSync9(dbPath2);
31675
+ } catch (err) {
31676
+ const code = err.code;
31677
+ if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
31678
+ return emptyReadout(true);
31679
+ }
31680
+ let db = null;
31681
+ let version2 = null;
31682
+ let packs2 = [];
31683
+ let policyCounts = {
31684
+ total: 0,
31685
+ disabled: 0,
31686
+ byAction: emptyActionCounts()
31687
+ };
31688
+ let findingsTotal = 0;
31689
+ let findingsFirstAt = null;
31690
+ let findingsLastAt = null;
31691
+ const currentReadout = () => ({
31692
+ storePresent: true,
31693
+ schemaVersion: version2,
31694
+ findingsTotal,
31695
+ findingsFirstAt,
31696
+ findingsLastAt,
31697
+ packs: packs2,
31698
+ policyCounts,
31699
+ readError: false
31700
+ });
31701
+ try {
31702
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
31703
+ db.exec("PRAGMA busy_timeout = 2000");
31704
+ version2 = db.prepare("PRAGMA user_version").get().user_version;
31705
+ try {
31706
+ const packRows = db.prepare(
31707
+ `SELECT namespace, pack_id, version, enabled, updated_at FROM installed_packs ORDER BY namespace, pack_id`
31708
+ ).all();
31709
+ packs2 = packRows.map((r) => ({
31710
+ packId: `${r.namespace}/${r.pack_id}`,
31711
+ version: r.version,
31712
+ enabled: r.enabled !== 0,
31713
+ updatedAt: r.updated_at == null ? null : String(r.updated_at)
31714
+ }));
31715
+ } catch (err) {
31716
+ if (!isSchemaAbsent(err)) throw err;
31717
+ }
31718
+ try {
31719
+ const policyRows = db.prepare(`SELECT action, enabled FROM policies`).all();
31720
+ const byAction = emptyActionCounts();
31721
+ let disabled = 0;
31722
+ for (const row of policyRows) {
31723
+ if (row.enabled === 0) disabled += 1;
31724
+ if (isActionTaken(row.action)) byAction[row.action] += 1;
31725
+ }
31726
+ policyCounts = { total: policyRows.length, disabled, byAction };
31727
+ } catch (err) {
31728
+ if (!isSchemaAbsent(err)) throw err;
31729
+ }
31730
+ try {
31731
+ const agg = db.prepare(
31732
+ `SELECT count(*) AS n, min(f.first_detected_at) AS firstAt, max(f.first_detected_at) AS lastAt
31733
+ FROM inspection_findings f JOIN audit_events e ON e.id = f.audit_event_id
31734
+ WHERE e.event_type IN ${CAPTURE_EVENT_TYPES_SQL2}`
31735
+ ).get();
31736
+ findingsTotal = agg.n;
31737
+ findingsFirstAt = agg.firstAt;
31738
+ findingsLastAt = agg.lastAt;
31739
+ } catch (err) {
31740
+ if (!isSchemaAbsent(err)) throw err;
31741
+ }
31742
+ return currentReadout();
31743
+ } catch {
31744
+ return emptyReadout(true);
31745
+ } finally {
31746
+ try {
31747
+ db?.close();
31748
+ } catch {
31749
+ }
31750
+ }
31751
+ }
31752
+
31753
+ // ../../packages/plugin-runtime/src/attached/posture-store.ts
31754
+ import { randomUUID as randomUUID17 } from "crypto";
31755
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
31756
+ import { join as join23 } from "path";
31757
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31758
+ function createPostureStore(dir = settingsDir(), legacyDir) {
31759
+ const file2 = join23(dir, "posture-state.json");
31760
+ const legacyFile = legacyDir === void 0 ? null : join23(legacyDir, "posture-state.json");
31761
+ async function persist(state) {
31762
+ await ensureDataDir(dir);
31763
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
31764
+ try {
31765
+ await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
31766
+ await publishByRename(tmp, file2);
31767
+ } catch (err) {
31768
+ await rm2(tmp, { force: true }).catch(() => void 0);
31769
+ throw err;
31770
+ }
31771
+ }
31772
+ async function readFrom(path) {
31773
+ let raw;
31774
+ try {
31775
+ raw = await readFile3(path, "utf8");
31776
+ } catch (err) {
31777
+ const code = err.code;
31778
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
31779
+ throw err;
31780
+ }
31781
+ try {
31782
+ const parsed2 = JSON.parse(raw);
31783
+ if (typeof parsed2 === "object" && parsed2 !== null) {
31784
+ const record2 = parsed2;
31785
+ if (typeof record2.deviceId === "string" && UUID_RE.test(record2.deviceId)) {
31786
+ const stamp = typeof record2.lastAttemptedAtMs === "number" ? record2.lastAttemptedAtMs : typeof record2.lastReportedAtMs === "number" ? record2.lastReportedAtMs : 0;
31787
+ return { deviceId: record2.deviceId, lastAttemptedAtMs: stamp };
31788
+ }
31789
+ }
31790
+ } catch {
31791
+ }
31792
+ return null;
31793
+ }
31794
+ async function read() {
31795
+ const current = await readFrom(file2);
31796
+ if (current) return current;
31797
+ const legacy = legacyFile === null || legacyFile === file2 ? null : await readFrom(legacyFile).catch(() => null);
31798
+ if (legacy) {
31799
+ try {
31800
+ await persist(legacy);
31801
+ } catch {
31802
+ }
31803
+ return legacy;
31804
+ }
31805
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
31806
+ try {
31807
+ await ensureDataDir(dir);
31808
+ if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
31809
+ } catch {
31810
+ return null;
31811
+ }
31812
+ const winner = await readFrom(file2).catch(() => null);
31813
+ if (winner) return winner;
31814
+ try {
31815
+ await persist(fresh);
31816
+ } catch {
31817
+ return null;
31818
+ }
31819
+ return fresh;
31820
+ }
31821
+ async function markAttempted(deviceId, atMs) {
31822
+ await persist({ deviceId, lastAttemptedAtMs: atMs });
31823
+ }
31824
+ return { read, markAttempted, file: file2 };
31825
+ }
31826
+
31827
+ // ../../packages/plugin-runtime/src/attached/sync-state.ts
31828
+ import { readFileSync as readFileSync15 } from "fs";
31829
+ import { join as join24 } from "path";
31830
+
31831
+ // ../../packages/plugin-runtime/src/attached/status.ts
31832
+ var REFUSAL_LINES = {
31833
+ unauthorized: "KEY REJECTED \u2014 re-attach with a valid plugin key",
31834
+ forbidden: "ACCESS REFUSED \u2014 key is valid but not permitted; ask your org admin"
31835
+ };
31836
+ var OUTCOME_LINES = {
31837
+ ok: "policy synced",
31838
+ "not-modified": "policy up to date",
31839
+ unauthorized: REFUSAL_LINES.unauthorized,
31840
+ forbidden: REFUSAL_LINES.forbidden,
31841
+ unreachable: "control plane unreachable at last attempt",
31842
+ "invalid-bundle": "control plane sent a policy bundle this build cannot read"
31843
+ };
31844
+
31845
+ // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
31846
+ import { spawn } from "child_process";
31847
+ import { fileURLToPath as fileURLToPath3 } from "url";
31848
+ var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
31849
+
31850
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31851
+ import { hostname as hostname5 } from "os";
30420
31852
 
30421
31853
  // ../../packages/plugin-runtime/src/standalone-gateway.ts
30422
- import { randomUUID as randomUUID15 } from "crypto";
31854
+ import { randomUUID as randomUUID18 } from "crypto";
30423
31855
 
30424
31856
  // ../../packages/plugin-runtime/src/recorder.ts
30425
31857
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -30460,12 +31892,12 @@ var StandaloneDataGateway = class {
30460
31892
  // reconciler drops the whole pass and recovers it idempotently on the next read.
30461
31893
  recordLlmCalls(inputs) {
30462
31894
  if (inputs.length === 0) return Promise.resolve();
30463
- return new Promise((resolve2, reject) => {
31895
+ return new Promise((resolve3, reject) => {
30464
31896
  try {
30465
31897
  this.db.auditEvents.runInTransaction(() => {
30466
31898
  for (const input of inputs) this.db.auditEvents.insertLlmCall(input);
30467
31899
  });
30468
- resolve2();
31900
+ resolve3();
30469
31901
  } catch (err) {
30470
31902
  reject(err instanceof Error ? err : new Error(String(err)));
30471
31903
  }
@@ -30477,12 +31909,12 @@ var StandaloneDataGateway = class {
30477
31909
  // drops the whole pass and recovers it idempotently next time.
30478
31910
  recordToolCalls(inputs) {
30479
31911
  if (inputs.length === 0) return Promise.resolve();
30480
- return new Promise((resolve2, reject) => {
31912
+ return new Promise((resolve3, reject) => {
30481
31913
  try {
30482
31914
  this.db.auditEvents.runInTransaction(() => {
30483
31915
  for (const input of inputs) this.writeToolCall(input);
30484
31916
  });
30485
- resolve2();
31917
+ resolve3();
30486
31918
  } catch (err) {
30487
31919
  reject(err instanceof Error ? err : new Error(String(err)));
30488
31920
  }
@@ -30624,7 +32056,7 @@ var StandaloneDataGateway = class {
30624
32056
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
30625
32057
  const installed = this.installedScanRules();
30626
32058
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
30627
- id: randomUUID15(),
32059
+ id: randomUUID18(),
30628
32060
  scope: "global",
30629
32061
  target: { ruleId },
30630
32062
  action,
@@ -30778,36 +32210,82 @@ var StandaloneDataGateway = class {
30778
32210
  }
30779
32211
  };
30780
32212
 
32213
+ // ../../packages/plugin-runtime/src/attached/factory.ts
32214
+ function resolveGatewayForConfig(config2, meta3) {
32215
+ const local = new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
32216
+ try {
32217
+ if (!isAttached(config2.settings)) return local;
32218
+ const connection = config2.settings.controlPlane;
32219
+ if (connection === void 0) return local;
32220
+ const state = readControlPlaneCredentialState(config2.settingsDir, connection);
32221
+ if (!state.usable) return local;
32222
+ const client = createRemoteClient({
32223
+ endpoint: connection.endpoint,
32224
+ apiKey: state.credential.apiKey
32225
+ });
32226
+ const store = createPolicyStore(config2.dataDir);
32227
+ const postureStore = createPostureStore(config2.settingsDir, config2.dataDir);
32228
+ const forward = createForwardPolicy({ dir: config2.dataDir });
32229
+ return new AttachedDataGateway({
32230
+ local,
32231
+ client,
32232
+ dataDir: config2.dataDir,
32233
+ readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
32234
+ forward,
32235
+ posture: createPostureReporter({
32236
+ // THROUGH THE BREAKER, and wrapped HERE rather than around
32237
+ // `PostureReporter.send`. The reporter swallows every error by
32238
+ // contract, so a wrap outside it would hand `forward.run` a resolved
32239
+ // promise for a send that failed — recording a SUCCESS, clearing
32240
+ // `consecutiveFailures` and `lastFailure`, and telling `aka status` the
32241
+ // forward recovered when nothing did. Wrapping the raw client call puts
32242
+ // the breaker above the swallow, where it can see the truth.
32243
+ //
32244
+ // What it buys: once the breaker is open — the plane already confirmed
32245
+ // down by the gateway's own writes — this stops paying a request
32246
+ // timeout per throttle interval to re-learn it.
32247
+ report: (snapshot) => forward.run(() => client.reportStorePosture(snapshot)).then(() => void 0),
32248
+ store: postureStore,
32249
+ readStore: () => readStorePosture(config2.dbPath),
32250
+ hostname: () => hostname5(),
32251
+ now: () => Date.now()
32252
+ })
32253
+ });
32254
+ } catch {
32255
+ return local;
32256
+ }
32257
+ }
32258
+
30781
32259
  // ../../packages/plugin-runtime/src/resolve.ts
30782
- var standaloneGatewayFactory = (config2, meta3) => new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
30783
- var defaultGatewayFactory = standaloneGatewayFactory;
32260
+ var configuredGatewayFactory = (config2, meta3) => resolveGatewayForConfig(config2, meta3);
32261
+ var defaultGatewayFactory = configuredGatewayFactory;
30784
32262
  function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFactory) {
30785
32263
  return gatewayFactory(config2, meta3);
30786
32264
  }
30787
32265
 
30788
32266
  // ../../packages/plugin-runtime/src/handle-session-start.ts
30789
- import { randomUUID as randomUUID16 } from "crypto";
32267
+ import { randomUUID as randomUUID19 } from "crypto";
30790
32268
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
30791
32269
 
30792
32270
  // src/history/transcripts.ts
30793
- import { closeSync as closeSync2, openSync as openSync2, readdirSync as readdirSync6, readFileSync as readFileSync12, readSync, statSync as statSync7 } from "fs";
32271
+ import { closeSync as closeSync2, openSync as openSync2, readdirSync as readdirSync6, readFileSync as readFileSync16, readSync, statSync as statSync10 } from "fs";
30794
32272
  import { homedir as homedir3 } from "os";
30795
- import { join as join18 } from "path";
32273
+ import { join as join25 } from "path";
30796
32274
  function transcriptsDir(home) {
30797
- return join18(home ?? homedir3(), ".codex", "sessions");
32275
+ return join25(home ?? homedir3(), ".codex", "sessions");
30798
32276
  }
30799
32277
  var DAY_MS5 = 24 * 60 * 60 * 1e3;
30800
32278
 
30801
32279
  // src/remediation/redact.ts
30802
- import { readFileSync as readFileSync13, realpathSync as realpathSync3, renameSync as renameSync5, rmSync as rmSync6, writeFileSync as writeFileSync9 } from "fs";
30803
- import { isAbsolute as isAbsolute2, relative, resolve } from "path";
32280
+ import { readFileSync as readFileSync17, realpathSync as realpathSync4, renameSync as renameSync5, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
32281
+ import { isAbsolute as isAbsolute2, relative, resolve as resolve2 } from "path";
30804
32282
  var REDACTED_PLACEHOLDER = "[REDACTED:SECRET]";
30805
32283
  function platformRedactionScope(home) {
30806
32284
  return { artifactRoots: [transcriptsDir(home)] };
30807
32285
  }
30808
32286
  function realPathOrNull(path) {
30809
32287
  try {
30810
- return realpathSync3(path);
32288
+ return realpathSync4(path);
30811
32289
  } catch {
30812
32290
  return null;
30813
32291
  }
@@ -30819,7 +32297,7 @@ function isWithinRoot(realTarget, root) {
30819
32297
  return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
30820
32298
  }
30821
32299
  function resolveRedactableArtifact(filePath, scope) {
30822
- const realTarget = realPathOrNull(resolve(filePath));
32300
+ const realTarget = realPathOrNull(resolve2(filePath));
30823
32301
  if (realTarget === null) return null;
30824
32302
  return scope.artifactRoots.some((root) => isWithinRoot(realTarget, root)) ? realTarget : null;
30825
32303
  }
@@ -30838,7 +32316,7 @@ function redactLeakedKeysDetailed(targets, scope = platformRedactionScope()) {
30838
32316
  for (const [filePath, fileTargets] of byFile) {
30839
32317
  let content;
30840
32318
  try {
30841
- content = readFileSync13(filePath, "utf8");
32319
+ content = readFileSync17(filePath, "utf8");
30842
32320
  } catch {
30843
32321
  continue;
30844
32322
  }
@@ -30861,7 +32339,7 @@ function redactLeakedKeysDetailed(targets, scope = platformRedactionScope()) {
30861
32339
  renameSync5(tmpPath, filePath);
30862
32340
  } catch {
30863
32341
  try {
30864
- rmSync6(tmpPath, { force: true, recursive: true });
32342
+ rmSync7(tmpPath, { force: true, recursive: true });
30865
32343
  } catch {
30866
32344
  }
30867
32345
  continue;
@@ -30914,7 +32392,7 @@ async function redactSurfacedSecrets(findings, overrides = {}) {
30914
32392
  for (const [filePath, fileFindings] of byFile) {
30915
32393
  let content;
30916
32394
  try {
30917
- content = readFileSync14(filePath, "utf8");
32395
+ content = readFileSync18(filePath, "utf8");
30918
32396
  } catch {
30919
32397
  unrecovered.push(...fileFindings);
30920
32398
  continue;
@@ -31068,11 +32546,11 @@ async function route(frameText, rawOption, rawPosture) {
31068
32546
  break;
31069
32547
  }
31070
32548
  }
31071
- if (process.argv[1] && fileURLToPath3(import.meta.url) === process.argv[1]) {
32549
+ if (process.argv[1] && fileURLToPath4(import.meta.url) === process.argv[1]) {
31072
32550
  try {
31073
32551
  const argv = process.argv.slice(2);
31074
32552
  const optionIndex = argv.indexOf("--option");
31075
- const frameText = readFileSync15(0, "utf8");
32553
+ const frameText = readFileSync19(0, "utf8");
31076
32554
  if (optionIndex === -1) {
31077
32555
  present(frameText);
31078
32556
  } else {